From 0ceae60141c3a779fe77e8597606e4abcd110a86 Mon Sep 17 00:00:00 2001 From: David Aguilar Date: Sun, 19 Mar 2023 00:28:58 -0700 Subject: [PATCH] pylint: rename variables for readability Signed-off-by: David Aguilar --- .pylintrc | 4 +- cola/compat.py | 4 +- cola/core.py | 22 ++++----- cola/decorators.py | 6 +-- cola/diffparse.py | 14 +++--- cola/fsmonitor.py | 4 +- cola/git.py | 32 ++++++------- cola/gitcfg.py | 32 ++++++------- cola/gitcmds.py | 6 +-- cola/inotify.py | 12 ++--- cola/models/selection.py | 60 ++++++++++++----------- cola/qtutils.py | 113 +++++++++++++++++++++++--------------------- cola/sequenceeditor.py | 8 ++-- cola/settings.py | 4 +- cola/spellcheck.py | 6 +-- cola/textwrap.py | 4 +- cola/themes.py | 2 +- cola/utils.py | 73 ++++++++++++++-------------- cola/version.py | 8 ++-- cola/widgets/bookmarks.py | 22 ++++----- cola/widgets/branch.py | 9 ++-- cola/widgets/browse.py | 1 + cola/widgets/cfgactions.py | 4 +- cola/widgets/clone.py | 4 +- cola/widgets/commitmsg.py | 12 ++--- cola/widgets/common.py | 12 ++--- cola/widgets/completion.py | 14 +++--- cola/widgets/dag.py | 92 ++++++++++++++++++------------------ cola/widgets/diff.py | 25 ++++++---- cola/widgets/editremotes.py | 4 +- cola/widgets/filelist.py | 8 ++-- cola/widgets/main.py | 32 ++++++++----- cola/widgets/startup.py | 20 ++++---- cola/widgets/status.py | 9 ++-- cola/widgets/text.py | 5 +- test/git_test.py | 16 +++---- 36 files changed, 364 insertions(+), 339 deletions(-) diff --git a/.pylintrc b/.pylintrc index 22a20955..42cc3a86 100644 --- a/.pylintrc +++ b/.pylintrc @@ -89,10 +89,10 @@ msg-template={path}:{line}:{column}: {msg} ({symbol}) [BASIC] # Good variable names which should always be accepted, separated by a comma -good-names=i,j,k,ex,Run,_ +good-names=f,i,j,k,ok,v,_ # Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata +bad-names= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. diff --git a/cola/compat.py b/cola/compat.py index 09889938..290cb517 100644 --- a/cola/compat.py +++ b/cola/compat.py @@ -21,8 +21,8 @@ ENCODING = 'utf-8' if PY3: - def bstr(x, encoding=ENCODING): - return bytes(x, encoding=encoding) + def bstr(value, encoding=ENCODING): + return bytes(value, encoding=encoding) elif PY26_PLUS: bstr = bytes diff --git a/cola/core.py b/cola/core.py index f77ecc98..455ad6c2 100644 --- a/cola/core.py +++ b/cola/core.py @@ -357,24 +357,24 @@ def _decorator_noop(x): return x -def wrap(action, fn, decorator=None): +def wrap(action, func, decorator=None): """Wrap arguments with `action`, optionally decorate the result""" if decorator is None: decorator = _decorator_noop - @functools.wraps(fn) + @functools.wraps(func) def wrapped(*args, **kwargs): - return decorator(fn(action(*args, **kwargs))) + return decorator(func(action(*args, **kwargs))) return wrapped -def decorate(decorator, fn): - """Decorate the result of `fn` with `action`""" +def decorate(decorator, func): + """Decorate the result of `func` with `action`""" - @functools.wraps(fn) + @functools.wraps(func) def decorated(*args, **kwargs): - return decorator(fn(*args, **kwargs)) + return decorator(func(*args, **kwargs)) return decorated @@ -475,11 +475,11 @@ def _find_executable(executable, path=None): executable = executable + '.exe' if not os.path.isfile(executable): - for p in paths: - f = os.path.join(p, executable) - if os.path.isfile(f): + for dirname in paths: + filename = os.path.join(dirname, executable) + if os.path.isfile(filename): # the file exists, we have a shot at spawn working - return f + return filename return None return executable diff --git a/cola/decorators.py b/cola/decorators.py index ab6dc05f..3d0c0e8f 100644 --- a/cola/decorators.py +++ b/cola/decorators.py @@ -18,10 +18,10 @@ def decorator(caller, func=None): # return a decorator # pylint: disable=unused-argument @functools.wraps(caller) - def _decorator(f, *dummy_args, **dummy_opts): - @functools.wraps(f) + def _decorator(func, *dummy_args, **dummy_opts): + @functools.wraps(func) def _caller(*args, **opts): - return caller(f, *args, **opts) + return caller(func, *args, **opts) return _caller diff --git a/cola/diffparse.py b/cola/diffparse.py index 3c1402d6..c0df0727 100644 --- a/cola/diffparse.py +++ b/cola/diffparse.py @@ -97,10 +97,10 @@ class DiffLines(object): def parse(self, diff_text): lines = [] - DIFF_STATE = 1 - state = INITIAL_STATE = 0 + diff_state = 1 + state = initial_state = 0 merge = self.merge = False - NO_NEWLINE = r'\ No newline at end of file' + no_newline = r'\ No newline at end of file' old = self.old.reset() new = self.new.reset() @@ -111,7 +111,7 @@ class DiffLines(object): if text.startswith('@@ -'): parts = text.split(' ', 4) if parts[0] == '@@' and parts[3] == '@@': - state = DIFF_STATE + state = diff_state old.parse(parts[1][1:]) new.parse(parts[2][1:]) lines.append((self.DASH, self.DASH)) @@ -120,13 +120,13 @@ class DiffLines(object): self.merge = merge = True parts = text.split(' ', 5) if parts[0] == '@@@' and parts[4] == '@@@': - state = DIFF_STATE + state = diff_state ours.parse(parts[1][1:]) theirs.parse(parts[2][1:]) new.parse(parts[3][1:]) lines.append((self.DASH, self.DASH, self.DASH)) continue - if state == INITIAL_STATE or text.rstrip() == NO_NEWLINE: + if state == initial_state or text.rstrip() == no_newline: if merge: lines.append((self.EMPTY, self.EMPTY, self.EMPTY)) else: @@ -157,7 +157,7 @@ class DiffLines(object): ours.tick() theirs.tick() else: - state = INITIAL_STATE + state = initial_state if merge: lines.append((self.EMPTY, self.EMPTY, self.EMPTY)) else: diff --git a/cola/fsmonitor.py b/cola/fsmonitor.py index dcc0bc51..08b3018b 100644 --- a/cola/fsmonitor.py +++ b/cola/fsmonitor.py @@ -454,10 +454,10 @@ if AVAILABLE == 'pywin32': timeout = self._NOTIFICATION_DELAY else: timeout = win32event.INFINITE - rc = win32event.WaitForMultipleObjects(events, False, timeout) + status = win32event.WaitForMultipleObjects(events, False, timeout) if not self._running: break - if rc == win32event.WAIT_TIMEOUT: + if status == win32event.WAIT_TIMEOUT: self.notify() else: self._handle_results() diff --git a/cola/git.py b/cola/git.py index 34e2b7de..d9b0b775 100644 --- a/cola/git.py +++ b/cola/git.py @@ -36,8 +36,8 @@ OID_LENGTH = 40 _index_lock = threading.Lock() -def dashify(s): - return s.replace('_', '-') +def dashify(value): + return value.replace('_', '-') def is_git_dir(git_dir): @@ -67,12 +67,12 @@ def is_git_dir(git_dir): return result -def is_git_file(f): - return core.isfile(f) and os.path.basename(f) == '.git' +def is_git_file(filename): + return core.isfile(filename) and os.path.basename(filename) == '.git' -def is_git_worktree(d): - return is_git_dir(join(d, '.git')) +def is_git_worktree(dirname): + return is_git_dir(join(dirname, '.git')) def is_git_repository(path): @@ -362,14 +362,14 @@ class Git(object): call.extend(args) try: result = self.execute(call, **_kwargs) - except OSError as e: - if WIN32 and e.errno == errno.ENOENT: + except OSError as exc: + if WIN32 and exc.errno == errno.ENOENT: # see if git exists at all. on win32 it can fail with ENOENT in # case of argv overflow. we should be safe from that but use # defensive coding for the worst-case scenario. On UNIX # we have ENAMETOOLONG but that doesn't exist on Windows. if _git_is_installed(): - raise e + raise exc _print_win32_git_hint() result = (1, '', "error: unable to execute '%s'" % GIT) return result @@ -407,20 +407,20 @@ def transform_kwargs(**kwargs): args = [] types_to_stringify = (ustr, float, str) + int_types - for k, v in kwargs.items(): + for k, value in kwargs.items(): if len(k) == 1: dashes = '-' - eq = '' + equals = '' else: dashes = '--' - eq = '=' + equals = '=' # isinstance(False, int) is True, so we have to check bool first - if isinstance(v, bool): - if v: + if isinstance(value, bool): + if value: args.append('%s%s' % (dashes, dashify(k))) # else: pass # False is ignored; flag=False inhibits --flag - elif isinstance(v, types_to_stringify): - args.append('%s%s%s%s' % (dashes, dashify(k), eq, v)) + elif isinstance(value, types_to_stringify): + args.append('%s%s%s%s' % (dashes, dashify(k), equals, value)) return args diff --git a/cola/gitcfg.py b/cola/gitcfg.py index 123fda7b..c648eae0 100644 --- a/cola/gitcfg.py +++ b/cola/gitcfg.py @@ -37,18 +37,18 @@ def _cache_key_from_paths(paths): return None -def _config_to_python(v): +def _config_to_python(value): """Convert a Git config string into a Python value""" - if v in ('true', 'yes'): - v = True - elif v in ('false', 'no'): - v = False + if value in ('true', 'yes'): + value = True + elif value in ('false', 'no'): + value = False else: try: - v = int(v) + value = int(value) except ValueError: pass - return v + return value def unhex(value): @@ -193,14 +193,14 @@ class GitConfig(QtCore.QObject): # Send a notification that the configuration has been updated. self.updated.emit() - def _get(self, src, key, default, fn=None, cached=True): + def _get(self, src, key, default, func=None, cached=True): if not cached or not src: self.update() try: value = self._get_value(src, key) except KeyError: - if fn: - value = fn() + if func: + value = func() else: value = default return value @@ -220,9 +220,9 @@ class GitConfig(QtCore.QObject): # Allow the final KeyError to bubble up return src[key.lower()] - def get(self, key, default=None, fn=None, cached=True): + def get(self, key, default=None, func=None, cached=True): """Return the string value for a config key.""" - return self._get(self._all, key, default, fn=fn, cached=cached) + return self._get(self._all, key, default, func=func, cached=cached) def get_all(self, key): """Return all values for a key sorted in priority order @@ -311,7 +311,7 @@ class GitConfig(QtCore.QObject): def is_per_file_attrs_enabled(self): return self.get( - 'cola.fileattributes', fn=lambda: os.path.exists('.gitattributes') + 'cola.fileattributes', func=lambda: os.path.exists('.gitattributes') ) def is_binary(self, path): @@ -423,11 +423,11 @@ class GitConfig(QtCore.QObject): struct_layout = core.encode('BBB') try: # pylint: disable=no-member - r, g, b = struct.unpack(struct_layout, unhex(value)) + red, green, blue = struct.unpack(struct_layout, unhex(value)) except (struct.error, TypeError): # pylint: disable=no-member - r, g, b = struct.unpack(struct_layout, unhex(default)) - return (r, g, b) + red, green, blue = struct.unpack(struct_layout, unhex(default)) + return (red, green, blue) def hooks(self): """Return the path to the git hooks directory""" diff --git a/cola/gitcmds.py b/cola/gitcmds.py index 686934d1..775fbecd 100644 --- a/cola/gitcmds.py +++ b/cola/gitcmds.py @@ -18,7 +18,7 @@ from .interaction import Interaction def add(context, items, u=False): """Run "git add" while preventing argument overflow""" git_add = context.git.add - return utils.slice_fn( + return utils.slice_func( items, lambda paths: git_add('--', force=True, verbose=True, u=u, *paths) ) @@ -584,8 +584,8 @@ def export_patchset(context, start, end, output='patches', **kwargs): def reset_paths(context, head, items): """Run "git reset" while preventing argument overflow""" items = list(set(items)) - fn = context.git.reset - status, out, err = utils.slice_fn(items, lambda paths: fn(head, '--', *paths)) + func = context.git.reset + status, out, err = utils.slice_func(items, lambda paths: func(head, '--', *paths)) return (status, out, err) diff --git a/cola/inotify.py b/cola/inotify.py index f2a9afd3..39e23040 100644 --- a/cola/inotify.py +++ b/cola/inotify.py @@ -69,19 +69,19 @@ rm_watch.errcheck = _errcheck def read_events(inotify_fd, count=64): buf = ctypes.create_string_buffer(MAX_EVENT_SIZE * count) - n = _read(inotify_fd, buf, ctypes.sizeof(buf)) + num = _read(inotify_fd, buf, ctypes.sizeof(buf)) addr = ctypes.addressof(buf) - while n: - assert n >= ctypes.sizeof(inotify_event) + while num: + assert num >= ctypes.sizeof(inotify_event) event = inotify_event.from_address(addr) addr += ctypes.sizeof(inotify_event) - n -= ctypes.sizeof(inotify_event) + num -= ctypes.sizeof(inotify_event) if event.len: - assert n >= event.len + assert num >= event.len name = ctypes.string_at(addr) addr += event.len - n -= event.len + num -= event.len else: name = None yield event.wd, event.mask, event.cookie, name diff --git a/cola/models/selection.py b/cola/models/selection.py index 5199bf88..b656378b 100644 --- a/cola/models/selection.py +++ b/cola/models/selection.py @@ -13,33 +13,37 @@ def create(): return SelectionModel() -def pick(s): +def pick(selection): """Choose the first list from stage, unmerged, modified, untracked""" - if s.staged: - files = s.staged - elif s.unmerged: - files = s.unmerged - elif s.modified: - files = s.modified - elif s.untracked: - files = s.untracked + if selection.staged: + files = selection.staged + elif selection.unmerged: + files = selection.unmerged + elif selection.modified: + files = selection.modified + elif selection.untracked: + files = selection.untracked else: files = [] return files -def union(s): +def union(selection): """Return the union of all selected items in a sorted list""" - return list(sorted(set(s.staged + s.unmerged + s.modified + s.untracked))) + values = set( + selection.staged + selection.unmerged + selection.modified + selection.untracked + ) + return list(sorted(values)) -def _filter(a, b): - b_set = set(b) - a_copy = list(a) - last = len(a_copy) - 1 - for idx, i in enumerate(reversed(a)): - if i not in b_set: - a.pop(last - idx) +def _filter(values, remove): + """Filter a list in-place by removing items""" + remove_set = set(remove) + values_copy = list(values) + last = len(values_copy) - 1 + for idx, value in enumerate(reversed(values)): + if value not in remove_set: + values.pop(last - idx) class SelectionModel(QtCore.QObject): @@ -91,22 +95,22 @@ class SelectionModel(QtCore.QObject): def single_selection(self): """Scan across staged, modified, etc. and return a single item.""" - st = None - m = None - um = None - ut = None + staged = None + modified = None + unmerged = None + untracked = None if self.staged: - st = self.staged[0] + staged = self.staged[0] elif self.modified: - m = self.modified[0] + modified = self.modified[0] elif self.unmerged: - um = self.unmerged[0] + unmerged = self.unmerged[0] elif self.untracked: - ut = self.untracked[0] - return State(st, um, m, ut) + untracked = self.untracked[0] + return State(staged, unmerged, modified, untracked) def filename(self): - paths = [p for p in self.single_selection() if p is not None] + paths = [path for path in self.single_selection() if path is not None] if paths: filename = paths[0] else: diff --git a/cola/qtutils.py b/cola/qtutils.py index bdf7a960..7969d3b6 100644 --- a/cola/qtutils.py +++ b/cola/qtutils.py @@ -34,33 +34,33 @@ def current_palette(): return QtWidgets.QApplication.instance().palette() -def connect_action(action, fn): +def connect_action(action, func): """Connect an action to a function""" - action.triggered[bool].connect(lambda x: fn(), type=Qt.QueuedConnection) + action.triggered[bool].connect(lambda x: func(), type=Qt.QueuedConnection) -def connect_action_bool(action, fn): +def connect_action_bool(action, func): """Connect a triggered(bool) action to a function""" - action.triggered[bool].connect(fn, type=Qt.QueuedConnection) + action.triggered[bool].connect(func, type=Qt.QueuedConnection) -def connect_button(button, fn): +def connect_button(button, func): """Connect a button to a function""" # Some versions of Qt send the `bool` argument to the clicked callback, # and some do not. The lambda consumes all callback-provided arguments. - button.clicked.connect(lambda *args, **kwargs: fn(), type=Qt.QueuedConnection) + button.clicked.connect(lambda *args, **kwargs: func(), type=Qt.QueuedConnection) -def connect_checkbox(widget, fn): +def connect_checkbox(widget, func): """Connect a checkbox to a function taking bool""" widget.clicked.connect( - lambda *args, **kwargs: fn(get(checkbox)), type=Qt.QueuedConnection + lambda *args, **kwargs: func(get(checkbox)), type=Qt.QueuedConnection ) -def connect_released(button, fn): +def connect_released(button, func): """Connect a button to a function""" - button.released.connect(fn, type=Qt.QueuedConnection) + button.released.connect(func, type=Qt.QueuedConnection) def button_action(button, action): @@ -68,9 +68,9 @@ def button_action(button, action): connect_button(button, action.trigger) -def connect_toggle(toggle, fn): +def connect_toggle(toggle, func): """Connect a toggle button to a function""" - toggle.toggled.connect(fn, type=Qt.QueuedConnection) + toggle.toggled.connect(func, type=Qt.QueuedConnection) def disconnect(signal): @@ -345,8 +345,8 @@ def prompt_n(msg, inputs): accepted = dialog.exec_() == QtWidgets.QDialog.Accepted text = get_values() - ok = accepted and all(text) - return (ok, text) + success = accepted and all(text) + return (success, text) def standard_item_type_value(value): @@ -393,7 +393,7 @@ def paths_from_indexes(model, indexes, item_type=TreeWidgetItem.TYPE, item_filte return paths_from_items(items, item_type=item_type, item_filter=item_filter) -def _true_filter(_x): +def _true_filter(_value): return True @@ -528,9 +528,9 @@ def persist_clipboard(): QtWidgets.QApplication.sendEvent(clipboard, event) -def add_action_bool(widget, text, fn, checked, *shortcuts): +def add_action_bool(widget, text, func, checked, *shortcuts): tip = text - action = _add_action(widget, text, tip, fn, connect_action_bool, *shortcuts) + action = _add_action(widget, text, tip, func, connect_action_bool, *shortcuts) action.setCheckable(True) action.setChecked(checked) return action @@ -561,13 +561,13 @@ def menu_separator(widget): return action -def _add_action(widget, text, tip, fn, connect, *shortcuts): +def _add_action(widget, text, tip, func, connect, *shortcuts): action = QtWidgets.QAction(text, widget) if hasattr(action, 'setIconVisibleInMenu'): action.setIconVisibleInMenu(True) if tip: action.setStatusTip(tip) - connect(action, fn) + connect(action, func) if shortcuts: action.setShortcuts(shortcuts) if hasattr(Qt, 'WidgetWithChildrenShortcut'): @@ -634,9 +634,9 @@ def desktop_size(): def center_on_screen(widget): """Move widget to the center of the default screen""" width, height = desktop_size() - cx = width // 2 - cy = height // 2 - widget.move(cx - widget.width() // 2, cy - widget.height() // 2) + center_x = width // 2 + center_y = height // 2 + widget.move(center_x - widget.width() // 2, center_y - widget.height() // 2) def default_size(parent, width, height, use_parent_height=True): @@ -848,7 +848,7 @@ class DockTitleBarWidget(QtWidgets.QFrame): self.toggle_button.setToolTip(tooltip) -def create_dock(name, title, parent, stretch=True, widget=None, fn=None): +def create_dock(name, title, parent, stretch=True, widget=None, func=None): """Create a dock widget and set it up accordingly.""" dock = QtWidgets.QDockWidget(parent) dock.setWindowTitle(title) @@ -858,9 +858,8 @@ def create_dock(name, title, parent, stretch=True, widget=None, fn=None): dock.setAutoFillBackground(True) if hasattr(parent, 'dockwidgets'): parent.dockwidgets.append(dock) - if fn: - widget = fn(dock) - assert isinstance(widget, QtWidgets.QFrame), "Docked widget has to be a QFrame" + if func: + widget = func(dock) if widget: dock.setWidget(widget) return dock @@ -1006,6 +1005,7 @@ class Channel(QtCore.QObject): class Task(QtCore.QRunnable): """Run a task in the background and return the result using a Channel""" + def __init__(self): QtCore.QRunnable.__init__(self) @@ -1031,15 +1031,15 @@ class Task(QtCore.QRunnable): class SimpleTask(Task): """Run a simple callable as a task""" - def __init__(self, fn, *args, **kwargs): + def __init__(self, func, *args, **kwargs): Task.__init__(self) - self.fn = fn + self.func = func self.args = args self.kwargs = kwargs def task(self): - return self.fn(*self.args, **self.kwargs) + return self.func(*self.args, **self.kwargs) class RunTask(QtCore.QObject): @@ -1050,11 +1050,11 @@ class RunTask(QtCore.QObject): self.tasks = [] self.task_details = {} self.threadpool = QtCore.QThreadPool.globalInstance() - self.result_fn = None + self.result_func = None def start(self, task, progress=None, finish=None, result=None): """Start the task and register a callback""" - self.result_fn = result + self.result_func = result if progress is not None: progress.show() if hasattr(progress, 'start'): @@ -1094,22 +1094,23 @@ class RunTask(QtCore.QObject): # Syntax highlighting -def rgb(r, g, b): + +def rgb(red, green, blue): """Create a QColor from r, g, b arguments""" color = QtGui.QColor() - color.setRgb(r, g, b) + color.setRgb(red, green, blue) return color -def rgba(r, g, b, a=255): +def rgba(red, green, blue, alpha=255): """Create a QColor with alpha from r, g, b, a arguments""" - color = rgb(r, g, b) - color.setAlpha(a) + color = rgb(red, green, blue) + color.setAlpha(alpha) return color -def RGB(args): - """Create a QColor from a list of [r, g, b] arguments""" +def rgb_triple(args): + """Create a QColor from an argument with an [r, g, b] triple""" return rgb(*args) @@ -1133,37 +1134,41 @@ def css_color(value): if value.startswith('#'): value = value[1:] try: - r = clamp_color(int(value[:2], base=16)) # ab + red = clamp_color(int(value[:2], base=16)) # ab except ValueError: - r = 255 + red = 255 try: - g = clamp_color(int(value[2:4], base=16)) # cd + green = clamp_color(int(value[2:4], base=16)) # cd except ValueError: - g = 255 + green = 255 try: - b = clamp_color(int(value[4:6], base=16)) # ef + blue = clamp_color(int(value[4:6], base=16)) # ef except ValueError: - b = 255 - return rgb(r, g, b) + blue = 255 + return rgb(red, green, blue) -def hsl(h, s, light): +def hsl(hue, saturation, lightness): + """Return a QColor from an hue, saturation and lightness""" return QtGui.QColor.fromHslF( - utils.clamp(h, 0.0, 1.0), utils.clamp(s, 0.0, 1.0), utils.clamp(light, 0.0, 1.0) + utils.clamp(hue, 0.0, 1.0), + utils.clamp(saturation, 0.0, 1.0), + utils.clamp(lightness, 0.0, 1.0), ) -def hsl_css(h, s, light): +def hsl_css(hue, saturation, lightness): """Convert HSL values to a CSS #abcdef color string""" - return rgb_css(hsl(h, s, light)) + return rgb_css(hsl(hue, saturation, lightness)) -def make_format(fg=None, bg=None, bold=False): +def make_format(foreground=None, background=None, bold=False): + """Create a QTextFormat from the provided foreground, background and bold values""" fmt = QtGui.QTextCharFormat() - if fg: - fmt.setForeground(fg) - if bg: - fmt.setBackground(bg) + if foreground: + fmt.setForeground(foreground) + if background: + fmt.setBackground(background) if bold: fmt.setFontWeight(QtGui.QFont.Bold) return fmt diff --git a/cola/sequenceeditor.py b/cola/sequenceeditor.py index a151a69b..d91400d2 100644 --- a/cola/sequenceeditor.py +++ b/cola/sequenceeditor.py @@ -292,8 +292,8 @@ class Editor(QtWidgets.QWidget): try: core.write(self.filename, string) status = 0 - except (OSError, IOError, ValueError) as e: - msg, details = utils.format_exception(e) + except (OSError, IOError, ValueError) as exc: + msg, details = utils.format_exception(exc) sys.stderr.write(msg + '\n\n' + details) status = 128 return status @@ -451,8 +451,8 @@ class RebaseTreeWidget(standard.DraggableTreeWidget): params = dag.DAG(oid, 2) repo = dag.RepoReader(context, params) commits = [] - for c in repo.get(): - commits.append(c) + for commit in repo.get(): + commits.append(commit) if commits: commits = commits[-1:] self.commits_selected.emit(commits) diff --git a/cola/settings.py b/cola/settings.py index 38d3f4e5..34b8deba 100644 --- a/cola/settings.py +++ b/cola/settings.py @@ -32,8 +32,8 @@ def mklist(obj): def read_json(path): try: - with core.open_read(path) as fp: - return mkdict(json.load(fp)) + with core.open_read(path) as f: + return mkdict(json.load(f)) except (ValueError, TypeError, OSError, IOError): # bad path or json return {} diff --git a/cola/spellcheck.py b/cola/spellcheck.py index 2c4571ab..3e15d174 100644 --- a/cola/spellcheck.py +++ b/cola/spellcheck.py @@ -10,7 +10,7 @@ __copyright__ = """ 2013-2018 David Aguilar """ -alphabet = 'abcdefghijklmnopqrstuvwxyz' +ALPHABET = 'abcdefghijklmnopqrstuvwxyz' def train(features, model): @@ -23,8 +23,8 @@ def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b) > 1] - replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] - inserts = [a + c + b for a, b in splits for c in alphabet] + replaces = [a + c + b[1:] for a, b in splits for c in ALPHABET if b] + inserts = [a + c + b for a, b in splits for c in ALPHABET] return set(deletes + transposes + replaces + inserts) diff --git a/cola/textwrap.py b/cola/textwrap.py index 1d547815..c06a5eeb 100644 --- a/cola/textwrap.py +++ b/cola/textwrap.py @@ -250,7 +250,7 @@ def word_wrap(text, tabwidth, limit, break_on_hyphens=False): r')' ) - w = TextWrapper( + wrapper = TextWrapper( width=limit, tabwidth=tabwidth, break_on_hyphens=break_on_hyphens, @@ -261,7 +261,7 @@ def word_wrap(text, tabwidth, limit, break_on_hyphens=False): if special_tag_rgx.match(line): lines.append(line) else: - lines.append(w.fill(line)) + lines.append(wrapper.fill(line)) return '\n'.join(lines) diff --git a/cola/themes.py b/cola/themes.py index e4e809c6..6e8c2319 100644 --- a/cola/themes.py +++ b/cola/themes.py @@ -679,7 +679,7 @@ def get_all_themes(): N_('Flat dark red'), True, style_sheet=EStylesheet.FLAT, - main_color='#cc5452' + main_color='#cc5452', ), Theme( 'flat-dark-grey', diff --git a/cola/utils.py b/cola/utils.py index 0ea6b31a..6b2efb84 100644 --- a/cola/utils.py +++ b/cola/utils.py @@ -25,9 +25,9 @@ def asint(obj, default=0): return value -def clamp(value, lo, hi): +def clamp(value, low, high): """Clamp a value to the specified range""" - return min(hi, max(lo, value)) + return min(high, max(low, value)) def epoch_millis(): @@ -49,25 +49,26 @@ def add_parents(paths): return all_paths -def format_exception(e): +def format_exception(exc): + """Format an exception object for display""" exc_type, exc_value, exc_tb = sys.exc_info() details = traceback.format_exception(exc_type, exc_value, exc_tb) details = '\n'.join(map(core.decode, details)) - if hasattr(e, 'msg'): - msg = e.msg + if hasattr(exc, 'msg'): + msg = exc.msg else: - msg = core.decode(repr(e)) + msg = core.decode(repr(exc)) return (msg, details) -def sublist(a, b): +def sublist(values, remove): """Subtracts list b from list a and returns the resulting list.""" # conceptually, c = a - b - c = [] - for item in a: - if item not in b: - c.append(item) - return c + result = [] + for item in values: + if item not in remove: + result.append(item) + return result __grep_cache = {} @@ -238,11 +239,11 @@ def strip_prefix(prefix, string): return string[len(prefix) :] -def sanitize(s): +def sanitize(value): """Removes shell metacharacters from a string.""" - for c in """ \t!@#$%^&*()\\;,<>"'[]{}~|""": - s = s.replace(c, '_') - return s + for char in """ \t!@#$%^&*()\\;,<>"'[]{}~|""": + value = value.replace(char, '_') + return value def tablength(word, tabwidth): @@ -255,41 +256,43 @@ def tablength(word, tabwidth): return len(word.replace('\t', '')) + word.count('\t') * tabwidth -def _shell_split_py2(s): +def _shell_split_py2(value): """Python2 requires bytes inputs to shlex.split(). Returns [unicode]""" try: - result = shlex.split(core.encode(s)) + result = shlex.split(core.encode(value)) except ValueError: - result = core.encode(s).strip().split() + result = core.encode(value).strip().split() # Decode to unicode strings return [core.decode(arg) for arg in result] -def _shell_split_py3(s): +def _shell_split_py3(value): """Python3 requires unicode inputs to shlex.split(). Converts to unicode""" try: - result = shlex.split(s) + result = shlex.split(value) except ValueError: - result = core.decode(s).strip().split() + result = core.decode(value).strip().split() # Already unicode return result -def shell_split(s): +def shell_split(value): if compat.PY2: # Encode before calling split() - values = _shell_split_py2(s) + values = _shell_split_py2(value) else: # Python3 does not need the encode/decode dance - values = _shell_split_py3(s) + values = _shell_split_py3(value) return values def tmp_filename(label, suffix=''): label = 'git-cola-' + label.replace('/', '-').replace('\\', '-') - fd = tempfile.NamedTemporaryFile(prefix=label + '-', suffix=suffix, delete=False) - fd.close() - return fd.name + handle = tempfile.NamedTemporaryFile( + prefix=label + '-', suffix=suffix, delete=False + ) + handle.close() + return handle.name def is_linux(): @@ -366,8 +369,8 @@ class Proxy(object): return getattr(self._obj, name) -def slice_fn(input_items, map_fn): - """Slice input_items and call map_fn over every slice +def slice_func(input_items, map_func): + """Slice input_items and call `map_func` over every slice This exists because of "errno: Argument list too long" @@ -405,7 +408,7 @@ def slice_fn(input_items, map_fn): items = copy.copy(input_items) while items: - stat, out, err = map_fn(items[:size]) + stat, out, err = map_func(items[:size]) if stat < 0: status = min(stat, status) else: @@ -417,19 +420,19 @@ def slice_fn(input_items, map_fn): return (status, '\n'.join(outs), '\n'.join(errs)) -class seq(object): +class Sequence(object): def __init__(self, sequence): - self.seq = sequence + self.sequence = sequence def index(self, item, default=-1): try: - idx = self.seq.index(item) + idx = self.sequence.index(item) except ValueError: idx = default return idx def __getitem__(self, idx): - return self.seq[idx] + return self.sequence[idx] def catch_runtime_error(func, *args, **kwargs): diff --git a/cola/version.py b/cola/version.py index de58577f..d518bf8b 100644 --- a/cola/version.py +++ b/cola/version.py @@ -95,12 +95,12 @@ def check_git(context, key): def version_to_list(value): """Convert a version string to a list of numbers or strings""" ver_list = [] - for p in value.split('.'): + for part in value.split('.'): try: - n = int(p) + number = int(part) except ValueError: - n = p - ver_list.append(n) + number = part + ver_list.append(number) return ver_list diff --git a/cola/widgets/bookmarks.py b/cola/widgets/bookmarks.py index 3d2b5fdf..5990c460 100644 --- a/cola/widgets/bookmarks.py +++ b/cola/widgets/bookmarks.py @@ -379,22 +379,22 @@ class BookmarksTreeView(standard.TreeView): item.setText(item.name) self.toggle_switcher.emit(False) - def apply_fn(self, fn, *args, **kwargs): + def apply_func(self, func, *args, **kwargs): item = self.selected_item() if item: - fn(item, *args, **kwargs) + func(item, *args, **kwargs) def copy(self): - self.apply_fn(lambda item: qtutils.set_clipboard(item.path)) + self.apply_func(lambda item: qtutils.set_clipboard(item.path)) self.toggle_switcher.emit(False) def open_default(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.OpenDefaultApp, context, [item.path])) + self.apply_func(lambda item: cmds.do(cmds.OpenDefaultApp, context, [item.path])) self.toggle_switcher.emit(False) def set_default_repo(self): - self.apply_fn(self.set_default_item) + self.apply_func(self.set_default_item) self.toggle_switcher.emit(False) def set_default_item(self, item): @@ -405,7 +405,7 @@ class BookmarksTreeView(standard.TreeView): self.toggle_switcher.emit(False) def clear_default_repo(self): - self.apply_fn(self.clear_default_item) + self.apply_func(self.clear_default_item) self.default_changed.emit() self.toggle_switcher.emit(False) @@ -421,7 +421,7 @@ class BookmarksTreeView(standard.TreeView): self.toggle_switcher.emit(False) def accept_repo(self): - self.apply_fn(self.accept_item) + self.apply_func(self.accept_item) self.toggle_switcher.emit(False) def accept_item(self, _item): @@ -437,7 +437,7 @@ class BookmarksTreeView(standard.TreeView): def open_repo(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.OpenRepo, context, item.path)) + self.apply_func(lambda item: cmds.do(cmds.OpenRepo, context, item.path)) def open_selected_repo(self): item = self.selected_item() @@ -447,17 +447,17 @@ class BookmarksTreeView(standard.TreeView): def open_new_repo(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.OpenNewRepo, context, item.path)) + self.apply_func(lambda item: cmds.do(cmds.OpenNewRepo, context, item.path)) self.toggle_switcher.emit(False) def launch_editor(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.Edit, context, [item.path])) + self.apply_func(lambda item: cmds.do(cmds.Edit, context, [item.path])) self.toggle_switcher.emit(False) def launch_terminal(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.LaunchTerminal, context, item.path)) + self.apply_func(lambda item: cmds.do(cmds.LaunchTerminal, context, item.path)) self.toggle_switcher.emit(False) def add_bookmark(self): diff --git a/cola/widgets/branch.py b/cola/widgets/branch.py index f56960b6..343832ea 100644 --- a/cola/widgets/branch.py +++ b/cola/widgets/branch.py @@ -21,16 +21,17 @@ from .. import qtutils from .text import LineEdit -def defer_fn(parent, title, fn, *args, **kwargs): - return qtutils.add_action(parent, title, partial(fn, *args, **kwargs)) +def defer_func(parent, title, func, *args, **kwargs): + """Return a QAction bound against a partial func with arguments""" + return qtutils.add_action(parent, title, partial(func, *args, **kwargs)) -def add_branch_to_menu(menu, branch, remote_branch, remote, upstream, fn): +def add_branch_to_menu(menu, branch, remote_branch, remote, upstream, func): """Add a remote branch to the context menu""" branch_remote, _ = gitcmds.parse_remote_branch(remote_branch) if branch_remote != remote: menu.addSeparator() - action = defer_fn(menu, remote_branch, fn, branch, remote_branch) + action = defer_func(menu, remote_branch, func, branch, remote_branch) if remote_branch == upstream: action.setIcon(icons.star()) menu.addAction(action) diff --git a/cola/widgets/browse.py b/cola/widgets/browse.py index f62fa1a5..34d6f8dc 100644 --- a/cola/widgets/browse.py +++ b/cola/widgets/browse.py @@ -54,6 +54,7 @@ def save_path(context, path, model): class Browser(standard.Widget): """A repository branch file browser. Browses files provided by GitRepoModel""" + # Read-only mode property mode = property(lambda self: self.model.mode) diff --git a/cola/widgets/cfgactions.py b/cola/widgets/cfgactions.py index 56f32d44..1a0439c6 100644 --- a/cola/widgets/cfgactions.py +++ b/cola/widgets/cfgactions.py @@ -123,8 +123,8 @@ class GitCommandWidget(standard.Dialog): text = self.read_stream(self.proc.readAllStandardError) self.err += text - def read_stream(self, fn): - data = fn().data() + def read_stream(self, func): + data = func().data() text = core.decode(data) self.append_text(text) return text diff --git a/cola/widgets/clone.py b/cola/widgets/clone.py index c62125f0..460c70b2 100644 --- a/cola/widgets/clone.py +++ b/cola/widgets/clone.py @@ -28,9 +28,9 @@ def clone(context, spawn=True, show=True): def clone_repo(context, show, progress, finish, spawn): """Clone a repository asynchronously with progress animation""" - fn = partial(start_clone_task, context, progress, finish, spawn) + func = partial(start_clone_task, context, progress, finish, spawn) prompt = prompt_for_clone(context, show=show) - prompt.result.connect(fn) + prompt.result.connect(func) return prompt diff --git a/cola/widgets/commitmsg.py b/cola/widgets/commitmsg.py index 3d268349..03e1f9ea 100644 --- a/cola/widgets/commitmsg.py +++ b/cola/widgets/commitmsg.py @@ -492,14 +492,14 @@ class CommitMessageEditor(QtWidgets.QFrame): commits = dag.RepoReader(context, params) menu_commits = [] - for idx, c in enumerate(commits.get()): - menu_commits.insert(0, c) + for idx, commit in enumerate(commits.get()): + menu_commits.insert(0, commit) if idx > 5: continue menu.clear() - for c in menu_commits: - menu.addAction(prefix + c.summary, cmds.run(cmd, context, c.oid)) + for commit in menu_commits: + menu.addAction(prefix + commit.summary, cmds.run(cmd, context, commit.oid)) if len(commits) == 6: menu.addSeparator() @@ -662,5 +662,5 @@ class CommitMessageTextEdit(SpellCheckTextEdit): def setFont(self, font): SpellCheckTextEdit.setFont(self, font) - fm = self.fontMetrics() - self.setMinimumSize(QtCore.QSize(fm.width('MMMM'), fm.height() * 2)) + metrics = self.fontMetrics() + self.setMinimumSize(QtCore.QSize(metrics.width('MMMM'), metrics.height() * 2)) diff --git a/cola/widgets/common.py b/cola/widgets/common.py index eff2db67..1a083387 100644 --- a/cola/widgets/common.py +++ b/cola/widgets/common.py @@ -9,23 +9,23 @@ from .. import qtutils from .. import utils -def cmd_action(parent, cmd, context, fn, *keys): +def cmd_action(parent, cmd, context, func, *keys): """Wrap a standard Command object in a QAction - This function assumes that :func:`fn()` takes no arguments, + This function assumes that :func:`func()` takes no arguments, that `cmd` has a :func:`name()` method, and that the `cmd` - constructor takes a single argument, as returned by `fn`. + constructor takes a single argument, as returned by `func`. """ return qtutils.add_action( - parent, cmd.name(), lambda: cmds.do(cmd, context, fn()), *keys + parent, cmd.name(), lambda: cmds.do(cmd, context, func()), *keys ) -def default_app_action(context, parent, fn): +def default_app_action(context, parent, func): """Open paths with the OS-default app -> QAction""" action = cmd_action( - parent, cmds.OpenDefaultApp, context, fn, hotkeys.PRIMARY_ACTION + parent, cmds.OpenDefaultApp, context, func, hotkeys.PRIMARY_ACTION ) action.setIcon(icons.default_app()) return action diff --git a/cola/widgets/completion.py b/cola/widgets/completion.py index 916c6c1f..9c075fd9 100644 --- a/cola/widgets/completion.py +++ b/cola/widgets/completion.py @@ -473,12 +473,12 @@ class CompletionModel(QtGui.QStandardItemModel): self.update_thread.dispose() -def _identity(x): - return x +def _identity(value): + return value -def _lower(x): - return x.lower() +def _lower(value): + return value.lower() def filter_matches(match_text, candidates, case_sensitive, sort_key=None): @@ -808,9 +808,9 @@ class GitDialog(QtWidgets.QDialog): dlg.show() def show_popup(): - x = dlg.lineedit.x() - y = dlg.lineedit.y() + dlg.lineedit.height() - point = QtCore.QPoint(x, y) + x_val = dlg.lineedit.x() + y_val = dlg.lineedit.y() + dlg.lineedit.height() + point = QtCore.QPoint(x_val, y_val) mapped = dlg.mapToGlobal(point) dlg.lineedit.popup().move(mapped.x(), mapped.y()) dlg.lineedit.popup().show() diff --git a/cola/widgets/dag.py b/cola/widgets/dag.py index 268a500d..0210a244 100644 --- a/cola/widgets/dag.py +++ b/cola/widgets/dag.py @@ -72,11 +72,11 @@ class FocusRedirectProxy(object): """Forward the captured action to the focused or default widget""" widget = QtWidgets.QApplication.focusWidget() if widget in self.widgets and hasattr(widget, name): - fn = getattr(widget, name) + func = getattr(widget, name) else: - fn = getattr(self.default, name) + func = getattr(self.default, name) - return fn(*args, **kwargs) + return func(*args, **kwargs) class ViewerMixin(object): @@ -114,20 +114,20 @@ class ViewerMixin(object): return self.clicked.oid return self.selected_oid() - def with_oid(self, fn): + def with_oid(self, func): """Run an operation with a commit object ID""" oid = self.clicked_oid() if oid: - result = fn(oid) + result = func(oid) else: result = None return result - def with_selected_oid(self, fn): + def with_selected_oid(self, func): """Run an operation with a commit object ID""" oid = self.selected_oid() if oid: - result = fn(oid) + result = func(oid) else: result = None return result @@ -1015,12 +1015,12 @@ class GitDAG(standard.MainWindow): self.graphview.set_initial_view() - def diff_commits(self, a, b): + def diff_commits(self, left, right): paths = self.params.paths() if paths: - cmds.difftool_launch(self.context, left=a, right=b, paths=paths) + cmds.difftool_launch(self.context, left=left, right=right, paths=paths) else: - difftool.diff_commits(self.context, self, a, b) + difftool.diff_commits(self.context, self, left, right) # Qt overrides def closeEvent(self, event): @@ -1071,7 +1071,7 @@ class ReaderThread(QtCore.QThread): repo.reset() self.begin.emit() commits = [] - for c in repo.get(): + for commit in repo.get(): self._mutex.lock() if self._stop: self._condition.wait(self._mutex) @@ -1079,7 +1079,7 @@ class ReaderThread(QtCore.QThread): if self._abort: repo.reset() return - commits.append(c) + commits.append(commit) if len(commits) >= 512: self.add.emit(commits) commits = [] @@ -1655,13 +1655,13 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): item_rect = item.sceneTransform().mapRect(item.boundingRect()) self.ensureVisible(item_rect) - def _get_item_by_generation(self, commits, criteria_fn): + def _get_item_by_generation(self, commits, criteria_func): """Return the item for the commit matching criteria""" if not commits: return None generation = None for commit in commits: - if generation is None or criteria_fn(generation, commit.generation): + if generation is None or criteria_func(generation, commit.generation): oid = commit.oid generation = commit.generation try: @@ -1769,12 +1769,12 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): for item in items: pos = item.pos() - x = pos.x() - y = pos.y() - x_min = min(x_min, x) - x_max = max(x_max, x) - y_min = min(y_min, y) - y_max = max(y_max, y) + x_val = pos.x() + y_val = pos.y() + x_min = min(x_min, x_val) + x_max = max(x_max, x_val) + y_min = min(y_min, y_val) + y_max = max(y_max, y_val) rect = QtCore.QRectF(x_min, y_min, abs(x_max - x_min), abs(y_max - y_min)) @@ -1802,27 +1802,27 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): def pan(self, event): pos = event.pos() - dx = pos.x() - self.mouse_start[0] - dy = pos.y() - self.mouse_start[1] + x_offset = pos.x() - self.mouse_start[0] + y_offset = pos.y() - self.mouse_start[1] - if dx == 0 and dy == 0: + if x_offset == 0 and y_offset == 0: return - rect = QtCore.QRect(0, 0, abs(dx), abs(dy)) + rect = QtCore.QRect(0, 0, abs(x_offset), abs(y_offset)) delta = self.mapToScene(rect).boundingRect() - tx = delta.width() - if dx < 0.0: - tx = -tx + x_translate = delta.width() + if x_offset < 0.0: + x_translate = -x_translate - ty = delta.height() - if dy < 0.0: - ty = -ty + y_translate = delta.height() + if y_offset < 0.0: + y_translate = -y_translate matrix = self.transform() matrix.reset() matrix *= self.saved_matrix - matrix.translate(tx, ty) + matrix.translate(x_translate, y_translate) self.setTransformationAnchor(QtWidgets.QGraphicsView.NoAnchor) self.setTransform(matrix) @@ -1933,12 +1933,12 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): # edges to prevent double edge invalidation. invalid_edges = set() - for oid, (x, y) in positions.items(): + for oid, (x_val, y_val) in positions.items(): item = self.items[oid] pos = item.pos() - if pos != (x, y): - item.setPos(x, y) + if pos != (x_val, y_val): + item.setPos(x_val, y_val) for edge in item.edges.values(): invalid_edges.add(edge) @@ -2049,12 +2049,12 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): # frontier values for fork children will be overridden in course of # propagate_frontier. for offset in itertools.count(1): - for c in [column + offset, column - offset]: - if c not in self.columns: - # Column 'c' is not occupied. + for value in (column + offset, column - offset): + if value not in self.columns: + # Column is not occupied. continue try: - frontier = self.frontier[c] + frontier = self.frontier[value] except KeyError: # Column 'c' was never allocated. continue @@ -2116,8 +2116,8 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): can_overlap = list(range(column + 1, self.max_column + 1)) else: can_overlap = list(range(column - 1, self.min_column - 1, -1)) - for c in can_overlap: - frontier = self.frontier[c] + for value in can_overlap: + frontier = self.frontier[value] if frontier > cell_row: cell_row = frontier @@ -2127,8 +2127,8 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): else: can_overlap = list(range(self.max_column, column, -1)) for cell_row in itertools.count(cell_row): - for c in can_overlap: - if (c, cell_row) in self.tagged_cells: + for value in can_overlap: + if (value, cell_row) in self.tagged_cells: # Overlapping. Try next row. break else: @@ -2220,11 +2220,11 @@ class GraphView(QtWidgets.QGraphicsView, ViewerMixin): positions = {} for node in self.commits: - x_pos = x_start + node.column * x_off - y_pos = y_off + node.row * y_off + x_val = x_start + node.column * x_off + y_val = y_off + node.row * y_off - positions[node.oid] = (x_pos, y_pos) - x_min = min(x_min, x_pos) + positions[node.oid] = (x_val, y_val) + x_min = min(x_min, x_val) self.x_min = x_min diff --git a/cola/widgets/diff.py b/cola/widgets/diff.py index 4ea57b11..30326e58 100644 --- a/cola/widgets/diff.py +++ b/cola/widgets/diff.py @@ -63,21 +63,27 @@ class DiffSyntaxHighlighter(QtGui.QSyntaxHighlighter): dark = palette.color(QPalette.Base).lightnessF() < 0.5 - self.color_text = qtutils.RGB(cfg.color('text', '030303')) - self.color_add = qtutils.RGB(cfg.color('add', '77aa77' if dark else 'd2ffe4')) - self.color_remove = qtutils.RGB( + self.color_text = qtutils.rgb_triple(cfg.color('text', '030303')) + self.color_add = qtutils.rgb_triple( + cfg.color('add', '77aa77' if dark else 'd2ffe4') + ) + self.color_remove = qtutils.rgb_triple( cfg.color('remove', 'aa7777' if dark else 'fee0e4') ) - self.color_header = qtutils.RGB(cfg.color('header', header)) + self.color_header = qtutils.rgb_triple(cfg.color('header', header)) - self.diff_header_fmt = qtutils.make_format(fg=self.color_header) - self.bold_diff_header_fmt = qtutils.make_format(fg=self.color_header, bold=True) + self.diff_header_fmt = qtutils.make_format(foreground=self.color_header) + self.bold_diff_header_fmt = qtutils.make_format( + foreground=self.color_header, bold=True + ) - self.diff_add_fmt = qtutils.make_format(fg=self.color_text, bg=self.color_add) + self.diff_add_fmt = qtutils.make_format( + foreground=self.color_text, background=self.color_add + ) self.diff_remove_fmt = qtutils.make_format( - fg=self.color_text, bg=self.color_remove + foreground=self.color_text, background=self.color_remove ) - self.bad_whitespace_fmt = qtutils.make_format(bg=Qt.red) + self.bad_whitespace_fmt = qtutils.make_format(background=Qt.red) self.setCurrentBlockState(self.INITIAL_STATE) def set_enabled(self, enabled): @@ -460,6 +466,7 @@ class DiffLineNumbers(TextDecorator): class Viewer(QtWidgets.QFrame): """Text and image diff viewers""" + INDEX_TEXT = 0 INDEX_IMAGE = 1 diff --git a/cola/widgets/editremotes.py b/cola/widgets/editremotes.py index ce801eed..0743d5b7 100644 --- a/cola/widgets/editremotes.py +++ b/cola/widgets/editremotes.py @@ -196,7 +196,7 @@ class RemoteEditor(standard.Dialog): self.current_name = name self.refresh(select=False) - remotes = utils.seq(self.remote_list) + remotes = utils.Sequence(self.remote_list) idx = remotes.index(name) self.select_remote(idx) gather = False # already done by select_remote() @@ -253,7 +253,7 @@ class RemoteEditor(standard.Dialog): self.select_remote(0) elif self.current_name and remotes: # Reselect the previously selected item - remote_seq = utils.seq(remotes) + remote_seq = utils.Sequence(remotes) idx = remote_seq.index(self.current_name) if idx >= 0: item = self.remotes.item(idx) diff --git a/cola/widgets/filelist.py b/cola/widgets/filelist.py index eea8b6ef..3cef1d85 100644 --- a/cola/widgets/filelist.py +++ b/cola/widgets/filelist.py @@ -83,8 +83,8 @@ class FileWidget(TreeWidget): if not files_log: return files = [] - for f in files_log: - item = FileTreeWidgetItem(f) + for filename in files_log: + item = FileTreeWidgetItem(filename) files.append(item) self.insertTopLevelItems(0, files) @@ -103,8 +103,8 @@ class FileWidget(TreeWidget): def show(self): self.adjust_columns(QSize(), QSize()) - def resizeEvent(self, e): - self.adjust_columns(e.size(), e.oldSize()) + def resizeEvent(self, event): + self.adjust_columns(event.size(), event.oldSize()) def contextMenuEvent(self, event): menu = qtutils.create_menu(N_('Actions'), self) diff --git a/cola/widgets/main.py b/cola/widgets/main.py index 142e3bdd..42f1d98d 100644 --- a/cola/widgets/main.py +++ b/cola/widgets/main.py @@ -101,7 +101,7 @@ class MainView(standard.MainWindow): 'Status', N_('Status'), self, - fn=lambda dock: status.StatusWidget(context, dock.titleBarWidget(), dock), + func=lambda dock: status.StatusWidget(context, dock.titleBarWidget(), dock), ) self.statuswidget = self.statusdock.widget() @@ -110,7 +110,7 @@ class MainView(standard.MainWindow): 'Favorites', N_('Favorites'), self, - fn=lambda dock: bookmarks.bookmark(context, dock), + func=lambda dock: bookmarks.bookmark(context, dock), ) bookmarkswidget = self.bookmarksdock.widget() qtutils.hide_dock(self.bookmarksdock) @@ -119,7 +119,7 @@ class MainView(standard.MainWindow): 'Recent', N_('Recent'), self, - fn=lambda dock: bookmarks.recent(context, dock), + func=lambda dock: bookmarks.recent(context, dock), ) recentwidget = self.recentdock.widget() qtutils.hide_dock(self.recentdock) @@ -127,7 +127,10 @@ class MainView(standard.MainWindow): # "Branch" widgets self.branchdock = create_dock( - 'Branches', N_('Branches'), self, fn=partial(branch.BranchesWidget, context) + 'Branches', + N_('Branches'), + self, + func=partial(branch.BranchesWidget, context), ) self.branchwidget = self.branchdock.widget() titlebar = self.branchdock.titleBarWidget() @@ -139,7 +142,7 @@ class MainView(standard.MainWindow): 'Submodules', N_('Submodules'), self, - fn=partial(submodules.SubmodulesWidget, context), + func=partial(submodules.SubmodulesWidget, context), ) self.submoduleswidget = self.submodulesdock.widget() @@ -151,8 +154,8 @@ class MainView(standard.MainWindow): self.position_label.setFont(font) # make the position label fixed size to avoid layout issues - fm = self.position_label.fontMetrics() - width = fm.width('99:999') + defs.spacing + metrics = self.position_label.fontMetrics() + width = metrics.width('99:999') + defs.spacing self.position_label.setMinimumWidth(width) editor = commitmsg.CommitMessageEditor(context, self) @@ -170,7 +173,10 @@ class MainView(standard.MainWindow): # "Diff Viewer" widget self.diffdock = create_dock( - 'Diff', N_('Diff'), self, fn=lambda dock: diff.Viewer(context, parent=dock) + 'Diff', + N_('Diff'), + self, + func=lambda dock: diff.Viewer(context, parent=dock), ) self.diffviewer = self.diffdock.widget() self.diffviewer.set_diff_type(self.model.diff_type) @@ -280,11 +286,11 @@ class MainView(standard.MainWindow): ) self.new_bare_repository_action.setIcon(icons.new()) - prefs_fn = partial( + prefs_func = partial( prefs_widget.preferences, context, parent=self, model=prefs_model ) self.preferences_action = add_action( - self, N_('Preferences'), prefs_fn, QtGui.QKeySequence.Preferences + self, N_('Preferences'), prefs_func, QtGui.QKeySequence.Preferences ) self.preferences_action.setIcon(icons.configure()) @@ -1356,9 +1362,9 @@ class FocusProxy(object): def callback(): focus = self.focus(name) - fn = getattr(focus, name, None) - if fn: - fn() + func = getattr(focus, name, None) + if func: + func() return callback diff --git a/cola/widgets/startup.py b/cola/widgets/startup.py index bae6e476..1616f74a 100644 --- a/cola/widgets/startup.py +++ b/cola/widgets/startup.py @@ -468,20 +468,20 @@ class BookmarksListView(QtWidgets.QListView): else: item.setText(item.name) - def apply_fn(self, fn, *args, **kwargs): + def apply_func(self, func, *args, **kwargs): item = self.selected_item() if item: - fn(item, *args, **kwargs) + func(item, *args, **kwargs) def copy(self): - self.apply_fn(lambda item: qtutils.set_clipboard(item.path)) + self.apply_func(lambda item: qtutils.set_clipboard(item.path)) def open_default(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.OpenDefaultApp, context, [item.path])) + self.apply_func(lambda item: cmds.do(cmds.OpenDefaultApp, context, [item.path])) def set_default_repo(self): - self.apply_fn(self.set_default_item) + self.apply_func(self.set_default_item) def set_default_item(self, item): context = self.context @@ -489,7 +489,7 @@ class BookmarksListView(QtWidgets.QListView): self.refresh() def clear_default_repo(self): - self.apply_fn(self.clear_default_item) + self.apply_func(self.clear_default_item) def clear_default_item(self, _item): context = self.context @@ -501,7 +501,7 @@ class BookmarksListView(QtWidgets.QListView): self.edit(index) def accept_repo(self): - self.apply_fn(self.accept_item) + self.apply_func(self.accept_item) def accept_item(self, _item): if self.state() & self.EditingState: @@ -516,15 +516,15 @@ class BookmarksListView(QtWidgets.QListView): def open_new_repo(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.OpenNewRepo, context, item.path)) + self.apply_func(lambda item: cmds.do(cmds.OpenNewRepo, context, item.path)) def launch_editor(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.Edit, context, [item.path])) + self.apply_func(lambda item: cmds.do(cmds.Edit, context, [item.path])) def launch_terminal(self): context = self.context - self.apply_fn(lambda item: cmds.do(cmds.LaunchTerminal, context, item.path)) + self.apply_func(lambda item: cmds.do(cmds.LaunchTerminal, context, item.path)) def delete_item(self): """Remove the selected repo item diff --git a/cola/widgets/status.py b/cola/widgets/status.py index bc95b028..eac03aa4 100644 --- a/cola/widgets/status.py +++ b/cola/widgets/status.py @@ -238,16 +238,12 @@ class StatusTreeWidget(QtWidgets.QTreeWidget): # Checkout the selected paths using "git checkout --ours". self.checkout_ours_action = qtutils.add_action( - self, - cmds.CheckoutOurs.name(), - cmds.run(cmds.CheckoutOurs, context) + self, cmds.CheckoutOurs.name(), cmds.run(cmds.CheckoutOurs, context) ) # Checkout the selected paths using "git checkout --theirs". self.checkout_theirs_action = qtutils.add_action( - self, - cmds.CheckoutTheirs.name(), - cmds.run(cmds.CheckoutTheirs, context) + self, cmds.CheckoutTheirs.name(), cmds.run(cmds.CheckoutTheirs, context) ) self.copy_path_action = qtutils.add_action( @@ -1329,6 +1325,7 @@ def show_help(context): class StatusFilterWidget(QtWidgets.QWidget): """Filter paths displayed by the Status tool""" + def __init__(self, context, parent=None): QtWidgets.QWidget.__init__(self, parent) self.context = context diff --git a/cola/widgets/text.py b/cola/widgets/text.py index 089b27f4..95041765 100644 --- a/cola/widgets/text.py +++ b/cola/widgets/text.py @@ -177,8 +177,8 @@ class BaseTextEditExtension(QtCore.QObject): def set_tabwidth(self, width): self._tabwidth = width font = self.widget.font() - fm = QtGui.QFontMetrics(font) - pixels = fm.width('M' * width) + metrics = QtGui.QFontMetrics(font) + pixels = metrics.width('M' * width) self.widget.setTabStopWidth(pixels) def selected_line(self): @@ -378,6 +378,7 @@ class PlainTextEdit(QtWidgets.QPlainTextEdit): class TextSearchWidget(QtWidgets.QWidget): """The search dialog that displays over a text edit field""" + search_text = Signal(object, bool) def __init__(self, parent): diff --git a/test/git_test.py b/test/git_test.py index ce57292f..b611b67c 100644 --- a/test/git_test.py +++ b/test/git_test.py @@ -217,17 +217,17 @@ def test_find_git_directory_uses_GIT_WORK_TREE(is_git_dir, getenv): git_dir = '/repo/worktree/.git' worktree = '/repo/worktree' - def is_git_dir_fn(path): + def is_git_dir_func(path): return path == git_dir - is_git_dir.side_effect = is_git_dir_fn + is_git_dir.side_effect = is_git_dir_func - def getenv_fn(name): + def getenv_func(name): if name == 'GIT_WORK_TREE': return worktree return None - getenv.side_effect = getenv_fn + getenv.side_effect = getenv_func paths = git.find_git_directory(worktree) assert is_git_dir.called @@ -242,17 +242,17 @@ def test_uses_cwd_for_worktree_with_GIT_DIR(is_git_dir, getenv): git_dir = '/repo/.yadm/repo.git' worktree = '/repo' - def getenv_fn(name): + def getenv_func(name): if name == 'GIT_DIR': return git_dir return None - getenv.side_effect = getenv_fn + getenv.side_effect = getenv_func - def is_git_dir_fn(path): + def is_git_dir_func(path): return path == git_dir - is_git_dir.side_effect = is_git_dir_fn + is_git_dir.side_effect = is_git_dir_func paths = git.find_git_directory(worktree) assert is_git_dir.called -- 2.11.4.GIT