Skip to content

Sourcery refactored master branch#1

Open
sourcery-ai[bot] wants to merge 1 commit intomasterfrom
sourcery/master
Open

Sourcery refactored master branch#1
sourcery-ai[bot] wants to merge 1 commit intomasterfrom
sourcery/master

Conversation

@sourcery-ai
Copy link

@sourcery-ai sourcery-ai bot commented Dec 7, 2022

Branch master refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

See our documentation here.

Run Sourcery locally

Reduce the feedback loop during development by using the Sourcery editor plugin:

Review changes via command line

To manually merge these changes, make sure you're on the master branch, then run:

git fetch origin sourcery/master
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

@sourcery-ai sourcery-ai bot requested a review from JesseDeLoore December 7, 2022 21:32
Copy link
Author

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Due to GitHub API limits, only the first 60 comments can be shown.

readme = f.read()


readme = pathlib.Path(str(_ROOT / 'README.rst')).read_text()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 68-71 refactored with the following changes:

  • Simplify basic file reads with pathlib (path-read)

Comment on lines -94 to +91
if git.returncode == 0:
commitish = git.stdout.strip().decode('ascii')
else:
commitish = 'unknown'

return commitish
return git.stdout.strip().decode('ascii') if git.returncode == 0 else 'unknown'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function git_commitish refactored with the following changes:

Comment on lines -110 to +104
with open(str(filename)) as f:
content = f.read()

content = pathlib.Path(str(filename)).read_text()
version_re = r"(.*__version__\s*=\s*)'[^']+'(.*)"
repl = r"\1'{}'\2".format(self.distribution.metadata.version)
repl = f"\1'{self.distribution.metadata.version}'\2"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function VersionMixin._fix_version refactored with the following changes:

Comment on lines -184 to +179
cfile = prefix + '.c'
cfile = f'{prefix}.c'

if os.path.exists(cfile) and not self.cython_always:
extension.sources[i] = cfile
else:
if os.path.exists(cfile):
cfiles[cfile] = os.path.getmtime(cfile)
else:
cfiles[cfile] = 0
cfiles[cfile] = os.path.getmtime(cfile) if os.path.exists(cfile) else 0
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function build_ext.finalize_options refactored with the following changes:

Comment on lines -35 to +44
username = '@{}'.format(commit['author']['login'])
username = f"@{commit['author']['login']}"
else:
username = commit['commit']['author']['name']
sha = commit["sha"][:8]

m = re.search(r'\#(?P<num>\d+)\b', message)
if m:
issue_num = m.group('num')
else:
issue_num = None

issue_num = (
m['num']
if (m := re.search(r'\#(?P<num>\d+)\b', message))
else None
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

Comment on lines -413 to +402
if not self._pg_bin_dir:
raise ClusterError(
'pg_config output did not provide the BINDIR value')
if not self._pg_bin_dir:
raise ClusterError(
'pg_config output did not provide the BINDIR value')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cluster._init_env refactored with the following changes:

Comment on lines -443 to +432
sockdir = lines[4]
hostaddr = lines[5]

if sockdir:
if sockdir := lines[4]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cluster._connection_addr_from_pidfile refactored with the following changes:

Comment on lines -473 to +459
for i in range(timeout):
for _ in range(timeout):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cluster._test_connection refactored with the following changes:

Comment on lines -512 to +505
else:
config = {}
config = {}

for line in stdout.splitlines():
k, eq, v = line.decode('utf-8').partition('=')
if eq:
config[k.strip().lower()] = v.strip()
for line in stdout.splitlines():
k, eq, v = line.decode('utf-8').partition('=')
if eq:
config[k.strip().lower()] = v.strip()

return config
return config
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cluster._run_pg_config refactored with the following changes:

Comment on lines -524 to +511
pg_install = (
os.environ.get('PGINSTALLATION')
or os.environ.get('PGBIN')
)
if pg_install:
if pg_install := (
os.environ.get('PGINSTALLATION') or os.environ.get('PGBIN')
):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cluster._find_pg_config refactored with the following changes:

Comment on lines -555 to +542
'could not find {} executable: '.format(binary) +
'{!r} does not exist or is not a file'.format(bpath))
(
f'could not find {binary} executable: '
+ '{!r} does not exist or is not a file'.format(bpath)
)
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Cluster._find_pg_binary refactored with the following changes:

