##// END OF EJS Templates
py3: use "%d" for integers instead of "%s"...
Pulkit Goyal -
r36322:6d6bc544 default
parent child Browse files
Show More
@@ -1,280 +1,280 b''
1 1 # config.py - configuration parsing for Mercurial
2 2 #
3 3 # Copyright 2009 Matt Mackall <mpm@selenic.com> and others
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import errno
11 11 import os
12 12
13 13 from .i18n import _
14 14 from . import (
15 15 error,
16 16 pycompat,
17 17 util,
18 18 )
19 19
20 20 class config(object):
21 21 def __init__(self, data=None, includepaths=None):
22 22 self._data = {}
23 23 self._unset = []
24 24 self._includepaths = includepaths or []
25 25 if data:
26 26 for k in data._data:
27 27 self._data[k] = data[k].copy()
28 28 self._source = data._source.copy()
29 29 else:
30 30 self._source = util.cowdict()
31 31 def copy(self):
32 32 return config(self)
33 33 def __contains__(self, section):
34 34 return section in self._data
35 35 def hasitem(self, section, item):
36 36 return item in self._data.get(section, {})
37 37 def __getitem__(self, section):
38 38 return self._data.get(section, {})
39 39 def __iter__(self):
40 40 for d in self.sections():
41 41 yield d
42 42 def update(self, src):
43 43 self._source = self._source.preparewrite()
44 44 for s, n in src._unset:
45 45 ds = self._data.get(s, None)
46 46 if ds is not None and n in ds:
47 47 self._data[s] = ds.preparewrite()
48 48 del self._data[s][n]
49 49 del self._source[(s, n)]
50 50 for s in src:
51 51 ds = self._data.get(s, None)
52 52 if ds:
53 53 self._data[s] = ds.preparewrite()
54 54 else:
55 55 self._data[s] = util.cowsortdict()
56 56 self._data[s].update(src._data[s])
57 57 self._source.update(src._source)
58 58 def get(self, section, item, default=None):
59 59 return self._data.get(section, {}).get(item, default)
60 60
61 61 def backup(self, section, item):
62 62 """return a tuple allowing restore to reinstall a previous value
63 63
64 64 The main reason we need it is because it handles the "no data" case.
65 65 """
66 66 try:
67 67 value = self._data[section][item]
68 68 source = self.source(section, item)
69 69 return (section, item, value, source)
70 70 except KeyError:
71 71 return (section, item)
72 72
73 73 def source(self, section, item):
74 74 return self._source.get((section, item), "")
75 75 def sections(self):
76 76 return sorted(self._data.keys())
77 77 def items(self, section):
78 78 return list(self._data.get(section, {}).iteritems())
79 79 def set(self, section, item, value, source=""):
80 80 if pycompat.ispy3:
81 81 assert not isinstance(value, str), (
82 82 'config values may not be unicode strings on Python 3')
83 83 if section not in self:
84 84 self._data[section] = util.cowsortdict()
85 85 else:
86 86 self._data[section] = self._data[section].preparewrite()
87 87 self._data[section][item] = value
88 88 if source:
89 89 self._source = self._source.preparewrite()
90 90 self._source[(section, item)] = source
91 91
92 92 def restore(self, data):
93 93 """restore data returned by self.backup"""
94 94 self._source = self._source.preparewrite()
95 95 if len(data) == 4:
96 96 # restore old data
97 97 section, item, value, source = data
98 98 self._data[section] = self._data[section].preparewrite()
99 99 self._data[section][item] = value
100 100 self._source[(section, item)] = source
101 101 else:
102 102 # no data before, remove everything
103 103 section, item = data
104 104 if section in self._data:
105 105 self._data[section].pop(item, None)
106 106 self._source.pop((section, item), None)
107 107
108 108 def parse(self, src, data, sections=None, remap=None, include=None):
109 109 sectionre = util.re.compile(br'\[([^\[]+)\]')
110 110 itemre = util.re.compile(br'([^=\s][^=]*?)\s*=\s*(.*\S|)')
111 111 contre = util.re.compile(br'\s+(\S|\S.*\S)\s*$')
112 112 emptyre = util.re.compile(br'(;|#|\s*$)')
113 113 commentre = util.re.compile(br'(;|#)')
114 114 unsetre = util.re.compile(br'%unset\s+(\S+)')
115 115 includere = util.re.compile(br'%include\s+(\S|\S.*\S)\s*$')
116 116 section = ""
117 117 item = None
118 118 line = 0
119 119 cont = False
120 120
121 121 if remap:
122 122 section = remap.get(section, section)
123 123
124 124 for l in data.splitlines(True):
125 125 line += 1
126 126 if line == 1 and l.startswith('\xef\xbb\xbf'):
127 127 # Someone set us up the BOM
128 128 l = l[3:]
129 129 if cont:
130 130 if commentre.match(l):
131 131 continue
132 132 m = contre.match(l)
133 133 if m:
134 134 if sections and section not in sections:
135 135 continue
136 136 v = self.get(section, item) + "\n" + m.group(1)
137 137 self.set(section, item, v, "%s:%d" % (src, line))
138 138 continue
139 139 item = None
140 140 cont = False
141 141 m = includere.match(l)
142 142
143 143 if m and include:
144 144 expanded = util.expandpath(m.group(1))
145 145 includepaths = [os.path.dirname(src)] + self._includepaths
146 146
147 147 for base in includepaths:
148 148 inc = os.path.normpath(os.path.join(base, expanded))
149 149
150 150 try:
151 151 include(inc, remap=remap, sections=sections)
152 152 break
153 153 except IOError as inst:
154 154 if inst.errno != errno.ENOENT:
155 155 raise error.ParseError(_("cannot include %s (%s)")
156 156 % (inc, inst.strerror),
157 "%s:%s" % (src, line))
157 "%s:%d" % (src, line))
158 158 continue
159 159 if emptyre.match(l):
160 160 continue
161 161 m = sectionre.match(l)
162 162 if m:
163 163 section = m.group(1)
164 164 if remap:
165 165 section = remap.get(section, section)
166 166 if section not in self:
167 167 self._data[section] = util.cowsortdict()
168 168 continue
169 169 m = itemre.match(l)
170 170 if m:
171 171 item = m.group(1)
172 172 cont = True
173 173 if sections and section not in sections:
174 174 continue
175 175 self.set(section, item, m.group(2), "%s:%d" % (src, line))
176 176 continue
177 177 m = unsetre.match(l)
178 178 if m:
179 179 name = m.group(1)
180 180 if sections and section not in sections:
181 181 continue
182 182 if self.get(section, name) is not None:
183 183 self._data[section] = self._data[section].preparewrite()
184 184 del self._data[section][name]
185 185 self._unset.append((section, name))
186 186 continue
187 187
188 raise error.ParseError(l.rstrip(), ("%s:%s" % (src, line)))
188 raise error.ParseError(l.rstrip(), ("%s:%d" % (src, line)))
189 189
190 190 def read(self, path, fp=None, sections=None, remap=None):
191 191 if not fp:
192 192 fp = util.posixfile(path, 'rb')
193 193 assert getattr(fp, 'mode', r'rb') == r'rb', (
194 194 'config files must be opened in binary mode, got fp=%r mode=%r' % (
195 195 fp, fp.mode))
196 196 self.parse(path, fp.read(),
197 197 sections=sections, remap=remap, include=self.read)
198 198
199 199 def parselist(value):
200 200 """parse a configuration value as a list of comma/space separated strings
201 201
202 202 >>> parselist(b'this,is "a small" ,test')
203 203 ['this', 'is', 'a small', 'test']
204 204 """
205 205
206 206 def _parse_plain(parts, s, offset):
207 207 whitespace = False
208 208 while offset < len(s) and (s[offset:offset + 1].isspace()
209 209 or s[offset:offset + 1] == ','):
210 210 whitespace = True
211 211 offset += 1
212 212 if offset >= len(s):
213 213 return None, parts, offset
214 214 if whitespace:
215 215 parts.append('')
216 216 if s[offset:offset + 1] == '"' and not parts[-1]:
217 217 return _parse_quote, parts, offset + 1
218 218 elif s[offset:offset + 1] == '"' and parts[-1][-1] == '\\':
219 219 parts[-1] = parts[-1][:-1] + s[offset:offset + 1]
220 220 return _parse_plain, parts, offset + 1
221 221 parts[-1] += s[offset:offset + 1]
222 222 return _parse_plain, parts, offset + 1
223 223
224 224 def _parse_quote(parts, s, offset):
225 225 if offset < len(s) and s[offset:offset + 1] == '"': # ""
226 226 parts.append('')
227 227 offset += 1
228 228 while offset < len(s) and (s[offset:offset + 1].isspace() or
229 229 s[offset:offset + 1] == ','):
230 230 offset += 1
231 231 return _parse_plain, parts, offset
232 232
233 233 while offset < len(s) and s[offset:offset + 1] != '"':
234 234 if (s[offset:offset + 1] == '\\' and offset + 1 < len(s)
235 235 and s[offset + 1:offset + 2] == '"'):
236 236 offset += 1
237 237 parts[-1] += '"'
238 238 else:
239 239 parts[-1] += s[offset:offset + 1]
240 240 offset += 1
241 241
242 242 if offset >= len(s):
243 243 real_parts = _configlist(parts[-1])
244 244 if not real_parts:
245 245 parts[-1] = '"'
246 246 else:
247 247 real_parts[0] = '"' + real_parts[0]
248 248 parts = parts[:-1]
249 249 parts.extend(real_parts)
250 250 return None, parts, offset
251 251
252 252 offset += 1
253 253 while offset < len(s) and s[offset:offset + 1] in [' ', ',']:
254 254 offset += 1
255 255
256 256 if offset < len(s):
257 257 if offset + 1 == len(s) and s[offset:offset + 1] == '"':
258 258 parts[-1] += '"'
259 259 offset += 1
260 260 else:
261 261 parts.append('')
262 262 else:
263 263 return None, parts, offset
264 264
265 265 return _parse_plain, parts, offset
266 266
267 267 def _configlist(s):
268 268 s = s.rstrip(' ,')
269 269 if not s:
270 270 return []
271 271 parser, parts, offset = _parse_plain, [''], 0
272 272 while parser:
273 273 parser, parts, offset = parser(parts, s, offset)
274 274 return parts
275 275
276 276 if value is not None and isinstance(value, bytes):
277 277 result = _configlist(value.lstrip(' ,\n'))
278 278 else:
279 279 result = value
280 280 return result or []
General Comments 0
You need to be logged in to leave comments. Login now