simplify git remote is comma check (#31284)

* simplify git remote is comma check

* cast to str

* eliminate default and always return string

* add type annotation for cache decorator

* fix up default handling
old-commit-hash: 7affba06d8
chrysler-long2
Greg Hogan 1 year ago committed by GitHub
parent 1da217f797
commit 14e12980f5
  1. 6
      selfdrive/athena/athenad.py
  2. 2
      selfdrive/controls/controlsd.py
  3. 2
      selfdrive/controls/lib/events.py
  4. 6
      selfdrive/manager/manager.py
  5. 2
      selfdrive/sentry.py
  6. 2
      selfdrive/test/process_replay/test_processes.py
  7. 2
      selfdrive/tombstoned.py
  8. 49
      system/version.py

@ -316,9 +316,9 @@ def getMessage(service: str, timeout: int = 1000) -> dict:
def getVersion() -> Dict[str, str]: def getVersion() -> Dict[str, str]:
return { return {
"version": get_version(), "version": get_version(),
"remote": get_normalized_origin(''), "remote": get_normalized_origin(),
"branch": get_short_branch(''), "branch": get_short_branch(),
"commit": get_commit(default=''), "commit": get_commit(),
} }

@ -60,7 +60,7 @@ class Controls:
config_realtime_process(4, Priority.CTRL_HIGH) config_realtime_process(4, Priority.CTRL_HIGH)
# Ensure the current branch is cached, otherwise the first iteration of controlsd lags # Ensure the current branch is cached, otherwise the first iteration of controlsd lags
self.branch = get_short_branch("") self.branch = get_short_branch()
# Setup sockets # Setup sockets
self.pm = messaging.PubMaster(['sendcan', 'controlsState', 'carState', self.pm = messaging.PubMaster(['sendcan', 'controlsState', 'carState',

@ -224,7 +224,7 @@ def user_soft_disable_alert(alert_text_2: str) -> AlertCallbackType:
return func return func
def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert: def startup_master_alert(CP: car.CarParams, CS: car.CarState, sm: messaging.SubMaster, metric: bool, soft_disable_time: int) -> Alert:
branch = get_short_branch("") # Ensure get_short_branch is cached to avoid lags on startup branch = get_short_branch() # Ensure get_short_branch is cached to avoid lags on startup
if "REPLAY" in os.environ: if "REPLAY" in os.environ:
branch = "replay" branch = "replay"

@ -65,9 +65,9 @@ def manager_init() -> None:
params.put("Version", get_version()) params.put("Version", get_version())
params.put("TermsVersion", terms_version) params.put("TermsVersion", terms_version)
params.put("TrainingVersion", training_version) params.put("TrainingVersion", training_version)
params.put("GitCommit", get_commit(default="")) params.put("GitCommit", get_commit())
params.put("GitBranch", get_short_branch(default="")) params.put("GitBranch", get_short_branch())
params.put("GitRemote", get_origin(default="")) params.put("GitRemote", get_origin())
params.put_bool("IsTestedBranch", is_tested_branch()) params.put_bool("IsTestedBranch", is_tested_branch())
params.put_bool("IsReleaseBranch", is_release_branch()) params.put_bool("IsReleaseBranch", is_release_branch())

@ -44,7 +44,7 @@ def set_tag(key: str, value: str) -> None:
def init(project: SentryProject) -> bool: def init(project: SentryProject) -> bool:
# forks like to mess with this, so double check # forks like to mess with this, so double check
comma_remote = is_comma_remote() and "commaai" in get_origin(default="") comma_remote = is_comma_remote() and "commaai" in get_origin()
if not comma_remote or not is_registered_device() or PC: if not comma_remote or not is_registered_device() or PC:
return False return False

@ -160,7 +160,7 @@ if __name__ == "__main__":
sys.exit(1) sys.exit(1)
cur_commit = get_commit() cur_commit = get_commit()
if cur_commit is None: if not cur_commit:
raise Exception("Couldn't get current commit") raise Exception("Couldn't get current commit")
print(f"***** testing against commit {ref_commit} *****") print(f"***** testing against commit {ref_commit} *****")

@ -124,7 +124,7 @@ def report_tombstone_apport(fn):
clean_path = path.replace('/', '_') clean_path = path.replace('/', '_')
date = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S") date = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M-%S")
new_fn = f"{date}_{get_commit(default='nocommit')[:8]}_{safe_fn(clean_path)}"[:MAX_TOMBSTONE_FN_LEN] new_fn = f"{date}_{(get_commit() or 'nocommit')[:8]}_{safe_fn(clean_path)}"[:MAX_TOMBSTONE_FN_LEN]
crashlog_dir = os.path.join(Paths.log_root(), "crash") crashlog_dir = os.path.join(Paths.log_root(), "crash")
os.makedirs(crashlog_dir, exist_ok=True) os.makedirs(crashlog_dir, exist_ok=True)

@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
import subprocess import subprocess
from typing import List, Optional from typing import List, Optional, Callable, TypeVar
from functools import lru_cache from functools import lru_cache
from openpilot.common.basedir import BASEDIR from openpilot.common.basedir import BASEDIR
@ -13,8 +13,8 @@ TESTED_BRANCHES = RELEASE_BRANCHES + ['devel', 'devel-staging']
training_version: bytes = b"0.2.0" training_version: bytes = b"0.2.0"
terms_version: bytes = b"2" terms_version: bytes = b"2"
_RT = TypeVar("_RT")
def cache(user_function, /): def cache(user_function: Callable[..., _RT], /) -> Callable[..., _RT]:
return lru_cache(maxsize=None)(user_function) return lru_cache(maxsize=None)(user_function)
@ -30,41 +30,37 @@ def run_cmd_default(cmd: List[str], default: Optional[str] = None) -> Optional[s
@cache @cache
def get_commit(branch: str = "HEAD", default: Optional[str] = None) -> Optional[str]: def get_commit(branch: str = "HEAD") -> str:
return run_cmd_default(["git", "rev-parse", branch], default=default) return run_cmd_default(["git", "rev-parse", branch]) or ""
@cache @cache
def get_short_branch(default: Optional[str] = None) -> Optional[str]: def get_short_branch() -> str:
return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"], default=default) return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "HEAD"]) or ""
@cache @cache
def get_branch(default: Optional[str] = None) -> Optional[str]: def get_branch() -> str:
return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], default=default) return run_cmd_default(["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]) or ""
@cache @cache
def get_origin(default: Optional[str] = None) -> Optional[str]: def get_origin() -> str:
try: try:
local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"]) local_branch = run_cmd(["git", "name-rev", "--name-only", "HEAD"])
tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"]) tracking_remote = run_cmd(["git", "config", "branch." + local_branch + ".remote"])
return run_cmd(["git", "config", "remote." + tracking_remote + ".url"]) return run_cmd(["git", "config", "remote." + tracking_remote + ".url"])
except subprocess.CalledProcessError: # Not on a branch, fallback except subprocess.CalledProcessError: # Not on a branch, fallback
return run_cmd_default(["git", "config", "--get", "remote.origin.url"], default=default) return run_cmd_default(["git", "config", "--get", "remote.origin.url"]) or ""
@cache @cache
def get_normalized_origin(default: Optional[str] = None) -> Optional[str]: def get_normalized_origin() -> str:
origin: Optional[str] = get_origin() return get_origin() \
.replace("git@", "", 1) \
if origin is None: .replace(".git", "", 1) \
return default .replace("https://", "", 1) \
.replace(":", "/", 1)
return origin.replace("git@", "", 1) \
.replace(".git", "", 1) \
.replace("https://", "", 1) \
.replace(":", "/", 1)
@cache @cache
@ -75,7 +71,7 @@ def get_version() -> str:
@cache @cache
def get_short_version() -> str: def get_short_version() -> str:
return get_version().split('-')[0] # type: ignore return get_version().split('-')[0]
@cache @cache
def is_prebuilt() -> bool: def is_prebuilt() -> bool:
@ -86,12 +82,7 @@ def is_prebuilt() -> bool:
def is_comma_remote() -> bool: def is_comma_remote() -> bool:
# note to fork maintainers, this is used for release metrics. please do not # note to fork maintainers, this is used for release metrics. please do not
# touch this to get rid of the orange startup alert. there's better ways to do that # touch this to get rid of the orange startup alert. there's better ways to do that
origin: Optional[str] = get_origin() return get_normalized_origin() == "github.com/commaai/openpilot"
if origin is None:
return False
return origin.startswith(('git@github.com:commaai', 'https://github.com/commaai'))
@cache @cache
def is_tested_branch() -> bool: def is_tested_branch() -> bool:
@ -105,7 +96,7 @@ def is_release_branch() -> bool:
def is_dirty() -> bool: def is_dirty() -> bool:
origin = get_origin() origin = get_origin()
branch = get_branch() branch = get_branch()
if (origin is None) or (branch is None): if not origin or not branch:
return True return True
dirty = False dirty = False

Loading…
Cancel
Save