28 from .
import PosixStorage, RepositoryCfg, safeFileIo, ParentsMismatch
34 def _write(butlerLocation, cfg):
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 butlerLocation : ButlerLocation
44 The location to write the RepositoryCfg.
45 cfg : RepositoryCfg instance
46 The RepositoryCfg to be serialized.
48 def setRoot(cfg, loc):
49 loc = os.path.split(loc)[0]
50 if loc
is None or cfg.root == loc:
57 loc = butlerLocation.storage.root
58 parseRes = urllib.parse.urlparse(loc
if loc
is not None else cfg.root)
59 loc = os.path.join(parseRes.path, butlerLocation.getLocations()[0])
61 with safeFileIo.SafeLockedFileForRead(loc)
as f:
62 existingCfg = _doRead(f, parseRes.path)
63 if existingCfg == cfg:
67 if e.errno != errno.ENOENT:
70 existingCfg = _doRead(f, parseRes.path)
71 if existingCfg
is None:
72 cfgToWrite = setRoot(cfg, loc)
74 if existingCfg == cfg:
78 existingCfg.extend(cfg)
79 cfgToWrite = setRoot(existingCfg, loc)
80 except ParentsMismatch
as e:
81 raise RuntimeError(
"Can not extend existing repository cfg because: {}".format(e))
82 yaml.dump(cfgToWrite, f)
86 def _doRead(fileObject, uri):
87 """Get a persisted RepositoryCfg from an open file object.
91 fileObject : an open file object
92 the file that contains the RepositoryCfg.
94 path to the repositoryCfg
98 A RepositoryCfg instance or None
100 repositoryCfg = yaml.load(fileObject)
101 if repositoryCfg
is not None:
102 if repositoryCfg.root
is None:
103 repositoryCfg.root = uri
107 def _read(butlerLocation):
108 """Deserialize a RepositoryCfg from a location.
112 butlerLocation : ButlerLocation
113 The lcoation from which to read the RepositoryCfg.
118 The deserialized RepoistoryCfg.
123 Raised if no repositoryCfg exists at the location.
126 loc = butlerLocation.storage.root
127 fileLoc = os.path.join(loc, butlerLocation.getLocations()[0])
129 with safeFileIo.SafeLockedFileForRead(fileLoc)
as f:
130 repositoryCfg = _doRead(f, loc)
132 if e.errno != errno.ENOENT:
137 PosixStorage.registerFormatters(RepositoryCfg, _read, _write)