# HG changeset patch # User RhodeCode Admin # Date 2023-07-18 12:29:55 # Node ID d68a72e0dc052821835986aa1e7e2940d7a3a896 # Parent 993cabc6db1a4c81996f5dcb023a46fc64fd9e88 vcsserver: modernize code for python3 diff --git a/vcsserver/config/settings_maker.py b/vcsserver/config/settings_maker.py --- a/vcsserver/config/settings_maker.py +++ b/vcsserver/config/settings_maker.py @@ -72,7 +72,7 @@ class SettingsMaker(object): os.makedirs(input_val, mode=mode, exist_ok=True) if not os.path.isdir(input_val): - raise Exception('Dir at {} does not exist'.format(input_val)) + raise Exception(f'Dir at {input_val} does not exist') return input_val @classmethod diff --git a/vcsserver/git_lfs/app.py b/vcsserver/git_lfs/app.py --- a/vcsserver/git_lfs/app.py +++ b/vcsserver/git_lfs/app.py @@ -212,7 +212,7 @@ def lfs_objects_verify(request): store_size = store.size_oid() if store_size != size: - msg = 'requested file size mismatch store size:%s requested:%s' % ( + msg = 'requested file size mismatch store size:{} requested:{}'.format( store_size, size) return write_response_error( HTTPUnprocessableEntity, msg) diff --git a/vcsserver/git_lfs/lib.py b/vcsserver/git_lfs/lib.py --- a/vcsserver/git_lfs/lib.py +++ b/vcsserver/git_lfs/lib.py @@ -51,7 +51,7 @@ class OidHandler(object): if not store.has_oid(): # error reply back to client that something is wrong with dl - err_msg = 'object: {} does not exist in store'.format(store.oid) + err_msg = f'object: {store.oid} does not exist in store' has_errors = OrderedDict( error=OrderedDict( code=404, diff --git a/vcsserver/hook_utils/__init__.py b/vcsserver/hook_utils/__init__.py --- a/vcsserver/hook_utils/__init__.py +++ b/vcsserver/hook_utils/__init__.py @@ -75,7 +75,7 @@ def install_git_hooks(repo_path, bare, e template = template.replace(b'_PATH_', safe_bytes(path)) f.write(template) os.chmod(_hook_file, 0o755) - except IOError: + except OSError: log.exception('error writing hook file %s', _hook_file) else: log.debug('skipping writing hook file') @@ -129,7 +129,7 @@ def install_svn_hooks(repo_path, executa f.write(template) os.chmod(_hook_file, 0o755) - except IOError: + except OSError: log.exception('error writing hook file %s', _hook_file) else: log.debug('skipping writing hook file') diff --git a/vcsserver/lib/_vendor/jsonlogger/__init__.py b/vcsserver/lib/_vendor/jsonlogger/__init__.py --- a/vcsserver/lib/_vendor/jsonlogger/__init__.py +++ b/vcsserver/lib/_vendor/jsonlogger/__init__.py @@ -84,7 +84,7 @@ class JsonEncoder(json.JSONEncoder): return str(obj) try: - return super(JsonEncoder, self).default(obj) + return super().default(obj) except TypeError: try: @@ -200,7 +200,7 @@ class JsonFormatter(ExceptionAwareFormat def serialize_log_record(self, log_record): """Returns the final representation of the log record.""" - return "%s%s" % (self.prefix, self.jsonify_log_record(log_record)) + return "{}{}".format(self.prefix, self.jsonify_log_record(log_record)) def format(self, record): """Formats a log record and serializes to json""" diff --git a/vcsserver/lib/_vendor/redis_lock/__init__.py b/vcsserver/lib/_vendor/redis_lock/__init__.py --- a/vcsserver/lib/_vendor/redis_lock/__init__.py +++ b/vcsserver/lib/_vendor/redis_lock/__init__.py @@ -219,7 +219,7 @@ class Lock(object): if self._held: owner_id = self.get_owner_id() - raise AlreadyAcquired("Already acquired from this Lock instance. Lock id: {}".format(owner_id)) + raise AlreadyAcquired(f"Already acquired from this Lock instance. Lock id: {owner_id}") if not blocking and timeout is not None: raise TimeoutNotUsable("Timeout cannot be used if blocking=False") diff --git a/vcsserver/lib/_vendor/statsd/__init__.py b/vcsserver/lib/_vendor/statsd/__init__.py --- a/vcsserver/lib/_vendor/statsd/__init__.py +++ b/vcsserver/lib/_vendor/statsd/__init__.py @@ -1,5 +1,3 @@ - - import logging from .stream import TCPStatsClient, UnixSocketStatsClient # noqa diff --git a/vcsserver/lib/_vendor/statsd/base.py b/vcsserver/lib/_vendor/statsd/base.py --- a/vcsserver/lib/_vendor/statsd/base.py +++ b/vcsserver/lib/_vendor/statsd/base.py @@ -1,5 +1,3 @@ - - import re import random from collections import deque diff --git a/vcsserver/lib/_vendor/statsd/stream.py b/vcsserver/lib/_vendor/statsd/stream.py --- a/vcsserver/lib/_vendor/statsd/stream.py +++ b/vcsserver/lib/_vendor/statsd/stream.py @@ -1,5 +1,3 @@ - - import socket from .base import StatsClientBase, PipelineBase diff --git a/vcsserver/lib/_vendor/statsd/timer.py b/vcsserver/lib/_vendor/statsd/timer.py --- a/vcsserver/lib/_vendor/statsd/timer.py +++ b/vcsserver/lib/_vendor/statsd/timer.py @@ -1,5 +1,3 @@ - - import functools from time import perf_counter as time_now diff --git a/vcsserver/lib/_vendor/statsd/udp.py b/vcsserver/lib/_vendor/statsd/udp.py --- a/vcsserver/lib/_vendor/statsd/udp.py +++ b/vcsserver/lib/_vendor/statsd/udp.py @@ -1,5 +1,3 @@ - - import socket from .base import StatsClientBase, PipelineBase @@ -8,7 +6,7 @@ from .base import StatsClientBase, Pipel class Pipeline(PipelineBase): def __init__(self, client): - super(Pipeline, self).__init__(client) + super().__init__(client) self._maxudpsize = client._maxudpsize def _send(self): diff --git a/vcsserver/lib/logging_formatter.py b/vcsserver/lib/logging_formatter.py --- a/vcsserver/lib/logging_formatter.py +++ b/vcsserver/lib/logging_formatter.py @@ -43,7 +43,7 @@ class ColorFormatter(logging.Formatter): """ Change record's levelname to use with COLORS enum """ - def_record = super(ColorFormatter, self).format(record) + def_record = super().format(record) levelname = record.levelname start = COLOR_SEQ % (COLORS[levelname]) diff --git a/vcsserver/lib/memory_lru_dict.py b/vcsserver/lib/memory_lru_dict.py --- a/vcsserver/lib/memory_lru_dict.py +++ b/vcsserver/lib/memory_lru_dict.py @@ -51,11 +51,11 @@ class LRUDictDebug(LRUDict): Wrapper to provide some debug options """ def _report_keys(self): - elems_cnt = '{}/{}'.format(len(list(self.keys())), self.size) + elems_cnt = f'{len(list(self.keys()))}/{self.size}' # trick for pformat print it more nicely fmt = '\n' for cnt, elem in enumerate(self.keys()): - fmt += '{} - {}\n'.format(cnt+1, safe_str(elem)) + fmt += f'{cnt+1} - {safe_str(elem)}\n' log.debug('current LRU keys (%s):%s', elems_cnt, fmt) def __getitem__(self, key): diff --git a/vcsserver/lib/rc_cache/utils.py b/vcsserver/lib/rc_cache/utils.py --- a/vcsserver/lib/rc_cache/utils.py +++ b/vcsserver/lib/rc_cache/utils.py @@ -173,7 +173,7 @@ def get_or_create_region(region_name, re region_obj = region_meta.dogpile_cache_regions.get(region_name) if not region_obj: reg_keys = list(region_meta.dogpile_cache_regions.keys()) - raise EnvironmentError(f'Region `{region_name}` not in configured: {reg_keys}.') + raise OSError(f'Region `{region_name}` not in configured: {reg_keys}.') region_uid_name = f'{region_name}:{region_namespace}' diff --git a/vcsserver/remote/git.py b/vcsserver/remote/git.py --- a/vcsserver/remote/git.py +++ b/vcsserver/remote/git.py @@ -483,7 +483,7 @@ class GitRemote(RemoteBase): q = {"service": 'git-upload-pack'} qs = '?%s' % urllib.parse.urlencode(q) - cu = "{}{}".format(test_uri, qs) + cu = f"{test_uri}{qs}" req = urllib.request.Request(cu, None, {}) try: @@ -494,7 +494,7 @@ class GitRemote(RemoteBase): except Exception as e: log.warning("URL cannot be opened: %s", obfuscated_uri, exc_info=True) # means it cannot be cloned - raise exceptions.URLError(e)("[{}] org_exc: {}".format(obfuscated_uri, e)) + raise exceptions.URLError(e)(f"[{obfuscated_uri}] org_exc: {e}") # now detect if it's proper git repo gitdata: bytes = resp.read() diff --git a/vcsserver/remote/hg.py b/vcsserver/remote/hg.py --- a/vcsserver/remote/hg.py +++ b/vcsserver/remote/hg.py @@ -464,7 +464,7 @@ class HgRemote(RemoteBase): q = {"cmd": 'between'} q.update({'pairs': "{}-{}".format('0' * 40, '0' * 40)}) qs = '?%s' % urllib.parse.urlencode(q) - cu = "{}{}".format(test_uri, qs) + cu = f"{test_uri}{qs}" req = urllib.request.Request(cu, None, {}) try: @@ -475,7 +475,7 @@ class HgRemote(RemoteBase): except Exception as e: log.warning("URL cannot be opened: %s", obfuscated_uri, exc_info=True) # means it cannot be cloned - raise exceptions.URLError(e)("[{}] org_exc: {}".format(obfuscated_uri, e)) + raise exceptions.URLError(e)(f"[{obfuscated_uri}] org_exc: {e}") # now check if it's a proper hg repo, but don't do it for svn try: diff --git a/vcsserver/subprocessio.py b/vcsserver/subprocessio.py --- a/vcsserver/subprocessio.py +++ b/vcsserver/subprocessio.py @@ -42,11 +42,11 @@ class StreamFeeder(threading.Thread): """ def __init__(self, source): - super(StreamFeeder, self).__init__() + super().__init__() self.daemon = True filelike = False - self.bytes = bytes() - if type(source) in (type(''), bytes, bytearray): # string-like + self.bytes = b'' + if type(source) in (str, bytes, bytearray): # string-like self.bytes = bytes(source) else: # can be either file pointer or file-like if isinstance(source, int): # file pointer it is @@ -85,7 +85,7 @@ class StreamFeeder(threading.Thread): class InputStreamChunker(threading.Thread): def __init__(self, source, target, buffer_size, chunk_size): - super(InputStreamChunker, self).__init__() + super().__init__() self.daemon = True # die die die. @@ -440,7 +440,7 @@ class SubprocessIOChunker(object): elif err and fail_on_stderr: text_err = err.decode() raise OSError( - "Subprocess exited due to an error:\n{}".format(text_err)) + f"Subprocess exited due to an error:\n{text_err}") if ret_code_fail and fail_on_return_code: text_err = err.decode() @@ -449,7 +449,7 @@ class SubprocessIOChunker(object): # in many cases git reports the errors on stdout too text_err = out.decode() raise OSError( - "Subprocess exited with non 0 ret code:{}: stderr:{}".format(return_code, text_err)) + f"Subprocess exited with non 0 ret code:{return_code}: stderr:{text_err}") self.stdout = bg_out self.stderr = bg_err @@ -482,7 +482,7 @@ class SubprocessIOChunker(object): self.stop_streams() err = self.get_stderr() raise OSError( - "Subprocess exited (exit_code:{}) due to an error during iteration:\n{}".format(return_code, err)) + f"Subprocess exited (exit_code:{return_code}) due to an error during iteration:\n{err}") if stop_iteration: raise stop_iteration diff --git a/vcsserver/tweens/request_wrapper.py b/vcsserver/tweens/request_wrapper.py --- a/vcsserver/tweens/request_wrapper.py +++ b/vcsserver/tweens/request_wrapper.py @@ -103,15 +103,15 @@ class RequestWrapperTween(object): statsd.timing( "vcsserver_req_timing.histogram", elapsed_time_ms, tags=[ - "view_name:{}".format(match_route), - "code:{}".format(resp_code) + f"view_name:{match_route}", + f"code:{resp_code}" ], use_decimals=False ) statsd.incr( "vcsserver_req_total", tags=[ - "view_name:{}".format(match_route), - "code:{}".format(resp_code) + f"view_name:{match_route}", + f"code:{resp_code}" ]) return response