Fix pylint messages in src/vcs

This commit is contained in:
Romain Failliot 2021-11-20 12:25:55 -05:00
parent 560f8a472e
commit 510cbc1cf3
13 changed files with 214 additions and 152 deletions

View File

@ -21,13 +21,12 @@
import sys
import gettext
import locale
pkgdatadir = '@pkgdatadir@'
localedir = '@localedir@'
PKGDATADIR = '@pkgdatadir@'
LOCALEDIR = '@localedir@'
sys.path.insert(1, pkgdatadir)
gettext.install('diffuse', localedir)
sys.path.insert(1, PKGDATADIR)
gettext.install('diffuse', LOCALEDIR)
if __name__ == '__main__':
from diffuse import main

View File

@ -55,10 +55,6 @@ from diffuse import utils
from diffuse import constants
from diffuse.vcs.vcs_registry import VcsRegistry
if not hasattr(__builtins__, 'WindowsError'):
# define 'WindowsError' so 'except' statements will work on all platforms
WindowsError = IOError
# avoid some dictionary lookups when string.whitespace is used in loops
# this is sorted based upon frequency to speed up code for stripping whitespace
whitespace = ' \t\n\r\x0b\x0c'
@ -131,38 +127,6 @@ class SyntaxParser:
start = end
return state_name, blocks
# split string into lines based upon DOS, Mac, and Unix line endings
def splitlines(s):
# split on new line characters
temp, i, n = [], 0, len(s)
while i < n:
j = s.find('\n', i)
if j < 0:
temp.append(s[i:])
break
j += 1
temp.append(s[i:j])
i = j
# split on carriage return characters
ss = []
for s in temp:
i, n = 0, len(s)
while i < n:
j = s.find('\r', i)
if j < 0:
ss.append(s[i:])
break
j += 1
if j < n and s[j] == '\n':
j += 1
ss.append(s[i:j])
i = j
return ss
# also recognise old Mac OS line endings
def readlines(fd):
return strip_eols(splitlines(fd.read()))
def readconfiglines(fd):
return fd.read().replace('\r', '').split('\n')
@ -1141,33 +1105,12 @@ def getFormat(ss):
flags |= UNIX_FORMAT
return flags
# returns the number of characters in the string excluding any line ending
# characters
def len_minus_line_ending(s):
if s is None:
return 0
n = len(s)
if s.endswith('\r\n'):
n -= 2
elif s.endswith('\r') or s.endswith('\n'):
n -= 1
return n
# returns the string without the line ending characters
def strip_eol(s):
if s is not None:
return s[:len_minus_line_ending(s)]
# returns the list of strings without line ending characters
def strip_eols(ss):
return [ strip_eol(s) for s in ss ]
# convenience method to change the line ending of a string
def convert_to_format(s, format):
if s is not None and format != 0:
old_format = getFormat([ s ])
if old_format != 0 and (old_format & format) == 0:
s = strip_eol(s)
s = utils.strip_eol(s)
# prefer the host line ending style
if (format & DOS_FORMAT) and os.linesep == '\r\n':
s += os.linesep
@ -1913,7 +1856,7 @@ class FileDiffViewer(Gtk.Grid):
# This is an inline loop over self.characterWidth() for performance reasons.
def stringWidth(self, s):
if not self.prefs.getBool('display_show_whitespace'):
s = strip_eol(s)
s = utils.strip_eol(s)
col = 0
for c in s:
try:
@ -1965,7 +1908,7 @@ class FileDiffViewer(Gtk.Grid):
def expand(self, s):
visible = self.prefs.getBool('display_show_whitespace')
if not visible:
s = strip_eol(s)
s = utils.strip_eol(s)
tab_width = self.prefs.getInt('display_tab_width')
col = 0
result = []
@ -2563,7 +2506,7 @@ class FileDiffViewer(Gtk.Grid):
# hashes for non-null lines should start with '+' to distinguish
# them from blank lines
if pref('align_ignore_endofline'):
text = strip_eol(text)
text = utils.strip_eol(text)
if pref('align_ignore_blanklines') and isBlank(text):
# consider all lines containing only white space as the same
return ''
@ -2792,8 +2735,8 @@ class FileDiffViewer(Gtk.Grid):
if text is None:
text = ''
# split the replacement text into lines
ss = splitlines(text)
if len(ss) == 0 or len(ss[-1]) != len_minus_line_ending(ss[-1]):
ss = utils.splitlines(text)
if len(ss) == 0 or len(ss[-1]) != utils.len_minus_line_ending(ss[-1]):
ss.append('')
# change the format to that of the target pane
if pane.format == 0:
@ -2807,7 +2750,7 @@ class FileDiffViewer(Gtk.Grid):
lastcol = 0
if len(ss) > 0:
last = ss[-1]
if len(last) == len_minus_line_ending(last):
if len(last) == utils.len_minus_line_ending(last):
del ss[-1]
lastcol = len(last)
cur_line = line0 + len(ss)
@ -3200,7 +3143,7 @@ class FileDiffViewer(Gtk.Grid):
x, y = -1, 0
i = min(y // self.font_height, len(self.panes[f].lines))
if self.mode == CHAR_MODE and f == self.current_pane:
text = strip_eol(self.getLineText(f, i))
text = utils.strip_eol(self.getLineText(f, i))
j = self._getPickedCharacter(text, x, True)
if extend:
si, sj = self.selection_line, self.selection_char
@ -3241,7 +3184,7 @@ class FileDiffViewer(Gtk.Grid):
self.emit('mode_changed')
elif self.mode == CHAR_MODE and self.current_pane == f:
# select word
text = strip_eol(self.getLineText(f, i))
text = utils.strip_eol(self.getLineText(f, i))
if text is not None:
n = len(text)
j = self._getPickedCharacter(text, x, False)
@ -3323,7 +3266,7 @@ class FileDiffViewer(Gtk.Grid):
else:
s = s2
if self.prefs.getBool('display_ignore_endofline'):
s = strip_eol(s)
s = utils.strip_eol(s)
s1 = nullToEmpty(self.getCompareString(f, i))
s2 = nullToEmpty(self.getCompareString(f + 1, i))
@ -3394,7 +3337,7 @@ class FileDiffViewer(Gtk.Grid):
s = line.getText()
if s is not None:
if self.prefs.getBool('display_ignore_endofline'):
s = strip_eol(s)
s = utils.strip_eol(s)
if self.prefs.getBool('display_ignore_blanklines') and isBlank(s):
return None
if self.prefs.getBool('display_ignore_whitespace'):
@ -3906,7 +3849,7 @@ class FileDiffViewer(Gtk.Grid):
# returns the maximum valid offset for a cursor position
# cursors cannot be moved to the right of line ending characters
def getMaxCharPosition(self, i):
return len_minus_line_ending(self.getLineText(self.current_pane, i))
return utils.len_minus_line_ending(self.getLineText(self.current_pane, i))
# 'enter_align_mode' keybinding action
def _line_mode_enter_align_mode(self):
@ -4132,7 +4075,7 @@ class FileDiffViewer(Gtk.Grid):
# move the cursor to column 'col' if possible
s = self.getLineText(f, i)
if s is not None:
s = strip_eol(s)
s = utils.strip_eol(s)
idx = 0
for c in s:
w = self.characterWidth(idx, c)
@ -4282,7 +4225,7 @@ class FileDiffViewer(Gtk.Grid):
self.recordEditMode()
for i in range(start, end + 1):
text = self.getLineText(f, i)
if text is not None and len_minus_line_ending(text) > 0:
if text is not None and utils.len_minus_line_ending(text) > 0:
# count spacing before the first non-whitespace character
j, w = 0, 0
while j < len(text) and text[j] in ' \t':
@ -4807,7 +4750,7 @@ class FileDiffViewer(Gtk.Grid):
text = self.getLineText(f, i)
if text is not None:
# locate trailing whitespace
old_n = n = len_minus_line_ending(text)
old_n = n = utils.len_minus_line_ending(text)
while n > 0 and text[n - 1] in whitespace:
n -= 1
# update line if it changed
@ -4914,7 +4857,7 @@ class FileDiffViewer(Gtk.Grid):
self.recordEditMode()
for i in range(start, end + 1):
text = self.getLineText(f, i)
if text is not None and len_minus_line_ending(text) > 0:
if text is not None and utils.len_minus_line_ending(text) > 0:
# count spacing before the first non-whitespace character
j, w = 0, 0
while j < len(text) and text[j] in ' \t':
@ -5628,8 +5571,8 @@ class Diffuse(Gtk.Window):
s, encoding = self.prefs.convertToUnicode(s)
else:
s = str(s, encoding=encoding)
ss = splitlines(s)
except (IOError, OSError, UnicodeDecodeError, WindowsError, LookupError):
ss = utils.splitlines(s)
except (IOError, OSError, UnicodeDecodeError, LookupError):
# FIXME: this can occur before the toplevel window is drawn
if rev is not None:
msg = _('Error reading revision %(rev)s of %(file)s.') % { 'rev': rev, 'file': name }
@ -6460,7 +6403,7 @@ class Diffuse(Gtk.Window):
name, rev = spec
viewer.load(i, FileInfo(name, encoding, vcs, rev))
viewer.setOptions(options)
except (IOError, OSError, WindowsError):
except (IOError, OSError):
utils.logErrorAndDialog(_('Error retrieving commits for %s.') % (dn, ), self.get_toplevel())
# create a new viewer for each modified file found in 'items'
@ -6489,7 +6432,7 @@ class Diffuse(Gtk.Window):
name, rev = spec
viewer.load(i, FileInfo(name, encoding, vcs, rev))
viewer.setOptions(options)
except (IOError, OSError, WindowsError):
except (IOError, OSError):
utils.logErrorAndDialog(_('Error retrieving modifications for %s.') % (dn, ), self.get_toplevel())
# close all tabs without differences

View File

@ -96,8 +96,8 @@ def relpath(a, b):
# helper function prevent files from being confused with command line options
# by prepending './' to the basename
def safeRelativePath(abspath1, name, prefs, cygwin_pref):
s = os.path.join(os.curdir, utils.relpath(abspath1, os.path.abspath(name)))
if utils.isWindows():
s = os.path.join(os.curdir, relpath(abspath1, os.path.abspath(name)))
if isWindows():
if prefs.getBool(cygwin_pref):
s = s.replace('\\', '/')
else:
@ -182,6 +182,55 @@ def globEscape(s):
m = dict([ (c, f'[{c}]') for c in '[]?*' ])
return ''.join([ m.get(c, c) for c in s ])
# returns the number of characters in the string excluding any line ending
# characters
def len_minus_line_ending(s):
if s is None:
return 0
n = len(s)
if s.endswith('\r\n'):
n -= 2
elif s.endswith('\r') or s.endswith('\n'):
n -= 1
return n
# returns the string without the line ending characters
def strip_eol(s):
if s is not None:
return s[:len_minus_line_ending(s)]
# split string into lines based upon DOS, Mac, and Unix line endings
def splitlines(s):
# split on new line characters
temp, i, n = [], 0, len(s)
while i < n:
j = s.find('\n', i)
if j < 0:
temp.append(s[i:])
break
j += 1
temp.append(s[i:j])
i = j
# split on carriage return characters
ss = []
for s in temp:
i, n = 0, len(s)
while i < n:
j = s.find('\r', i)
if j < 0:
ss.append(s[i:])
break
j += 1
if j < n and s[j] == '\n':
j += 1
ss.append(s[i:j])
i = j
return ss
# also recognize old Mac OS line endings
def readlines(fd):
return [ strip_eol(s) for s in splitlines(fd.read()) ]
# use the program's location as a starting place to search for supporting files
# such as icon and help documentation
if hasattr(sys, 'frozen'):

View File

@ -41,11 +41,11 @@ class Cvs(VcsInterface):
if len(r):
prev = '.'.join(r)
for k in sorted(names):
if prev is None:
k0 = None
else:
k0 = k
result.append([ (k0, prev), (k, rev) ])
if prev is None:
k0 = None
else:
k0 = k
result.append([ (k0, prev), (k, rev) ])
except ValueError:
utils.logError(_('Error parsing revision %s.') % (rev, ))
return result
@ -73,7 +73,6 @@ class Cvs(VcsInterface):
if s[0] == 'R':
# removed
modified[k] = [ (k, prev), (None, None) ]
pass
elif s[0] == 'A':
# added
modified[k] = [ (None, None), (k, None) ]

View File

@ -42,4 +42,3 @@ class FolderSet:
if abspath.startswith(f):
return True
return False

View File

@ -65,7 +65,14 @@ class Git(VcsInterface):
def getFolderTemplate(self, prefs, names):
# build command
args = [ prefs.getString('git_bin'), 'status', '--porcelain', '-s', '--untracked-files=no', '--ignore-submodules=all' ]
args = [
prefs.getString('git_bin'),
'status',
'--porcelain',
'-s',
'--untracked-files=no',
'--ignore-submodules=all'
]
# build list of interesting files
pwd = os.path.abspath(os.curdir)
isabs = False
@ -142,14 +149,13 @@ class Git(VcsInterface):
return result
def getRevision(self, prefs, name, rev):
relpath = utils.relpath(self.root, os.path.abspath(name)).replace(os.sep, '/')
return utils.popenRead(
self.root,
[
prefs.getString('git_bin'),
'show',
'{}:{}'.format(
rev,
utils.relpath(self.root, os.path.abspath(name)).replace(os.sep, '/'))
f'{rev}:{relpath}'
],
prefs,
'git_bash')

View File

@ -32,7 +32,11 @@ class Hg(VcsInterface):
def _getPreviousRevision(self, prefs, rev):
if rev is None:
if self.working_rev is None:
ss = utils.popenReadLines(self.root, [ prefs.getString('hg_bin'), 'id', '-i', '-t' ], prefs, 'hg_bash')
ss = utils.popenReadLines(
self.root,
[ prefs.getString('hg_bin'), 'id', '-i', '-t' ],
prefs,
'hg_bash')
if len(ss) != 1:
raise IOError('Unknown working revision')
ss = ss[0].split(' ')
@ -81,7 +85,11 @@ class Hg(VcsInterface):
return [ modified[k] for k in sorted(modified.keys()) ]
def getCommitTemplate(self, prefs, rev, names):
return self._getCommitTemplate(prefs, names, [ 'log', '--template', 'A\t{file_adds}\nM\t{file_mods}\nR\t{file_dels}\n', '-r', rev ], rev)
return self._getCommitTemplate(
prefs,
names,
[ 'log', '--template', 'A\t{file_adds}\nM\t{file_mods}\nR\t{file_dels}\n', '-r', rev ],
rev)
def getFolderTemplate(self, prefs, names):
return self._getCommitTemplate(prefs, names, [ 'status', '-q' ], None)

View File

@ -33,7 +33,11 @@ class Mtn(VcsInterface):
def getCommitTemplate(self, prefs, rev, names):
# build command
vcs_bin = prefs.getString('mtn_bin')
ss = utils.popenReadLines(self.root, [ vcs_bin, 'automate', 'select', '-q', rev ], prefs, 'mtn_bash')
ss = utils.popenReadLines(
self.root,
[ vcs_bin, 'automate', 'select', '-q', rev ],
prefs,
'mtn_bash')
if len(ss) != 1:
raise IOError('Ambiguous revision specifier')
args = [ vcs_bin, 'automate', 'get_revision', ss[0] ]
@ -59,7 +63,7 @@ class Mtn(VcsInterface):
break
prev = arg1[1:-1]
continue
elif prev is None:
if prev is None:
continue
if arg == 'delete':
# deleted file
@ -88,7 +92,11 @@ class Mtn(VcsInterface):
if removed or renamed:
# remove directories
removed_dirs = set()
for s in utils.popenReadLines(self.root, [ vcs_bin, 'automate', 'get_manifest_of', prev ], prefs, 'mtn_bash'):
for s in utils.popenReadLines(
self.root,
[ vcs_bin, 'automate', 'get_manifest_of', prev ],
prefs,
'mtn_bash'):
s = shlex.split(s)
if len(s) > 1 and s[0] == 'dir':
removed_dirs.add(s[1])
@ -130,7 +138,14 @@ class Mtn(VcsInterface):
fs = FolderSet(names)
result = []
pwd, isabs = os.path.abspath(os.curdir), False
args = [ prefs.getString('mtn_bin'), 'automate', 'inventory', '--no-ignored', '--no-unchanged', '--no-unknown' ]
args = [
prefs.getString('mtn_bin'),
'automate',
'inventory',
'--no-ignored',
'--no-unchanged',
'--no-unknown'
]
for name in names:
isabs |= os.path.isabs(name)
# build list of interesting files
@ -168,7 +183,11 @@ class Mtn(VcsInterface):
k = utils.relpath(pwd, k)
added[k] = [ (None, None), (k, None) ]
processed = True
if 'rename_target' in s and 'file' in m.get('new_type', []) and len(m.get('old_path', [])) > 0:
if (
'rename_target' in s and
'file' in m.get('new_type', []) and
len(m.get('old_path', [])) > 0
):
# renamed file
k0 = os.path.join(self.root, prefs.convertToNativePath(m['old_path'][0]))
k1 = os.path.join(self.root, prefs.convertToNativePath(p))

View File

@ -25,7 +25,12 @@ from diffuse.vcs.vcs_interface import VcsInterface
# RCS support
class Rcs(VcsInterface):
def getFileTemplate(self, prefs, name):
args = [ prefs.getString('rcs_bin_rlog'), '-L', '-h', utils.safeRelativePath(self.root, name, prefs, 'rcs_cygwin') ]
args = [
prefs.getString('rcs_bin_rlog'),
'-L',
'-h',
utils.safeRelativePath(self.root, name, prefs, 'rcs_cygwin')
]
rev = ''
for line in utils.popenReadLines(self.root, args, prefs, 'rcs_bash'):
if line.startswith('head: '):
@ -69,12 +74,12 @@ class Rcs(VcsInterface):
recurse = os.path.isdir(os.path.join(s, 'RCS'))
if ex or recurse:
ex = False
for v in os.listdir(s):
dn = os.path.join(s, v)
if v.endswith(',v') and os.path.isfile(dn):
for d in os.listdir(s):
dn = os.path.join(s, d)
if d.endswith(',v') and os.path.isfile(dn):
# map to checkout name
r.append(dn[:-2])
elif v == 'RCS' and os.path.isdir(dn):
elif d == 'RCS' and os.path.isdir(dn):
for v in os.listdir(dn):
if os.path.isfile(os.path.join(dn, v)):
if v.endswith(',v'):

View File

@ -18,7 +18,6 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os
import glob
from diffuse import utils
from diffuse.vcs.svn import Svn
@ -32,7 +31,7 @@ class Svk(Svn):
def _parseStatusLine(self, s):
if len(s) < 4 or s[0] not in 'ACDMR':
return
return '', ''
return s[0], s[4:]
def _getPreviousRevision(self, rev):
@ -43,6 +42,7 @@ class Svk(Svn):
return str(int(rev) - 1)
def getRevision(self, prefs, name, rev):
relpath = utils.relpath(self.root, os.path.abspath(name)).replace(os.sep, '/')
return utils.popenRead(
self.root,
[
@ -50,9 +50,7 @@ class Svk(Svn):
'cat',
'-r',
rev,
'{}/{}'.format(
self._getURL(prefs),
utils.relpath(self.root, os.path.abspath(name)).replace(os.sep, '/'))
f'{self._getURL(prefs)}/{relpath}'
],
prefs,
'svk_bash')

View File

@ -39,7 +39,7 @@ class Svn(VcsInterface):
def _parseStatusLine(self, s):
if len(s) < 8 or s[0] not in 'ACDMR':
return
return '', ''
# subversion 1.6 adds a new column
k = 7
if k < len(s) and s[k] == ' ':
@ -50,8 +50,7 @@ class Svn(VcsInterface):
if rev is None:
return 'BASE'
m = int(rev)
if m > 1:
return str(m - 1)
return str(max(m > 1, 0))
def _getURL(self, prefs):
if self.url is None:
@ -152,7 +151,7 @@ class Svn(VcsInterface):
m[d] = set()
m[d].add(b)
# remove items we can easily determine to be directories
for k in m.keys():
for k in m:
d = os.path.dirname(k)
if d in m:
m[d].discard(os.path.basename(k))
@ -161,7 +160,18 @@ class Svn(VcsInterface):
# determine which are directories
added = {}
for p, v in m.items():
for s in utils.popenReadLines(self.root, [ vcs_bin, 'list', '-r', rev, '{}/{}'.format(self._getURL(prefs), p.replace(os.sep, '/')) ], prefs, vcs_bash):
lines = utils.popenReadLines(
self.root,
[
vcs_bin,
'list',
'-r',
rev,
f"{self._getURL(prefs)}/{p.replace(os.sep, '/')}"
],
prefs,
vcs_bash)
for s in lines:
if s in v:
# confirmed as added file
k = os.path.join(self.root, os.path.join(p, s))
@ -187,7 +197,18 @@ class Svn(VcsInterface):
m[d].add(b)
removed_dir, removed = set(), {}
for p, v in m.items():
for s in utils.popenReadLines(self.root, [ vcs_bin, 'list', '-r', prev, '{}/{}'.format(self._getURL(prefs), p.replace(os.sep, '/')) ], prefs, vcs_bash):
lines = utils.popenReadLines(
self.root,
[
vcs_bin,
'list',
'-r',
prev,
f"{self._getURL(prefs)}/{p.replace(os.sep, '/')}"
],
prefs,
vcs_bash)
for s in lines:
if s.endswith('/'):
s = s[:-1]
if s in v:
@ -205,7 +226,18 @@ class Svn(VcsInterface):
tmp = removed_dir
removed_dir = set()
for p in tmp:
for s in utils.popenReadLines(self.root, [ vcs_bin, 'list', '-r', prev, '{}/{}'.format(self._getURL(prefs), p.replace(os.sep, '/')) ], prefs, vcs_bash):
lines = utils.popenReadLines(
self.root,
[
vcs_bin,
'list',
'-r',
prev,
f"{self._getURL(prefs)}/{p.replace(os.sep, '/')}"
],
prefs,
vcs_bash)
for s in lines:
if s.endswith('/'):
# confirmed item as directory
removed_dir.add(os.path.join(p, s[:-1]))
@ -239,7 +271,7 @@ class Svn(VcsInterface):
[
vcs_bin,
'cat',
'{}@{}'.format(utils.safeRelativePath(self.root, name, prefs, 'svn_cygwin'), rev)
f"{utils.safeRelativePath(self.root, name, prefs, 'svn_cygwin')}@{rev}"
],
prefs,
'svn_bash')
@ -248,10 +280,10 @@ class Svn(VcsInterface):
[
vcs_bin,
'cat',
'{}/{}@{}'.format(
self._getURL(prefs),
utils.relpath(self.root, os.path.abspath(name)).replace(os.sep, '/'),
rev)
(
f"{self._getURL(prefs)}/"
f"{utils.relpath(self.root, os.path.abspath(name)).replace(os.sep, '/')}@{rev}"
)
],
prefs,
'svn_bash')

