2525import json
2626import os
2727import 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 ():
0 commit comments