From b11b63156666589ec9749fa318fe7ecd9d1f136d Mon Sep 17 00:00:00 2001 From: Matěj Cepl Date: Thu, 18 Jan 2024 19:40:16 +0100 Subject: conversion of cmp() function --- libbe/bug.py | 62 ++++++++++++++++----------------- libbe/command/html.py | 21 +++++------- libbe/command/merge.py | 9 +++-- libbe/comment.py | 56 +++++++++++++++--------------- libbe/diff.py | 26 ++++++++------ libbe/storage/base.py | 46 +++++++++++++------------ libbe/storage/util/properties.py | 21 +++++++----- libbe/storage/vcs/base.py | 74 ++++++++++++++++++++++------------------ libbe/storage/vcs/darcs.py | 28 +++++++++------ libbe/storage/vcs/monotone.py | 13 ++++--- libbe/util/tree.py | 11 +++--- libbe/util/wsgi.py | 14 +++++--- 12 files changed, 205 insertions(+), 176 deletions(-) diff --git a/libbe/bug.py b/libbe/bug.py index a4ef53d..d211c30 100644 --- a/libbe/bug.py +++ b/libbe/bug.py @@ -25,16 +25,8 @@ """ import copy -import os -import os.path -import errno -import sys import time -import types -try: # import core module, Python >= 2.5 - from xml.etree import ElementTree -except ImportError: # look for non-core module - from elementtree import ElementTree +from xml.etree import ElementTree import xml.sax.saxutils import libbe @@ -47,7 +39,7 @@ import libbe.storage.util.mapfile as mapfile import libbe.comment as comment import libbe.util.utility as utility -if libbe.TESTING == True: +if libbe.TESTING: import doctest @@ -86,7 +78,7 @@ def load_severities(severity_def): global severity_values global severity_description global severity_index - if severity_def == None: + if severity_def is None: return severity_values = tuple([val for val,description in severity_def]) severity_description = dict(severity_def) @@ -95,6 +87,12 @@ def load_severities(severity_def): severity_index[severity] = i load_severities(severity_def) + +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + active_status_values = [] inactive_status_values = [] status_values = [] @@ -106,9 +104,9 @@ def load_status(active_status_def, inactive_status_def): global status_values global status_description global status_index - if active_status_def == None: + if active_status_def is None: active_status_def = globals()["active_status_def"] - if inactive_status_def == None: + if inactive_status_def is None: inactive_status_def = globals()["inactive_status_def"] active_status_values = tuple([val for val,description in active_status_def]) inactive_status_values = tuple([val for val,description in inactive_status_def]) @@ -197,7 +195,7 @@ class Bug (settings_object.SavedSettingsObject): def time_string(): return {} def _get_time(self): - if self.time_string == None: + if self.time_string is None: self._cached_time_string = None self._cached_time = None return None @@ -253,7 +251,7 @@ class Bug (settings_object.SavedSettingsObject): self.uuid = uuid self.id = libbe.util.id.ID(self, 'bug') if from_storage == False: - if uuid == None: + if uuid is None: self.uuid = libbe.util.id.uuid_gen() self.time = int(time.time()) # only save to second precision self.summary = summary @@ -277,7 +275,7 @@ class Bug (settings_object.SavedSettingsObject): def _setting_attr_string(self, setting): value = getattr(self, setting) - if value == None: + if value is None: return "" if type(value) not in (str,): return str(value) @@ -285,7 +283,7 @@ class Bug (settings_object.SavedSettingsObject): def string(self, shortlist=False, show_comments=False): if shortlist == False: - if self.time == None: + if self.time is None: timestring = "" else: htime = utility.handy_time(self.time) @@ -309,7 +307,7 @@ class Bug (settings_object.SavedSettingsObject): chars = "%c%c" % (statuschar, severitychar) bugout = "%s:%s: %s" % (self.id.user(),chars,self.summary.rstrip('\n')) - if show_comments == True: + if show_comments: self.comment_root.sort(cmp=libbe.comment.cmp_time, reverse=True) comout = self.comment_root.string_thread(flatten=False) output = bugout + '\n' + comout.rstrip('\n') @@ -409,7 +407,7 @@ class Bug (settings_object.SavedSettingsObject): """ - if self.time == None: + if self.time is None: timestring = "" else: timestring = utility.time_to_str(self.time) @@ -429,7 +427,7 @@ class Bug (settings_object.SavedSettingsObject): lines.append(' <%s>%s' % (k,xml.sax.saxutils.escape(v),k)) for estr in self.extra_strings: lines.append(' %s' % estr) - if show_comments == True: + if show_comments: comout = self.comment_root.xml_thread(indent=indent+2) if comout: comout = comout[indent:] # strip leading indent spaces @@ -588,7 +586,7 @@ class Bug (settings_object.SavedSettingsObject): default parent via default_parent. """ uuid_map = {} - if default_parent == None: + if default_parent is None: default_parent = self.comment_root for c in list(self.comments()) + comments: assert c.uuid != None @@ -609,7 +607,7 @@ class Bug (settings_object.SavedSettingsObject): try: parent = uuid_map[c.in_reply_to] except KeyError: - if ignore_missing_references == True: + if ignore_missing_references: libbe.LOG.warning( 'ignoring missing reference to {0}'.format( c.in_reply_to)) @@ -715,9 +713,9 @@ class Bug (settings_object.SavedSettingsObject): ).format(attr, old, new, self.uuid)) for estr in other.extra_strings: if not estr in self.extra_strings: - if accept_extra_strings == True: + if accept_extra_strings: self.extra_strings += [estr] - elif change_exception == True: + elif change_exception: raise ValueError('Merge would add extra string "%s" for bug %s' \ % (estr, self.uuid)) for o_comm in other.comments(): @@ -728,13 +726,13 @@ class Bug (settings_object.SavedSettingsObject): s_comm = self.comment_root.comment_from_uuid(o_comm.alt_id) except KeyError as e: s_comm = None - if s_comm == None: - if accept_comments == True: + if s_comm is None: + if accept_comments: o_comm_copy = copy.copy(o_comm) o_comm_copy.bug = self o_comm_copy.id = libbe.util.id.ID(o_comm_copy, 'comment') self.comment_root.add_reply(o_comm_copy) - elif change_exception == True: + elif change_exception: raise ValueError('Merge would add comment %s (alt: %s) to bug %s' \ % (o_comm.uuid, o_comm.alt_id, self.uuid)) else: @@ -745,7 +743,7 @@ class Bug (settings_object.SavedSettingsObject): # methods for saving/loading/acessing settings and properties. def load_settings(self, settings_mapfile=None): - if settings_mapfile == None: + if settings_mapfile is None: settings_mapfile = self.storage.get( self.id.storage('values'), '{}\n') try: @@ -782,7 +780,7 @@ class Bug (settings_object.SavedSettingsObject): comment.save_comments(self) def load_comments(self, load_full=True): - if load_full == True: + if load_full: # Force a complete load of the whole comment tree self.comment_root = self._get_comment_root(load_full=True) else: @@ -895,8 +893,8 @@ def cmp_attr(bug_1, bug_2, attr, invert=False): return 1 val_1 = getattr(bug_1, attr) val_2 = getattr(bug_2, attr) - if val_1 == None: val_1 = None - if val_2 == None: val_2 = None + if val_1 is None: val_1 = None + if val_2 is None: val_2 = None if invert == True : return -cmp(val_1, val_2) @@ -970,5 +968,5 @@ def cmp_last_modified(bug_1, bug_2): return -cmp(val_1, val_2) -if libbe.TESTING == True: +if libbe.TESTING: suite = doctest.DocTestSuite() diff --git a/libbe/command/html.py b/libbe/command/html.py index df87450..ed43808 100644 --- a/libbe/command/html.py +++ b/libbe/command/html.py @@ -21,14 +21,11 @@ # You should have received a copy of the GNU General Public License along with # Bugs Everywhere. If not, see . -import codecs import email.utils -import html.entities import itertools import os import os.path import re -import string import time import xml.sax.saxutils @@ -81,7 +78,7 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject, } # handlers - def style(self, environ, start_response): + def style(self, environ, start_response): template = self.template.get_template('style.css') content = template.render() return self.ok_response( @@ -125,7 +122,7 @@ class ServerApp (libbe.util.wsgi.WSGI_AppObject, self.bugdirs, target))) for target in bugs] else: - template = self.template.get_template('standard_index.html') + template = self.template.get_template('standard_index.html') content = template.render(template_info)+'\n' return self.ok_response( environ, start_response, content, content_type='text/html') @@ -351,7 +348,7 @@ div.main { margin-top: 1em; background-color: #fcfcfc; border-radius: 10px; - + } div.footer { @@ -397,7 +394,7 @@ table { border-spacing: 0px 0px; width: auto; padding: 0px; - + } tb { border: 1px; } @@ -463,14 +460,14 @@ td.tab { td.sel.tab { background-color: #c3d9ff ; border: 1px solid #c3d9ff; - font-weight:bold; + font-weight:bold; border-top-left-radius: 15px; border-top-right-radius: 15px; } -td.nsel.tab { +td.nsel.tab { border: 1px solid #c3d9ff; - font-weight:bold; + font-weight:bold; border-top-left-radius: 5px; border-top-right-radius: 5px; } @@ -480,7 +477,7 @@ table.bug_list { border-style: solid; border-color: #c3d9ff; padding: 0px; - width: 100%; + width: 100%; border: 1px solid #c3d9ff; } @@ -917,7 +914,7 @@ will exit after the dump without serving anything over the wire. for url_,path_ in url_mappings: content = content.replace(url_, path_) if not os.path.isdir(bug_dir_path): - self._make_dir(bug_dir_path) + self._make_dir(bug_dir_path) self._write_file(content=content, path_array=path_array) def _get_content(self, caller, app, path, data_dict=None): diff --git a/libbe/command/merge.py b/libbe/command/merge.py index 85fbb60..cf9eb91 100644 --- a/libbe/command/merge.py +++ b/libbe/command/merge.py @@ -18,7 +18,6 @@ # Bugs Everywhere. If not, see . import copy -import os import libbe import libbe.command @@ -67,8 +66,8 @@ class Merge (libbe.command.Command): Short name : abc/a Severity : minor Status : open - Assigned : - Reporter : + Assigned : + Reporter : Creator : John Doe Created : ... Bug A @@ -114,8 +113,8 @@ class Merge (libbe.command.Command): Short name : abc/b Severity : minor Status : closed - Assigned : - Reporter : + Assigned : + Reporter : Creator : Jane Doe Created : ... Bug B diff --git a/libbe/comment.py b/libbe/comment.py index d03f8ce..ca5f884 100644 --- a/libbe/comment.py +++ b/libbe/comment.py @@ -23,11 +23,7 @@ """ import base64 -import os -import os.path -import sys import time -import types try: from email.mime.base import MIMEBase from email.encoders import encode_base64 @@ -35,10 +31,7 @@ except ImportError: # adjust to old python 2.4 from email.MIMEBase import MIMEBase from email.Encoders import encode_base64 -try: # import core module, Python >= 2.5 - from xml.etree import ElementTree -except ImportError: # look for non-core module - from elementtree import ElementTree +from xml.etree import ElementTree import xml.sax.saxutils import libbe @@ -51,10 +44,15 @@ import libbe.storage.util.mapfile as mapfile from libbe.util.tree import Tree import libbe.util.utility as utility -if libbe.TESTING == True: +if libbe.TESTING: import doctest +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + class MissingReference(ValueError): def __init__(self, comment): msg = "Missing reference to %s" % (comment.in_reply_to) @@ -77,7 +75,7 @@ def load_comments(bug, load_full=False): comments = [] for uuid in uuids: comm = Comment(bug, uuid, from_storage=True) - if load_full == True: + if load_full: comm.load_settings() dummy = comm.body # force the body to load comments.append(comm) @@ -141,7 +139,7 @@ class Comment (Tree, settings_object.SavedSettingsObject): def date(): return {} def _get_time(self): - if self.date == None: + if self.date is None: return None return utility.str_to_time(self.date) def _set_time(self, value): @@ -211,7 +209,7 @@ class Comment (Tree, settings_object.SavedSettingsObject): self.uuid = uuid self.id = libbe.util.id.ID(self, 'comment') if from_storage == False: - if uuid == None: + if uuid is None: self.uuid = libbe.util.id.uuid_gen() self.time = int(time.time()) # only save to second precision self.in_reply_to = in_reply_to @@ -254,7 +252,7 @@ class Comment (Tree, settings_object.SavedSettingsObject): def _setting_attr_string(self, setting): value = getattr(self, setting) - if value == None: + if value is None: return "" if type(value) not in (str,): return str(value) @@ -268,7 +266,7 @@ class Comment (Tree, settings_object.SavedSettingsObject): * if that id matches another comments .alt_id, in which case return the matching comments .uuid. """ - if self.in_reply_to == None: + if self.in_reply_to is None: return None else: try: @@ -478,9 +476,9 @@ class Comment (Tree, settings_object.SavedSettingsObject): self.alt_id = None for estr in other.extra_strings: if not estr in self.extra_strings: - if accept_extra_strings == True: + if accept_extra_strings: self.extra_strings.append(estr) - elif change_exception == True: + elif change_exception: raise ValueError('Merge would add extra string "%s" to comment %s' \ % (estr, self.uuid)) @@ -492,7 +490,7 @@ class Comment (Tree, settings_object.SavedSettingsObject): >>> print comm.string(indent=2) --------- Comment --------- Name: //abc - From: + From: Date: Thu, 01 Jan 1970 00:00:00 +0000 Some @@ -544,50 +542,50 @@ class Comment (Tree, settings_object.SavedSettingsObject): >>> print a.string_thread(flatten=True) --------- Comment --------- Name: //a - From: + From: Date: Thu, 20 Nov 2008 01:00:00 +0000 Insightful remarks --------- Comment --------- Name: //b - From: + From: Date: Thu, 20 Nov 2008 02:00:00 +0000 Critique original comment --------- Comment --------- Name: //c - From: + From: Date: Thu, 20 Nov 2008 03:00:00 +0000 Begin flamewar :p --------- Comment --------- Name: //d - From: + From: Date: Thu, 20 Nov 2008 04:00:00 +0000 Useful examples >>> print a.string_thread() --------- Comment --------- Name: //a - From: + From: Date: Thu, 20 Nov 2008 01:00:00 +0000 Insightful remarks --------- Comment --------- Name: //b - From: + From: Date: Thu, 20 Nov 2008 02:00:00 +0000 Critique original comment --------- Comment --------- Name: //c - From: + From: Date: Thu, 20 Nov 2008 03:00:00 +0000 Begin flamewar :p --------- Comment --------- Name: //d - From: + From: Date: Thu, 20 Nov 2008 04:00:00 +0000 Useful examples @@ -607,7 +605,7 @@ class Comment (Tree, settings_object.SavedSettingsObject): def load_settings(self, settings_mapfile=None): if self.uuid == INVALID_UUID: return - if settings_mapfile == None: + if settings_mapfile is None: settings_mapfile = self.storage.get( self.id.storage('values'), '{}\n') try: @@ -732,8 +730,8 @@ def cmp_attr(comment_1, comment_2, attr, invert=False): return 1 val_1 = getattr(comment_1, attr) val_2 = getattr(comment_2, attr) - if val_1 == None: val_1 = None - if val_2 == None: val_2 = None + if val_1 is None: val_1 = None + if val_2 is None: val_2 = None if invert == True : return -cmp(val_1, val_2) @@ -767,5 +765,5 @@ class CommentCompoundComparator (object): cmp_full = CommentCompoundComparator() -if libbe.TESTING == True: +if libbe.TESTING: suite = doctest.DocTestSuite() diff --git a/libbe/diff.py b/libbe/diff.py index c2f9c8e..fe83881 100644 --- a/libbe/diff.py +++ b/libbe/diff.py @@ -32,6 +32,12 @@ from libbe.storage.util.settings_object import setting_name_to_attr_name from libbe.util.utility import time_to_str +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + + class SubscriptionType (libbe.util.tree.Tree): """Trees of subscription types to allow users to select exactly what notifications they want to subscribe to. @@ -132,7 +138,7 @@ def subscriptions_from_string(string=None, subscription_sep=',', id_sep=':'): ... ValueError: Invalid subscription "DIR::new", should be ID:TYPE """ - if string == None: + if string is None: return [Subscription(BUGDIR_ID, BUGDIR_TYPE_ALL)] subscriptions = [] for subscription in string.split(','): @@ -196,7 +202,7 @@ class DiffTree (libbe.util.tree.Tree): self.masked = masked def paths(self, parent_path=None): paths = [] - if parent_path == None: + if parent_path is None: path = self.name else: path = '%s/%s' % (parent_path, self.name) @@ -225,16 +231,16 @@ class DiffTree (libbe.util.tree.Tree): raise KeyError('%s points to child not in %s' % (names, [c.name for c in self])) def report_string(self): report = self.report() - if report == None: + if report is None: return '' return '\n'.join(report) def report(self, root=None, parent=None, depth=0): - if root == None: + if root is None: root = self.make_root() - if self.masked == True: + if self.masked: return root data_part = self.data_part(depth) - if self.requires_children == True \ + if self.requires_children \ and len([c for c in self if c.masked == False]) == 0: pass else: @@ -250,12 +256,12 @@ class DiffTree (libbe.util.tree.Tree): if data_part != None: root.append(data_part) def data_part(self, depth, indent=True): - if self.data == None: + if self.data is None: return None if hasattr(self, '_cached_data_part'): return self._cached_data_part data_part = self.data_part_fn(self.data) - if indent == True: + if indent: data_part_lines = data_part.splitlines() indent = ' '*(depth) line_sep = '\n'+indent @@ -574,11 +580,11 @@ class Diff (object): can pass in a DiffTree subclass via diff_tree to override the default report assembly process. """ - if allow_cached == True \ + if allow_cached \ and hasattr(self, '_cached_full_report') \ and diff_tree == self._cached_full_report_diff_tree: return self._sub_report(subscriptions) - if subscriptions == None: + if subscriptions is None: subscriptions = [Subscription(BUGDIR_ID, BUGDIR_TYPE_ALL)] bugdir_settings = sorted(self.new_bugdir.settings_properties) root = diff_tree('bugdir') diff --git a/libbe/storage/base.py b/libbe/storage/base.py index 4c05287..7020c10 100644 --- a/libbe/storage/base.py +++ b/libbe/storage/base.py @@ -23,7 +23,6 @@ Abstract bug repository data storage to easily support multiple backends. import copy import os import pickle -import types from libbe.error import NotSupported import libbe.storage @@ -32,7 +31,7 @@ from libbe.util import InvalidObject import libbe.version from libbe import TESTING -if TESTING == True: +if TESTING: import doctest import os.path import sys @@ -40,12 +39,17 @@ if TESTING == True: from libbe.util.utility import Dir +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + class ConnectionError (Exception): pass class InvalidStorageVersion(ConnectionError): def __init__(self, active_version, expected_version=None): - if expected_version == None: + if expected_version is None: expected_version = libbe.storage.STORAGE_VERSION msg = 'Storage in "%s" not the expected "%s"' \ % (active_version, expected_version) @@ -60,7 +64,7 @@ class InvalidID (KeyError): self.id = id self.revision = revision def __str__(self): - if self.msg == None: + if self.msg is None: return '%s in revision %s' % (self.id, self.revision) return self.msg @@ -93,7 +97,7 @@ class _EMPTY (object): class Entry (Tree): def __init__(self, id, value=_EMPTY, parent=None, directory=False, children=None): - if children == None: + if children is None: Tree.__init__(self) else: Tree.__init__(self, children) @@ -114,14 +118,14 @@ class Entry (Tree): return str(self) def __cmp__(self, other, local=False): - if other == None: + if other is None: return cmp(1, None) if cmp(self.id, other.id) != 0: return cmp(self.id, other.id) if cmp(self.value, other.value) != 0: return cmp(self.value, other.value) if local == False: - if self.parent == None: + if self.parent is None: if cmp(self.parent, other.parent) != 0: return cmp(self.parent, other.parent) elif self.parent.__cmp__(other.parent, local=True) != 0: @@ -250,7 +254,7 @@ class Storage (object): self._add(id, *args, **kwargs) def _add(self, id, parent=None, directory=False): - if parent == None: + if parent is None: parent = '__ROOT__' p = self._data[parent] self._data[id] = Entry(id, parent=p, directory=directory) @@ -296,7 +300,7 @@ class Storage (object): return self._ancestors(*args, **kwargs) def _ancestors(self, id=None, revision=None): - if id == None: + if id is None: return [] ancestors = [] stack = [id] @@ -316,7 +320,7 @@ class Storage (object): return self._children(*args, **kwargs) def _children(self, id=None, revision=None): - if id == None: + if id is None: id = '__ROOT__' return [c.id for c in self._data[id] if not c.id.startswith('__')] @@ -362,7 +366,7 @@ class Storage (object): def _set(self, id, value): if id not in self._data: raise InvalidID(id) - if self._data[id].directory == True: + if self._data[id].directory: raise InvalidDirectory( 'Directory %s cannot have data' % self.parent) self._data[id].value = value @@ -408,13 +412,13 @@ class VersionedStorage (Storage): self._data = None def _add(self, id, parent=None, directory=False): - if parent == None: + if parent is None: parent = '__ROOT__' p = self._data[-1][parent] self._data[-1][id] = Entry(id, parent=p, directory=directory) def _exists(self, id, revision=None): - if revision == None: + if revision is None: revision = -1 else: revision = int(revision) @@ -432,9 +436,9 @@ class VersionedStorage (Storage): self._remove(entry.id) def _ancestors(self, id=None, revision=None): - if id == None: + if id is None: return [] - if revision == None: + if revision is None: revision = -1 else: revision = int(revision) @@ -450,9 +454,9 @@ class VersionedStorage (Storage): return ancestors def _children(self, id=None, revision=None): - if id == None: + if id is None: id = '__ROOT__' - if revision == None: + if revision is None: revision = -1 else: revision = int(revision) @@ -460,7 +464,7 @@ class VersionedStorage (Storage): if not c.id.startswith('__')] def _get(self, id, default=InvalidObject, revision=None): - if revision == None: + if revision is None: revision = -1 else: revision = int(revision) @@ -508,7 +512,7 @@ class VersionedStorage (Storage): If the specified revision does not exist, raise InvalidRevision. """ - if index == None: + if index is None: return None try: if int(index) != index: @@ -518,7 +522,7 @@ class VersionedStorage (Storage): L = len(self._data) - 1 # -1 b/c of initial commit if index >= -L and index <= L: return str(index % L) - raise InvalidRevision(i) + raise InvalidRevision(index) def changed(self, revision): """Return a tuple of lists of ids `(new, modified, removed)` from the @@ -540,7 +544,7 @@ class VersionedStorage (Storage): return (new, modified, removed) -if TESTING == True: +if TESTING: class StorageTestCase (unittest.TestCase): """Test cases for Storage class.""" diff --git a/libbe/storage/util/properties.py b/libbe/storage/util/properties.py index 4aa3ce6..ad9d06c 100644 --- a/libbe/storage/util/properties.py +++ b/libbe/storage/util/properties.py @@ -42,10 +42,15 @@ import copy import types import libbe -if libbe.TESTING == True: +if libbe.TESTING: import unittest +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + class ValueCheckError (ValueError): def __init__(self, name, value, allowed): action = "in" # some list of allowed values @@ -103,7 +108,7 @@ def local_property(name, null=None, mutable_null=False): def _fget(self): if fget is not None: fget(self) - if mutable_null == True: + if mutable_null: ret_null = copy.deepcopy(null) else: ret_null = null @@ -203,7 +208,7 @@ def defaulting_property(default=None, null=None, def _fget(self): value = fget(self) if value == null: - if mutable_default == True: + if mutable_default: return copy.deepcopy(default) else: return default @@ -380,7 +385,7 @@ def change_hook_property(hook, mutable=False, default=None): fset = funcs.get("fset") name = funcs.get("name", "") def _fget(self, new_value=None, from_fset=False): # only used if mutable == True - if from_fset == True: + if from_fset: value = new_value # compare new value with cached else: value = fget(self) # compare current value with cached @@ -388,26 +393,26 @@ def change_hook_property(hook, mutable=False, default=None): # there has been a change, cache new value old_value = _get_cached_mutable_property(self, "change hook property", name, default) _set_cached_mutable_property(self, "change hook property", name, value) - if from_fset == True: # return previously cached value + if from_fset: # return previously cached value value = old_value else: # the value changed while we weren't looking hook(self, old_value, value) return value def _fset(self, value): - if mutable == True: # get cached previous value + if mutable: # get cached previous value old_value = _fget(self, new_value=value, from_fset=True) else: old_value = fget(self) fset(self, value) if value != old_value: hook(self, old_value, value) - if mutable == True: + if mutable: funcs["fget"] = _fget funcs["fset"] = _fset return funcs return decorator -if libbe.TESTING == True: +if libbe.TESTING: class DecoratorTests(unittest.TestCase): def testLocalDoc(self): class Test(object): diff --git a/libbe/storage/vcs/base.py b/libbe/storage/vcs/base.py index dfd007f..579935e 100644 --- a/libbe/storage/vcs/base.py +++ b/libbe/storage/vcs/base.py @@ -44,12 +44,18 @@ from libbe.util.subproc import CommandError, invoke from libbe.util.plugin import import_by_name import libbe.storage.util.upgrade as upgrade -if libbe.TESTING == True: +if libbe.TESTING: import unittest import doctest import libbe.ui.util.user + +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + VCS_ORDER = ['bzr', 'darcs', 'git', 'hg', 'monotone'] """List VCS modules in order of preference. @@ -75,7 +81,7 @@ def _get_matching_vcs(matchfn): for submodname in VCS_ORDER: module = import_by_name('libbe.storage.vcs.%s' % submodname) vcs = module.new() - if matchfn(vcs) == True: + if matchfn(vcs): return vcs return VCS() @@ -117,7 +123,7 @@ class VCSUnableToRoot (libbe.storage.base.ConnectionError): class InvalidPath (InvalidID): def __init__(self, path, root, msg=None, **kwargs): - if msg == None: + if msg is None: msg = 'Path "%s" not in root "%s"' % (path, root) InvalidID.__init__(self, msg=msg, **kwargs) self.path = path @@ -132,7 +138,7 @@ class SpacerCollision (InvalidPath): class CachedPathID (object): """Cache Storage ID <-> path policy. - + Paths generated following:: .../.be/BUGDIR/bugs/BUG/comments/COMMENT @@ -209,7 +215,7 @@ class CachedPathID (object): UUID\tPATH """ - if cache == None: + if cache is None: self._cache = {} else: self._cache = cache @@ -231,7 +237,7 @@ class CachedPathID (object): pass if self._cache != cache: self._changed = True - if cache == None: + if cache is None: self.disconnect() def destroy(self): @@ -253,7 +259,7 @@ class CachedPathID (object): f.close() def disconnect(self): - if self._changed == True: + if self._changed: f = codecs.open(self._cache_path, 'w', self.encoding) for uuid,path in list(self._cache.items()): f.write('%s\t%s\n' % (uuid, path)) @@ -271,7 +277,7 @@ class CachedPathID (object): self.init(cache=self._cache) if uuid not in self._cache: raise InvalidID(uuid) - if relpath == True: + if relpath: return os.path.join(self._cache[uuid], *extra) return os.path.join(self._root, self._cache[uuid], *extra) @@ -285,7 +291,7 @@ class CachedPathID (object): # already added path = self.path(id) else: - if parent == None: + if parent is None: parent_path = '' spacer = self._spacer_dirs[0] else: @@ -445,7 +451,7 @@ class VCS (libbe.storage.base.VersionedStorage): def _vcs_path(self, id, revision): """ Return the relative path to object id as of revision. - + Revision will not be None. """ raise NotImplementedError @@ -454,7 +460,7 @@ class VCS (libbe.storage.base.VersionedStorage): """ Return True if path (as returned by _vcs_path) was a directory as of revision, False otherwise. - + Revision will not be None. """ raise NotImplementedError @@ -463,7 +469,7 @@ class VCS (libbe.storage.base.VersionedStorage): """ Return a list of the contents of the directory path (as returned by _vcs_path) as of revision. - + Revision will not be None, and ._vcs_isdir(path, revision) will be True. """ @@ -610,7 +616,7 @@ class VCS (libbe.storage.base.VersionedStorage): """ if not hasattr(self, 'user_id'): self.user_id = self._vcs_get_user_id() - if self.user_id == None: + if self.user_id is None: # guess missing info name = libbe.ui.util.user.get_fallback_fullname() email = libbe.ui.util.user.get_fallback_email() @@ -696,13 +702,13 @@ class VCS (libbe.storage.base.VersionedStorage): self._cached_path_id.disconnect() def path(self, id, revision=None, relpath=True): - if revision == None: + if revision is None: path = self._cached_path_id.path(id) - if relpath == True: + if relpath: return self._u_rel_path(path) return path path = self._vcs_path(id, revision) - if relpath == True: + if relpath: return path return os.path.join(self.repo, path) @@ -729,7 +735,7 @@ class VCS (libbe.storage.base.VersionedStorage): self._add_path(path, **kwargs) def _exists(self, id, revision=None): - if revision == None: + if revision is None: try: path = self.path(id, revision, relpath=False) except InvalidID as e: @@ -781,11 +787,11 @@ class VCS (libbe.storage.base.VersionedStorage): id = self._u_path_to_id(path) ancestors.append(id) except (SpacerCollision, InvalidPath): - pass + pass return ancestors def _children(self, id=None, revision=None): - if revision == None: + if revision is None: isdir = os.path.isdir listdir = os.listdir else: @@ -797,7 +803,7 @@ class VCS (libbe.storage.base.VersionedStorage): path = self.be_dir else: path = self.path(id, revision, relpath=False) - if isdir(path) == False: + if isdir(path) == False: return [] children = listdir(path) for i,c in enumerate(children): @@ -809,7 +815,7 @@ class VCS (libbe.storage.base.VersionedStorage): children[i] = None children[i] = None for i,c in enumerate(children): - if c == None: continue + if c is None: continue cpath = os.path.join(path, c) children[i] = self._u_path_to_id(cpath) return [c for c in children if c != None] @@ -861,7 +867,7 @@ class VCS (libbe.storage.base.VersionedStorage): return revision def revision_id(self, index=None): - if index == None: + if index is None: return None try: if int(index) != index: @@ -869,7 +875,7 @@ class VCS (libbe.storage.base.VersionedStorage): except ValueError: raise InvalidRevision(index) revid = self._vcs_revision_id(index) - if revid == None: + if revid is None: raise libbe.storage.base.InvalidRevision(index) return revid @@ -930,7 +936,7 @@ class VCS (libbe.storage.base.VersionedStorage): def _u_find_id_from_manifest(self, id, manifest, revision=None): """Search for the relative path to id using manifest, a list of all files. - + Returns None if the id is not found. """ be_dir = self._cached_path_id._spacer_dirs[0] @@ -991,8 +997,8 @@ class VCS (libbe.storage.base.VersionedStorage): >>> vcs._u_rel_path("./a", ".") 'a' """ - if root == None: - if self.repo == None: + if root is None: + if self.repo is None: raise VCSNotRooted(self) root = self.repo path = os.path.abspath(path) @@ -1015,7 +1021,7 @@ class VCS (libbe.storage.base.VersionedStorage): >>> vcs._u_abspath(".be", "/a.b/c") '/a.b/c/.be' """ - if root == None: + if root is None: assert self.repo != None, "VCS not rooted" root = self.repo return os.path.abspath(os.path.join(root, path)) @@ -1045,11 +1051,11 @@ class VCS (libbe.storage.base.VersionedStorage): -------- libbe.storage.util.upgrade """ - if path == None: + if path is None: path = os.path.join(self.repo, '.be', 'version') if not os.path.exists(path): raise libbe.storage.InvalidStorageVersion(None) - if revision == None: # don't require connection + if revision is None: # don't require connection return libbe.util.encoding.get_file_contents( path, decode=True).rstrip() relpath = self._u_rel_path(path) @@ -1070,7 +1076,7 @@ class VCS (libbe.storage.base.VersionedStorage): self._vcs_add(self._u_rel_path(path)) -if libbe.TESTING == True: +if libbe.TESTING: class VCSTestCase (unittest.TestCase): """ Test cases for base VCS class (in addition to the Storage test @@ -1089,13 +1095,13 @@ if libbe.TESTING == True: self.dir = Dir() self.dirname = self.dir.path self.s = self.Class(repo=self.dirname) - if self.s.installed() == True: + if self.s.installed(): self.s.init() self.s.connect() def tearDown(self): super(VCSTestCase, self).tearDown() - if self.s.installed() == True: + if self.s.installed(): self.s.disconnect() self.s.destroy() self.dir.cleanup() @@ -1147,7 +1153,7 @@ if libbe.TESTING == True: """Should get the existing user ID.""" if self.s.installed(): user_id = self.s.get_user_id() - if user_id == None: + if user_id is None: return name,email = libbe.ui.util.user.parse_user_id(user_id) if email != None: @@ -1156,7 +1162,7 @@ if libbe.TESTING == True: def make_vcs_testcase_subclasses(vcs_class, namespace): c = vcs_class() if c.installed(): - if c.versioned == True: + if c.versioned: libbe.storage.base.make_versioned_storage_testcase_subclasses( vcs_class, namespace) else: diff --git a/libbe/storage/vcs/darcs.py b/libbe/storage/vcs/darcs.py index 41262f5..5ec9a26 100644 --- a/libbe/storage/vcs/darcs.py +++ b/libbe/storage/vcs/darcs.py @@ -39,11 +39,17 @@ import libbe from ...util.subproc import CommandError from . import base -if libbe.TESTING == True: +if libbe.TESTING: import doctest import unittest +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + + def new(): return Darcs() @@ -98,7 +104,7 @@ class Darcs(base.VCS): NotImplementedError: Cannot parse non-integer portion "0pre2" of Darcs version "2.0.0pre2" """ if not hasattr(self, '_parsed_version') \ - or self._parsed_version == None: + or self._parsed_version is None: num_part = self.version().split(' ')[0] self._parsed_version = [] for num in num_part.split('.'): @@ -119,12 +125,12 @@ class Darcs(base.VCS): def _vcs_get_user_id(self): # following http://darcs.net/manual/node4.html#SECTION00410030000000000000 # as of June 22th, 2010 - if self.repo == None: + if self.repo is None: return None for pref_file in ['author', 'email']: for prefs_dir in [os.path.join(self.repo, '_darcs', 'prefs'), os.path.expanduser(os.path.join('~', '.darcs'))]: - if prefs_dir == None: + if prefs_dir is None: continue pref_path = os.path.join(prefs_dir, pref_file) if os.path.exists(pref_path): @@ -135,7 +141,7 @@ class Darcs(base.VCS): return None def _vcs_detect(self, path): - if self._u_search_parent_directories(path, "_darcs") != None : + if self._u_search_parent_directories(path, "_darcs") is not None : return True return False @@ -146,7 +152,7 @@ class Darcs(base.VCS): if os.path.isdir(path) != True: path = os.path.dirname(path) darcs_dir = self._u_search_parent_directories(path, '_darcs') - if darcs_dir == None: + if darcs_dir is None: return None return os.path.dirname(darcs_dir) @@ -175,7 +181,7 @@ class Darcs(base.VCS): pass # darcs notices changes def _vcs_get_file_contents(self, path, revision=None): - if revision == None: + if revision is None: return base.VCS._vcs_get_file_contents(self, path, revision) if self.version_cmp(2, 0, 0) == 1: status,output,error = self._u_invoke_client( \ @@ -266,7 +272,7 @@ class Darcs(base.VCS): else: revline = re.compile("Finished recording patch '(.*)'") match = revline.search(output) - assert match != None, output+error + assert match is not None, output+error assert len(match.groups()) == 1 revision = match.groups()[0] return revision @@ -308,7 +314,7 @@ class Darcs(base.VCS): if i+1 < len(revisions): next_rev = revisions[i+1] args.extend(['--from-patch', next_rev]) - if path != None: + if path is not None: args.append(path) kwargs = {'unicode_output':unicode_output} status,output,error = self._u_invoke_client( @@ -356,7 +362,7 @@ class Darcs(base.VCS): @@ -1 +0,0 @@ -this entry will be deleted \ No newline at end of file - + """ new = [] modified = [] @@ -404,7 +410,7 @@ class Darcs(base.VCS): return self._parse_diff(self._diff(revision)) -if libbe.TESTING == True: +if libbe.TESTING: base.make_vcs_testcase_subclasses(Darcs, sys.modules[__name__]) unitsuite =unittest.TestLoader().loadTestsFromModule(sys.modules[__name__]) diff --git a/libbe/storage/vcs/monotone.py b/libbe/storage/vcs/monotone.py index abd3142..add7be9 100644 --- a/libbe/storage/vcs/monotone.py +++ b/libbe/storage/vcs/monotone.py @@ -38,6 +38,11 @@ if libbe.TESTING == True: import sys +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + def new(): return Monotone() @@ -315,15 +320,15 @@ class Monotone (base.VCS): # old_revision [1ce9ac2cfe3166b8ad23a60555f8a70f37686c25] # # delete ".be/dir/bugs/moved" - # + # # delete ".be/dir/bugs/removed" - # + # # add_file ".be/dir/bugs/moved2" # content [33e4510df9abef16dad7c65c0775e74602cc5005] - # + # # add_file ".be/dir/bugs/new" # content [45c45b5630f7446f83b0e14ee1525e449a06131c] - # + # # patch ".be/dir/bugs/modified" # from [809bf3b80423c361849386008a0ce01199d30929] # to [f13d3ec08972e2b41afecd9a90d4bc71cdcea338] diff --git a/libbe/util/tree.py b/libbe/util/tree.py index c6aa46b..5d0da49 100644 --- a/libbe/util/tree.py +++ b/libbe/util/tree.py @@ -22,9 +22,10 @@ """ import libbe -if libbe.TESTING == True: +if libbe.TESTING: import doctest + class Tree(list): """A traversable tree structure. @@ -115,7 +116,7 @@ class Tree(list): True """ def __cmp__(self, other): - return cmp(id(self), id(other)) + return (id(self) > id(other)) - (id(self) < id(other)) def __eq__(self, other): return self.__cmp__(other) == 0 @@ -172,7 +173,7 @@ class Tree(list): in the order they are stored, so you might want to :py:meth:`sort` your tree first. """ - if depth_first == True: + if depth_first: yield self for child in self: for descendant in child.traverse(): @@ -213,7 +214,7 @@ class Tree(list): """ stack = [] # ancestry of the current node - if flatten == True: + if flatten: depthDict = {} for node in self.traverse(depth_first=True): @@ -256,5 +257,5 @@ class Tree(list): return True return False -if libbe.TESTING == True: +if libbe.TESTING: suite = doctest.DocTestSuite() diff --git a/libbe/util/wsgi.py b/libbe/util/wsgi.py index 96ddf60..46e1b3c 100644 --- a/libbe/util/wsgi.py +++ b/libbe/util/wsgi.py @@ -36,7 +36,6 @@ import io import sys import time import traceback -import types import urllib.request, urllib.parse, urllib.error import urllib.parse import wsgiref.simple_server @@ -67,7 +66,12 @@ import libbe.util.http import libbe.util.id -if libbe.TESTING == True: +# https://stackoverflow.com/a/56719588/164233 +def cmp(a, b): + return (int(a) > int(b)) - (int(a) < int(b)) + + +if libbe.TESTING: import doctest import unittest import wsgiref.validate @@ -627,7 +631,7 @@ class ServerCommand (libbe.command.base.Command): 'PID file {} already exists'.format(params['pidfile'])) pid = os.getpid() with open(params['pidfile'], 'w') as f: # race between exist and open - f.write(str(os.getpid())) + f.write(str(os.getpid())) self.logger.log( self.log_level, 'Got PID file as {}'.format(pid)) @@ -935,12 +939,12 @@ def _make_certs(server_name, logger=None, level=None): `mk_certs(server_name) -> (pkey_filename, cert_filename)` """ - if OpenSSL == None: + if OpenSSL is None: raise libbe.command.UserError( 'SSL certificate generation requires the OpenSSL module') pkey_file,cert_file = _get_cert_filenames( server_name, autogenerate=False) - if logger != None: + if logger is not None: logger.log( level, 'Generating certificates {} {}'.format( pkey_file, cert_file)) -- cgit