##// END OF EJS Templates
ui: trusted_users -> _trustusers, trusted_groups -> _trustgroups
Matt Mackall -
r8201:7cf2b987 default
parent child Browse files
Show More
@@ -1,351 +1,350
1 1 # ui.py - user interface bits for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from i18n import _
9 9 import errno, getpass, os, re, socket, sys, tempfile
10 10 import config, traceback, util, error
11 11
12 12 _booleans = {'1':True, 'yes':True, 'true':True, 'on':True,
13 13 '0':False, 'no':False, 'false':False, 'off':False}
14 14
15 15 class ui(object):
16 16 def __init__(self, src=None):
17 17 self.buffers = []
18 18 self.quiet = self.verbose = self.debugflag = self.traceback = False
19 19 self.interactive = self.report_untrusted = True
20 20 self.overlay = config.config()
21 21 self.cdata = config.config()
22 22 self.ucdata = config.config()
23 self.trusted_users = {}
24 self.trusted_groups = {}
23 self._trustusers = {}
24 self._trustgroups = {}
25 25
26 26 if src:
27 27 self.cdata = src.cdata.copy()
28 28 self.ucdata = src.ucdata.copy()
29 29 self.overlay = src.overlay.copy()
30 self.trusted_users = src.trusted_users.copy()
31 self.trusted_groups = src.trusted_groups.copy()
30 self._trustusers = src._trustusers.copy()
31 self._trustgroups = src._trustgroups.copy()
32 32 self.fixconfig()
33 33 else:
34 34 # we always trust global config files
35 35 for f in util.rcpath():
36 36 self.readconfig(f, trust=True)
37 37 def copy(self):
38 38 return ui(self)
39 39
40 40 _isatty = None
41 41 def isatty(self):
42 42 if ui._isatty is None:
43 43 try:
44 44 ui._isatty = sys.stdin.isatty()
45 45 except AttributeError: # not a real file object
46 46 ui._isatty = False
47 47 except IOError:
48 48 # access to stdin is unsafe in a WSGI environment
49 49 ui._isatty = False
50 50 return ui._isatty
51 51
52 52 def _is_trusted(self, fp, f):
53 53 st = util.fstat(fp)
54 54 if util.isowner(fp, st):
55 55 return True
56 56
57 tusers = self.trusted_users
58 tgroups = self.trusted_groups
57 tusers, tgroups = self._trustusers, self._trustgroups
59 58 if '*' in tusers or '*' in tgroups:
60 59 return True
61 60
62 61 user = util.username(st.st_uid)
63 62 group = util.groupname(st.st_gid)
64 63 if user in tusers or group in tgroups or user == util.username():
65 64 return True
66 65
67 66 if self.report_untrusted:
68 67 self.warn(_('Not trusting file %s from untrusted '
69 68 'user %s, group %s\n') % (f, user, group))
70 69 return False
71 70
72 71 def readconfig(self, filename, root=None, trust=False,
73 72 sections = None):
74 73 try:
75 74 fp = open(filename)
76 75 except IOError:
77 76 if not sections: # ignore unless we were looking for something
78 77 return
79 78 raise
80 79
81 80 cdata = config.config()
82 81 trusted = sections or trust or self._is_trusted(fp, filename)
83 82
84 83 try:
85 84 cdata.read(filename, fp, sections=sections)
86 85 except error.ConfigError, inst:
87 86 if trusted:
88 87 raise
89 88 self.warn(_("Ignored: %s\n") % str(inst))
90 89
91 90 if trusted:
92 91 self.cdata.update(cdata)
93 92 self.cdata.update(self.overlay)
94 93 self.ucdata.update(cdata)
95 94 self.ucdata.update(self.overlay)
96 95
97 96 if root is None:
98 97 root = os.path.expanduser('~')
99 98 self.fixconfig(root=root)
100 99
101 100 def fixconfig(self, root=None):
102 101 # translate paths relative to root (or home) into absolute paths
103 102 root = root or os.getcwd()
104 103 for c in self.cdata, self.ucdata, self.overlay:
105 104 for n, p in c.items('paths'):
106 105 if p and "://" not in p and not os.path.isabs(p):
107 106 c.set("paths", n, os.path.normpath(os.path.join(root, p)))
108 107
109 108 # update ui options
110 109 self.debugflag = self.configbool('ui', 'debug')
111 110 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
112 111 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
113 112 if self.verbose and self.quiet:
114 113 self.quiet = self.verbose = False
115 114 self.report_untrusted = self.configbool("ui", "report_untrusted", True)
116 115 self.interactive = self.configbool("ui", "interactive", self.isatty())
117 116 self.traceback = self.configbool('ui', 'traceback', False)
118 117
119 118 # update trust information
120 119 for user in self.configlist('trusted', 'users'):
121 self.trusted_users[user] = 1
120 self._trustusers[user] = 1
122 121 for group in self.configlist('trusted', 'groups'):
123 self.trusted_groups[group] = 1
122 self._trustgroups[group] = 1
124 123
125 124 def setconfig(self, section, name, value):
126 125 for cdata in (self.overlay, self.cdata, self.ucdata):
127 126 cdata.set(section, name, value)
128 127 self.fixconfig()
129 128
130 129 def _data(self, untrusted):
131 130 return untrusted and self.ucdata or self.cdata
132 131
133 132 def configsource(self, section, name, untrusted=False):
134 133 return self._data(untrusted).source(section, name) or 'none'
135 134
136 135 def config(self, section, name, default=None, untrusted=False):
137 136 value = self._data(untrusted).get(section, name, default)
138 137 if self.debugflag and not untrusted:
139 138 uvalue = self.ucdata.get(section, name)
140 139 if uvalue is not None and uvalue != value:
141 140 self.warn(_("Ignoring untrusted configuration option "
142 141 "%s.%s = %s\n") % (section, name, uvalue))
143 142 return value
144 143
145 144 def configbool(self, section, name, default=False, untrusted=False):
146 145 v = self.config(section, name, None, untrusted)
147 146 if v == None:
148 147 return default
149 148 if v.lower() not in _booleans:
150 149 raise error.ConfigError(_("%s.%s not a boolean ('%s')")
151 150 % (section, name, v))
152 151 return _booleans[v.lower()]
153 152
154 153 def configlist(self, section, name, default=None, untrusted=False):
155 154 """Return a list of comma/space separated strings"""
156 155 result = self.config(section, name, untrusted=untrusted)
157 156 if result is None:
158 157 result = default or []
159 158 if isinstance(result, basestring):
160 159 result = result.replace(",", " ").split()
161 160 return result
162 161
163 162 def has_section(self, section, untrusted=False):
164 163 '''tell whether section exists in config.'''
165 164 return section in self._data(untrusted)
166 165
167 166 def configitems(self, section, untrusted=False):
168 167 items = self._data(untrusted).items(section)
169 168 if self.debugflag and not untrusted:
170 169 for k,v in self.ucdata.items(section):
171 170 if self.cdata.get(section, k) != v:
172 171 self.warn(_("Ignoring untrusted configuration option "
173 172 "%s.%s = %s\n") % (section, k, v))
174 173 return items
175 174
176 175 def walkconfig(self, untrusted=False):
177 176 cdata = self._data(untrusted)
178 177 for section in cdata.sections():
179 178 for name, value in self.configitems(section, untrusted):
180 179 yield section, name, str(value).replace('\n', '\\n')
181 180
182 181 def username(self):
183 182 """Return default username to be used in commits.
184 183
185 184 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
186 185 and stop searching if one of these is set.
187 186 If not found and ui.askusername is True, ask the user, else use
188 187 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
189 188 """
190 189 user = os.environ.get("HGUSER")
191 190 if user is None:
192 191 user = self.config("ui", "username")
193 192 if user is None:
194 193 user = os.environ.get("EMAIL")
195 194 if user is None and self.configbool("ui", "askusername"):
196 195 user = self.prompt(_("enter a commit username:"), default=None)
197 196 if user is None:
198 197 try:
199 198 user = '%s@%s' % (util.getuser(), socket.getfqdn())
200 199 self.warn(_("No username found, using '%s' instead\n") % user)
201 200 except KeyError:
202 201 pass
203 202 if not user:
204 203 raise util.Abort(_("Please specify a username."))
205 204 if "\n" in user:
206 205 raise util.Abort(_("username %s contains a newline\n") % repr(user))
207 206 return user
208 207
209 208 def shortuser(self, user):
210 209 """Return a short representation of a user name or email address."""
211 210 if not self.verbose: user = util.shortuser(user)
212 211 return user
213 212
214 213 def _path(self, loc):
215 214 p = self.config('paths', loc)
216 215 if p and '%%' in p:
217 216 ui.warn('(deprecated \'\%\%\' in path %s=%s from %s)\n' %
218 217 (loc, p, self.configsource('paths', loc)))
219 218 p = p.replace('%%', '%')
220 219 return p
221 220
222 221 def expandpath(self, loc, default=None):
223 222 """Return repository location relative to cwd or from [paths]"""
224 223 if "://" in loc or os.path.isdir(os.path.join(loc, '.hg')):
225 224 return loc
226 225
227 226 path = self._path(loc)
228 227 if not path and default is not None:
229 228 path = self._path(default)
230 229 return path or loc
231 230
232 231 def pushbuffer(self):
233 232 self.buffers.append([])
234 233
235 234 def popbuffer(self):
236 235 return "".join(self.buffers.pop())
237 236
238 237 def write(self, *args):
239 238 if self.buffers:
240 239 self.buffers[-1].extend([str(a) for a in args])
241 240 else:
242 241 for a in args:
243 242 sys.stdout.write(str(a))
244 243
245 244 def write_err(self, *args):
246 245 try:
247 246 if not sys.stdout.closed: sys.stdout.flush()
248 247 for a in args:
249 248 sys.stderr.write(str(a))
250 249 # stderr may be buffered under win32 when redirected to files,
251 250 # including stdout.
252 251 if not sys.stderr.closed: sys.stderr.flush()
253 252 except IOError, inst:
254 253 if inst.errno != errno.EPIPE:
255 254 raise
256 255
257 256 def flush(self):
258 257 try: sys.stdout.flush()
259 258 except: pass
260 259 try: sys.stderr.flush()
261 260 except: pass
262 261
263 262 def _readline(self, prompt=''):
264 263 if self.isatty():
265 264 try:
266 265 # magically add command line editing support, where
267 266 # available
268 267 import readline
269 268 # force demandimport to really load the module
270 269 readline.read_history_file
271 270 # windows sometimes raises something other than ImportError
272 271 except Exception:
273 272 pass
274 273 line = raw_input(prompt)
275 274 # When stdin is in binary mode on Windows, it can cause
276 275 # raw_input() to emit an extra trailing carriage return
277 276 if os.linesep == '\r\n' and line and line[-1] == '\r':
278 277 line = line[:-1]
279 278 return line
280 279
281 280 def prompt(self, msg, pat=None, default="y"):
282 281 """Prompt user with msg, read response, and ensure it matches pat
283 282
284 283 If not interactive -- the default is returned
285 284 """
286 285 if not self.interactive:
287 286 self.note(msg, ' ', default, "\n")
288 287 return default
289 288 while True:
290 289 try:
291 290 r = self._readline(msg + ' ')
292 291 if not r:
293 292 return default
294 293 if not pat or re.match(pat, r):
295 294 return r
296 295 else:
297 296 self.write(_("unrecognized response\n"))
298 297 except EOFError:
299 298 raise util.Abort(_('response expected'))
300 299
301 300 def getpass(self, prompt=None, default=None):
302 301 if not self.interactive: return default
303 302 try:
304 303 return getpass.getpass(prompt or _('password: '))
305 304 except EOFError:
306 305 raise util.Abort(_('response expected'))
307 306 def status(self, *msg):
308 307 if not self.quiet: self.write(*msg)
309 308 def warn(self, *msg):
310 309 self.write_err(*msg)
311 310 def note(self, *msg):
312 311 if self.verbose: self.write(*msg)
313 312 def debug(self, *msg):
314 313 if self.debugflag: self.write(*msg)
315 314 def edit(self, text, user):
316 315 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
317 316 text=True)
318 317 try:
319 318 f = os.fdopen(fd, "w")
320 319 f.write(text)
321 320 f.close()
322 321
323 322 editor = self.geteditor()
324 323
325 324 util.system("%s \"%s\"" % (editor, name),
326 325 environ={'HGUSER': user},
327 326 onerr=util.Abort, errprefix=_("edit failed"))
328 327
329 328 f = open(name)
330 329 t = f.read()
331 330 f.close()
332 331 t = re.sub("(?m)^HG:.*\n", "", t)
333 332 finally:
334 333 os.unlink(name)
335 334
336 335 return t
337 336
338 337 def print_exc(self):
339 338 '''print exception traceback if traceback printing enabled.
340 339 only to call in exception handler. returns true if traceback
341 340 printed.'''
342 341 if self.traceback:
343 342 traceback.print_exc()
344 343 return self.traceback
345 344
346 345 def geteditor(self):
347 346 '''return editor to use'''
348 347 return (os.environ.get("HGEDITOR") or
349 348 self.config("ui", "editor") or
350 349 os.environ.get("VISUAL") or
351 350 os.environ.get("EDITOR", "vi"))
General Comments 0
You need to be logged in to leave comments. Login now