Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery refactored master branch #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 59 additions & 71 deletions aotools/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ def get_keywords():
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
git_date = "$Format:%ci$"
keywords = {"refnames": git_refnames, "full": git_full, "date": git_date}
return keywords
return {"refnames": git_refnames, "full": git_full, "date": git_date}
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_keywords refactored with the following changes:



class VersioneerConfig:
Expand Down Expand Up @@ -86,20 +85,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % dispcmd)
print(f"unable to run {dispcmd}")
print(e)
return None, None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print(f"unable to find command, tried {commands}")
return None, None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % dispcmd)
print("stdout was %s" % stdout)
print(f"unable to run {dispcmd} (error)")
print(f"stdout was {stdout}")
Comment on lines -89 to +101
Copy link
Author

Choose a reason for hiding this comment

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

Function run_command refactored with the following changes:

return None, p.returncode
return stdout, p.returncode

Expand All @@ -113,19 +112,19 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
"""
rootdirs = []

for i in range(3):
for _ in range(3):
dirname = os.path.basename(root)
if dirname.startswith(parentdir_prefix):
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None, "date": None}
else:
rootdirs.append(root)
root = os.path.dirname(root) # up a level
rootdirs.append(root)
root = os.path.dirname(root) # up a level

if verbose:
print("Tried directories %s but none started with prefix %s" %
(str(rootdirs), parentdir_prefix))
print(
f"Tried directories {rootdirs} but none started with prefix {parentdir_prefix}"
)
Comment on lines -116 to +127
Copy link
Author

Choose a reason for hiding this comment

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

Function versions_from_parentdir refactored with the following changes:

raise NotThisMethod("rootdir doesn't start with parentdir_prefix")


Expand All @@ -138,21 +137,17 @@ def git_get_keywords(versionfile_abs):
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
if line.strip().startswith("git_date ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["date"] = mo.group(1)
f.close()
with open(versionfile_abs, "r") as f:
for line in f:
if line.strip().startswith("git_refnames ="):
if mo := re.search(r'=\s*"(.*)"', line):
keywords["refnames"] = mo[1]
if line.strip().startswith("git_full ="):
if mo := re.search(r'=\s*"(.*)"', line):
keywords["full"] = mo[1]
if line.strip().startswith("git_date ="):
if mo := re.search(r'=\s*"(.*)"', line):
keywords["date"] = mo[1]
Comment on lines -141 to +150
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_get_keywords refactored with the following changes:

except EnvironmentError:
pass
return keywords
Expand All @@ -177,11 +172,11 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
if verbose:
print("keywords are unexpanded, not using")
raise NotThisMethod("unexpanded keywords, not a git-archive tarball")
refs = set([r.strip() for r in refnames.strip("()").split(",")])
refs = {r.strip() for r in refnames.strip("()").split(",")}
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
Comment on lines -180 to +179
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_versions_from_keywords refactored with the following changes:

if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
Expand All @@ -190,17 +185,17 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
tags = {r for r in refs if re.search(r'\d', r)}
if verbose:
print("discarding '%s', no digits" % ",".join(refs - tags))
print(f"""discarding '{",".join(refs - tags)}', no digits""")
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
print(f'likely tags: {",".join(sorted(tags))}')
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
print(f"picking {r}")
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
Expand All @@ -221,23 +216,29 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree.
"""
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]

GITS = ["git.cmd", "git.exe"] if sys.platform == "win32" else ["git"]
out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root,
hide_stderr=True)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
print(f"Directory {root} not under git control")
raise NotThisMethod("'git rev-parse --git-dir' returned error")

# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
describe_out, rc = run_command(
GITS,
[
"describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
f"{tag_prefix}*",
],
cwd=root,
)
Comment on lines -224 to +241
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_pieces_from_vcs refactored with the following changes:

This removes the following comments ( why? ):

# maybe improved later

# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
Expand All @@ -247,11 +248,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
raise NotThisMethod("'git rev-parse' failed")
full_out = full_out.strip()

pieces = {}
pieces["long"] = full_out
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None

pieces = {"long": full_out, "short": full_out[:7], "error": None}
# parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]
# TAG might have hyphens.
git_describe = describe_out
Expand All @@ -269,26 +266,23 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = f"unable to parse git-describe output: '{describe_out}'"
return pieces

# tag
full_tag = mo.group(1)
full_tag = mo[1]
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
print(f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'")
pieces["error"] = f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]

# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
pieces["distance"] = int(mo[2])