Comment on lines -28 to +30
r = ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, buf)
if r:
if r := ctypes.windll.shell32.SHGetFolderPathW(
0, CSIDL_APPDATA, 0, 0, buf
):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_pg_home_directory refactored with the following changes:

PGPASSFILE = 'pgpass.conf'
else:
PGPASSFILE = '.pgpass'
PGPASSFILE = 'pgpass.conf' if _system == 'Windows' else '.pgpass'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 75-78 refactored with the following changes:

Comment on lines -81 to +78
def _read_password_file(passfile: pathlib.Path) \
-> typing.List[typing.Tuple[str, ...]]:
def _read_password_file(passfile: pathlib.Path) -> typing.List[typing.Tuple[str, ...]]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _read_password_file refactored with the following changes:

Comment on lines -146 to +149
if phost != '*' and phost != host:
if phost not in ['*', host]:
continue
if pport != '*' and pport != str(port):
if pport not in ['*', str(port)]:
continue
if pdatabase != '*' and pdatabase != database:
if pdatabase not in ['*', database]:
continue
if puser != '*' and puser != user:
if puser not in ['*', user]:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _read_password_from_pgpass refactored with the following changes:

  • Replace multiple comparisons of same variable with in operator [×4] (merge-comparisons)

Comment on lines -743 to +737
tabname = utils._quote_ident(schema_name) + '.' + tabname
tabname = f'{utils._quote_ident(schema_name)}.{tabname}'

if columns:
cols = '({})'.format(
', '.join(utils._quote_ident(c) for c in columns))
cols = f"({', '.join(utils._quote_ident(c) for c in columns)})"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection.copy_from_table refactored with the following changes:

Comment on lines -879 to +872
tabname = utils._quote_ident(schema_name) + '.' + tabname
tabname = f'{utils._quote_ident(schema_name)}.{tabname}'

if columns:
cols = '({})'.format(
', '.join(utils._quote_ident(c) for c in columns))
cols = f"({', '.join(utils._quote_ident(c) for c in columns)})"
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection.copy_to_table refactored with the following changes:

Comment on lines -965 to +958
tabname = utils._quote_ident(schema_name) + '.' + tabname
tabname = f'{utils._quote_ident(schema_name)}.{tabname}'

if columns:
col_list = ', '.join(utils._quote_ident(c) for c in columns)
cols = '({})'.format(col_list)
cols = f'({col_list})'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection.copy_records_to_table refactored with the following changes:

Comment on lines -1009 to +1000
opts.append('{} {}'.format(k.upper(), v))
opts.append(f'{k.upper()} {v}')

if opts:
return '(' + ', '.join(opts) + ')'
else:
return ''
return '(' + ', '.join(opts) + ')' if opts else ''
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection._format_copy_opts refactored with the following changes:

Comment on lines -1225 to +1212
'cannot use custom codec on non-scalar type {}.{}'.format(
schema, typename))
f'cannot use custom codec on non-scalar type {schema}.{typename}'
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection.set_type_codec refactored with the following changes:

Comment on lines -1304 to +1291
'cannot alias non-scalar type {}.{}'.format(
schema, typename))
f'cannot alias non-scalar type {schema}.{typename}'
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection.set_builtin_type_codec refactored with the following changes:

Comment on lines -1516 to +1502
if self._proxy is None:
con_ref = self
else:
# `_proxy` is not None when the connection is a member
# of a connection pool. Which means that the user is working
# with a `PoolConnectionProxy` instance, and expects to see it
# (and not the actual Connection) in their event callbacks.
con_ref = self._proxy
return con_ref
return self if self._proxy is None else self._proxy
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Connection._unwrap refactored with the following changes:

This removes the following comments ( why? ):

