28 from .
import PosixStorage, RepositoryCfg, safeFileIo, ParentsMismatch
34 def write(cls, cfg, butlerLocation):
35 """Serialize a RepositoryCfg to a location.
37 When the location is the same as cfg.root, the RepositoryCfg is to be written at the root location of
38 the repository. In that case, root is not written in the serialized cfg; it is implicit in the
39 location of the cfg. This allows the cfg to move from machine to machine without modification.
43 cfg : RepositoryCfg instance
44 The RepositoryCfg to be serialized.
45 butlerLocation : ButlerLocation
46 The location to write the RepositoryCfg.
48 def setRoot(cfg, loc):
49 loc = os.path.split(loc)[0]
50 if loc
is None or cfg.root == loc:
58 loc = butlerLocation.storage.root
59 parseRes = urllib.parse.urlparse(loc
if loc
is not None else cfg.root)
60 loc = os.path.join(parseRes.path, butlerLocation.getLocations()[0])
62 with safeFileIo.SafeLockedFileForRead(loc)
as f:
63 existingCfg = RepositoryCfgPosixFormatter._read(f, parseRes.path)
64 if existingCfg == cfg:
68 if e.errno != errno.ENOENT:
71 existingCfg = RepositoryCfgPosixFormatter._read(f, parseRes.path)
72 if existingCfg
is None:
73 cfgToWrite = setRoot(cfg, loc)
75 if existingCfg == cfg:
79 existingCfg.extend(cfg)
80 cfgToWrite = setRoot(existingCfg, loc)
81 except ParentsMismatch
as e:
82 raise RuntimeError(
"Can not extend existing repository cfg because: {}".format(e))
83 yaml.dump(cfgToWrite, f)
87 def _read(cls, fileObject, uri):
88 """Get a persisted RepositoryCfg from an open file object.
92 fileObject : an open file object
93 the file that contains the RepositoryCfg.
97 A RepositoryCfg instance or None
99 repositoryCfg = yaml.load(fileObject)
100 if repositoryCfg
is not None:
101 if repositoryCfg.root
is None:
102 repositoryCfg.root = uri
108 loc = butlerLocation.storage.root
109 fileLoc = os.path.join(loc, butlerLocation.getLocations()[0])
111 with safeFileIo.SafeLockedFileForRead(fileLoc)
as f:
112 repositoryCfg = RepositoryCfgPosixFormatter._read(f, loc)
114 if e.errno != errno.ENOENT:
119 PosixStorage.registerFormatter(RepositoryCfg, RepositoryCfgPosixFormatter)