View File

@ -18,22 +18,21 @@
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
class VcsInterface:
"""Interface for the VCSs."""
def __init__(self, root):
"""The object will initialized with the repository's root folder."""
self.root = root
def getFileTemplate(self, prefs, name):
"""Indicates which revisions to display for a file when none were explicitly requested."""
pass
"""Indicates which revisions to display for a file when none were explicitly
requested."""
def getCommitTemplate(self, prefs, rev, names):
"""Indicates which file revisions to display for a commit."""
pass
def getFolderTemplate(self, prefs, names):
"""Indicates which file revisions to display for a set of folders."""
def getRevision(self, prefs, name, rev):
"""Returns the contents of the specified file revision"""
pass

View File

@ -46,9 +46,6 @@ class VcsRegistry:
'svn': _get_svn_repo
}
def setSearchOrder(self, ordering):
self._search_order = ordering
# determines which VCS to use for files in the named folder
def findByFolder(self, path, prefs):
path = os.path.abspath(path)
@ -57,11 +54,13 @@ class VcsRegistry:
repo = self._get_repo[vcs](path, prefs)
if repo:
return repo
return None
# determines which VCS to use for the named file
def findByFilename(self, name, prefs):
if name is not None:
return self.findByFolder(os.path.dirname(name), prefs)
return None
# utility method to help find folders used by version control systems
@ -77,29 +76,34 @@ def _find_parent_dir_with(path, dir_name):
def _get_bzr_repo(path, prefs):
p = _find_parent_dir_with(path, '.bzr')
if p:
return Bzr(p)
return Bzr(p) if p else None
def _get_cvs_repo(path, prefs):
if os.path.isdir(os.path.join(path, 'CVS')):
return Cvs(path)
return Cvs(path) if os.path.isdir(os.path.join(path, 'CVS')) else None
def _get_darcs_repo(path, prefs):
p = _find_parent_dir_with(path, '_darcs')
if p:
return Darcs(p)
return Darcs(p) if p else None
def _get_git_repo(path, prefs):
if 'GIT_DIR' in os.environ:
try:
d = path
ss = utils.popenReadLines(d, [ prefs.getString('git_bin'), 'rev-parse', '--show-prefix' ], prefs, 'git_bash')
ss = utils.popenReadLines(
d,
[
prefs.getString('git_bin'),
'rev-parse',
'--show-prefix'
],
prefs,
'git_bash')
if len(ss) > 0:
# be careful to handle trailing slashes
d = d.split(os.sep)
if d[-1] != '':
d.append('')
ss = strip_eol(ss[0]).split('/')
ss = utils.strip_eol(ss[0]).split('/')
if ss[-1] != '':
ss.append('')
n = len(ss)
@ -110,7 +114,7 @@ def _get_git_repo(path, prefs):
else:
d = os.sep.join(d)
return Git(d)
except (IOError, OSError, WindowsError):
except (IOError, OSError):
# working tree not found
pass
# search for .git directory (project) or .git file (submodule)
@ -125,13 +129,11 @@ def _get_git_repo(path, prefs):
def _get_hg_repo(path, prefs):
p = _find_parent_dir_with(path, '.hg')
if p:
return Hg(p)
return Hg(p) if p else None
def _get_mtn_repo(path, prefs):
p = _find_parent_dir_with(path, '_MTN')
if p:
return Mtn(p)
return Mtn(p) if p else None
def _get_rcs_repo(path, prefs):
if os.path.isdir(os.path.join(path, 'RCS')):
@ -147,11 +149,11 @@ def _get_rcs_repo(path, prefs):
except OSError:
# the user specified an invalid folder name
pass
return None
def _get_svn_repo(path, prefs):
p = _find_parent_dir_with(path, '.svn')
if p:
return Svn(p)
return Svn(p) if p else None
def _get_svk_repo(path, prefs):
name = path
@ -166,9 +168,8 @@ def _get_svk_repo(path, prefs):
if os.path.isfile(svkconfig):
try:
# find working copies by parsing the config file
f = open(svkconfig, 'r')
ss = readlines(f)
f.close()
with open(svkconfig, 'r', encoding='utf-8') as f:
ss = utils.readlines(f)
projs, sep = [], os.sep
# find the separator character
for s in ss:
@ -183,7 +184,11 @@ def _get_svk_repo(path, prefs):
while i < len(ss) and ss[i].startswith(' '):
s = ss[i]
i += 1
if s.endswith(': ') and i < len(ss) and ss[i].startswith(' depotpath: '):
if (
s.endswith(': ') and
i < len(ss) and
ss[i].startswith(' depotpath: ')
):
key = s[4:-2].replace(sep, os.sep)
# parse directory path
j, n, tt = 0, len(key), []
@ -195,7 +200,7 @@ def _get_svk_repo(path, prefs):
if key[j] == '"':
j += 1
break
elif key[j] == '\\':
if key[j] == '\\':
# escaped character
j += 1
if j < n:
@ -214,3 +219,4 @@ def _get_svk_repo(path, prefs):
return Svk(path)
except IOError:
utils.logError(_('Error parsing %s.') % (svkconfig, ))
return None