55import stat
66from collections import namedtuple
77from datetime import datetime , timezone , timedelta
8+ from pathlib import Path
89from time import perf_counter
910
1011from borgstore .backends .errors import PermissionDenied
@@ -63,7 +64,7 @@ def discover_files_cache_names(path, files_cache_name="files"):
6364 :param files_cache_name: base name of the files cache files
6465 :return: list of files cache file names
6566 """
66- return [fn for fn in os . listdir ( path ) if fn .startswith (files_cache_name + "." )]
67+ return [p . name for p in path . iterdir ( ) if p . name .startswith (files_cache_name + "." )]
6768
6869
6970# chunks is a list of ChunkListEntry
@@ -92,34 +93,33 @@ class SecurityManager:
9293
9394 def __init__ (self , repository ):
9495 self .repository = repository
95- self .dir = get_security_dir (repository .id_str , legacy = (repository .version == 1 ))
96- self .cache_dir = cache_dir (repository )
97- self .key_type_file = os .path .join (self .dir , "key-type" )
98- self .location_file = os .path .join (self .dir , "location" )
99- self .manifest_ts_file = os .path .join (self .dir , "manifest-timestamp" )
96+ self .dir = Path (get_security_dir (repository .id_str , legacy = (repository .version == 1 )))
97+ self .key_type_file = self .dir / "key-type"
98+ self .location_file = self .dir / "location"
99+ self .manifest_ts_file = self .dir / "manifest-timestamp"
100100
101101 @staticmethod
102102 def destroy (repository , path = None ):
103103 """destroy the security dir for ``repository`` or at ``path``"""
104104 path = path or get_security_dir (repository .id_str , legacy = (repository .version == 1 ))
105- if os . path .exists (path ):
105+ if Path ( path ) .exists ():
106106 shutil .rmtree (path )
107107
108108 def known (self ):
109- return all (os . path . exists (f ) for f in (self .key_type_file , self .location_file , self .manifest_ts_file ))
109+ return all (f . exists () for f in (self .key_type_file , self .location_file , self .manifest_ts_file ))
110110
111111 def key_matches (self , key ):
112112 if not self .known ():
113113 return False
114114 try :
115- with open ( self .key_type_file ) as fd :
115+ with self .key_type_file . open ( ) as fd :
116116 type = fd .read ()
117117 return type == str (key .TYPE )
118118 except OSError as exc :
119119 logger .warning ("Could not read/parse key type file: %s" , exc )
120120
121121 def save (self , manifest , key ):
122- logger .debug ("security: saving state for %s to %s" , self .repository .id_str , self .dir )
122+ logger .debug ("security: saving state for %s to %s" , self .repository .id_str , str ( self .dir ) )
123123 current_location = self .repository ._location .canonical_path ()
124124 logger .debug ("security: current location %s" , current_location )
125125 logger .debug ("security: key type %s" , str (key .TYPE ))
@@ -134,7 +134,7 @@ def save(self, manifest, key):
134134 def assert_location_matches (self ):
135135 # Warn user before sending data to a relocated repository
136136 try :
137- with open ( self .location_file ) as fd :
137+ with self .location_file . open ( ) as fd :
138138 previous_location = fd .read ()
139139 logger .debug ("security: read previous location %r" , previous_location )
140140 except FileNotFoundError :
@@ -167,7 +167,7 @@ def assert_location_matches(self):
167167
168168 def assert_no_manifest_replay (self , manifest , key ):
169169 try :
170- with open ( self .manifest_ts_file ) as fd :
170+ with self .manifest_ts_file . open ( ) as fd :
171171 timestamp = fd .read ()
172172 logger .debug ("security: read manifest timestamp %r" , timestamp )
173173 except FileNotFoundError :
@@ -235,15 +235,15 @@ def assert_secure(repository, manifest):
235235
236236
237237def cache_dir (repository , path = None ):
238- return path or os . path . join (get_cache_dir (), repository .id_str )
238+ return Path ( path ) if path else Path (get_cache_dir ()) / repository .id_str
239239
240240
241241class CacheConfig :
242242 def __init__ (self , repository , path = None ):
243243 self .repository = repository
244244 self .path = cache_dir (repository , path )
245245 logger .debug ("Using %s as cache" , self .path )
246- self .config_path = os . path . join ( self .path , "config" )
246+ self .config_path = self .path / "config"
247247
248248 def __enter__ (self ):
249249 self .open ()
@@ -253,7 +253,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
253253 self .close ()
254254
255255 def exists (self ):
256- return os . path .exists (self . config_path )
256+ return self . config_path .exists ()
257257
258258 def create (self ):
259259 assert not self .exists ()
@@ -272,7 +272,7 @@ def open(self):
272272
273273 def load (self ):
274274 self ._config = configparser .ConfigParser (interpolation = None )
275- with open ( self .config_path ) as fd :
275+ with self .config_path . open ( ) as fd :
276276 self ._config .read_file (fd )
277277 self ._check_upgrade (self .config_path )
278278 self .id = self ._config .get ("cache" , "repository" )
@@ -361,10 +361,10 @@ def break_lock(repository, path=None):
361361 @staticmethod
362362 def destroy (repository , path = None ):
363363 """destroy the cache for ``repository`` or at ``path``"""
364- path = path or os . path . join ( get_cache_dir (), repository . id_str )
365- config = os . path . join ( path , "config" )
366- if os . path . exists (config ):
367- os . remove ( config ) # kill config first
364+ path = cache_dir ( repository , path )
365+ config = path / "config"
366+ if config . exists ():
367+ config . unlink ( ) # kill config first
368368 shutil .rmtree (path )
369369
370370 def __new__ (
@@ -540,7 +540,7 @@ def _read_files_cache(self):
540540 msg = None
541541 try :
542542 with IntegrityCheckedFile (
543- path = os . path . join (self .path , self .files_cache_name ()),
543+ path = str (self .path / self .files_cache_name ()),
544544 write = False ,
545545 integrity_data = self .cache_config .integrity .get (self .files_cache_name ()),
546546 ) as fd :
@@ -583,7 +583,7 @@ def _write_files_cache(self, files):
583583 ttl = int (os .environ .get ("BORG_FILES_CACHE_TTL" , 2 ))
584584 files_cache_logger .debug ("FILES-CACHE-SAVE: starting..." )
585585 # TODO: use something like SaveFile here, but that didn't work due to SyncFile missing .seek().
586- with IntegrityCheckedFile (path = os . path . join (self .path , self .files_cache_name ()), write = True ) as fd :
586+ with IntegrityCheckedFile (path = str (self .path / self .files_cache_name ()), write = True ) as fd :
587587 entries = 0
588588 age_discarded = 0
589589 race_discarded = 0
@@ -983,7 +983,7 @@ def __init__(
983983 self .cache_config = CacheConfig (self .repository , self .path )
984984
985985 # Warn user before sending data to a never seen before unencrypted repository
986- if not os .path .exists (self . path ):
986+ if not self .path .exists ():
987987 self .security_manager .assert_access_unknown (warn_if_unencrypted , manifest , self .key )
988988 self .create ()
989989
@@ -1009,13 +1009,13 @@ def __exit__(self, exc_type, exc_val, exc_tb):
10091009
10101010 def create (self ):
10111011 """Create a new empty cache at `self.path`"""
1012- os . makedirs ( self .path )
1013- with open (os . path . join ( self .path , "README" ) , "w" ) as fd :
1012+ self .path . mkdir ( parents = True , exist_ok = True )
1013+ with open (self .path / "README" , "w" ) as fd :
10141014 fd .write (CACHE_README )
10151015 self .cache_config .create ()
10161016
10171017 def open (self ):
1018- if not os .path .isdir ( self . path ):
1018+ if not self .path .is_dir ( ):
10191019 raise Exception ("%s Does not look like a Borg cache" % self .path )
10201020 self .cache_config .open ()
10211021 self .cache_config .load ()
0 commit comments