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 sys
import gettext import gettext
import locale
pkgdatadir = '@pkgdatadir@' PKGDATADIR = '@pkgdatadir@'
localedir = '@localedir@' LOCALEDIR = '@localedir@'
sys.path.insert(1, pkgdatadir) sys.path.insert(1, PKGDATADIR)
gettext.install('diffuse', localedir) gettext.install('diffuse', LOCALEDIR)
if __name__ == '__main__': if __name__ == '__main__':
from diffuse import main from diffuse import main

View File

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

View File

@ -73,7 +73,6 @@ class Cvs(VcsInterface):
if s[0] == 'R': if s[0] == 'R':
# removed # removed
modified[k] = [ (k, prev), (None, None) ] modified[k] = [ (k, prev), (None, None) ]
pass
elif s[0] == 'A': elif s[0] == 'A':
# added # added
modified[k] = [ (None, None), (k, None) ] modified[k] = [ (None, None), (k, None) ]

View File

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

View File

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

View File

@ -32,7 +32,11 @@ class Hg(VcsInterface):
def _getPreviousRevision(self, prefs, rev): def _getPreviousRevision(self, prefs, rev):
if rev is None: if rev is None:
if self.working_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: if len(ss) != 1:
raise IOError('Unknown working revision') raise IOError('Unknown working revision')
ss = ss[0].split(' ') ss = ss[0].split(' ')
@ -81,7 +85,11 @@ class Hg(VcsInterface):
return [ modified[k] for k in sorted(modified.keys()) ] return [ modified[k] for k in sorted(modified.keys()) ]
def getCommitTemplate(self, prefs, rev, names): 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): def getFolderTemplate(self, prefs, names):
return self._getCommitTemplate(prefs, names, [ 'status', '-q' ], None) return self._getCommitTemplate(prefs, names, [ 'status', '-q' ], None)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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