# commit: short hex revision ID
pieces["short"] = mo.group(3)
pieces["short"] = mo[3]

else:
# HEX: no tags
Expand All @@ -307,9 +301,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):

def plus_or_dot(pieces):
"""Return a + if we don't already have one, else return a ."""
if "+" in pieces.get("closest-tag", ""):
return "."
return "+"
return "." if "+" in pieces.get("closest-tag", "") else "+"
Comment on lines -310 to +304
Copy link
Author

Choose a reason for hiding this comment

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

Function plus_or_dot refactored with the following changes:



def render_pep440(pieces):
Expand All @@ -326,14 +318,12 @@ def render_pep440(pieces):
if pieces["distance"] or pieces["dirty"]:
rendered += plus_or_dot(pieces)
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
if pieces["dirty"]:
rendered += ".dirty"
Comment on lines -329 to +326
Copy link
Author

Choose a reason for hiding this comment

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

Function render_pep440 refactored with the following changes:

return rendered


Expand Down Expand Up @@ -370,13 +360,13 @@ def render_pep440_post(pieces):
if pieces["dirty"]:
rendered += ".dev0"
rendered += plus_or_dot(pieces)
rendered += "g%s" % pieces["short"]
rendered += f'g{pieces["short"]}'
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
rendered += "+g%s" % pieces["short"]
rendered += f'+g{pieces["short"]}'
Comment on lines -373 to +369
Copy link
Author

Choose a reason for hiding this comment

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

Function render_pep440_post refactored with the following changes:

return rendered


Expand All @@ -392,13 +382,11 @@ def render_pep440_old(pieces):
rendered = pieces["closest-tag"]
if pieces["distance"] or pieces["dirty"]:
rendered += ".post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
else:
# exception #1
rendered = "0.post%d" % pieces["distance"]
if pieces["dirty"]:
rendered += ".dev0"
if pieces["dirty"]:
rendered += ".dev0"
Comment on lines -395 to +389
Copy link
Author

Choose a reason for hiding this comment

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

Function render_pep440_old refactored with the following changes:

return rendered


Expand Down Expand Up @@ -467,7 +455,7 @@ def render(pieces, style):
elif style == "git-describe-long":
rendered = render_git_describe_long(pieces)
else:
raise ValueError("unknown style '%s'" % style)
raise ValueError(f"unknown style '{style}'")
Comment on lines -470 to +458
Copy link
Author

Choose a reason for hiding this comment

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

Function render refactored with the following changes:


return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
Expand Down Expand Up @@ -495,7 +483,7 @@ def get_versions():
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
for _ in cfg.versionfile_source.split('/'):
Comment on lines -498 to +486
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_versions refactored with the following changes:

root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
Expand Down
10 changes: 3 additions & 7 deletions aotools/astronomy/_astronomy.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def photons_per_mag(mag, mask, pixel_scale, wvlBand, exposure_time):

photonPerSec = photonPerSecPerArea * area

photons = float(photonPerSec * exposure_time)

return photons
return float(photonPerSec * exposure_time)
Copy link
Author

Choose a reason for hiding this comment

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

Function photons_per_mag refactored with the following changes:



def photons_per_band(mag, mask, pxlScale, expTime, waveband='V'):
Expand Down Expand Up @@ -88,8 +86,7 @@ def magnitude_to_flux(magnitude, waveband='V'):
"""

flux_Jy = FLUX_DICTIONARY[waveband][2] * 10 ** (-0.4 * magnitude)
flux_photons = flux_Jy * 1.51E7 * FLUX_DICTIONARY[waveband][1] # photons sec^-1 m^-2
return flux_photons
return flux_Jy * 1.51E7 * FLUX_DICTIONARY[waveband][1]
Comment on lines -91 to +89
Copy link
Author

Choose a reason for hiding this comment

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

Function magnitude_to_flux refactored with the following changes:

This removes the following comments ( why? ):

# photons sec^-1 m^-2



def flux_to_magnitude(flux, waveband='V'):
Expand All @@ -105,5 +102,4 @@ def flux_to_magnitude(flux, waveband='V'):
"""

flux_Jy = flux / (1.51E7 * FLUX_DICTIONARY[waveband][1])
magnitude = float(-2.5 * numpy.log10(flux_Jy / FLUX_DICTIONARY[waveband][2]))
return magnitude
return float(-2.5 * numpy.log10(flux_Jy / FLUX_DICTIONARY[waveband][2]))
Loading
Loading