Skip to content

Commit

Permalink
Merge commit 'b659b9adcdb70151cdba2ebb9e8c4c56e1fe71a2' into fix-sv-n…
Browse files Browse the repository at this point in the history
…orm-type
  • Loading branch information
Eugene-ISG committed Sep 4, 2024
2 parents 41b9a4a + b659b9a commit e22f008
Show file tree
Hide file tree
Showing 24 changed files with 459 additions and 273 deletions.
8 changes: 6 additions & 2 deletions .github/workflows/python-cicd-units.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
python-version: ["3.9", "3.10", "3.11", "3.12"]

steps:
- uses: actions/checkout@v2
- name: Set up Python 3.12
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: "3.12"
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
Expand Down
3 changes: 2 additions & 1 deletion gnssanalysis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@
)

from . import _version
__version__ = _version.get_versions()['version']

__version__ = _version.get_versions()["version"]
143 changes: 79 additions & 64 deletions gnssanalysis/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
Expand Down Expand Up @@ -68,12 +67,14 @@ class NotThisMethod(Exception):

def register_vcs_handler(vcs: str, method: str) -> Callable: # decorator
"""Create decorator to mark a method as the handler of a VCS."""

def decorate(f: Callable) -> Callable:
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f

return decorate


Expand All @@ -100,10 +101,14 @@ def run_command(
try:
dispcmd = str([command] + args)
# remember shell=False, so use git.cmd on windows, not just git
process = subprocess.Popen([command] + args, cwd=cwd, env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None), **popen_kwargs)
process = subprocess.Popen(
[command] + args,
cwd=cwd,
env=env,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
**popen_kwargs,
)
break
except OSError as e:
if e.errno == errno.ENOENT:
Expand Down Expand Up @@ -141,15 +146,18 @@ def versions_from_parentdir(
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}
return {
"version": dirname[len(parentdir_prefix) :],
"full-revisionid": None,
"dirty": False,
"error": None,
"date": None,
}
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("Tried directories %s but none started with prefix %s" % (str(rootdirs), parentdir_prefix))
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")


Expand Down Expand Up @@ -212,7 +220,7 @@ def git_versions_from_keywords(
# 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 = {r[len(TAG):] for r in refs if r.startswith(TAG)}
tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
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 @@ -221,41 +229,43 @@ def git_versions_from_keywords(
# 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 = {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))
if verbose:
print("likely tags: %s" % ",".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):]
r = ref[len(tag_prefix) :]
# Filter out refs that exactly match prefix or that don't start
# with a number once the prefix is stripped (mostly a concern
# when prefix is '')
if not re.match(r'\d', r):
if not re.match(r"\d", r):
continue
if verbose:
print("picking %s" % r)
return {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None,
"date": date}
return {
"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": None,
"date": date,
}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags", "date": None}
return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
"date": None,
}