# of a connection pool.  Which means that the user is working
# with a `PoolConnectionProxy` instance, and expects to see it
# `_proxy` is not None when the connection is a member
# (and not the actual Connection) in their event callbacks.

Comment on lines -2323 to -2331
elif hasattr(connection_settings, 'crdb_version'):
elif hasattr(connection_settings, 'crdb_version') or hasattr(
connection_settings, 'crate_version'
):
# CockroachDB detected.
advisory_locks = False
notifications = False
plpgsql = False
sql_reset = False
sql_close_all = False
elif hasattr(connection_settings, 'crate_version'):
# CrateDB detected.
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _detect_server_capabilities refactored with the following changes:

This removes the following comments ( why? ):

# CrateDB detected.

Comment on lines -36 to +42
'cannot call {}.{}(): '
'the underlying connection has been released back '
'to the pool'.format(self.__class__.__name__, meth_name))
f'cannot call {self.__class__.__name__}.{meth_name}(): the underlying connection has been released back to the pool'
)

if self._connection.is_closed():
raise exceptions.InterfaceError(
'cannot call {}.{}(): '
'the underlying connection is closed'.format(
self.__class__.__name__, meth_name))
f'cannot call {self.__class__.__name__}.{meth_name}(): the underlying connection is closed'
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ConnectionResource._check_conn_validity refactored with the following changes:

Comment on lines -144 to +146
buffer = await protocol.bind(self._state, self._args,
self._portal_name,
timeout)
return buffer
return await protocol.bind(
self._state, self._args, self._portal_name, timeout
)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BaseCursor._bind refactored with the following changes:

Comment on lines -192 to +188
if self._nested:
query = 'ROLLBACK TO {};'.format(self._id)
else:
query = 'ROLLBACK;'

query = f'ROLLBACK TO {self._id};' if self._nested else 'ROLLBACK;'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Transaction.__rollback refactored with the following changes:

Comment on lines -222 to +214
attrs = []
attrs.append('state:{}'.format(self._state.name.lower()))

attrs = [f'state:{self._state.name.lower()}']
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Transaction.__repr__ refactored with the following changes:

Comment on lines -125 to +141
if not isinstance(other, Range):
return NotImplemented

