Mercurial > public > mercurial-scm > hg
diff mercurial/scmutil.py @ 31553:56acc4250900
scmutil: add a simple key-value file helper
The purpose of the added class is to serve purposes like save files of shelve
or state files of shelve, rebase and histedit. Keys of these files can be
alphanumeric and start with letters, while values must not contain newlines.
In light of Mercurial's reluctancy to use Python's json module, this tries
to provide a reasonable alternative for a non-nested named data.
Comparing to current approach of storing state in plain text files, where
semantic meaning of lines of text is only determined by their oreder,
simple key-value file allows for reordering lines and thus helps handle
optional values.
Initial use-case I see for this is obs-shelve's shelve files. Later we
can possibly migrate state files to this approach.
The test is in a new file beause I did not figure out where to put it
within existing test suite. If you give me a better idea, I will gladly
follow it.
author | Kostia Balytskyi <ikostia@fb.com> |
---|---|
date | Fri, 10 Mar 2017 14:33:42 -0800 |
parents | 1fc3d1f02865 |
children | 0f8ba0bc1154 |
line wrap: on
line diff
--- a/mercurial/scmutil.py Mon Mar 20 11:50:55 2017 +0900 +++ b/mercurial/scmutil.py Fri Mar 10 14:33:42 2017 -0800 @@ -965,3 +965,41 @@ """ # experimental config: format.generaldelta return ui.configbool('format', 'generaldelta', False) + +class simplekeyvaluefile(object): + """A simple file with key=value lines + + Keys must be alphanumerics and start with a letter, values must not + contain '\n' characters""" + + def __init__(self, vfs, path, keys=None): + self.vfs = vfs + self.path = path + + def read(self): + lines = self.vfs.readlines(self.path) + try: + d = dict(line[:-1].split('=', 1) for line in lines if line) + except ValueError as e: + raise error.CorruptedState(str(e)) + return d + + def write(self, data): + """Write key=>value mapping to a file + data is a dict. Keys must be alphanumerical and start with a letter. + Values must not contain newline characters.""" + lines = [] + for k, v in data.items(): + if not k[0].isalpha(): + e = "keys must start with a letter in a key-value file" + raise error.ProgrammingError(e) + if not k.isalnum(): + e = "invalid key name in a simple key-value file" + raise error.ProgrammingError(e) + if '\n' in v: + e = "invalid value in a simple key-value file" + raise error.ProgrammingError(e) + lines.append("%s=%s\n" % (k, v)) + with self.vfs(self.path, mode='wb', atomictemp=True) as fp: + fp.write(''.join(lines)) +