Skip to content

Commit bfa747d

Browse files
committed
Default to use cached remote index and also take repo details from
environment variables. In support of #59.
1 parent 4824b0f commit bfa747d

File tree

2 files changed

+40
-15
lines changed

2 files changed

+40
-15
lines changed

cmdebug/svd_fetcher.py

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,19 @@
2525
import json
2626
import os
2727
import dataclasses
28+
import time
29+
30+
31+
def _str_or_env(default: str, env_var: str) -> str:
32+
env = os.getenv(env_var)
33+
return default if env is None else env
34+
2835

2936
_REPO_OWNER = "cmsis-svd"
3037
_REPO_NAME = "cmsis-svd-data"
31-
_BRANCH = "main"
32-
_BASE_API_URL = f"https://api.github.com/repos/{_REPO_OWNER}/{_REPO_NAME}"
33-
_DEFAULT_CACHE_PATH = Path.home() / ".cache" / "cmsis-svd"
38+
_BRANCH = _str_or_env("main", "SVD_BRANCH")
39+
_BASE_API_URL = _str_or_env(f"https://api.github.com/repos/{_REPO_OWNER}/{_REPO_NAME}", "SVD_API_URL")
40+
_DEFAULT_CACHE_PATH = Path(_str_or_env(str(Path.home() / ".cache" / "cmsis-svd"), "SVD_CACHE_PATH"))
3441

3542
_VERBOSE = True
3643

@@ -68,6 +75,7 @@ def __init__(self, cache_dir: Optional[Path] = None):
6875
cache_dir = _DEFAULT_CACHE_PATH
6976
self.cache_dir = Path(cache_dir)
7077
self.cache_dir.mkdir(parents=True, exist_ok=True)
78+
self.cache_file = self.cache_dir / "devices.json"
7179

7280
self.session = requests.Session()
7381
# Add GitHub token if available via environment variable
@@ -76,20 +84,30 @@ def __init__(self, cache_dir: Optional[Path] = None):
7684
self.session.headers["Authorization"] = f"token {token}"
7785

7886
def save(self, vendors: Dict[str, List[RemoteSVDFile]]):
79-
cache_file = self.cache_dir / "devices.json"
80-
8187
all_tuples = [(vendor, [c.as_dict() for c in chips]) for vendor, chips in vendors.items()]
8288
serializable_dict: Dict[str, List[Dict[str, str]]] = {}
8389
for (vendor, chips) in all_tuples:
8490
serializable_dict[vendor] = chips
8591

86-
open(str(cache_file), "w").write(json.dumps(serializable_dict))
92+
open(str(self.cache_file), "w").write(json.dumps(serializable_dict))
8793

88-
def restore(self) -> Optional[Dict[str, List[RemoteSVDFile]]]:
89-
cache_file = self.cache_dir / "devices.json"
94+
def cache_age_seconds(self) -> Optional[int]:
95+
"""Get approximate time since cache file was modified
9096
91-
if cache_file.exists():
92-
raw: Dict[str, List[Dict[str, str]]] = json.loads(open(str(cache_file)).read())
97+
Returns:
98+
Optional[int]: seconds since modification or None if nonexistent
99+
"""
100+
if not self.cache_file.exists():
101+
return None
102+
mtime = os.path.getmtime(str(self.cache_file.absolute()))
103+
104+
return int(time.time() - mtime)
105+
106+
107+
def restore(self) -> Optional[Dict[str, List[RemoteSVDFile]]]:
108+
if self.cache_file.exists():
109+
_log(f"Restoring cached index from {self.cache_file}")
110+
raw: Dict[str, List[Dict[str, str]]] = json.loads(open(str(self.cache_file)).read())
93111
good_dict: Dict[str, List[RemoteSVDFile]] = dict()
94112
# Raw _should_ be dict of vendors with a list of chips under each
95113
for (vendor, chips_dicts) in raw.items():

cmdebug/svd_gdb.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@
2020
import math
2121
import sys
2222
import struct
23-
23+
import os
2424

2525
from typing import Optional, Dict, List
2626

27-
sys.path.append('.')
27+
sys.path.append(os.path.realpath(os.path.dirname(__file__) + "/.."))
2828
from cmdebug.svd import SVDFile
29-
from cmdebug import svd_fetcher
29+
from cmdebug.svd_fetcher import SVDFetcher, RemoteSVDFile
3030

3131
BITS_TO_UNPACK_FORMAT = {
3232
8: "B",
@@ -82,12 +82,19 @@ class LoadSVDRemote(gdb.Command):
8282
"""
8383

8484
def __init__(self) -> None:
85-
self.fetcher = svd_fetcher.SVDFetcher()
86-
self.vendors: Optional[Dict[str, List[svd_fetcher.RemoteSVDFile]]] = None
85+
self.fetcher = SVDFetcher()
86+
self.vendors: Optional[Dict[str, List[RemoteSVDFile]]] = None
8787

8888
gdb.Command.__init__(self, "svd_load_remote", gdb.COMMAND_USER)
8989

9090
def try_to_get_vendors(self) -> bool:
91+
MAX_DAYS = 1
92+
if self.vendors == None:
93+
# First, check if we have a fresh-enough cache file
94+
cache_age = self.fetcher.cache_age_seconds()
95+
if cache_age is not None and cache_age < (MAX_DAYS * 24 * 60 * 60):
96+
self.vendors = self.fetcher.restore()
97+
9198
if self.vendors == None:
9299
try:
93100
# Get the vendors and cache them

0 commit comments

Comments
 (0)