return (
self._lower,
self._upper,
self._lower_inc,
self._upper_inc,
self._empty
) == (
other._lower,
other._upper,
other._lower_inc,
other._upper_inc,
other._empty
(
self._lower,
self._upper,
self._lower_inc,
self._upper_inc,
self._empty,
)
== (
other._lower,
other._upper,
other._lower_inc,
other._upper_inc,
other._empty,
)
if isinstance(other, Range)
else NotImplemented
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Range.__eq__ refactored with the following changes:

Comment on lines -155 to +166
if self._lower is None or not self._lower_inc:
lb = '('
else:
lb = '['

lb = '(' if self._lower is None or not self._lower_inc else '['
if self._lower is not None:
lb += repr(self._lower)

if self._upper is not None:
ub = repr(self._upper)
else:
ub = ''

if self._upper is None or not self._upper_inc:
ub += ')'
else:
ub += ']'

desc = '{}, {}'.format(lb, ub)
ub = (repr(self._upper) if self._upper is not None else '') + (
')' if self._upper is None or not self._upper_inc else ']'
)
desc = f'{lb}, {ub}'

return '<Range {}>'.format(desc)
return f'<Range {desc}>'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Range.__repr__ refactored with the following changes:


def _quote_ident(ident):
return '"{}"'.format(ident.replace('"', '""'))
return f""""{ident.replace('"', '""')}\""""
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _quote_ident refactored with the following changes:

@sourcery-ai
Copy link
Author

sourcery-ai bot commented Dec 7, 2022

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 0.07%.

Quality metrics Before After Change
Complexity 14.86 🙂 14.82 🙂 -0.04 👍
Method Length 76.11 🙂 75.92 🙂 -0.19 👍
Working memory 6.57 🙂 6.62 🙂 0.05 👎
Quality 68.57% 🙂 68.64% 🙂 0.07% 👍
Other metrics Before After Change
Lines 13335 13179 -156
Changed files Quality Before Quality After Quality Change
setup.py 55.66% 🙂 55.60% 🙂 -0.06% 👎
.github/release_log.py 59.60% 🙂 55.53% 🙂 -4.07% 👎
asyncpg/cluster.py 66.78% 🙂 67.10% 🙂 0.32% 👍
asyncpg/compat.py 91.17% ⭐ 90.42% ⭐ -0.75% 👎
asyncpg/connect_utils.py 28.75% 😞 28.55% 😞 -0.20% 👎
asyncpg/connection.py 71.74% 🙂 71.80% 🙂 0.06% 👍
asyncpg/connresource.py 88.55% ⭐ 86.22% ⭐ -2.33% 👎
asyncpg/cursor.py 79.86% ⭐ 79.87% ⭐ 0.01% 👍
asyncpg/pool.py 74.40% 🙂 74.40% 🙂 0.00%
asyncpg/prepared_stmt.py 85.79% ⭐ 86.97% ⭐ 1.18% 👍
asyncpg/transaction.py 71.26% 🙂 70.40% 🙂 -0.86% 👎
asyncpg/types.py 77.30% ⭐ 78.64% ⭐ 1.34% 👍
asyncpg/utils.py 70.38% 🙂 70.61% 🙂 0.23% 👍
asyncpg/_testbase/__init__.py 81.66% ⭐ 81.57% ⭐ -0.09% 👎
asyncpg/_testbase/fuzzer.py 77.88% ⭐ 78.14% ⭐ 0.26% 👍
asyncpg/exceptions/_base.py 79.50% ⭐ 79.00% ⭐ -0.50% 👎
tests/__init__.py 93.12% ⭐ 94.73% ⭐ 1.61% 👍
tests/test__environment.py 83.15% ⭐ 83.04% ⭐ -0.11% 👎
tests/test__sourcecode.py 80.94% ⭐ 81.06% ⭐ 0.12% 👍
tests/test_codecs.py 63.17% 🙂 63.24% 🙂 0.07% 👍
tests/test_connect.py 71.76% 🙂 71.82% 🙂 0.06% 👍
tests/test_copy.py 76.10% ⭐ 76.77% ⭐ 0.67% 👍
tests/test_cursor.py 78.85% ⭐ 78.87% ⭐ 0.02% 👍
tests/test_execute.py 82.89% ⭐ 83.03% ⭐ 0.14% 👍
tests/test_listeners.py 66.98% 🙂 66.95% 🙂 -0.03% 👎
tests/test_prepare.py 79.51% ⭐ 79.56% ⭐ 0.05% 👍
tests/test_record.py 74.48% 🙂 74.42% 🙂 -0.06% 👎
tests/test_timeout.py 80.64% ⭐ 80.64% ⭐ 0.00%
tests/test_types.py 57.24% 🙂 57.16% 🙂 -0.08% 👎
tests/test_utils.py 84.48% ⭐ 84.57% ⭐ 0.09% 👍
tests/certs/gen.py 65.49% 🙂 65.42% 🙂 -0.07% 👎
tools/generate_exceptions.py 22.89% ⛔ 24.20% ⛔ 1.31% 👍
tools/generate_type_map.py 66.68% 🙂 66.68% 🙂 0.00%

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
asyncpg/connect_utils.py _parse_connect_dsn_and_args 276 ⛔ 1309 ⛔ 27 ⛔ 1.40% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
tools/generate_exceptions.py main 41 ⛔ 412 ⛔ 9.63% ⛔ Refactor to reduce nesting. Try splitting into smaller methods
tests/test_codecs.py TestCodecs.test_standard_codecs 47 ⛔ 290 ⛔ 13 😞 18.77% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
asyncpg/connect_utils.py _parse_hostlist 31 😞 205 ⛔ 17 ⛔ 23.70% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
asyncpg/cluster.py Cluster.start 25 😞 376 ⛔ 13 😞 25.03% 😞 Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request.


Please see our documentation here for details on how these metrics are calculated.

We are actively working on this report - lots more documentation and extra metrics to come!

Help us improve this quality report!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants