PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/ui.py

https://bitbucket.org/mirror/mercurial/
Python | 851 lines | 813 code | 23 blank | 15 comment | 45 complexity | e229d118726c079a332ace7e0c39a856 MD5 | raw file
Possible License(s): GPL-2.0
  1. # ui.py - user interface bits for mercurial
  2. #
  3. # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7. from i18n import _
  8. import errno, getpass, os, socket, sys, tempfile, traceback
  9. import config, scmutil, util, error, formatter
  10. from node import hex
  11. class ui(object):
  12. def __init__(self, src=None):
  13. # _buffers: used for temporary capture of output
  14. self._buffers = []
  15. # _bufferstates: Should the temporary capture includes stderr
  16. self._bufferstates = []
  17. self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
  18. self._reportuntrusted = True
  19. self._ocfg = config.config() # overlay
  20. self._tcfg = config.config() # trusted
  21. self._ucfg = config.config() # untrusted
  22. self._trustusers = set()
  23. self._trustgroups = set()
  24. self.callhooks = True
  25. if src:
  26. self.fout = src.fout
  27. self.ferr = src.ferr
  28. self.fin = src.fin
  29. self._tcfg = src._tcfg.copy()
  30. self._ucfg = src._ucfg.copy()
  31. self._ocfg = src._ocfg.copy()
  32. self._trustusers = src._trustusers.copy()
  33. self._trustgroups = src._trustgroups.copy()
  34. self.environ = src.environ
  35. self.callhooks = src.callhooks
  36. self.fixconfig()
  37. else:
  38. self.fout = sys.stdout
  39. self.ferr = sys.stderr
  40. self.fin = sys.stdin
  41. # shared read-only environment
  42. self.environ = os.environ
  43. # we always trust global config files
  44. for f in scmutil.rcpath():
  45. self.readconfig(f, trust=True)
  46. def copy(self):
  47. return self.__class__(self)
  48. def formatter(self, topic, opts):
  49. return formatter.formatter(self, topic, opts)
  50. def _trusted(self, fp, f):
  51. st = util.fstat(fp)
  52. if util.isowner(st):
  53. return True
  54. tusers, tgroups = self._trustusers, self._trustgroups
  55. if '*' in tusers or '*' in tgroups:
  56. return True
  57. user = util.username(st.st_uid)
  58. group = util.groupname(st.st_gid)
  59. if user in tusers or group in tgroups or user == util.username():
  60. return True
  61. if self._reportuntrusted:
  62. self.warn(_('not trusting file %s from untrusted '
  63. 'user %s, group %s\n') % (f, user, group))
  64. return False
  65. def readconfig(self, filename, root=None, trust=False,
  66. sections=None, remap=None):
  67. try:
  68. fp = open(filename)
  69. except IOError:
  70. if not sections: # ignore unless we were looking for something
  71. return
  72. raise
  73. cfg = config.config()
  74. trusted = sections or trust or self._trusted(fp, filename)
  75. try:
  76. cfg.read(filename, fp, sections=sections, remap=remap)
  77. fp.close()
  78. except error.ConfigError, inst:
  79. if trusted:
  80. raise
  81. self.warn(_("ignored: %s\n") % str(inst))
  82. if self.plain():
  83. for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
  84. 'logtemplate', 'style',
  85. 'traceback', 'verbose'):
  86. if k in cfg['ui']:
  87. del cfg['ui'][k]
  88. for k, v in cfg.items('defaults'):
  89. del cfg['defaults'][k]
  90. # Don't remove aliases from the configuration if in the exceptionlist
  91. if self.plain('alias'):
  92. for k, v in cfg.items('alias'):
  93. del cfg['alias'][k]
  94. if trusted:
  95. self._tcfg.update(cfg)
  96. self._tcfg.update(self._ocfg)
  97. self._ucfg.update(cfg)
  98. self._ucfg.update(self._ocfg)
  99. if root is None:
  100. root = os.path.expanduser('~')
  101. self.fixconfig(root=root)
  102. def fixconfig(self, root=None, section=None):
  103. if section in (None, 'paths'):
  104. # expand vars and ~
  105. # translate paths relative to root (or home) into absolute paths
  106. root = root or os.getcwd()
  107. for c in self._tcfg, self._ucfg, self._ocfg:
  108. for n, p in c.items('paths'):
  109. if not p:
  110. continue
  111. if '%%' in p:
  112. self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
  113. % (n, p, self.configsource('paths', n)))
  114. p = p.replace('%%', '%')
  115. p = util.expandpath(p)
  116. if not util.hasscheme(p) and not os.path.isabs(p):
  117. p = os.path.normpath(os.path.join(root, p))
  118. c.set("paths", n, p)
  119. if section in (None, 'ui'):
  120. # update ui options
  121. self.debugflag = self.configbool('ui', 'debug')
  122. self.verbose = self.debugflag or self.configbool('ui', 'verbose')
  123. self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
  124. if self.verbose and self.quiet:
  125. self.quiet = self.verbose = False
  126. self._reportuntrusted = self.debugflag or self.configbool("ui",
  127. "report_untrusted", True)
  128. self.tracebackflag = self.configbool('ui', 'traceback', False)
  129. if section in (None, 'trusted'):
  130. # update trust information
  131. self._trustusers.update(self.configlist('trusted', 'users'))
  132. self._trustgroups.update(self.configlist('trusted', 'groups'))
  133. def backupconfig(self, section, item):
  134. return (self._ocfg.backup(section, item),
  135. self._tcfg.backup(section, item),
  136. self._ucfg.backup(section, item),)
  137. def restoreconfig(self, data):
  138. self._ocfg.restore(data[0])
  139. self._tcfg.restore(data[1])
  140. self._ucfg.restore(data[2])
  141. def setconfig(self, section, name, value, source=''):
  142. for cfg in (self._ocfg, self._tcfg, self._ucfg):
  143. cfg.set(section, name, value, source)
  144. self.fixconfig(section=section)
  145. def _data(self, untrusted):
  146. return untrusted and self._ucfg or self._tcfg
  147. def configsource(self, section, name, untrusted=False):
  148. return self._data(untrusted).source(section, name) or 'none'
  149. def config(self, section, name, default=None, untrusted=False):
  150. if isinstance(name, list):
  151. alternates = name
  152. else:
  153. alternates = [name]
  154. for n in alternates:
  155. value = self._data(untrusted).get(section, n, None)
  156. if value is not None:
  157. name = n
  158. break
  159. else:
  160. value = default
  161. if self.debugflag and not untrusted and self._reportuntrusted:
  162. for n in alternates:
  163. uvalue = self._ucfg.get(section, n)
  164. if uvalue is not None and uvalue != value:
  165. self.debug("ignoring untrusted configuration option "
  166. "%s.%s = %s\n" % (section, n, uvalue))
  167. return value
  168. def configpath(self, section, name, default=None, untrusted=False):
  169. 'get a path config item, expanded relative to repo root or config file'
  170. v = self.config(section, name, default, untrusted)
  171. if v is None:
  172. return None
  173. if not os.path.isabs(v) or "://" not in v:
  174. src = self.configsource(section, name, untrusted)
  175. if ':' in src:
  176. base = os.path.dirname(src.rsplit(':')[0])
  177. v = os.path.join(base, os.path.expanduser(v))
  178. return v
  179. def configbool(self, section, name, default=False, untrusted=False):
  180. """parse a configuration element as a boolean
  181. >>> u = ui(); s = 'foo'
  182. >>> u.setconfig(s, 'true', 'yes')
  183. >>> u.configbool(s, 'true')
  184. True
  185. >>> u.setconfig(s, 'false', 'no')
  186. >>> u.configbool(s, 'false')
  187. False
  188. >>> u.configbool(s, 'unknown')
  189. False
  190. >>> u.configbool(s, 'unknown', True)
  191. True
  192. >>> u.setconfig(s, 'invalid', 'somevalue')
  193. >>> u.configbool(s, 'invalid')
  194. Traceback (most recent call last):
  195. ...
  196. ConfigError: foo.invalid is not a boolean ('somevalue')
  197. """
  198. v = self.config(section, name, None, untrusted)
  199. if v is None:
  200. return default
  201. if isinstance(v, bool):
  202. return v
  203. b = util.parsebool(v)
  204. if b is None:
  205. raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
  206. % (section, name, v))
  207. return b
  208. def configint(self, section, name, default=None, untrusted=False):
  209. """parse a configuration element as an integer
  210. >>> u = ui(); s = 'foo'
  211. >>> u.setconfig(s, 'int1', '42')
  212. >>> u.configint(s, 'int1')
  213. 42
  214. >>> u.setconfig(s, 'int2', '-42')
  215. >>> u.configint(s, 'int2')
  216. -42
  217. >>> u.configint(s, 'unknown', 7)
  218. 7
  219. >>> u.setconfig(s, 'invalid', 'somevalue')
  220. >>> u.configint(s, 'invalid')
  221. Traceback (most recent call last):
  222. ...
  223. ConfigError: foo.invalid is not an integer ('somevalue')
  224. """
  225. v = self.config(section, name, None, untrusted)
  226. if v is None:
  227. return default
  228. try:
  229. return int(v)
  230. except ValueError:
  231. raise error.ConfigError(_("%s.%s is not an integer ('%s')")
  232. % (section, name, v))
  233. def configbytes(self, section, name, default=0, untrusted=False):
  234. """parse a configuration element as a quantity in bytes
  235. Units can be specified as b (bytes), k or kb (kilobytes), m or
  236. mb (megabytes), g or gb (gigabytes).
  237. >>> u = ui(); s = 'foo'
  238. >>> u.setconfig(s, 'val1', '42')
  239. >>> u.configbytes(s, 'val1')
  240. 42
  241. >>> u.setconfig(s, 'val2', '42.5 kb')
  242. >>> u.configbytes(s, 'val2')
  243. 43520
  244. >>> u.configbytes(s, 'unknown', '7 MB')
  245. 7340032
  246. >>> u.setconfig(s, 'invalid', 'somevalue')
  247. >>> u.configbytes(s, 'invalid')
  248. Traceback (most recent call last):
  249. ...
  250. ConfigError: foo.invalid is not a byte quantity ('somevalue')
  251. """
  252. value = self.config(section, name)
  253. if value is None:
  254. if not isinstance(default, str):
  255. return default
  256. value = default
  257. try:
  258. return util.sizetoint(value)
  259. except error.ParseError:
  260. raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
  261. % (section, name, value))
  262. def configlist(self, section, name, default=None, untrusted=False):
  263. """parse a configuration element as a list of comma/space separated
  264. strings
  265. >>> u = ui(); s = 'foo'
  266. >>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
  267. >>> u.configlist(s, 'list1')
  268. ['this', 'is', 'a small', 'test']
  269. """
  270. def _parse_plain(parts, s, offset):
  271. whitespace = False
  272. while offset < len(s) and (s[offset].isspace() or s[offset] == ','):
  273. whitespace = True
  274. offset += 1
  275. if offset >= len(s):
  276. return None, parts, offset
  277. if whitespace:
  278. parts.append('')
  279. if s[offset] == '"' and not parts[-1]:
  280. return _parse_quote, parts, offset + 1
  281. elif s[offset] == '"' and parts[-1][-1] == '\\':
  282. parts[-1] = parts[-1][:-1] + s[offset]
  283. return _parse_plain, parts, offset + 1
  284. parts[-1] += s[offset]
  285. return _parse_plain, parts, offset + 1
  286. def _parse_quote(parts, s, offset):
  287. if offset < len(s) and s[offset] == '"': # ""
  288. parts.append('')
  289. offset += 1
  290. while offset < len(s) and (s[offset].isspace() or
  291. s[offset] == ','):
  292. offset += 1
  293. return _parse_plain, parts, offset
  294. while offset < len(s) and s[offset] != '"':
  295. if (s[offset] == '\\' and offset + 1 < len(s)
  296. and s[offset + 1] == '"'):
  297. offset += 1
  298. parts[-1] += '"'
  299. else:
  300. parts[-1] += s[offset]
  301. offset += 1
  302. if offset >= len(s):
  303. real_parts = _configlist(parts[-1])
  304. if not real_parts:
  305. parts[-1] = '"'
  306. else:
  307. real_parts[0] = '"' + real_parts[0]
  308. parts = parts[:-1]
  309. parts.extend(real_parts)
  310. return None, parts, offset
  311. offset += 1
  312. while offset < len(s) and s[offset] in [' ', ',']:
  313. offset += 1
  314. if offset < len(s):
  315. if offset + 1 == len(s) and s[offset] == '"':
  316. parts[-1] += '"'
  317. offset += 1
  318. else:
  319. parts.append('')
  320. else:
  321. return None, parts, offset
  322. return _parse_plain, parts, offset
  323. def _configlist(s):
  324. s = s.rstrip(' ,')
  325. if not s:
  326. return []
  327. parser, parts, offset = _parse_plain, [''], 0
  328. while parser:
  329. parser, parts, offset = parser(parts, s, offset)
  330. return parts
  331. result = self.config(section, name, untrusted=untrusted)
  332. if result is None:
  333. result = default or []
  334. if isinstance(result, basestring):
  335. result = _configlist(result.lstrip(' ,\n'))
  336. if result is None:
  337. result = default or []
  338. return result
  339. def has_section(self, section, untrusted=False):
  340. '''tell whether section exists in config.'''
  341. return section in self._data(untrusted)
  342. def configitems(self, section, untrusted=False):
  343. items = self._data(untrusted).items(section)
  344. if self.debugflag and not untrusted and self._reportuntrusted:
  345. for k, v in self._ucfg.items(section):
  346. if self._tcfg.get(section, k) != v:
  347. self.debug("ignoring untrusted configuration option "
  348. "%s.%s = %s\n" % (section, k, v))
  349. return items
  350. def walkconfig(self, untrusted=False):
  351. cfg = self._data(untrusted)
  352. for section in cfg.sections():
  353. for name, value in self.configitems(section, untrusted):
  354. yield section, name, value
  355. def plain(self, feature=None):
  356. '''is plain mode active?
  357. Plain mode means that all configuration variables which affect
  358. the behavior and output of Mercurial should be
  359. ignored. Additionally, the output should be stable,
  360. reproducible and suitable for use in scripts or applications.
  361. The only way to trigger plain mode is by setting either the
  362. `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
  363. The return value can either be
  364. - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
  365. - True otherwise
  366. '''
  367. if 'HGPLAIN' not in os.environ and 'HGPLAINEXCEPT' not in os.environ:
  368. return False
  369. exceptions = os.environ.get('HGPLAINEXCEPT', '').strip().split(',')
  370. if feature and exceptions:
  371. return feature not in exceptions
  372. return True
  373. def username(self):
  374. """Return default username to be used in commits.
  375. Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
  376. and stop searching if one of these is set.
  377. If not found and ui.askusername is True, ask the user, else use
  378. ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
  379. """
  380. user = os.environ.get("HGUSER")
  381. if user is None:
  382. user = self.config("ui", "username")
  383. if user is not None:
  384. user = os.path.expandvars(user)
  385. if user is None:
  386. user = os.environ.get("EMAIL")
  387. if user is None and self.configbool("ui", "askusername"):
  388. user = self.prompt(_("enter a commit username:"), default=None)
  389. if user is None and not self.interactive():
  390. try:
  391. user = '%s@%s' % (util.getuser(), socket.getfqdn())
  392. self.warn(_("no username found, using '%s' instead\n") % user)
  393. except KeyError:
  394. pass
  395. if not user:
  396. raise util.Abort(_('no username supplied'),
  397. hint=_('use "hg config --edit" '
  398. 'to set your username'))
  399. if "\n" in user:
  400. raise util.Abort(_("username %s contains a newline\n") % repr(user))
  401. return user
  402. def shortuser(self, user):
  403. """Return a short representation of a user name or email address."""
  404. if not self.verbose:
  405. user = util.shortuser(user)
  406. return user
  407. def expandpath(self, loc, default=None):
  408. """Return repository location relative to cwd or from [paths]"""
  409. if util.hasscheme(loc) or os.path.isdir(os.path.join(loc, '.hg')):
  410. return loc
  411. path = self.config('paths', loc)
  412. if not path and default is not None:
  413. path = self.config('paths', default)
  414. return path or loc
  415. def pushbuffer(self, error=False):
  416. """install a buffer to capture standar output of the ui object
  417. If error is True, the error output will be captured too."""
  418. self._buffers.append([])
  419. self._bufferstates.append(error)
  420. def popbuffer(self, labeled=False):
  421. '''pop the last buffer and return the buffered output
  422. If labeled is True, any labels associated with buffered
  423. output will be handled. By default, this has no effect
  424. on the output returned, but extensions and GUI tools may
  425. handle this argument and returned styled output. If output
  426. is being buffered so it can be captured and parsed or
  427. processed, labeled should not be set to True.
  428. '''
  429. self._bufferstates.pop()
  430. return "".join(self._buffers.pop())
  431. def write(self, *args, **opts):
  432. '''write args to output
  433. By default, this method simply writes to the buffer or stdout,
  434. but extensions or GUI tools may override this method,
  435. write_err(), popbuffer(), and label() to style output from
  436. various parts of hg.
  437. An optional keyword argument, "label", can be passed in.
  438. This should be a string containing label names separated by
  439. space. Label names take the form of "topic.type". For example,
  440. ui.debug() issues a label of "ui.debug".
  441. When labeling output for a specific command, a label of
  442. "cmdname.type" is recommended. For example, status issues
  443. a label of "status.modified" for modified files.
  444. '''
  445. if self._buffers:
  446. self._buffers[-1].extend([str(a) for a in args])
  447. else:
  448. for a in args:
  449. self.fout.write(str(a))
  450. def write_err(self, *args, **opts):
  451. try:
  452. if self._bufferstates and self._bufferstates[-1]:
  453. return self.write(*args, **opts)
  454. if not getattr(self.fout, 'closed', False):
  455. self.fout.flush()
  456. for a in args:
  457. self.ferr.write(str(a))
  458. # stderr may be buffered under win32 when redirected to files,
  459. # including stdout.
  460. if not getattr(self.ferr, 'closed', False):
  461. self.ferr.flush()
  462. except IOError, inst:
  463. if inst.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
  464. raise
  465. def flush(self):
  466. try: self.fout.flush()
  467. except (IOError, ValueError): pass
  468. try: self.ferr.flush()
  469. except (IOError, ValueError): pass
  470. def _isatty(self, fh):
  471. if self.configbool('ui', 'nontty', False):
  472. return False
  473. return util.isatty(fh)
  474. def interactive(self):
  475. '''is interactive input allowed?
  476. An interactive session is a session where input can be reasonably read
  477. from `sys.stdin'. If this function returns false, any attempt to read
  478. from stdin should fail with an error, unless a sensible default has been
  479. specified.
  480. Interactiveness is triggered by the value of the `ui.interactive'
  481. configuration variable or - if it is unset - when `sys.stdin' points
  482. to a terminal device.
  483. This function refers to input only; for output, see `ui.formatted()'.
  484. '''
  485. i = self.configbool("ui", "interactive", None)
  486. if i is None:
  487. # some environments replace stdin without implementing isatty
  488. # usually those are non-interactive
  489. return self._isatty(self.fin)
  490. return i
  491. def termwidth(self):
  492. '''how wide is the terminal in columns?
  493. '''
  494. if 'COLUMNS' in os.environ:
  495. try:
  496. return int(os.environ['COLUMNS'])
  497. except ValueError:
  498. pass
  499. return util.termwidth()
  500. def formatted(self):
  501. '''should formatted output be used?
  502. It is often desirable to format the output to suite the output medium.
  503. Examples of this are truncating long lines or colorizing messages.
  504. However, this is not often not desirable when piping output into other
  505. utilities, e.g. `grep'.
  506. Formatted output is triggered by the value of the `ui.formatted'
  507. configuration variable or - if it is unset - when `sys.stdout' points
  508. to a terminal device. Please note that `ui.formatted' should be
  509. considered an implementation detail; it is not intended for use outside
  510. Mercurial or its extensions.
  511. This function refers to output only; for input, see `ui.interactive()'.
  512. This function always returns false when in plain mode, see `ui.plain()'.
  513. '''
  514. if self.plain():
  515. return False
  516. i = self.configbool("ui", "formatted", None)
  517. if i is None:
  518. # some environments replace stdout without implementing isatty
  519. # usually those are non-interactive
  520. return self._isatty(self.fout)
  521. return i
  522. def _readline(self, prompt=''):
  523. if self._isatty(self.fin):
  524. try:
  525. # magically add command line editing support, where
  526. # available
  527. import readline
  528. # force demandimport to really load the module
  529. readline.read_history_file
  530. # windows sometimes raises something other than ImportError
  531. except Exception:
  532. pass
  533. # call write() so output goes through subclassed implementation
  534. # e.g. color extension on Windows
  535. self.write(prompt)
  536. # instead of trying to emulate raw_input, swap (self.fin,
  537. # self.fout) with (sys.stdin, sys.stdout)
  538. oldin = sys.stdin
  539. oldout = sys.stdout
  540. sys.stdin = self.fin
  541. sys.stdout = self.fout
  542. line = raw_input(' ')
  543. sys.stdin = oldin
  544. sys.stdout = oldout
  545. # When stdin is in binary mode on Windows, it can cause
  546. # raw_input() to emit an extra trailing carriage return
  547. if os.linesep == '\r\n' and line and line[-1] == '\r':
  548. line = line[:-1]
  549. return line
  550. def prompt(self, msg, default="y"):
  551. """Prompt user with msg, read response.
  552. If ui is not interactive, the default is returned.
  553. """
  554. if not self.interactive():
  555. self.write(msg, ' ', default, "\n")
  556. return default
  557. try:
  558. r = self._readline(self.label(msg, 'ui.prompt'))
  559. if not r:
  560. return default
  561. return r
  562. except EOFError:
  563. raise util.Abort(_('response expected'))
  564. @staticmethod
  565. def extractchoices(prompt):
  566. """Extract prompt message and list of choices from specified prompt.
  567. This returns tuple "(message, choices)", and "choices" is the
  568. list of tuple "(response character, text without &)".
  569. """
  570. parts = prompt.split('$$')
  571. msg = parts[0].rstrip(' ')
  572. choices = [p.strip(' ') for p in parts[1:]]
  573. return (msg,
  574. [(s[s.index('&') + 1].lower(), s.replace('&', '', 1))
  575. for s in choices])
  576. def promptchoice(self, prompt, default=0):
  577. """Prompt user with a message, read response, and ensure it matches
  578. one of the provided choices. The prompt is formatted as follows:
  579. "would you like fries with that (Yn)? $$ &Yes $$ &No"
  580. The index of the choice is returned. Responses are case
  581. insensitive. If ui is not interactive, the default is
  582. returned.
  583. """
  584. msg, choices = self.extractchoices(prompt)
  585. resps = [r for r, t in choices]
  586. while True:
  587. r = self.prompt(msg, resps[default])
  588. if r.lower() in resps:
  589. return resps.index(r.lower())
  590. self.write(_("unrecognized response\n"))
  591. def getpass(self, prompt=None, default=None):
  592. if not self.interactive():
  593. return default
  594. try:
  595. self.write_err(self.label(prompt or _('password: '), 'ui.prompt'))
  596. # disable getpass() only if explicitly specified. it's still valid
  597. # to interact with tty even if fin is not a tty.
  598. if self.configbool('ui', 'nontty'):
  599. return self.fin.readline().rstrip('\n')
  600. else:
  601. return getpass.getpass('')
  602. except EOFError:
  603. raise util.Abort(_('response expected'))
  604. def status(self, *msg, **opts):
  605. '''write status message to output (if ui.quiet is False)
  606. This adds an output label of "ui.status".
  607. '''
  608. if not self.quiet:
  609. opts['label'] = opts.get('label', '') + ' ui.status'
  610. self.write(*msg, **opts)
  611. def warn(self, *msg, **opts):
  612. '''write warning message to output (stderr)
  613. This adds an output label of "ui.warning".
  614. '''
  615. opts['label'] = opts.get('label', '') + ' ui.warning'
  616. self.write_err(*msg, **opts)
  617. def note(self, *msg, **opts):
  618. '''write note to output (if ui.verbose is True)
  619. This adds an output label of "ui.note".
  620. '''
  621. if self.verbose:
  622. opts['label'] = opts.get('label', '') + ' ui.note'
  623. self.write(*msg, **opts)
  624. def debug(self, *msg, **opts):
  625. '''write debug message to output (if ui.debugflag is True)
  626. This adds an output label of "ui.debug".
  627. '''
  628. if self.debugflag:
  629. opts['label'] = opts.get('label', '') + ' ui.debug'
  630. self.write(*msg, **opts)
  631. def edit(self, text, user, extra={}):
  632. (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
  633. text=True)
  634. try:
  635. f = os.fdopen(fd, "w")
  636. f.write(text)
  637. f.close()
  638. environ = {'HGUSER': user}
  639. if 'transplant_source' in extra:
  640. environ.update({'HGREVISION': hex(extra['transplant_source'])})
  641. for label in ('source', 'rebase_source'):
  642. if label in extra:
  643. environ.update({'HGREVISION': extra[label]})
  644. break
  645. editor = self.geteditor()
  646. util.system("%s \"%s\"" % (editor, name),
  647. environ=environ,
  648. onerr=util.Abort, errprefix=_("edit failed"),
  649. out=self.fout)
  650. f = open(name)
  651. t = f.read()
  652. f.close()
  653. finally:
  654. os.unlink(name)
  655. return t
  656. def traceback(self, exc=None, force=False):
  657. '''print exception traceback if traceback printing enabled or forced.
  658. only to call in exception handler. returns true if traceback
  659. printed.'''
  660. if self.tracebackflag or force:
  661. if exc is None:
  662. exc = sys.exc_info()
  663. cause = getattr(exc[1], 'cause', None)
  664. if cause is not None:
  665. causetb = traceback.format_tb(cause[2])
  666. exctb = traceback.format_tb(exc[2])
  667. exconly = traceback.format_exception_only(cause[0], cause[1])
  668. # exclude frame where 'exc' was chained and rethrown from exctb
  669. self.write_err('Traceback (most recent call last):\n',
  670. ''.join(exctb[:-1]),
  671. ''.join(causetb),
  672. ''.join(exconly))
  673. else:
  674. traceback.print_exception(exc[0], exc[1], exc[2],
  675. file=self.ferr)
  676. return self.tracebackflag or force
  677. def geteditor(self):
  678. '''return editor to use'''
  679. if sys.platform == 'plan9':
  680. # vi is the MIPS instruction simulator on Plan 9. We
  681. # instead default to E to plumb commit messages to
  682. # avoid confusion.
  683. editor = 'E'
  684. else:
  685. editor = 'vi'
  686. return (os.environ.get("HGEDITOR") or
  687. self.config("ui", "editor") or
  688. os.environ.get("VISUAL") or
  689. os.environ.get("EDITOR", editor))
  690. def progress(self, topic, pos, item="", unit="", total=None):
  691. '''show a progress message
  692. With stock hg, this is simply a debug message that is hidden
  693. by default, but with extensions or GUI tools it may be
  694. visible. 'topic' is the current operation, 'item' is a
  695. non-numeric marker of the current position (i.e. the currently
  696. in-process file), 'pos' is the current numeric position (i.e.
  697. revision, bytes, etc.), unit is a corresponding unit label,
  698. and total is the highest expected pos.
  699. Multiple nested topics may be active at a time.
  700. All topics should be marked closed by setting pos to None at
  701. termination.
  702. '''
  703. if pos is None or not self.debugflag:
  704. return
  705. if unit:
  706. unit = ' ' + unit
  707. if item:
  708. item = ' ' + item
  709. if total:
  710. pct = 100.0 * pos / total
  711. self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
  712. % (topic, item, pos, total, unit, pct))
  713. else:
  714. self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
  715. def log(self, service, *msg, **opts):
  716. '''hook for logging facility extensions
  717. service should be a readily-identifiable subsystem, which will
  718. allow filtering.
  719. message should be a newline-terminated string to log.
  720. '''
  721. pass
  722. def label(self, msg, label):
  723. '''style msg based on supplied label
  724. Like ui.write(), this just returns msg unchanged, but extensions
  725. and GUI tools can override it to allow styling output without
  726. writing it.
  727. ui.write(s, 'label') is equivalent to
  728. ui.write(ui.label(s, 'label')).
  729. '''
  730. return msg