@register_vcs_handler("git", "pieces_from_vcs")
def git_pieces_from_vcs(
tag_prefix: str,
root: str,
verbose: bool,
runner: Callable = run_command
) -> Dict[str, Any]:
def git_pieces_from_vcs(tag_prefix: str, root: str, verbose: bool, runner: Callable = run_command) -> Dict[str, Any]:
"""Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
Expand All @@ -273,19 +283,17 @@ def git_pieces_from_vcs(
env.pop("GIT_DIR", None)
runner = functools.partial(runner, env=env)

_, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root,
hide_stderr=not verbose)
_, rc = runner(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=not verbose)
if rc != 0:
if verbose:
print("Directory %s not under git control" % root)
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 = runner(GITS, [
"describe", "--tags", "--dirty", "--always", "--long",
"--match", f"{tag_prefix}[[:digit:]]*"
], cwd=root)
describe_out, rc = runner(
GITS, ["describe", "--tags", "--dirty", "--always", "--long", "--match", f"{tag_prefix}[[:digit:]]*"], cwd=root
)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
Expand All @@ -300,8 +308,7 @@ def git_pieces_from_vcs(
pieces["short"] = full_out[:7] # maybe improved later
pieces["error"] = None

branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
branch_name, rc = runner(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
# --abbrev-ref was added in git-1.6.3
if rc != 0 or branch_name is None:
raise NotThisMethod("'git rev-parse --abbrev-ref' returned error")
Expand Down Expand Up @@ -341,17 +348,16 @@ def git_pieces_from_vcs(
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
git_describe = git_describe[: git_describe.rindex("-dirty")]

# now we have TAG-NUM-gHEX or HEX

if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
if not mo:
# unparsable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
return pieces

# tag
Expand All @@ -360,10 +366,9 @@ def git_pieces_from_vcs(
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))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
pieces["closest-tag"] = full_tag[len(tag_prefix) :]

# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
Expand Down Expand Up @@ -412,8 +417,7 @@ def render_pep440(pieces: Dict[str, Any]) -> str:
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
Expand Down Expand Up @@ -442,8 +446,7 @@ def render_pep440_branch(pieces: Dict[str, Any]) -> str:
rendered = "0"
if pieces["branch"] != "master":
rendered += ".dev0"
rendered += "+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
rendered += "+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
Expand Down Expand Up @@ -604,11 +607,13 @@ def render_git_describe_long(pieces: Dict[str, Any]) -> str:
def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None}
return {
"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
"date": None,
}

if not style or style == "default":
style = "pep440" # the default
Expand All @@ -632,9 +637,13 @@ def render(pieces: Dict[str, Any], style: str) -> Dict[str, Any]:
else:
raise ValueError("unknown style '%s'" % style)

return {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None,
"date": pieces.get("date")}
return {
"version": rendered,
"full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
"date": pieces.get("date"),
}


def get_versions() -> Dict[str, Any]:
Expand All @@ -648,8 +657,7 @@ def get_versions() -> Dict[str, Any]:
verbose = cfg.verbose

try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
except NotThisMethod:
pass

Expand All @@ -658,13 +666,16 @@ def get_versions() -> Dict[str, Any]:
# 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 _ in cfg.versionfile_source.split('/'):
for _ in cfg.versionfile_source.split("/"):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
"date": None}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
"date": None,
}

try:
pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)
Expand All @@ -678,6 +689,10 @@ def get_versions() -> Dict[str, Any]:
except NotThisMethod:
pass

return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version", "date": None}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to compute version",
"date": None,
}
16 changes: 16 additions & 0 deletions gnssanalysis/enum_meta_properties.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class EnumMetaProperties(type):
"""
This metaclass:
- intercepts attempts to set *class* attributes, and rejects them.
- NOTE: In the class or abstract class using this, you should also define an __init__() which raises
an exception, to prevent instantiation.
- defines the class string representation as being *just* the class name, without any fluff.
Loosely based on carefully reviewed AI generated examples from Microsoft Copilot.
"""

def __setattr__(cls, name: str, value) -> None:
raise AttributeError(f"Attributes of {cls} act as constants. Do not modify them.")

def __repr__(cls) -> str:
return f"{cls.__name__}"
29 changes: 14 additions & 15 deletions gnssanalysis/filenames.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,21 +407,20 @@ def convert_nominal_span(nominal_span: str) -> datetime.timedelta:
"""
span = int(nominal_span[0:2])
unit = nominal_span[2].upper()
if unit == "S":
return datetime.timedelta(seconds=span)
elif unit == "M":
return datetime.timedelta(minutes=span)
elif unit == "H":
return datetime.timedelta(hours=span)
elif unit == "D":
return datetime.timedelta(days=span)
elif unit == "W":
return datetime.timedelta(weeks=span)
elif unit == "L":
return datetime.timedelta(days=span * 28)
elif unit == "Y":
return datetime.timedelta(days=span * 365)
else:
unit_to_timedelta_args = {
"S": {"seconds": 1},
"M": {"minutes": 1},
"H": {"hours": 1},
"D": {"days": 1},
"W": {"weeks": 1},
"L": {"days": 28},
"Y": {"days": 365},
}
try:
timedelta_args = unit_to_timedelta_args[unit]
return datetime.timedelta(**{k: v * span for k, v in timedelta_args.items()})
except KeyError:
logging.warning("Time unit '%s' not understood", unit)
return datetime.timedelta()


Expand Down
Loading

0 comments on commit e22f008

Please sign in to comment.