mercurial/ui.py
author Gregory Szorc <gregory.szorc@gmail.com>
Mon, 10 Dec 2018 20:06:58 +0000
changeset 41063 6603de284b0a
parent 40994 ab92e2111408
child 41076 8ecb17b7f432
permissions -rw-r--r--
progress: avoid ui.configbool() lookup when progress bar is active Profiling revealed that the ui.configbool('progress', 'debug') during progress bar updates was consuming a significant amount of overhead. This commit adds an attribute on progress bar instances that caches this config option. The impact on `hg perfprogress` with default options is significant: before: ! wall 4.641942 comb 4.580000 user 4.210000 sys 0.370000 (best of 3) after: ! wall 1.948626 comb 1.950000 user 1.950000 sys 0.000000 (best of 5) After this change, profiling reveals that progress.progbar.progress() is now consuming ~73% of time. This change does not improve the execution time if the progress bar is disabled. We may want a more comprehensive solution for that case, as the progress bar won't be enabled in a number of scenarios (e.g. servers and processes not attached to an interactive TTY). I also think that overhead of ~2.0s for 1M updates is a bit high. I suspect further refactoring of the progress bar can significantly reduce overhead. I don't have plans to do this, however. Differential Revision: https://phab.mercurial-scm.org/D5408
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
207
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
     1
# ui.py - user interface bits for mercurial
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
     2
#
4635
63b9d2deed48 Updated copyright notices and add "and others" to "hg version"
Thomas Arendsen Hein <thomas@intevation.de>
parents: 4633
diff changeset
     3
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
207
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
     4
#
8225
46293a0c7e9f updated license to be explicit about GPL version 2
Martin Geisler <mg@lazybytes.net>
parents: 8222
diff changeset
     5
# This software may be used and distributed according to the terms of the
10263
25e572394f5c Update license to GPLv2+
Matt Mackall <mpm@selenic.com>
parents: 10243
diff changeset
     6
# GNU General Public License version 2 or any later version.
207
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
     7
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
     8
from __future__ import absolute_import
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
     9
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
    10
import collections
30480
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
    11
import contextlib
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    12
import errno
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    13
import getpass
25629
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
    14
import inspect
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    15
import os
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
    16
import re
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
    17
import signal
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    18
import socket
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
    19
import subprocess
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    20
import sys
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    21
import traceback
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    22
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    23
from .i18n import _
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    24
from .node import hex
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    25
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    26
from . import (
31087
894bdcdc75df color: move the 'colorlabel' call to the core 'ui' class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31083
diff changeset
    27
    color,
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    28
    config,
32984
6d983e8af49c configitems: introduce a central registry for config option
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32967
diff changeset
    29
    configitems,
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
    30
    encoding,
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    31
    error,
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    32
    formatter,
40994
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
    33
    loggingutil,
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    34
    progress,
30519
20a42325fdef py3: use pycompat.getcwd() instead of os.getcwd()
Pulkit Goyal <7895pulkit@gmail.com>
parents: 30480
diff changeset
    35
    pycompat,
31679
0f8ba0bc1154 rcutil: move scmutil.*rcpath to rcutil (API)
Jun Wu <quark@fb.com>
parents: 31624
diff changeset
    36
    rcutil,
25989
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    37
    scmutil,
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    38
    util,
2cc4e8385661 ui: use absolute_import
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25660
diff changeset
    39
)
37084
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
    40
from .utils import (
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
    41
    dateutil,
37119
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
    42
    procutil,
37084
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
    43
    stringutil,
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
    44
)
207
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
    45
29378
fea71f66ebff url: remember http password database in ui object
liscju <piotr.listkiewicz@gmail.com>
parents: 29366
diff changeset
    46
urlreq = util.urlreq
fea71f66ebff url: remember http password database in ui object
liscju <piotr.listkiewicz@gmail.com>
parents: 29366
diff changeset
    47
30979
fd598149112b ui: time calls to ui.system
Simon Farnsworth <simonfar@fb.com>
parents: 30978
diff changeset
    48
# for use with str.translate(None, _keepalnum), to keep just alphanumerics
31253
64596338ba10 py3: factor out bytechr() function
Yuya Nishihara <yuya@tcha.org>
parents: 31178
diff changeset
    49
_keepalnum = ''.join(c for c in map(pycompat.bytechr, range(256))
64596338ba10 py3: factor out bytechr() function
Yuya Nishihara <yuya@tcha.org>
parents: 31178
diff changeset
    50
                     if not c.isalnum())
30979
fd598149112b ui: time calls to ui.system
Simon Farnsworth <simonfar@fb.com>
parents: 30978
diff changeset
    51
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    52
# The config knobs that will be altered (if unset) by ui.tweakdefaults.
35911
704095e27c5c py3: add b'' to tweakdefaults config string
Pulkit Goyal <7895pulkit@gmail.com>
parents: 35900
diff changeset
    53
tweakrc = b"""
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    54
[ui]
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    55
# The rollback command is dangerous. As a rule, don't use it.
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    56
rollback = False
35067
929858db4d22 tweakdefaults: turn on ui.statuscopies
Martin von Zweigbergk <martinvonz@google.com>
parents: 34957
diff changeset
    57
# Make `hg status` report copy information
929858db4d22 tweakdefaults: turn on ui.statuscopies
Martin von Zweigbergk <martinvonz@google.com>
parents: 34957
diff changeset
    58
statuscopies = yes
35306
03a83ace9816 ui: add curses interface to tweakdefaults
Augie Fackler <augie@google.com>
parents: 35186
diff changeset
    59
# Prefer curses UIs when available. Revert to plain-text with `text`.
03a83ace9816 ui: add curses interface to tweakdefaults
Augie Fackler <augie@google.com>
parents: 35186
diff changeset
    60
interface = curses
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    61
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    62
[commands]
38652
bfcd5c7cbf9a grep: restore pre-9ef10437bb88 behavior, enable wdir search by tweakdefaults
Yuya Nishihara <yuya@tcha.org>
parents: 38623
diff changeset
    63
# Grep working directory by default.
bfcd5c7cbf9a grep: restore pre-9ef10437bb88 behavior, enable wdir search by tweakdefaults
Yuya Nishihara <yuya@tcha.org>
parents: 38623
diff changeset
    64
grep.all-files = True
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    65
# Make `hg status` emit cwd-relative paths by default.
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    66
status.relative = yes
34707
6cd8d8203204 tweakdefaults: make commands.update.check be `noconflict`
Augie Fackler <augie@google.com>
parents: 34645
diff changeset
    67
# Refuse to perform an `hg update` that would cause a file content merge
6cd8d8203204 tweakdefaults: make commands.update.check be `noconflict`
Augie Fackler <augie@google.com>
parents: 34645
diff changeset
    68
update.check = noconflict
36910
98487ad0cf8b tweakdefaults: add commands.status.verbose to tweakefaults
Pulkit Goyal <7895pulkit@gmail.com>
parents: 36834
diff changeset
    69
# Show conflicts information in `hg status`
98487ad0cf8b tweakdefaults: add commands.status.verbose to tweakefaults
Pulkit Goyal <7895pulkit@gmail.com>
parents: 36834
diff changeset
    70
status.verbose = True
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    71
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    72
[diff]
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    73
git = 1
35307
4caafe280488 ui: add diff.showfunc to tweakdefaults
Augie Fackler <augie@google.com>
parents: 35306
diff changeset
    74
showfunc = 1
38623
92c845c097aa tweakdefaults: enable word-diff by default
Augie Fackler <augie@google.com>
parents: 38575
diff changeset
    75
word-diff = 1
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    76
"""
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
    77
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    78
samplehgrcs = {
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    79
    'user':
33687
6294654453ee py3: use bytes IO to write sample hgrc
Yuya Nishihara <yuya@tcha.org>
parents: 33585
diff changeset
    80
b"""# example user config (see 'hg help config' for more info)
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    81
[ui]
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    82
# name and email, e.g.
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    83
# username = Jane Doe <jdoe@example.com>
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    84
username =
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    85
34568
63c19b7fa100 ui: recommend tweakdefaults in the default hgrc template
Augie Fackler <augie@google.com>
parents: 34482
diff changeset
    86
# We recommend enabling tweakdefaults to get slight improvements to
63c19b7fa100 ui: recommend tweakdefaults in the default hgrc template
Augie Fackler <augie@google.com>
parents: 34482
diff changeset
    87
# the UI over time. Make sure to set HGPLAIN in the environment when
63c19b7fa100 ui: recommend tweakdefaults in the default hgrc template
Augie Fackler <augie@google.com>
parents: 34482
diff changeset
    88
# writing scripts!
63c19b7fa100 ui: recommend tweakdefaults in the default hgrc template
Augie Fackler <augie@google.com>
parents: 34482
diff changeset
    89
# tweakdefaults = True
63c19b7fa100 ui: recommend tweakdefaults in the default hgrc template
Augie Fackler <augie@google.com>
parents: 34482
diff changeset
    90
32093
4d438efb825a color: reflect the new default in the example hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32078
diff changeset
    91
# uncomment to disable color in command output
32094
2de67783dd31 color: point to the global help in the example hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32093
diff changeset
    92
# (see 'hg help color' for details)
32093
4d438efb825a color: reflect the new default in the example hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32078
diff changeset
    93
# color = never
31124
791ea883fc44 config: suggest the 'ui.color' instead of the 'color' extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31119
diff changeset
    94
32100
21eb863187ea pager: advertise the config option in the default hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32097
diff changeset
    95
# uncomment to disable command output pagination
21eb863187ea pager: advertise the config option in the default hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32097
diff changeset
    96
# (see 'hg help pager' for details)
32104
f06d23af6cdf pager: rename 'pager.enable' to 'ui.paginate'
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32100
diff changeset
    97
# paginate = never
32100
21eb863187ea pager: advertise the config option in the default hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32097
diff changeset
    98
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
    99
[extensions]
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   100
# uncomment these lines to enable some popular extensions
29978
3d2ea1403c62 samplehgrcs: use single quotes in use warning
timeless <timeless@mozdev.org>
parents: 29762
diff changeset
   101
# (see 'hg help extensions' for more info)
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   102
#
32096
726121fa86e1 config: use "churn" as an example extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32094
diff changeset
   103
# churn =
32097
601bfcddccdc config: drop pager from the recommended extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32096
diff changeset
   104
""",
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   105
22837
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   106
    'cloned':
33687
6294654453ee py3: use bytes IO to write sample hgrc
Yuya Nishihara <yuya@tcha.org>
parents: 33585
diff changeset
   107
b"""# example repository config (see 'hg help config' for more info)
22837
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   108
[paths]
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   109
default = %s
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   110
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   111
# path aliases to other clones of this repo in URLs or filesystem paths
29978
3d2ea1403c62 samplehgrcs: use single quotes in use warning
timeless <timeless@mozdev.org>
parents: 29762
diff changeset
   112
# (see 'hg help config.paths' for more info)
22837
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   113
#
31064
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   114
# default:pushurl = ssh://jdoe@example.net/hg/jdoes-fork
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   115
# my-fork         = ssh://jdoe@example.net/hg/jdoes-fork
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   116
# my-clone        = /home/jdoe/jdoes-clone
22837
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   117
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   118
[ui]
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   119
# name and email (local to this repository, optional), e.g.
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   120
# username = Jane Doe <jdoe@example.com>
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   121
""",
2be7d5ebd4d0 config: use the same hgrc for a cloned repo as for an uninitted repo
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22836
diff changeset
   122
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   123
    'local':
33687
6294654453ee py3: use bytes IO to write sample hgrc
Yuya Nishihara <yuya@tcha.org>
parents: 33585
diff changeset
   124
b"""# example repository config (see 'hg help config' for more info)
22836
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   125
[paths]
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   126
# path aliases to other clones of this repo in URLs or filesystem paths
29978
3d2ea1403c62 samplehgrcs: use single quotes in use warning
timeless <timeless@mozdev.org>
parents: 29762
diff changeset
   127
# (see 'hg help config.paths' for more info)
22836
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   128
#
31064
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   129
# default         = http://example.com/hg/example-repo
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   130
# default:pushurl = ssh://jdoe@example.net/hg/jdoes-fork
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   131
# my-fork         = ssh://jdoe@example.net/hg/jdoes-fork
4431add9aef9 ui: replace obsolete default-push with default:pushurl (issue5485)
Rishabh Madan <rishabhmadan96@gmail.com>
parents: 30848
diff changeset
   132
# my-clone        = /home/jdoe/jdoes-clone
22836
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   133
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   134
[ui]
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   135
# name and email (local to this repository, optional), e.g.
5a831e4e6d7a config: give a more detailed sample repo config
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 22783
diff changeset
   136
# username = Jane Doe <jdoe@example.com>
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   137
""",
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   138
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   139
    'global':
33687
6294654453ee py3: use bytes IO to write sample hgrc
Yuya Nishihara <yuya@tcha.org>
parents: 33585
diff changeset
   140
b"""# example system-wide hg config (see 'hg help config' for more info)
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   141
31124
791ea883fc44 config: suggest the 'ui.color' instead of the 'color' extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31119
diff changeset
   142
[ui]
32093
4d438efb825a color: reflect the new default in the example hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32078
diff changeset
   143
# uncomment to disable color in command output
32094
2de67783dd31 color: point to the global help in the example hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32093
diff changeset
   144
# (see 'hg help color' for details)
32093
4d438efb825a color: reflect the new default in the example hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32078
diff changeset
   145
# color = never
31124
791ea883fc44 config: suggest the 'ui.color' instead of the 'color' extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31119
diff changeset
   146
32100
21eb863187ea pager: advertise the config option in the default hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32097
diff changeset
   147
# uncomment to disable command output pagination
21eb863187ea pager: advertise the config option in the default hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32097
diff changeset
   148
# (see 'hg help pager' for details)
32104
f06d23af6cdf pager: rename 'pager.enable' to 'ui.paginate'
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32100
diff changeset
   149
# paginate = never
32100
21eb863187ea pager: advertise the config option in the default hgrc
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32097
diff changeset
   150
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   151
[extensions]
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   152
# uncomment these lines to enable some popular extensions
29978
3d2ea1403c62 samplehgrcs: use single quotes in use warning
timeless <timeless@mozdev.org>
parents: 29762
diff changeset
   153
# (see 'hg help extensions' for more info)
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   154
#
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   155
# blackbox =
32096
726121fa86e1 config: use "churn" as an example extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32094
diff changeset
   156
# churn =
32097
601bfcddccdc config: drop pager from the recommended extension
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 32096
diff changeset
   157
""",
22419
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   158
}
fdfc9faca273 ui: move samplehgrcs from config
Matt Mackall <mpm@selenic.com>
parents: 22291
diff changeset
   159
34482
75de5d456b60 ui: convert to/from Optional[bytes] to Optional[str] in password manager
Augie Fackler <augie@google.com>
parents: 34426
diff changeset
   160
def _maybestrurl(maybebytes):
38575
152f4822d210 pycompat: move rapply() from util
Yuya Nishihara <yuya@tcha.org>
parents: 38526
diff changeset
   161
    return pycompat.rapply(pycompat.strurl, maybebytes)
34482
75de5d456b60 ui: convert to/from Optional[bytes] to Optional[str] in password manager
Augie Fackler <augie@google.com>
parents: 34426
diff changeset
   162
75de5d456b60 ui: convert to/from Optional[bytes] to Optional[str] in password manager
Augie Fackler <augie@google.com>
parents: 34426
diff changeset
   163
def _maybebytesurl(maybestr):
38575
152f4822d210 pycompat: move rapply() from util
Yuya Nishihara <yuya@tcha.org>
parents: 38526
diff changeset
   164
    return pycompat.rapply(pycompat.bytesurl, maybestr)
30945
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   165
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   166
class httppasswordmgrdbproxy(object):
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   167
    """Delays loading urllib2 until it's needed."""
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   168
    def __init__(self):
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   169
        self._mgr = None
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   170
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   171
    def _get_mgr(self):
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   172
        if self._mgr is None:
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   173
            self._mgr = urlreq.httppasswordmgrwithdefaultrealm()
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   174
        return self._mgr
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   175
34426
ae2fcf7af409 httppasswordmgrdbproxy: specify exact arguments
Augie Fackler <augie@google.com>
parents: 34367
diff changeset
   176
    def add_password(self, realm, uris, user, passwd):
34482
75de5d456b60 ui: convert to/from Optional[bytes] to Optional[str] in password manager
Augie Fackler <augie@google.com>
parents: 34426
diff changeset
   177
        return self._get_mgr().add_password(
35900
72de5c504833 py3: factor out helpers to apply string conversion recursively
Yuya Nishihara <yuya@tcha.org>
parents: 35897
diff changeset
   178
            _maybestrurl(realm), _maybestrurl(uris),
34482
75de5d456b60 ui: convert to/from Optional[bytes] to Optional[str] in password manager
Augie Fackler <augie@google.com>
parents: 34426
diff changeset
   179
            _maybestrurl(user), _maybestrurl(passwd))
30945
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   180
34426
ae2fcf7af409 httppasswordmgrdbproxy: specify exact arguments
Augie Fackler <augie@google.com>
parents: 34367
diff changeset
   181
    def find_user_password(self, realm, uri):
35900
72de5c504833 py3: factor out helpers to apply string conversion recursively
Yuya Nishihara <yuya@tcha.org>
parents: 35897
diff changeset
   182
        mgr = self._get_mgr()
72de5c504833 py3: factor out helpers to apply string conversion recursively
Yuya Nishihara <yuya@tcha.org>
parents: 35897
diff changeset
   183
        return _maybebytesurl(mgr.find_user_password(_maybestrurl(realm),
72de5c504833 py3: factor out helpers to apply string conversion recursively
Yuya Nishihara <yuya@tcha.org>
parents: 35897
diff changeset
   184
                                                     _maybestrurl(uri)))
30945
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   185
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
   186
def _catchterm(*args):
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
   187
    raise error.SignalInterrupt
30945
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   188
32958
4a3f1d362e5f config: explicitly track the use of the standard default value
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32872
diff changeset
   189
# unique object used to detect no default value has been provided when
4a3f1d362e5f config: explicitly track the use of the standard default value
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32872
diff changeset
   190
# retrieving configuration value.
4a3f1d362e5f config: explicitly track the use of the standard default value
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32872
diff changeset
   191
_unset = object()
4a3f1d362e5f config: explicitly track the use of the standard default value
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32872
diff changeset
   192
34882
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
   193
# _reqexithandlers: callbacks run at the end of a request
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
   194
_reqexithandlers = []
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
   195
1559
59b3639df0a9 Convert all classes to new-style classes by deriving them from object.
Eric Hopper <hopper@omnifarious.org>
parents: 1483
diff changeset
   196
class ui(object):
8190
9b8ac5fb7760 ui: kill most users of parentui name and arg, replace with .copy()
Matt Mackall <mpm@selenic.com>
parents: 8189
diff changeset
   197
    def __init__(self, src=None):
30559
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   198
        """Create a fresh new ui object if no src given
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   199
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   200
        Use uimod.ui.load() to create a ui which knows global and user configs.
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   201
        In most cases, you should use ui.copy() to create a copy of an existing
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   202
        ui object.
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   203
        """
21132
350dc24a553d ui: pushbuffer can now also capture stderr
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 20788
diff changeset
   204
        # _buffers: used for temporary capture of output
8202
4746113269c7 ui: buffers -> _buffers
Matt Mackall <mpm@selenic.com>
parents: 8201
diff changeset
   205
        self._buffers = []
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   206
        # 3-tuple describing how each buffer in the stack behaves.
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   207
        # Values are (capture stderr, capture subprocesses, apply labels).
21132
350dc24a553d ui: pushbuffer can now also capture stderr
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 20788
diff changeset
   208
        self._bufferstates = []
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   209
        # When a buffer is active, defines whether we are expanding labels.
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   210
        # This exists to prevent an extra list lookup.
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   211
        self._bufferapplylabels = None
9851
9e7b2c49d25d Make it possible to debug failed hook imports via use of --traceback
Bryan O'Sullivan <bos@serpentine.com>
parents: 9786
diff changeset
   212
        self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
8208
32a2a1e244f1 ui: make interactive a method
Matt Mackall <mpm@selenic.com>
parents: 8206
diff changeset
   213
        self._reportuntrusted = True
32984
6d983e8af49c configitems: introduce a central registry for config option
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32967
diff changeset
   214
        self._knownconfig = configitems.coreitems
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   215
        self._ocfg = config.config() # overlay
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   216
        self._tcfg = config.config() # trusted
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   217
        self._ucfg = config.config() # untrusted
8478
d728f126c1b7 ui: use set instead of dict
Martin Geisler <mg@lazybytes.net>
parents: 8409
diff changeset
   218
        self._trustusers = set()
d728f126c1b7 ui: use set instead of dict
Martin Geisler <mg@lazybytes.net>
parents: 8409
diff changeset
   219
        self._trustgroups = set()
17048
15d4d475de9e ui: add a variable to control whether hooks should be called
Idan Kamara <idankk86@gmail.com>
parents: 16383
diff changeset
   220
        self.callhooks = True
29109
e9ce33c642e8 ui: add an instance flag to hold --insecure bit
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29096
diff changeset
   221
        # Insecure server connections requested.
e9ce33c642e8 ui: add an instance flag to hold --insecure bit
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29096
diff changeset
   222
        self.insecureconnections = False
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   223
        # Blocked time
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   224
        self.logblockedtimes = False
31106
a185b903bda3 color: have the 'ui' object carry the '_colormode' directly
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31094
diff changeset
   225
        # color mode: see mercurial/color.py for possible value
a185b903bda3 color: have the 'ui' object carry the '_colormode' directly
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31094
diff changeset
   226
        self._colormode = None
31113
268caf97c38f color: move the dict with terminfo parameters on the ui object
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31108
diff changeset
   227
        self._terminfoparams = {}
31115
f5131d4f512a color: move 'styles' definition on the 'ui' object
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31114
diff changeset
   228
        self._styles = {}
38526
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   229
        self._uninterruptible = False
8136
6b5522cb2ad2 ui: refactor option setting
Matt Mackall <mpm@selenic.com>
parents: 8135
diff changeset
   230
8190
9b8ac5fb7760 ui: kill most users of parentui name and arg, replace with .copy()
Matt Mackall <mpm@selenic.com>
parents: 8189
diff changeset
   231
        if src:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   232
            self._fout = src._fout
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   233
            self._ferr = src._ferr
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   234
            self._fin = src._fin
40587
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   235
            self._fmsg = src._fmsg
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   236
            self._fmsgout = src._fmsgout
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   237
            self._fmsgerr = src._fmsgerr
39809
23a00bc90a3c chgserver: do not send system() back to client if stdio redirected (issue5992)
Yuya Nishihara <yuya@tcha.org>
parents: 38762
diff changeset
   238
            self._finoutredirected = src._finoutredirected
40730
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
   239
            self._loggers = src._loggers.copy()
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
   240
            self.pageractive = src.pageractive
31026
9c827087df38 ui: rename neverpager to disablepager
Augie Fackler <augie@google.com>
parents: 31014
diff changeset
   241
            self._disablepager = src._disablepager
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   242
            self._tweaked = src._tweaked
14612
4e1ccd4c2b6d ui: add I/O descriptors
Idan Kamara <idankk86@gmail.com>
parents: 14515
diff changeset
   243
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   244
            self._tcfg = src._tcfg.copy()
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   245
            self._ucfg = src._ucfg.copy()
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   246
            self._ocfg = src._ocfg.copy()
8201
7cf2b987acd3 ui: trusted_users -> _trustusers, trusted_groups -> _trustgroups
Matt Mackall <mpm@selenic.com>
parents: 8200
diff changeset
   247
            self._trustusers = src._trustusers.copy()
7cf2b987acd3 ui: trusted_users -> _trustusers, trusted_groups -> _trustgroups
Matt Mackall <mpm@selenic.com>
parents: 8200
diff changeset
   248
            self._trustgroups = src._trustgroups.copy()
9887
38170eeed18c ui: add environ property to access os.environ or wsgirequest.environ
Sune Foldager <cryo@cyanite.org>
parents: 9851
diff changeset
   249
            self.environ = src.environ
17048
15d4d475de9e ui: add a variable to control whether hooks should be called
Idan Kamara <idankk86@gmail.com>
parents: 16383
diff changeset
   250
            self.callhooks = src.callhooks
29109
e9ce33c642e8 ui: add an instance flag to hold --insecure bit
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29096
diff changeset
   251
            self.insecureconnections = src.insecureconnections
31106
a185b903bda3 color: have the 'ui' object carry the '_colormode' directly
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31094
diff changeset
   252
            self._colormode = src._colormode
31113
268caf97c38f color: move the dict with terminfo parameters on the ui object
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31108
diff changeset
   253
            self._terminfoparams = src._terminfoparams.copy()
31115
f5131d4f512a color: move 'styles' definition on the 'ui' object
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31114
diff changeset
   254
            self._styles = src._styles.copy()
31106
a185b903bda3 color: have the 'ui' object carry the '_colormode' directly
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31094
diff changeset
   255
8143
507c49e297e1 ui: simplify init, kill dupconfig
Matt Mackall <mpm@selenic.com>
parents: 8142
diff changeset
   256
            self.fixconfig()
29378
fea71f66ebff url: remember http password database in ui object
liscju <piotr.listkiewicz@gmail.com>
parents: 29366
diff changeset
   257
fea71f66ebff url: remember http password database in ui object
liscju <piotr.listkiewicz@gmail.com>
parents: 29366
diff changeset
   258
            self.httppasswordmgrdb = src.httppasswordmgrdb
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   259
            self._blockedtimes = src._blockedtimes
8143
507c49e297e1 ui: simplify init, kill dupconfig
Matt Mackall <mpm@selenic.com>
parents: 8142
diff changeset
   260
        else:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   261
            self._fout = procutil.stdout
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   262
            self._ferr = procutil.stderr
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   263
            self._fin = procutil.stdin
40587
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   264
            self._fmsg = None
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   265
            self._fmsgout = self.fout  # configurable
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   266
            self._fmsgerr = self.ferr  # configurable
39809
23a00bc90a3c chgserver: do not send system() back to client if stdio redirected (issue5992)
Yuya Nishihara <yuya@tcha.org>
parents: 38762
diff changeset
   267
            self._finoutredirected = False
40730
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
   268
            self._loggers = {}
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
   269
            self.pageractive = False
31026
9c827087df38 ui: rename neverpager to disablepager
Augie Fackler <augie@google.com>
parents: 31014
diff changeset
   270
            self._disablepager = False
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   271
            self._tweaked = False
14612
4e1ccd4c2b6d ui: add I/O descriptors
Idan Kamara <idankk86@gmail.com>
parents: 14515
diff changeset
   272
9887
38170eeed18c ui: add environ property to access os.environ or wsgirequest.environ
Sune Foldager <cryo@cyanite.org>
parents: 9851
diff changeset
   273
            # shared read-only environment
30637
344e68882cd3 py3: replace os.environ with encoding.environ (part 4 of 5)
Pulkit Goyal <7895pulkit@gmail.com>
parents: 30618
diff changeset
   274
            self.environ = encoding.environ
8222
d30a21594812 more whitespace cleanup and some other style nits
Dirkjan Ochtman <dirkjan@ochtman.nl>
parents: 8220
diff changeset
   275
30945
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   276
            self.httppasswordmgrdb = httppasswordmgrdbproxy()
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   277
            self._blockedtimes = collections.defaultdict(int)
29378
fea71f66ebff url: remember http password database in ui object
liscju <piotr.listkiewicz@gmail.com>
parents: 29366
diff changeset
   278
30832
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   279
        allowed = self.configlist('experimental', 'exportableenviron')
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   280
        if '*' in allowed:
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   281
            self._exportableenviron = self.environ
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   282
        else:
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   283
            self._exportableenviron = {}
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   284
            for k in allowed:
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   285
                if k in self.environ:
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   286
                    self._exportableenviron[k] = self.environ[k]
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
   287
30559
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   288
    @classmethod
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   289
    def load(cls):
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   290
        """Create a ui and load global and user configs"""
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   291
        u = cls()
31685
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   292
        # we always trust global config files and environment variables
31683
00e569a2da97 rcutil: let rccomponents return different types of configs (API)
Jun Wu <quark@fb.com>
parents: 31682
diff changeset
   293
        for t, f in rcutil.rccomponents():
00e569a2da97 rcutil: let rccomponents return different types of configs (API)
Jun Wu <quark@fb.com>
parents: 31682
diff changeset
   294
            if t == 'path':
00e569a2da97 rcutil: let rccomponents return different types of configs (API)
Jun Wu <quark@fb.com>
parents: 31682
diff changeset
   295
                u.readconfig(f, trust=True)
31685
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   296
            elif t == 'items':
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   297
                sections = set()
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   298
                for section, name, value, source in f:
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   299
                    # do not set u._ocfg
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   300
                    # XXX clean this up once immutable config object is a thing
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   301
                    u._tcfg.set(section, name, value, source)
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   302
                    u._ucfg.set(section, name, value, source)
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   303
                    sections.add(section)
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   304
                for section in sections:
d83e51654c8a rcutil: let environ override system configs (BC)
Jun Wu <quark@fb.com>
parents: 31683
diff changeset
   305
                    u.fixconfig(section=section)
31683
00e569a2da97 rcutil: let rccomponents return different types of configs (API)
Jun Wu <quark@fb.com>
parents: 31682
diff changeset
   306
            else:
00e569a2da97 rcutil: let rccomponents return different types of configs (API)
Jun Wu <quark@fb.com>
parents: 31682
diff changeset
   307
                raise error.ProgrammingError('unknown rctype: %s' % t)
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   308
        u._maybetweakdefaults()
30559
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   309
        return u
d83ca854fa21 ui: factor out ui.load() to create a ui without loading configs (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30537
diff changeset
   310
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   311
    def _maybetweakdefaults(self):
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   312
        if not self.configbool('ui', 'tweakdefaults'):
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   313
            return
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   314
        if self._tweaked or self.plain('tweakdefaults'):
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   315
            return
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   316
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   317
        # Note: it is SUPER IMPORTANT that you set self._tweaked to
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   318
        # True *before* any calls to setconfig(), otherwise you'll get
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   319
        # infinite recursion between setconfig and this method.
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   320
        #
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   321
        # TODO: We should extract an inner method in setconfig() to
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   322
        # avoid this weirdness.
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   323
        self._tweaked = True
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   324
        tmpcfg = config.config()
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   325
        tmpcfg.parse('<tweakdefaults>', tweakrc)
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   326
        for section in tmpcfg:
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   327
            for name, value in tmpcfg.items(section):
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   328
                if not self.hasconfig(section, name):
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   329
                    self.setconfig(section, name, value, "<tweakdefaults>")
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   330
8189
d2899a856f9f ui: replace parentui mechanism with repo.baseui
Matt Mackall <mpm@selenic.com>
parents: 8187
diff changeset
   331
    def copy(self):
8220
6e6ebeb52899 ui: ui.copy() now takes the ui class into account
Ronny Pfannschmidt <Ronny.Pfannschmidt@gmx.de>
parents: 8208
diff changeset
   332
        return self.__class__(self)
1839
876e4e6ad82b Create local ui object per repository, so .hg/hgrc don't get mixed.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1637
diff changeset
   333
29366
d269e7db2f55 ui: provide official way to reset internal state per command
Yuya Nishihara <yuya@tcha.org>
parents: 29109
diff changeset
   334
    def resetstate(self):
d269e7db2f55 ui: provide official way to reset internal state per command
Yuya Nishihara <yuya@tcha.org>
parents: 29109
diff changeset
   335
        """Clear internal state that shouldn't persist across commands"""
d269e7db2f55 ui: provide official way to reset internal state per command
Yuya Nishihara <yuya@tcha.org>
parents: 29109
diff changeset
   336
        if self._progbar:
d269e7db2f55 ui: provide official way to reset internal state per command
Yuya Nishihara <yuya@tcha.org>
parents: 29109
diff changeset
   337
            self._progbar.resetstate()  # reset last-print time of progress bar
30945
8b83b626fb1e ui: remove urllib2 from being imported early
Kyle Lippincott <spectral@google.com>
parents: 30932
diff changeset
   338
        self.httppasswordmgrdb = httppasswordmgrdbproxy()
29366
d269e7db2f55 ui: provide official way to reset internal state per command
Yuya Nishihara <yuya@tcha.org>
parents: 29109
diff changeset
   339
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   340
    @contextlib.contextmanager
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   341
    def timeblockedsection(self, key):
30978
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
   342
        # this is open-coded below - search for timeblockedsection to find them
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   343
        starttime = util.timer()
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   344
        try:
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   345
            yield
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   346
        finally:
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   347
            self._blockedtimes[key + '_blocked'] += \
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   348
                (util.timer() - starttime) * 1000
29366
d269e7db2f55 ui: provide official way to reset internal state per command
Yuya Nishihara <yuya@tcha.org>
parents: 29109
diff changeset
   349
38526
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   350
    @contextlib.contextmanager
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   351
    def uninterruptable(self):
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   352
        """Mark an operation as unsafe.
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   353
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   354
        Most operations on a repository are safe to interrupt, but a
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   355
        few are risky (for example repair.strip). This context manager
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   356
        lets you advise Mercurial that something risky is happening so
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   357
        that control-C etc can be blocked if desired.
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   358
        """
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   359
        enabled = self.configbool('experimental', 'nointerrupt')
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   360
        if (enabled and
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   361
            self.configbool('experimental', 'nointerrupt-interactiveonly')):
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   362
            enabled = self.interactive()
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   363
        if self._uninterruptible or not enabled:
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   364
            # if nointerrupt support is turned off, the process isn't
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   365
            # interactive, or we're already in an uninterruptable
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   366
            # block, do nothing.
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   367
            yield
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   368
            return
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   369
        def warn():
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   370
            self.warn(_("shutting down cleanly\n"))
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   371
            self.warn(
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   372
                _("press ^C again to terminate immediately (dangerous)\n"))
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   373
            return True
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   374
        with procutil.uninterruptable(warn):
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   375
            try:
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   376
                self._uninterruptible = True
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   377
                yield
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   378
            finally:
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   379
                self._uninterruptible = False
313a940d49a3 ui: add an uninterruptable context manager that can block SIGINT
Augie Fackler <augie@google.com>
parents: 38345
diff changeset
   380
16135
ae5f92e154d3 ui: add formatter method
Matt Mackall <mpm@selenic.com>
parents: 15919
diff changeset
   381
    def formatter(self, topic, opts):
32579
012e0da5b759 formatter: add option to redirect output to file object
Yuya Nishihara <yuya@tcha.org>
parents: 32462
diff changeset
   382
        return formatter.formatter(self, self, topic, opts)
16135
ae5f92e154d3 ui: add formatter method
Matt Mackall <mpm@selenic.com>
parents: 15919
diff changeset
   383
14859
dccecfaebdd2 ui: rename _is_trusted to _trusted
Matt Mackall <mpm@selenic.com>
parents: 14738
diff changeset
   384
    def _trusted(self, fp, f):
3677
1a0fa3914c46 Avoid looking up usernames if the current user owns the .hgrc file
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3676
diff changeset
   385
        st = util.fstat(fp)
8657
3fa92c618624 posix: do not use fstat in isowner
Martin Geisler <mg@lazybytes.net>
parents: 8656
diff changeset
   386
        if util.isowner(st):
3677
1a0fa3914c46 Avoid looking up usernames if the current user owns the .hgrc file
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3676
diff changeset
   387
            return True
8141
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   388
8201
7cf2b987acd3 ui: trusted_users -> _trustusers, trusted_groups -> _trustgroups
Matt Mackall <mpm@selenic.com>
parents: 8200
diff changeset
   389
        tusers, tgroups = self._trustusers, self._trustgroups
8141
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   390
        if '*' in tusers or '*' in tgroups:
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   391
            return True
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   392
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   393
        user = util.username(st.st_uid)
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   394
        group = util.groupname(st.st_gid)
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   395
        if user in tusers or group in tgroups or user == util.username():
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   396
            return True
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   397
8204
797586be575d ui: report_untrusted fixes
Matt Mackall <mpm@selenic.com>
parents: 8203
diff changeset
   398
        if self._reportuntrusted:
16939
fa91ddfc3f36 ui: lowercase "not trusting file" warning message
Martin Geisler <mg@aragost.com>
parents: 16938
diff changeset
   399
            self.warn(_('not trusting file %s from untrusted '
8141
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   400
                        'user %s, group %s\n') % (f, user, group))
e40b629bedd1 ui: cleanup _is_trusted a bit
Matt Mackall <mpm@selenic.com>
parents: 8140
diff changeset
   401
        return False
3551
3b07e223534b Only read .hg/hgrc files from trusted users/groups
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3489
diff changeset
   402
8200
865d2c646f29 ui: assumetrusted -> trust
Matt Mackall <mpm@selenic.com>
parents: 8199
diff changeset
   403
    def readconfig(self, filename, root=None, trust=False,
8345
dcebff8a25dd hgwebdir: read --webdir-conf as actual configuration to ui (issue1586)
Alexander Solovyov <piranha@piranha.org.ua>
parents: 8312
diff changeset
   404
                   sections=None, remap=None):
8142
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   405
        try:
38767
eb2945f0a4a1 ui: fix implicit unicode-to-bytes conversion introduced in 9df29b7c62cf
Augie Fackler <augie@google.com>
parents: 38762
diff changeset
   406
            fp = open(filename, r'rb')
8142
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   407
        except IOError:
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   408
            if not sections: # ignore unless we were looking for something
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   409
                return
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   410
            raise
8139
9302404b60f3 ui: always have ucdata
Matt Mackall <mpm@selenic.com>
parents: 8138
diff changeset
   411
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   412
        cfg = config.config()
14859
dccecfaebdd2 ui: rename _is_trusted to _trusted
Matt Mackall <mpm@selenic.com>
parents: 14738
diff changeset
   413
        trusted = sections or trust or self._trusted(fp, filename)
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   414
8142
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   415
        try:
8345
dcebff8a25dd hgwebdir: read --webdir-conf as actual configuration to ui (issue1586)
Alexander Solovyov <piranha@piranha.org.ua>
parents: 8312
diff changeset
   416
            cfg.read(filename, fp, sections=sections, remap=remap)
15407
ee112eb69d2a misc: adding missing file close() calls
Matt Mackall <mpm@selenic.com>
parents: 15089
diff changeset
   417
            fp.close()
25660
328739ea70c3 global: mass rewrite to use modern exception syntax
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25629
diff changeset
   418
        except error.ConfigError as inst:
8142
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   419
            if trusted:
8144
fca54469480e ui: introduce new config parser
Matt Mackall <mpm@selenic.com>
parents: 8143
diff changeset
   420
                raise
37084
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
   421
            self.warn(_("ignored: %s\n") % stringutil.forcebytestr(inst))
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   422
10455
40dfd46d098f ui: add HGPLAIN environment variable for easier scripting
Brodie Rao <me+hg@dackz.net>
parents: 10426
diff changeset
   423
        if self.plain():
10507
79dd96774187 ui: unset ui.slash when HGPLAIN is set
Brodie Rao <me+hg@dackz.net>
parents: 10506
diff changeset
   424
            for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   425
                      'logtemplate', 'message-output', 'statuscopies', 'style',
10507
79dd96774187 ui: unset ui.slash when HGPLAIN is set
Brodie Rao <me+hg@dackz.net>
parents: 10506
diff changeset
   426
                      'traceback', 'verbose'):
10455
40dfd46d098f ui: add HGPLAIN environment variable for easier scripting
Brodie Rao <me+hg@dackz.net>
parents: 10426
diff changeset
   427
                if k in cfg['ui']:
40dfd46d098f ui: add HGPLAIN environment variable for easier scripting
Brodie Rao <me+hg@dackz.net>
parents: 10426
diff changeset
   428
                    del cfg['ui'][k]
14373
a599431b0ab6 ui: enable alias exception when reading config in plain mode
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14372
diff changeset
   429
            for k, v in cfg.items('defaults'):
a599431b0ab6 ui: enable alias exception when reading config in plain mode
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14372
diff changeset
   430
                del cfg['defaults'][k]
31588
37a0ad669051 plain: ignore [commands] config
Martin von Zweigbergk <martinvonz@google.com>
parents: 31535
diff changeset
   431
            for k, v in cfg.items('commands'):
37a0ad669051 plain: ignore [commands] config
Martin von Zweigbergk <martinvonz@google.com>
parents: 31535
diff changeset
   432
                del cfg['commands'][k]
14373
a599431b0ab6 ui: enable alias exception when reading config in plain mode
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14372
diff changeset
   433
        # Don't remove aliases from the configuration if in the exceptionlist
a599431b0ab6 ui: enable alias exception when reading config in plain mode
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14372
diff changeset
   434
        if self.plain('alias'):
10506
42afde35e9f7 ui: suppress aliases when HGPLAIN is set
Brodie Rao <me+hg@dackz.net>
parents: 10455
diff changeset
   435
            for k, v in cfg.items('alias'):
42afde35e9f7 ui: suppress aliases when HGPLAIN is set
Brodie Rao <me+hg@dackz.net>
parents: 10455
diff changeset
   436
                del cfg['alias'][k]
24883
09049042ab99 ui: disable revsetaliases in plain mode (BC)
Siddharth Agarwal <sid0@fb.com>
parents: 24848
diff changeset
   437
        if self.plain('revsetalias'):
09049042ab99 ui: disable revsetaliases in plain mode (BC)
Siddharth Agarwal <sid0@fb.com>
parents: 24848
diff changeset
   438
            for k, v in cfg.items('revsetalias'):
09049042ab99 ui: disable revsetaliases in plain mode (BC)
Siddharth Agarwal <sid0@fb.com>
parents: 24848
diff changeset
   439
                del cfg['revsetalias'][k]
28958
77e566fe31ec ui: drop template aliases by HGPLAIN
Yuya Nishihara <yuya@tcha.org>
parents: 28635
diff changeset
   440
        if self.plain('templatealias'):
77e566fe31ec ui: drop template aliases by HGPLAIN
Yuya Nishihara <yuya@tcha.org>
parents: 28635
diff changeset
   441
            for k, v in cfg.items('templatealias'):
77e566fe31ec ui: drop template aliases by HGPLAIN
Yuya Nishihara <yuya@tcha.org>
parents: 28635
diff changeset
   442
                del cfg['templatealias'][k]
10455
40dfd46d098f ui: add HGPLAIN environment variable for easier scripting
Brodie Rao <me+hg@dackz.net>
parents: 10426
diff changeset
   443
8142
912bfef12ba6 ui: fold readsections into readconfig
Matt Mackall <mpm@selenic.com>
parents: 8141
diff changeset
   444
        if trusted:
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   445
            self._tcfg.update(cfg)
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   446
            self._tcfg.update(self._ocfg)
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   447
        self._ucfg.update(cfg)
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   448
        self._ucfg.update(self._ocfg)
8139
9302404b60f3 ui: always have ucdata
Matt Mackall <mpm@selenic.com>
parents: 8138
diff changeset
   449
3347
bce7c1b4c1c8 ui.py: normalize settings every time the configuration changes
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3346
diff changeset
   450
        if root is None:
bce7c1b4c1c8 ui.py: normalize settings every time the configuration changes
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3346
diff changeset
   451
            root = os.path.expanduser('~')
bce7c1b4c1c8 ui.py: normalize settings every time the configuration changes
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3346
diff changeset
   452
        self.fixconfig(root=root)
3014
01454af644b8 load extensions only after the ui object has been completely initialized
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3013
diff changeset
   453
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   454
    def fixconfig(self, root=None, section=None):
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   455
        if section in (None, 'paths'):
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   456
            # expand vars and ~
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   457
            # translate paths relative to root (or home) into absolute paths
39818
24e493ec2229 py3: rename pycompat.getcwd() to encoding.getcwd() (API)
Matt Harbison <matt_harbison@yahoo.com>
parents: 39662
diff changeset
   458
            root = root or encoding.getcwd()
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   459
            for c in self._tcfg, self._ucfg, self._ocfg:
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   460
                for n, p in c.items('paths'):
29412
b62bce819d0c ui: don't fixup [paths] sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29378
diff changeset
   461
                    # Ignore sub-options.
b62bce819d0c ui: don't fixup [paths] sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29378
diff changeset
   462
                    if ':' in n:
b62bce819d0c ui: don't fixup [paths] sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29378
diff changeset
   463
                        continue
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   464
                    if not p:
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   465
                        continue
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   466
                    if '%%' in p:
30618
201b44c8875c ui: do not translate empty configsource() to 'none' (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30569
diff changeset
   467
                        s = self.configsource('paths', n) or 'none'
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   468
                        self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
30618
201b44c8875c ui: do not translate empty configsource() to 'none' (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30569
diff changeset
   469
                                  % (n, p, s))
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   470
                        p = p.replace('%%', '%')
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   471
                    p = util.expandpath(p)
14076
924c82157d46 url: move URL parsing functions into util to improve startup time
Brodie Rao <brodie@bitheap.org>
parents: 13984
diff changeset
   472
                    if not util.hasscheme(p) and not os.path.isabs(p):
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   473
                        p = os.path.normpath(os.path.join(root, p))
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   474
                    c.set("paths", n, p)
3347
bce7c1b4c1c8 ui.py: normalize settings every time the configuration changes
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3346
diff changeset
   475
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   476
        if section in (None, 'ui'):
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   477
            # update ui options
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   478
            self._fmsgout, self._fmsgerr = _selectmsgdests(self)
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   479
            self.debugflag = self.configbool('ui', 'debug')
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   480
            self.verbose = self.debugflag or self.configbool('ui', 'verbose')
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   481
            self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   482
            if self.verbose and self.quiet:
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   483
                self.quiet = self.verbose = False
13493
95b0d4c1c9e1 ui: always report untrusted hgrc files when debug enabled
Ry4an Brase <ry4an-hg@ry4an.org>
parents: 13238
diff changeset
   484
            self._reportuntrusted = self.debugflag or self.configbool("ui",
33499
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
   485
                "report_untrusted")
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
   486
            self.tracebackflag = self.configbool('ui', 'traceback')
30976
e92daf156d5c ui: provide a mechanism to track and log blocked time
Simon Farnsworth <simonfar@fb.com>
parents: 30945
diff changeset
   487
            self.logblockedtimes = self.configbool('ui', 'logblockedtimes')
3350
ab900698b832 update ui.quiet/verbose/debug/interactive every time the config changes
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3349
diff changeset
   488
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   489
        if section in (None, 'trusted'):
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   490
            # update trust information
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   491
            self._trustusers.update(self.configlist('trusted', 'users'))
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   492
            self._trustgroups.update(self.configlist('trusted', 'groups'))
3551
3b07e223534b Only read .hg/hgrc files from trusted users/groups
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3489
diff changeset
   493
40994
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   494
        if section in (None, b'devel', b'ui') and self.debugflag:
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   495
            tracked = set()
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   496
            if self.configbool(b'devel', b'debug.extensions'):
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   497
                tracked.add(b'extension')
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   498
            if tracked:
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   499
                logger = loggingutil.fileobjectlogger(self._ferr, tracked)
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   500
                self.setlogger(b'debug', logger)
ab92e2111408 ui: install logger that sends debug.extensions messages to stderr
Yuya Nishihara <yuya@tcha.org>
parents: 40761
diff changeset
   501
15919
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   502
    def backupconfig(self, section, item):
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   503
        return (self._ocfg.backup(section, item),
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   504
                self._tcfg.backup(section, item),
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   505
                self._ucfg.backup(section, item),)
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   506
    def restoreconfig(self, data):
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   507
        self._ocfg.restore(data[0])
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   508
        self._tcfg.restore(data[1])
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   509
        self._ucfg.restore(data[2])
69e792cf7851 config: have a way to backup and restore value in config
Pierre-Yves David <pierre-yves.david@logilab.fr>
parents: 15407
diff changeset
   510
20788
f144928dd058 config: give a useful hint of source for the most common command line settings
Mads Kiilerich <madski@unity3d.com>
parents: 20787
diff changeset
   511
    def setconfig(self, section, name, value, source=''):
20787
be179da10d5f config: backout 77f1f206e135 - 743daa601445 removed the only use of overlay
Mads Kiilerich <madski@unity3d.com>
parents: 20606
diff changeset
   512
        for cfg in (self._ocfg, self._tcfg, self._ucfg):
20788
f144928dd058 config: give a useful hint of source for the most common command line settings
Mads Kiilerich <madski@unity3d.com>
parents: 20787
diff changeset
   513
            cfg.set(section, name, value, source)
12764
ad2506f097d3 ui: only fix config if the relevant section has changed
Nicolas Dumazet <nicdumz.commits@gmail.com>
parents: 12689
diff changeset
   514
        self.fixconfig(section=section)
32872
9fcb6df413c9 ui: add support for a tweakdefaults knob
Augie Fackler <augie@google.com>
parents: 32579
diff changeset
   515
        self._maybetweakdefaults()
960
abfb5cc97fcd Add ui.setconfig overlay
mpm@selenic.com
parents: 953
diff changeset
   516
8199
e9f90e5989d9 ui: _get_cdata -> _data
Matt Mackall <mpm@selenic.com>
parents: 8198
diff changeset
   517
    def _data(self, untrusted):
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   518
        return untrusted and self._ucfg or self._tcfg
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   519
8182
b97abc7c1135 showconfig: show source file and line with --debug
Matt Mackall <mpm@selenic.com>
parents: 8175
diff changeset
   520
    def configsource(self, section, name, untrusted=False):
30618
201b44c8875c ui: do not translate empty configsource() to 'none' (API)
Yuya Nishihara <yuya@tcha.org>
parents: 30569
diff changeset
   521
        return self._data(untrusted).source(section, name)
8182
b97abc7c1135 showconfig: show source file and line with --debug
Matt Mackall <mpm@selenic.com>
parents: 8175
diff changeset
   522
32958
4a3f1d362e5f config: explicitly track the use of the standard default value
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32872
diff changeset
   523
    def config(self, section, name, default=_unset, untrusted=False):
33058
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   524
        """return the plain string version of a config"""
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   525
        value = self._config(section, name, default=default,
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   526
                             untrusted=untrusted)
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   527
        if value is _unset:
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   528
            return None
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   529
        return value
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   530
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   531
    def _config(self, section, name, default=_unset, untrusted=False):
34947
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   532
        value = itemdefault = default
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   533
        item = self._knownconfig.get(section, {}).get(name)
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   534
        alternates = [(section, name)]
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   535
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   536
        if item is not None:
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   537
            alternates.extend(item.alias)
34947
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   538
            if callable(item.default):
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   539
                itemdefault = item.default()
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   540
            else:
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   541
                itemdefault = item.default
34858
85a2db47ad50 configitems: adds a developer warning when accessing undeclared configuration
Boris Feld <boris.feld@octobus.net>
parents: 34849
diff changeset
   542
        else:
85a2db47ad50 configitems: adds a developer warning when accessing undeclared configuration
Boris Feld <boris.feld@octobus.net>
parents: 34849
diff changeset
   543
            msg = ("accessing unregistered config item: '%s.%s'")
85a2db47ad50 configitems: adds a developer warning when accessing undeclared configuration
Boris Feld <boris.feld@octobus.net>
parents: 34849
diff changeset
   544
            msg %= (section, name)
85a2db47ad50 configitems: adds a developer warning when accessing undeclared configuration
Boris Feld <boris.feld@octobus.net>
parents: 34849
diff changeset
   545
            self.develwarn(msg, 2, 'warn-config-unknown')
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   546
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   547
        if default is _unset:
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   548
            if item is None:
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   549
                value = default
33471
d74141ccfd8b configitems: handle case were the default value is not static
Boris Feld <boris.feld@octobus.net>
parents: 33329
diff changeset
   550
            elif item.default is configitems.dynamicdefault:
d74141ccfd8b configitems: handle case were the default value is not static
Boris Feld <boris.feld@octobus.net>
parents: 33329
diff changeset
   551
                value = None
d74141ccfd8b configitems: handle case were the default value is not static
Boris Feld <boris.feld@octobus.net>
parents: 33329
diff changeset
   552
                msg = "config item requires an explicit default value: '%s.%s'"
d74141ccfd8b configitems: handle case were the default value is not static
Boris Feld <boris.feld@octobus.net>
parents: 33329
diff changeset
   553
                msg %= (section, name)
d74141ccfd8b configitems: handle case were the default value is not static
Boris Feld <boris.feld@octobus.net>
parents: 33329
diff changeset
   554
                self.develwarn(msg, 2, 'warn-config-default')
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   555
            else:
34947
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   556
                value = itemdefault
33471
d74141ccfd8b configitems: handle case were the default value is not static
Boris Feld <boris.feld@octobus.net>
parents: 33329
diff changeset
   557
        elif (item is not None
34947
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   558
              and item.default is not configitems.dynamicdefault
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   559
              and default != itemdefault):
ff2110eadbfa configitems: relax warning about unwanted default value
Yuya Nishihara <yuya@tcha.org>
parents: 34882
diff changeset
   560
            msg = ("specifying a mismatched default value for a registered "
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   561
                   "config item: '%s.%s' '%s'")
36126
8f5c7f906f9b ui: use pycompat.bytestr() to get a bytes-repr of config default
Augie Fackler <augie@google.com>
parents: 35961
diff changeset
   562
            msg %= (section, name, pycompat.bytestr(default))
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   563
            self.develwarn(msg, 2, 'warn-config-default')
32989
149b68224b08 configitems: issue a devel warning when overriding default config
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32985
diff changeset
   564
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   565
        for s, n in alternates:
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   566
            candidate = self._data(untrusted).get(s, n, None)
33058
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   567
            if candidate is not None:
1aa05203f7f6 config: extract the core config logic into a private method
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32989
diff changeset
   568
                value = candidate
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   569
                section = s
15035
cc669e4fec95 ui: allow alternatives for config options
Matt Mackall <mpm@selenic.com>
parents: 15002
diff changeset
   570
                name = n
cc669e4fec95 ui: allow alternatives for config options
Matt Mackall <mpm@selenic.com>
parents: 15002
diff changeset
   571
                break
cc669e4fec95 ui: allow alternatives for config options
Matt Mackall <mpm@selenic.com>
parents: 15002
diff changeset
   572
8204
797586be575d ui: report_untrusted fixes
Matt Mackall <mpm@selenic.com>
parents: 8203
diff changeset
   573
        if self.debugflag and not untrusted and self._reportuntrusted:
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   574
            for s, n in alternates:
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   575
                uvalue = self._ucfg.get(s, n)
19536
ab3cf67740d6 ui.config: fix bug in config alternatives from cc669e4fec95
Augie Fackler <durin42@gmail.com>
parents: 19226
diff changeset
   576
                if uvalue is not None and uvalue != value:
ab3cf67740d6 ui.config: fix bug in config alternatives from cc669e4fec95
Augie Fackler <durin42@gmail.com>
parents: 19226
diff changeset
   577
                    self.debug("ignoring untrusted configuration option "
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   578
                               "%s.%s = %s\n" % (s, n, uvalue))
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   579
        return value
3341
a7cec14c9b40 ui.py: move common code out of config and configbool
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3340
diff changeset
   580
32967
cd2fd1765654 config: use the new '_unset' value for 'configsuboptions'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32966
diff changeset
   581
    def configsuboptions(self, section, name, default=_unset, untrusted=False):
27252
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   582
        """Get a config option and all sub-options.
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   583
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   584
        Some config options have sub-options that are declared with the
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   585
        format "key:opt = value". This method is used to return the main
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   586
        option and all its declared sub-options.
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   587
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   588
        Returns a 2-tuple of ``(option, sub-options)``, where `sub-options``
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   589
        is a dict of defined sub-options where keys and values are strings.
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   590
        """
32966
61a8321c9962 config: use the 'config' method in 'configsuboptions'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32965
diff changeset
   591
        main = self.config(section, name, default, untrusted=untrusted)
27252
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   592
        data = self._data(untrusted)
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   593
        sub = {}
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   594
        prefix = '%s:' % name
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   595
        for k, v in data.items(section):
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   596
            if k.startswith(prefix):
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   597
                sub[k[len(prefix):]] = v
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   598
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   599
        if self.debugflag and not untrusted and self._reportuntrusted:
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   600
            for k, v in sub.items():
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   601
                uvalue = self._ucfg.get(section, '%s:%s' % (name, k))
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   602
                if uvalue is not None and uvalue != v:
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   603
                    self.debug('ignoring untrusted configuration option '
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   604
                               '%s:%s.%s = %s\n' % (section, name, k, uvalue))
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   605
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   606
        return main, sub
dccbebcff075 ui: add method to return option and all sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27153
diff changeset
   607
32965
36e16797df32 config: use the new '_unset' value for 'configpath'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32964
diff changeset
   608
    def configpath(self, section, name, default=_unset, untrusted=False):
14924
545e00279670 ui: config path relative to repo root
Simon Heimberg <simohe@besonet.ch>
parents: 14923
diff changeset
   609
        'get a path config item, expanded relative to repo root or config file'
13238
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   610
        v = self.config(section, name, default, untrusted)
14923
351624f8f523 ui: providing no default value to configpath should not raise an Error
Simon Heimberg <simohe@besonet.ch>
parents: 14922
diff changeset
   611
        if v is None:
351624f8f523 ui: providing no default value to configpath should not raise an Error
Simon Heimberg <simohe@besonet.ch>
parents: 14922
diff changeset
   612
            return None
13238
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   613
        if not os.path.isabs(v) or "://" not in v:
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   614
            src = self.configsource(section, name, untrusted)
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   615
            if ':' in src:
14922
1bc970a77977 ui: fix error, base can not be a list
Simon Heimberg <simohe@besonet.ch>
parents: 14859
diff changeset
   616
                base = os.path.dirname(src.rsplit(':')[0])
13238
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   617
                v = os.path.join(base, os.path.expanduser(v))
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   618
        return v
1b591f9b7fd2 ui: add configpath helper
Matt Mackall <mpm@selenic.com>
parents: 13031
diff changeset
   619
32959
b39dafe681df config: use the new '_unset' value for 'configbool'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32958
diff changeset
   620
    def configbool(self, section, name, default=_unset, untrusted=False):
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   621
        """parse a configuration element as a boolean
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   622
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   623
        >>> u = ui(); s = b'foo'
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   624
        >>> u.setconfig(s, b'true', b'yes')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   625
        >>> u.configbool(s, b'true')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   626
        True
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   627
        >>> u.setconfig(s, b'false', b'no')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   628
        >>> u.configbool(s, b'false')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   629
        False
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   630
        >>> u.configbool(s, b'unknown')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   631
        False
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   632
        >>> u.configbool(s, b'unknown', True)
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   633
        True
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   634
        >>> u.setconfig(s, b'invalid', b'somevalue')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   635
        >>> u.configbool(s, b'invalid')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   636
        Traceback (most recent call last):
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   637
            ...
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   638
        ConfigError: foo.invalid is not a boolean ('somevalue')
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   639
        """
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   640
33059
1dc2ffe0123b config: use '_config' within 'configbool'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 33058
diff changeset
   641
        v = self._config(section, name, default, untrusted=untrusted)
8527
f9a80054dd3c use 'x is None' instead of 'x == None'
Martin Geisler <mg@lazybytes.net>
parents: 8478
diff changeset
   642
        if v is None:
33059
1dc2ffe0123b config: use '_config' within 'configbool'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 33058
diff changeset
   643
            return v
1dc2ffe0123b config: use '_config' within 'configbool'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 33058
diff changeset
   644
        if v is _unset:
32959
b39dafe681df config: use the new '_unset' value for 'configbool'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32958
diff changeset
   645
            if default is _unset:
b39dafe681df config: use the new '_unset' value for 'configbool'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32958
diff changeset
   646
                return False
8144
fca54469480e ui: introduce new config parser
Matt Mackall <mpm@selenic.com>
parents: 8143
diff changeset
   647
            return default
10243
cd3e5c47d663 ui: just return it if it's already a bool
Dirkjan Ochtman <dirkjan@ochtman.nl>
parents: 10220
diff changeset
   648
        if isinstance(v, bool):
cd3e5c47d663 ui: just return it if it's already a bool
Dirkjan Ochtman <dirkjan@ochtman.nl>
parents: 10220
diff changeset
   649
            return v
37084
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
   650
        b = stringutil.parsebool(v)
12087
a88a4720c2f0 parsebool: create new function and use it for config parsing
Augie Fackler <durin42@gmail.com>
parents: 11984
diff changeset
   651
        if b is None:
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   652
            raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
8144
fca54469480e ui: introduce new config parser
Matt Mackall <mpm@selenic.com>
parents: 8143
diff changeset
   653
                                    % (section, name, v))
12087
a88a4720c2f0 parsebool: create new function and use it for config parsing
Augie Fackler <durin42@gmail.com>
parents: 11984
diff changeset
   654
        return b
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   655
32960
6ff6eb33f353 config: use the new '_unset' value for 'configwith'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32959
diff changeset
   656
    def configwith(self, convert, section, name, default=_unset,
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   657
                   desc=None, untrusted=False):
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   658
        """parse a configuration element with a conversion function
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   659
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   660
        >>> u = ui(); s = b'foo'
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   661
        >>> u.setconfig(s, b'float1', b'42')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   662
        >>> u.configwith(float, s, b'float1')
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   663
        42.0
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   664
        >>> u.setconfig(s, b'float2', b'-4.25')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   665
        >>> u.configwith(float, s, b'float2')
30932
f61c5680a862 ui: fix configwith doctest
Jun Wu <quark@fb.com>
parents: 30927
diff changeset
   666
        -4.25
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   667
        >>> u.configwith(float, s, b'unknown', 7)
32960
6ff6eb33f353 config: use the new '_unset' value for 'configwith'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32959
diff changeset
   668
        7.0
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   669
        >>> u.setconfig(s, b'invalid', b'somevalue')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   670
        >>> u.configwith(float, s, b'invalid')
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   671
        Traceback (most recent call last):
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   672
            ...
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   673
        ConfigError: foo.invalid is not a valid float ('somevalue')
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   674
        >>> u.configwith(float, s, b'invalid', desc=b'womble')
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   675
        Traceback (most recent call last):
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   676
            ...
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   677
        ConfigError: foo.invalid is not a valid womble ('somevalue')
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   678
        """
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   679
32960
6ff6eb33f353 config: use the new '_unset' value for 'configwith'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32959
diff changeset
   680
        v = self.config(section, name, default, untrusted)
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   681
        if v is None:
32960
6ff6eb33f353 config: use the new '_unset' value for 'configwith'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32959
diff changeset
   682
            return v # do not attempt to convert None
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   683
        try:
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   684
            return convert(v)
32462
bb18728ea617 util: raise ParseError when parsing dates (BC)
Boris Feld <boris.feld@octobus.net>
parents: 32449
diff changeset
   685
        except (ValueError, error.ParseError):
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   686
            if desc is None:
34208
0a2fd3bfc704 py3: convert function name to bytes in ui.configwith()
Yuya Nishihara <yuya@tcha.org>
parents: 34131
diff changeset
   687
                desc = pycompat.sysbytes(convert.__name__)
30926
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   688
            raise error.ConfigError(_("%s.%s is not a valid %s ('%s')")
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   689
                                    % (section, name, desc, v))
120682fce099 ui: add a configwith method
Bryan O'Sullivan <bryano@fb.com>
parents: 30925
diff changeset
   690
32961
24111157f967 config: use the new '_unset' value for 'configint'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32960
diff changeset
   691
    def configint(self, section, name, default=_unset, untrusted=False):
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   692
        """parse a configuration element as an integer
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   693
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   694
        >>> u = ui(); s = b'foo'
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   695
        >>> u.setconfig(s, b'int1', b'42')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   696
        >>> u.configint(s, b'int1')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   697
        42
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   698
        >>> u.setconfig(s, b'int2', b'-42')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   699
        >>> u.configint(s, b'int2')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   700
        -42
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   701
        >>> u.configint(s, b'unknown', 7)
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   702
        7
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   703
        >>> u.setconfig(s, b'invalid', b'somevalue')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   704
        >>> u.configint(s, b'invalid')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   705
        Traceback (most recent call last):
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   706
            ...
30927
8fa3ab6221b9 ui: rewrite configint in terms of configwith
Bryan O'Sullivan <bryano@fb.com>
parents: 30926
diff changeset
   707
        ConfigError: foo.invalid is not a valid integer ('somevalue')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   708
        """
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   709
30927
8fa3ab6221b9 ui: rewrite configint in terms of configwith
Bryan O'Sullivan <bryano@fb.com>
parents: 30926
diff changeset
   710
        return self.configwith(int, section, name, default, 'integer',
8fa3ab6221b9 ui: rewrite configint in terms of configwith
Bryan O'Sullivan <bryano@fb.com>
parents: 30926
diff changeset
   711
                               untrusted)
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   712
32962
0bf986cfa82b config: use the new '_unset' value for 'configbytes'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32961
diff changeset
   713
    def configbytes(self, section, name, default=_unset, untrusted=False):
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   714
        """parse a configuration element as a quantity in bytes
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   715
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   716
        Units can be specified as b (bytes), k or kb (kilobytes), m or
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   717
        mb (megabytes), g or gb (gigabytes).
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   718
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   719
        >>> u = ui(); s = b'foo'
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   720
        >>> u.setconfig(s, b'val1', b'42')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   721
        >>> u.configbytes(s, b'val1')
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   722
        42
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   723
        >>> u.setconfig(s, b'val2', b'42.5 kb')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   724
        >>> u.configbytes(s, b'val2')
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   725
        43520
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   726
        >>> u.configbytes(s, b'unknown', b'7 MB')
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   727
        7340032
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   728
        >>> u.setconfig(s, b'invalid', b'somevalue')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   729
        >>> u.configbytes(s, b'invalid')
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   730
        Traceback (most recent call last):
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   731
            ...
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   732
        ConfigError: foo.invalid is not a byte quantity ('somevalue')
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   733
        """
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   734
33060
e70cbae4c4e6 config: use '_config' within 'configbytes'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 33059
diff changeset
   735
        value = self._config(section, name, default, untrusted)
e70cbae4c4e6 config: use '_config' within 'configbytes'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 33059
diff changeset
   736
        if value is _unset:
32962
0bf986cfa82b config: use the new '_unset' value for 'configbytes'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32961
diff changeset
   737
            if default is _unset:
0bf986cfa82b config: use the new '_unset' value for 'configbytes'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32961
diff changeset
   738
                default = 0
19195
9311cd5c09ed ui: use util.sizetoint in configbytes
Bryan O'Sullivan <bryano@fb.com>
parents: 19085
diff changeset
   739
            value = default
33585
d90f9e4704de ui: fix configbytes isinstance check to look for bytes and not str
Augie Fackler <augie@google.com>
parents: 33499
diff changeset
   740
        if not isinstance(value, bytes):
32962
0bf986cfa82b config: use the new '_unset' value for 'configbytes'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32961
diff changeset
   741
            return value
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   742
        try:
19195
9311cd5c09ed ui: use util.sizetoint in configbytes
Bryan O'Sullivan <bryano@fb.com>
parents: 19085
diff changeset
   743
            return util.sizetoint(value)
9311cd5c09ed ui: use util.sizetoint in configbytes
Bryan O'Sullivan <bryano@fb.com>
parents: 19085
diff changeset
   744
        except error.ParseError:
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   745
            raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
19195
9311cd5c09ed ui: use util.sizetoint in configbytes
Bryan O'Sullivan <bryano@fb.com>
parents: 19085
diff changeset
   746
                                    % (section, name, value))
19065
2c4cd1c42365 ui: add a configbytes method, for space configuration
Bryan O'Sullivan <bryano@fb.com>
parents: 18966
diff changeset
   747
32963
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   748
    def configlist(self, section, name, default=_unset, untrusted=False):
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   749
        """parse a configuration element as a list of comma/space separated
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   750
        strings
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   751
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   752
        >>> u = ui(); s = b'foo'
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   753
        >>> u.setconfig(s, b'list1', b'this,is "a small" ,test')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   754
        >>> u.configlist(s, b'list1')
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   755
        ['this', 'is', 'a small', 'test']
34957
58e7791e243b ui: add configlist doctest to document a bit more of the whitespace behavior
Augie Fackler <augie@google.com>
parents: 34947
diff changeset
   756
        >>> u.setconfig(s, b'list2', b'this, is "a small" , test ')
58e7791e243b ui: add configlist doctest to document a bit more of the whitespace behavior
Augie Fackler <augie@google.com>
parents: 34947
diff changeset
   757
        >>> u.configlist(s, b'list2')
58e7791e243b ui: add configlist doctest to document a bit more of the whitespace behavior
Augie Fackler <augie@google.com>
parents: 34947
diff changeset
   758
        ['this', 'is', 'a small', 'test']
14171
fa2b596db182 ui: add configint function and tests
Sune Foldager <cryo@cyanite.org>
parents: 14076
diff changeset
   759
        """
31481
a7c687c35119 ui: move configlist parser to config.py
Jun Wu <quark@fb.com>
parents: 31479
diff changeset
   760
        # default is not always a list
32963
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   761
        v = self.configwith(config.parselist, section, name, default,
31481
a7c687c35119 ui: move configlist parser to config.py
Jun Wu <quark@fb.com>
parents: 31479
diff changeset
   762
                               'list', untrusted)
32963
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   763
        if isinstance(v, bytes):
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   764
            return config.parselist(v)
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   765
        elif v is None:
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   766
            return []
88b3a38d39e3 config: use the new '_unset' value for 'configlist'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32962
diff changeset
   767
        return v
2499
894435215344 Added ui.configlist method to get comma/space separated lists of strings.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 2498
diff changeset
   768
32964
6599b7372387 config: use the new '_unset' value for 'configdate'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32963
diff changeset
   769
    def configdate(self, section, name, default=_unset, untrusted=False):
32408
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   770
        """parse a configuration element as a tuple of ints
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   771
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   772
        >>> u = ui(); s = b'foo'
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   773
        >>> u.setconfig(s, b'date', b'0 0')
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
   774
        >>> u.configdate(s, b'date')
32408
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   775
        (0, 0)
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   776
        """
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   777
        if self.config(section, name, default, untrusted):
36607
c6061cadb400 util: extract all date-related utils in utils/dateutil module
Boris Feld <boris.feld@octobus.net>
parents: 36422
diff changeset
   778
            return self.configwith(dateutil.parsedate, section, name, default,
32408
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   779
                                   'date', untrusted)
32964
6599b7372387 config: use the new '_unset' value for 'configdate'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32963
diff changeset
   780
        if default is _unset:
6599b7372387 config: use the new '_unset' value for 'configdate'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 32963
diff changeset
   781
            return None
32408
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   782
        return default
420e93b0d9dc ui: add the possiblity to get a date config field
Boris Feld <boris.feld@octobus.net>
parents: 32105
diff changeset
   783
27696
e70c97cc9243 config: add hasconfig method and supporting plumbing
Bryan O'Sullivan <bos@serpentine.com>
parents: 27563
diff changeset
   784
    def hasconfig(self, section, name, untrusted=False):
e70c97cc9243 config: add hasconfig method and supporting plumbing
Bryan O'Sullivan <bos@serpentine.com>
parents: 27563
diff changeset
   785
        return self._data(untrusted).hasitem(section, name)
e70c97cc9243 config: add hasconfig method and supporting plumbing
Bryan O'Sullivan <bos@serpentine.com>
parents: 27563
diff changeset
   786
4487
1b5b98837bb5 ui: Rename has_config to has_section.
Bryan O'Sullivan <bos@serpentine.com>
parents: 4258
diff changeset
   787
    def has_section(self, section, untrusted=False):
2343
af81d8770620 add ui.has_config method.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 2335
diff changeset
   788
        '''tell whether section exists in config.'''
8199
e9f90e5989d9 ui: _get_cdata -> _data
Matt Mackall <mpm@selenic.com>
parents: 8198
diff changeset
   789
        return section in self._data(untrusted)
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   790
27253
f43988e5954c ui: optionally ignore sub-options from configitems()
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27252
diff changeset
   791
    def configitems(self, section, untrusted=False, ignoresub=False):
8199
e9f90e5989d9 ui: _get_cdata -> _data
Matt Mackall <mpm@selenic.com>
parents: 8198
diff changeset
   792
        items = self._data(untrusted).items(section)
27253
f43988e5954c ui: optionally ignore sub-options from configitems()
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27252
diff changeset
   793
        if ignoresub:
37134
6890b7e991a4 help: supporting both help and doc for aliases
Rodrigo Damazio <rdamazio@google.com>
parents: 37120
diff changeset
   794
            items = [i for i in items if ':' not in i[0]]
8204
797586be575d ui: report_untrusted fixes
Matt Mackall <mpm@selenic.com>
parents: 8203
diff changeset
   795
        if self.debugflag and not untrusted and self._reportuntrusted:
8222
d30a21594812 more whitespace cleanup and some other style nits
Dirkjan Ochtman <dirkjan@ochtman.nl>
parents: 8220
diff changeset
   796
            for k, v in self._ucfg.items(section):
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   797
                if self._tcfg.get(section, k) != v:
14708
8083f4d00bd1 i18n: remove translation of debug messages
David Soria Parra <dsp@php.net>
parents: 14614
diff changeset
   798
                    self.debug("ignoring untrusted configuration option "
8083f4d00bd1 i18n: remove translation of debug messages
David Soria Parra <dsp@php.net>
parents: 14614
diff changeset
   799
                               "%s.%s = %s\n" % (section, k, v))
8144
fca54469480e ui: introduce new config parser
Matt Mackall <mpm@selenic.com>
parents: 8143
diff changeset
   800
        return items
285
5a1e6d27f399 ui: add configuration file support
mpm@selenic.com
parents: 249
diff changeset
   801
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   802
    def walkconfig(self, untrusted=False):
8203
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   803
        cfg = self._data(untrusted)
3377fa11af67 ui: privatize cdata vars
Matt Mackall <mpm@selenic.com>
parents: 8202
diff changeset
   804
        for section in cfg.sections():
3552
9b52239dc740 save settings from untrusted config files in a separate configparser
Alexis S. L. Carvalho <alexis@cecm.usp.br>
parents: 3551
diff changeset
   805
            for name, value in self.configitems(section, untrusted):
13576
edd06611a7c6 ui: yield unchanged values in walkconfig
Martin Geisler <mg@aragost.com>
parents: 13493
diff changeset
   806
                yield section, name, value
1028
25e7ea0f2cff Add commands.debugconfig.
Bryan O'Sullivan <bos@serpentine.com>
parents: 981
diff changeset
   807
14372
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   808
    def plain(self, feature=None):
11325
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
   809
        '''is plain mode active?
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
   810
13849
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   811
        Plain mode means that all configuration variables which affect
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   812
        the behavior and output of Mercurial should be
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   813
        ignored. Additionally, the output should be stable,
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   814
        reproducible and suitable for use in scripts or applications.
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   815
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   816
        The only way to trigger plain mode is by setting either the
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   817
        `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
11325
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
   818
14372
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   819
        The return value can either be
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   820
        - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
35170
c9740b69b9b7 dispatch: add HGPLAIN=+strictflags to restrict early parsing of global options
Yuya Nishihara <yuya@tcha.org>
parents: 34947
diff changeset
   821
        - False if feature is disabled by default and not included in HGPLAIN
14372
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   822
        - True otherwise
11325
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
   823
        '''
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
   824
        if ('HGPLAIN' not in encoding.environ and
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
   825
                'HGPLAINEXCEPT' not in encoding.environ):
13849
9f97de157aad HGPLAIN: allow exceptions to plain mode, like i18n, via HGPLAINEXCEPT
Brodie Rao <brodie@bitheap.org>
parents: 13827
diff changeset
   826
            return False
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
   827
        exceptions = encoding.environ.get('HGPLAINEXCEPT',
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
   828
                '').strip().split(',')
35170
c9740b69b9b7 dispatch: add HGPLAIN=+strictflags to restrict early parsing of global options
Yuya Nishihara <yuya@tcha.org>
parents: 34947
diff changeset
   829
        # TODO: add support for HGPLAIN=+feature,-feature syntax
c9740b69b9b7 dispatch: add HGPLAIN=+strictflags to restrict early parsing of global options
Yuya Nishihara <yuya@tcha.org>
parents: 34947
diff changeset
   830
        if '+strictflags' not in encoding.environ.get('HGPLAIN', '').split(','):
c9740b69b9b7 dispatch: add HGPLAIN=+strictflags to restrict early parsing of global options
Yuya Nishihara <yuya@tcha.org>
parents: 34947
diff changeset
   831
            exceptions.append('strictflags')
14372
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   832
        if feature and exceptions:
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   833
            return feature not in exceptions
be0daa0eeb3e ui: test plain mode against exceptions
"Yann E. MORIN" <yann.morin.1998@anciens.enib.fr>
parents: 14171
diff changeset
   834
        return True
10455
40dfd46d098f ui: add HGPLAIN environment variable for easier scripting
Brodie Rao <me+hg@dackz.net>
parents: 10426
diff changeset
   835
34849
9f2891fb426c ui: add the possibility to returns None as username in ui
Boris Feld <boris.feld@octobus.net>
parents: 34707
diff changeset
   836
    def username(self, acceptempty=False):
1985
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   837
        """Return default username to be used in commits.
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   838
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   839
        Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   840
        and stop searching if one of these is set.
34849
9f2891fb426c ui: add the possibility to returns None as username in ui
Boris Feld <boris.feld@octobus.net>
parents: 34707
diff changeset
   841
        If not found and acceptempty is True, returns None.
6862
7192876ac329 ui: add an option to prompt for the username when it isn't provided
Benoit Boissinot <benoit.boissinot@ens-lyon.org>
parents: 6762
diff changeset
   842
        If not found and ui.askusername is True, ask the user, else use
7192876ac329 ui: add an option to prompt for the username when it isn't provided
Benoit Boissinot <benoit.boissinot@ens-lyon.org>
parents: 6762
diff changeset
   843
        ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
34849
9f2891fb426c ui: add the possibility to returns None as username in ui
Boris Feld <boris.feld@octobus.net>
parents: 34707
diff changeset
   844
        If no username could be found, raise an Abort error.
1985
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   845
        """
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
   846
        user = encoding.environ.get("HGUSER")
1985
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   847
        if user is None:
33329
e714159860fd configitems: add alias support in config
David Demelier <demelier.david@gmail.com>
parents: 33150
diff changeset
   848
            user = self.config("ui", "username")
11225
d6dbd5e4ee72 ui.username(): expand environment variables in username configuration value.
Chad Dombrova <chadrik@gmail.com>
parents: 11036
diff changeset
   849
            if user is not None:
d6dbd5e4ee72 ui.username(): expand environment variables in username configuration value.
Chad Dombrova <chadrik@gmail.com>
parents: 11036
diff changeset
   850
                user = os.path.expandvars(user)
1985
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   851
        if user is None:
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
   852
            user = encoding.environ.get("EMAIL")
34849
9f2891fb426c ui: add the possibility to returns None as username in ui
Boris Feld <boris.feld@octobus.net>
parents: 34707
diff changeset
   853
        if user is None and acceptempty:
9f2891fb426c ui: add the possibility to returns None as username in ui
Boris Feld <boris.feld@octobus.net>
parents: 34707
diff changeset
   854
            return user
6862
7192876ac329 ui: add an option to prompt for the username when it isn't provided
Benoit Boissinot <benoit.boissinot@ens-lyon.org>
parents: 6762
diff changeset
   855
        if user is None and self.configbool("ui", "askusername"):
7600
f7739cf3833c lowercase prompts
Martin Geisler <mg@daimi.au.dk>
parents: 7497
diff changeset
   856
            user = self.prompt(_("enter a commit username:"), default=None)
9613
c63c336ee2f7 ui: only use "user@host" as username in noninteractive mode
Martin Geisler <mg@lazybytes.net>
parents: 9610
diff changeset
   857
        if user is None and not self.interactive():
3721
98f2507c5551 only print a warning when no username is specified
Benoit Boissinot <benoit.boissinot@ens-lyon.org>
parents: 3678
diff changeset
   858
            try:
37120
a8a902d7176e procutil: bulk-replace function calls to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37119
diff changeset
   859
                user = '%s@%s' % (procutil.getuser(),
36784
e3732c3ab92d py3: fix type of default username
Yuya Nishihara <yuya@tcha.org>
parents: 36732
diff changeset
   860
                                  encoding.strtolocal(socket.getfqdn()))
16940
6409a5c75125 ui: lowercase "no username" warning
Martin Geisler <mg@aragost.com>
parents: 16939
diff changeset
   861
                self.warn(_("no username found, using '%s' instead\n") % user)
3721
98f2507c5551 only print a warning when no username is specified
Benoit Boissinot <benoit.boissinot@ens-lyon.org>
parents: 3678
diff changeset
   862
            except KeyError:
4044
78a0dd93db0b Abort on empty username so specifying a username can be forced.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 3984
diff changeset
   863
                pass
78a0dd93db0b Abort on empty username so specifying a username can be forced.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 3984
diff changeset
   864
        if not user:
26587
56b2bcea2529 error: get Abort from 'error' instead of 'util'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 26451
diff changeset
   865
            raise error.Abort(_('no username supplied'),
28962
ad2cd2ef25d9 config: use single quotes around command hint
timeless <timeless@mozdev.org>
parents: 28958
diff changeset
   866
                             hint=_("use 'hg config --edit' "
20580
b75a23eec9c9 ui: fix extra space in username abort
Matt Mackall <mpm@selenic.com>
parents: 20574
diff changeset
   867
                                    'to set your username'))
6351
eed0a6a05096 ui: disallow newlines in usernames (issue1034)
Matt Mackall <mpm@selenic.com>
parents: 6333
diff changeset
   868
        if "\n" in user:
36228
ddeb7653b31c py3: use pycompat.bytestr to convert str to bytes
Pulkit Goyal <7895pulkit@gmail.com>
parents: 36127
diff changeset
   869
            raise error.Abort(_("username %r contains a newline\n")
ddeb7653b31c py3: use pycompat.bytestr to convert str to bytes
Pulkit Goyal <7895pulkit@gmail.com>
parents: 36127
diff changeset
   870
                              % pycompat.bytestr(user))
1985
c577689006fa Adapted behaviour of ui.username() to documentation and mention it explicitly:
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1984
diff changeset
   871
        return user
608
d2994b5298fb Add username/merge/editor to .hgrc
Matt Mackall <mpm@selenic.com>
parents: 565
diff changeset
   872
1129
ee4f60abad93 Move generating short username to display in hg/hgweb annotate to ui module.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1071
diff changeset
   873
    def shortuser(self, user):
ee4f60abad93 Move generating short username to display in hg/hgweb annotate to ui module.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1071
diff changeset
   874
        """Return a short representation of a user name or email address."""
10282
08a0f04b56bd many, many trivial check-code fixups
Matt Mackall <mpm@selenic.com>
parents: 10264
diff changeset
   875
        if not self.verbose:
37084
f0b6fbea00cf stringutil: bulk-replace call sites to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 36910
diff changeset
   876
            user = stringutil.shortuser(user)
1129
ee4f60abad93 Move generating short username to display in hg/hgweb annotate to ui module.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1071
diff changeset
   877
        return user
ee4f60abad93 Move generating short username to display in hg/hgweb annotate to ui module.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1071
diff changeset
   878
2494
73ac95671788 push, outgoing, bundle: fall back to "default" if "default-push" not defined
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 2470
diff changeset
   879
    def expandpath(self, loc, default=None):
1892
622ee75cb4c9 Directory names take precedence over symbolic names consistently.
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1882
diff changeset
   880
        """Return repository location relative to cwd or from [paths]"""
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   881
        try:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   882
            p = self.paths.getpath(loc)
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   883
            if p:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   884
                return p.rawloc
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   885
        except error.RepoError:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   886
            pass
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   887
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   888
        if default:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   889
            try:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   890
                p = self.paths.getpath(default)
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   891
                if p:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   892
                    return p.rawloc
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   893
            except error.RepoError:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   894
                pass
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
   895
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
   896
        return loc
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
   897
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
   898
    @util.propertycache
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
   899
    def paths(self):
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
   900
        return paths(self)
506
1f81ebff98c9 [PATCH] Add ui.expandpath command
mpm@selenic.com
parents: 350
diff changeset
   901
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   902
    @property
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   903
    def fout(self):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   904
        return self._fout
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   905
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   906
    @fout.setter
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   907
    def fout(self, f):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   908
        self._fout = f
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   909
        self._fmsgout, self._fmsgerr = _selectmsgdests(self)
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   910
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   911
    @property
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   912
    def ferr(self):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   913
        return self._ferr
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   914
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   915
    @ferr.setter
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   916
    def ferr(self, f):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   917
        self._ferr = f
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
   918
        self._fmsgout, self._fmsgerr = _selectmsgdests(self)
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   919
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   920
    @property
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   921
    def fin(self):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   922
        return self._fin
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   923
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   924
    @fin.setter
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   925
    def fin(self, f):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   926
        self._fin = f
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   927
40587
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   928
    @property
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   929
    def fmsg(self):
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   930
        """Stream dedicated for status/error messages; may be None if
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   931
        fout/ferr are used"""
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   932
        return self._fmsg
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   933
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   934
    @fmsg.setter
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   935
    def fmsg(self, f):
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   936
        self._fmsg = f
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   937
        self._fmsgout, self._fmsgerr = _selectmsgdests(self)
5542bc9125c9 dispatch: pass around ui.fmsg channel
Yuya Nishihara <yuya@tcha.org>
parents: 40578
diff changeset
   938
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   939
    def pushbuffer(self, error=False, subproc=False, labeled=False):
23139
e53f6b72a0e4 spelling: fixes from proofreading of spell checker issues
Mads Kiilerich <madski@unity3d.com>
parents: 23053
diff changeset
   940
        """install a buffer to capture standard output of the ui object
21132
350dc24a553d ui: pushbuffer can now also capture stderr
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 20788
diff changeset
   941
24848
2f88821856eb ui: allow capture of subprocess output
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 24687
diff changeset
   942
        If error is True, the error output will be captured too.
2f88821856eb ui: allow capture of subprocess output
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 24687
diff changeset
   943
2f88821856eb ui: allow capture of subprocess output
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 24687
diff changeset
   944
        If subproc is True, output from subprocesses (typically hooks) will be
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   945
        captured too.
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   946
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   947
        If labeled is True, any labels associated with buffered
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   948
        output will be handled. By default, this has no effect
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   949
        on the output returned, but extensions and GUI tools may
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   950
        handle this argument and returned styled output. If output
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   951
        is being buffered so it can be captured and parsed or
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   952
        processed, labeled should not be set to True.
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   953
        """
8202
4746113269c7 ui: buffers -> _buffers
Matt Mackall <mpm@selenic.com>
parents: 8201
diff changeset
   954
        self._buffers.append([])
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   955
        self._bufferstates.append((error, subproc, labeled))
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   956
        self._bufferapplylabels = labeled
3737
9f5c46c50118 add a simple nested buffering scheme to ui
Matt Mackall <mpm@selenic.com>
parents: 3721
diff changeset
   957
27109
a93d53f79e6e ui: remove labeled argument from popbuffer
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27106
diff changeset
   958
    def popbuffer(self):
a93d53f79e6e ui: remove labeled argument from popbuffer
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27106
diff changeset
   959
        '''pop the last buffer and return the buffered output'''
21132
350dc24a553d ui: pushbuffer can now also capture stderr
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 20788
diff changeset
   960
        self._bufferstates.pop()
27106
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   961
        if self._bufferstates:
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   962
            self._bufferapplylabels = self._bufferstates[-1][2]
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   963
        else:
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   964
            self._bufferapplylabels = None
6ef17697b03d ui: track label expansion when creating buffers
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27068
diff changeset
   965
8202
4746113269c7 ui: buffers -> _buffers
Matt Mackall <mpm@selenic.com>
parents: 8201
diff changeset
   966
        return "".join(self._buffers.pop())
3737
9f5c46c50118 add a simple nested buffering scheme to ui
Matt Mackall <mpm@selenic.com>
parents: 3721
diff changeset
   967
40541
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
   968
    def _isbuffered(self, dest):
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   969
        if dest is self._fout:
40541
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
   970
            return bool(self._buffers)
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
   971
        if dest is self._ferr:
40541
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
   972
            return bool(self._bufferstates and self._bufferstates[-1][0])
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
   973
        return False
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
   974
35961
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   975
    def canwritewithoutlabels(self):
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   976
        '''check if write skips the label'''
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   977
        if self._buffers and not self._bufferapplylabels:
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   978
            return True
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   979
        return self._colormode is None
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   980
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   981
    def canbatchlabeledwrites(self):
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   982
        '''check if write calls with labels are batchable'''
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   983
        # Windows color printing is special, see ``write``.
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   984
        return self._colormode != 'win32'
0ff41ced4c12 diff: improve ui.write performance when not coloring on Windows
Joerg Sonnenberger <joerg@bec.de>
parents: 35957
diff changeset
   985
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   986
    def write(self, *args, **opts):
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   987
        '''write args to output
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   988
31091
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   989
        By default, this method simply writes to the buffer or stdout.
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   990
        Color mode can be set on the UI class to have the output decorated
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   991
        with color modifier before being written to stdout.
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   992
31091
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   993
        The color used is controlled by an optional keyword argument, "label".
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   994
        This should be a string containing label names separated by space.
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   995
        Label names take the form of "topic.type". For example, ui.debug()
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
   996
        issues a label of "ui.debug".
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   997
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   998
        When labeling output for a specific command, a label of
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
   999
        "cmdname.type" is recommended. For example, status issues
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1000
        a label of "status.modified" for modified files.
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1001
        '''
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1002
        self._write(self._fout, *args, **opts)
40541
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
  1003
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
  1004
    def write_err(self, *args, **opts):
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1005
        self._write(self._ferr, *args, **opts)
40541
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
  1006
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
  1007
    def _write(self, dest, *args, **opts):
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
  1008
        if self._isbuffered(dest):
31091
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
  1009
            if self._bufferapplylabels:
35373
4e377c43e80b py3: handle keyword arguments correctly in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 35307
diff changeset
  1010
                label = opts.get(r'label', '')
31091
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
  1011
                self._buffers[-1].extend(self.label(a, label) for a in args)
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
  1012
            else:
ad074f900907 color: move 'write' logic to the core ui class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31090
diff changeset
  1013
                self._buffers[-1].extend(args)
35957
b62c4154bb28 ui: add explicit path to write prompt text bypassing buffers
Yuya Nishihara <yuya@tcha.org>
parents: 35956
diff changeset
  1014
        else:
40541
c2aea007130b ui: add inner function to select write destination
Yuya Nishihara <yuya@tcha.org>
parents: 40540
diff changeset
  1015
            self._writenobuf(dest, *args, **opts)
35957
b62c4154bb28 ui: add explicit path to write prompt text bypassing buffers
Yuya Nishihara <yuya@tcha.org>
parents: 35956
diff changeset
  1016
40538
c5e964f75bf7 ui: pass in file object to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40524
diff changeset
  1017
    def _writenobuf(self, dest, *args, **opts):
40519
3c4b9dace7de ui: consolidate places where _progclear() is called
Yuya Nishihara <yuya@tcha.org>
parents: 40226
diff changeset
  1018
        self._progclear()
40522
51091816a355 ui: simply concatenate messages before applying color labels
Yuya Nishihara <yuya@tcha.org>
parents: 40521
diff changeset
  1019
        msg = b''.join(args)
31090
e9f96ccf36a6 ui: extract the low level part of 'write' in a dedicated function
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31087
diff changeset
  1020
31128
0bb3089fe735 ui: remove superfluous indent in _write()
Yuya Nishihara <yuya@tcha.org>
parents: 31124
diff changeset
  1021
        # opencode timeblockedsection because this is a critical path
0bb3089fe735 ui: remove superfluous indent in _write()
Yuya Nishihara <yuya@tcha.org>
parents: 31124
diff changeset
  1022
        starttime = util.timer()
0bb3089fe735 ui: remove superfluous indent in _write()
Yuya Nishihara <yuya@tcha.org>
parents: 31124
diff changeset
  1023
        try:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1024
            if dest is self._ferr and not getattr(self._fout, 'closed', False):
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1025
                self._fout.flush()
40589
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  1026
            if getattr(dest, 'structured', False):
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  1027
                # channel for machine-readable output with metadata, where
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  1028
                # no extra colorization is necessary.
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  1029
                dest.write(msg, **opts)
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  1030
            elif self._colormode == 'win32':
40523
0c7b2035a604 ui: indent _writenobuf() to prepare moving bits from _write() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40522
diff changeset
  1031
                # windows color printing is its own can of crab, defer to
0c7b2035a604 ui: indent _writenobuf() to prepare moving bits from _write() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40522
diff changeset
  1032
                # the color module and that is it.
40540
06e841e72523 ui: remove _write() and _write_err() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40539
diff changeset
  1033
                color.win32print(self, dest.write, msg, **opts)
40523
0c7b2035a604 ui: indent _writenobuf() to prepare moving bits from _write() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40522
diff changeset
  1034
            else:
0c7b2035a604 ui: indent _writenobuf() to prepare moving bits from _write() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40522
diff changeset
  1035
                if self._colormode is not None:
0c7b2035a604 ui: indent _writenobuf() to prepare moving bits from _write() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40522
diff changeset
  1036
                    label = opts.get(r'label', '')
0c7b2035a604 ui: indent _writenobuf() to prepare moving bits from _write() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40522
diff changeset
  1037
                    msg = self.label(msg, label)
40540
06e841e72523 ui: remove _write() and _write_err() functions
Yuya Nishihara <yuya@tcha.org>
parents: 40539
diff changeset
  1038
                dest.write(msg)
40539
04a9dd8da959 ui: move pre/post processes from low-level write()s to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40538
diff changeset
  1039
            # stderr may be buffered under win32 when redirected to files,
04a9dd8da959 ui: move pre/post processes from low-level write()s to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40538
diff changeset
  1040
            # including stdout.
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1041
            if dest is self._ferr and not getattr(self._ferr, 'closed', False):
40539
04a9dd8da959 ui: move pre/post processes from low-level write()s to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40538
diff changeset
  1042
                dest.flush()
31961
db823e38a61c stdio: raise StdioError if something goes wrong in ui._write
Bryan O'Sullivan <bryano@fb.com>
parents: 31958
diff changeset
  1043
        except IOError as err:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1044
            if (dest is self._ferr
40539
04a9dd8da959 ui: move pre/post processes from low-level write()s to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40538
diff changeset
  1045
                and err.errno in (errno.EPIPE, errno.EIO, errno.EBADF)):
04a9dd8da959 ui: move pre/post processes from low-level write()s to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40538
diff changeset
  1046
                # no way to report the error, so ignore it
04a9dd8da959 ui: move pre/post processes from low-level write()s to _writenobuf()
Yuya Nishihara <yuya@tcha.org>
parents: 40538
diff changeset
  1047
                return
31961
db823e38a61c stdio: raise StdioError if something goes wrong in ui._write
Bryan O'Sullivan <bryano@fb.com>
parents: 31958
diff changeset
  1048
            raise error.StdioError(err)
31128
0bb3089fe735 ui: remove superfluous indent in _write()
Yuya Nishihara <yuya@tcha.org>
parents: 31124
diff changeset
  1049
        finally:
0bb3089fe735 ui: remove superfluous indent in _write()
Yuya Nishihara <yuya@tcha.org>
parents: 31124
diff changeset
  1050
            self._blockedtimes['stdio_blocked'] += \
0bb3089fe735 ui: remove superfluous indent in _write()
Yuya Nishihara <yuya@tcha.org>
parents: 31124
diff changeset
  1051
                (util.timer() - starttime) * 1000
565
9a80418646dd [PATCH] Make ui.warn write to stderr
mpm@selenic.com
parents: 515
diff changeset
  1052
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1053
    def _writemsg(self, dest, *args, **opts):
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1054
        _writemsgwith(self._write, dest, *args, **opts)
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1055
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1056
    def _writemsgnobuf(self, dest, *args, **opts):
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1057
        _writemsgwith(self._writenobuf, dest, *args, **opts)
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1058
1837
6f67a4c93493 make ui flush output. this makes error happen if printing to /dev/full.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 1637
diff changeset
  1059
    def flush(self):
30978
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1060
        # opencode timeblockedsection because this is a critical path
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1061
        starttime = util.timer()
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1062
        try:
31963
1bfb9a63b98e stdio: raise StdioError if something goes wrong in ui.flush
Bryan O'Sullivan <bryano@fb.com>
parents: 31962
diff changeset
  1063
            try:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1064
                self._fout.flush()
31963
1bfb9a63b98e stdio: raise StdioError if something goes wrong in ui.flush
Bryan O'Sullivan <bryano@fb.com>
parents: 31962
diff changeset
  1065
            except IOError as err:
33755
cde4cfeb6e3e ui: restore behavior to ignore some I/O errors (issue5658)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 33627
diff changeset
  1066
                if err.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
cde4cfeb6e3e ui: restore behavior to ignore some I/O errors (issue5658)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 33627
diff changeset
  1067
                    raise error.StdioError(err)
31963
1bfb9a63b98e stdio: raise StdioError if something goes wrong in ui.flush
Bryan O'Sullivan <bryano@fb.com>
parents: 31962
diff changeset
  1068
            finally:
1bfb9a63b98e stdio: raise StdioError if something goes wrong in ui.flush
Bryan O'Sullivan <bryano@fb.com>
parents: 31962
diff changeset
  1069
                try:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1070
                    self._ferr.flush()
31963
1bfb9a63b98e stdio: raise StdioError if something goes wrong in ui.flush
Bryan O'Sullivan <bryano@fb.com>
parents: 31962
diff changeset
  1071
                except IOError as err:
33755
cde4cfeb6e3e ui: restore behavior to ignore some I/O errors (issue5658)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 33627
diff changeset
  1072
                    if err.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
cde4cfeb6e3e ui: restore behavior to ignore some I/O errors (issue5658)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 33627
diff changeset
  1073
                        raise error.StdioError(err)
30978
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1074
        finally:
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1075
            self._blockedtimes['stdio_blocked'] += \
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1076
                (util.timer() - starttime) * 1000
1837
6f67a4c93493 make ui flush output. this makes error happen if printing to /dev/full.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 1637
diff changeset
  1077
16751
2d432a1fc0db ui: add _isatty method to easily disable cooked I/O
Matt Mackall <mpm@selenic.com>
parents: 16703
diff changeset
  1078
    def _isatty(self, fh):
33499
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
  1079
        if self.configbool('ui', 'nontty'):
16751
2d432a1fc0db ui: add _isatty method to easily disable cooked I/O
Matt Mackall <mpm@selenic.com>
parents: 16703
diff changeset
  1080
            return False
37120
a8a902d7176e procutil: bulk-replace function calls to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37119
diff changeset
  1081
        return procutil.isatty(fh)
1837
6f67a4c93493 make ui flush output. this makes error happen if printing to /dev/full.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 1637
diff changeset
  1082
31026
9c827087df38 ui: rename neverpager to disablepager
Augie Fackler <augie@google.com>
parents: 31014
diff changeset
  1083
    def disablepager(self):
9c827087df38 ui: rename neverpager to disablepager
Augie Fackler <augie@google.com>
parents: 31014
diff changeset
  1084
        self._disablepager = True
30994
3ed6e43998df ui: introduce neverpager() call
Augie Fackler <augie@google.com>
parents: 30992
diff changeset
  1085
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1086
    def pager(self, command):
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1087
        """Start a pager for subsequent command output.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1088
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1089
        Commands which produce a long stream of output should call
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1090
        this function to activate the user's preferred pagination
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1091
        mechanism (which may be no pager). Calling this function
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1092
        precludes any future use of interactive functionality, such as
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1093
        prompting the user or activating curses.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1094
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1095
        Args:
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1096
          command: The full, non-aliased name of the command. That is, "log"
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1097
                   not "history, "summary" not "summ", etc.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1098
        """
31026
9c827087df38 ui: rename neverpager to disablepager
Augie Fackler <augie@google.com>
parents: 31014
diff changeset
  1099
        if (self._disablepager
33620
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1100
            or self.pageractive):
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1101
            # how pager should do is already determined
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1102
            return
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1103
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1104
        if not command.startswith('internal-always-') and (
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1105
            # explicit --pager=on (= 'internal-always-' prefix) should
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1106
            # take precedence over disabling factors below
cc047a733f69 ui: enable pager always for explicit --pager=on (issue5580)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 33585
diff changeset
  1107
            command in self.configlist('pager', 'ignore')
33499
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
  1108
            or not self.configbool('ui', 'paginate')
30997
29a4a8d01bc9 ui: respect historic pager.attend-$COMMAND=no
Augie Fackler <augie@google.com>
parents: 30995
diff changeset
  1109
            or not self.configbool('pager', 'attend-' + command, True)
39313
6f38284b23f4 pager: do not enable when TERM=dumb
Valentin Gatien-Baron <valentin.gatienbaron@gmail.com>
parents: 38858
diff changeset
  1110
            or encoding.environ.get('TERM') == 'dumb'
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1111
            # TODO: if we want to allow HGPLAINEXCEPT=pager,
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1112
            # formatted() will need some adjustment.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1113
            or not self.formatted()
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1114
            or self.plain()
34021
31a2eb0f74e5 pager: do not start pager if `ui` has been `pushbuffer`-ed
Jun Wu <quark@fb.com>
parents: 33865
diff changeset
  1115
            or self._buffers
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1116
            # TODO: expose debugger-enabled on the UI object
31341
66f1c244b43a ui: check for --debugger in sys.argv using r-string to avoid bytes on py3
Augie Fackler <augie@google.com>
parents: 31253
diff changeset
  1117
            or '--debugger' in pycompat.sysargv):
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1118
            # We only want to paginate if the ui appears to be
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1119
            # interactive, the user didn't say HGPLAIN or
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1120
            # HGPLAINEXCEPT=pager, and the user didn't specify --debug.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1121
            return
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1122
32078
bf5e13e38390 pager: use less as a fallback on Unix
Yuya Nishihara <yuya@tcha.org>
parents: 31963
diff changeset
  1123
        pagercmd = self.config('pager', 'pager', rcutil.fallbackpager)
31079
873ebdd6e84d pager: do not try to run an empty pager command
Yuya Nishihara <yuya@tcha.org>
parents: 31062
diff changeset
  1124
        if not pagercmd:
873ebdd6e84d pager: do not try to run an empty pager command
Yuya Nishihara <yuya@tcha.org>
parents: 31062
diff changeset
  1125
            return
873ebdd6e84d pager: do not try to run an empty pager command
Yuya Nishihara <yuya@tcha.org>
parents: 31062
diff changeset
  1126
31954
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1127
        pagerenv = {}
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1128
        for name, value in rcutil.defaultpagerenv().items():
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1129
            if name not in encoding.environ:
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1130
                pagerenv[name] = value
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1131
40226
0d403e9f049a py3: use stringutil.pprint() instead of '%r'
Pulkit Goyal <pulkit@yandex-team.ru>
parents: 39840
diff changeset
  1132
        self.debug('starting pager for command %s\n' %
0d403e9f049a py3: use stringutil.pprint() instead of '%r'
Pulkit Goyal <pulkit@yandex-team.ru>
parents: 39840
diff changeset
  1133
                   stringutil.pprint(command))
31490
8122cc5cb543 pager: flush outputs before firing pager process
Yuya Nishihara <yuya@tcha.org>
parents: 31481
diff changeset
  1134
        self.flush()
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1135
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1136
        wasformatted = self.formatted()
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1137
        if util.safehasattr(signal, "SIGPIPE"):
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1138
            signal.signal(signal.SIGPIPE, _catchterm)
31954
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1139
        if self._runpager(pagercmd, pagerenv):
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1140
            self.pageractive = True
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1141
            # Preserve the formatted-ness of the UI. This is important
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1142
            # because we mess with stdout, which might confuse
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1143
            # auto-detection of things being formatted.
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1144
            self.setconfig('ui', 'formatted', wasformatted, 'pager')
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1145
            self.setconfig('ui', 'interactive', False, 'pager')
31691
c3ca0ad8ab9c ui: rerun color.setup() once the pager has spawned to honor 'color.pagermode'
Matt Harbison <matt_harbison@yahoo.com>
parents: 31690
diff changeset
  1146
c3ca0ad8ab9c ui: rerun color.setup() once the pager has spawned to honor 'color.pagermode'
Matt Harbison <matt_harbison@yahoo.com>
parents: 31690
diff changeset
  1147
            # If pagermode differs from color.mode, reconfigure color now that
c3ca0ad8ab9c ui: rerun color.setup() once the pager has spawned to honor 'color.pagermode'
Matt Harbison <matt_harbison@yahoo.com>
parents: 31690
diff changeset
  1148
            # pageractive is set.
c3ca0ad8ab9c ui: rerun color.setup() once the pager has spawned to honor 'color.pagermode'
Matt Harbison <matt_harbison@yahoo.com>
parents: 31690
diff changeset
  1149
            cm = self._colormode
c3ca0ad8ab9c ui: rerun color.setup() once the pager has spawned to honor 'color.pagermode'
Matt Harbison <matt_harbison@yahoo.com>
parents: 31690
diff changeset
  1150
            if cm != self.config('color', 'pagermode', cm):
c3ca0ad8ab9c ui: rerun color.setup() once the pager has spawned to honor 'color.pagermode'
Matt Harbison <matt_harbison@yahoo.com>
parents: 31690
diff changeset
  1151
                color.setup(self)
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1152
        else:
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1153
            # If the pager can't be spawned in dispatch when --pager=on is
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1154
            # given, don't try again when the command runs, to avoid a duplicate
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1155
            # warning about a missing pager command.
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1156
            self.disablepager()
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1157
31954
e518192d6bac pager: set some environment variables if they're not set
Jun Wu <quark@fb.com>
parents: 31778
diff changeset
  1158
    def _runpager(self, command, env=None):
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1159
        """Actually start the pager and set up file descriptors.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1160
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1161
        This is separate in part so that extensions (like chg) can
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1162
        override how a pager is invoked.
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1163
        """
31479
96929bd6e58d pager: skip running the pager if it's set to 'cat'
Augie Fackler <augie@google.com>
parents: 31478
diff changeset
  1164
        if command == 'cat':
96929bd6e58d pager: skip running the pager if it's set to 'cat'
Augie Fackler <augie@google.com>
parents: 31478
diff changeset
  1165
            # Save ourselves some work.
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1166
            return False
31478
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1167
        # If the command doesn't contain any of these characters, we
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1168
        # assume it's a binary and exec it directly. This means for
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1169
        # simple pager command configurations, we can degrade
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1170
        # gracefully and tell the user about their broken pager.
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1171
        shell = any(c in command for c in "|&;<>()$`\\\"' \t\n*?[#~=%")
31624
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1172
34645
75979c8d4572 codemod: use pycompat.iswindows
Jun Wu <quark@fb.com>
parents: 34616
diff changeset
  1173
        if pycompat.iswindows and not shell:
31624
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1174
            # Window's built-in `more` cannot be invoked with shell=False, but
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1175
            # its `more.com` can.  Hide this implementation detail from the
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1176
            # user so we can also get sane bad PAGER behavior.  MSYS has
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1177
            # `more.exe`, so do a cmd.exe style resolution of the executable to
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1178
            # determine which one to use.
37120
a8a902d7176e procutil: bulk-replace function calls to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37119
diff changeset
  1179
            fullcmd = procutil.findexe(command)
31624
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1180
            if not fullcmd:
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1181
                self.warn(_("missing pager command '%s', skipping pager\n")
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1182
                          % command)
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1183
                return False
31624
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1184
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1185
            command = fullcmd
c60091fa1426 pager: improve support for various flavors of `more` on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 31592
diff changeset
  1186
31478
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1187
        try:
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1188
            pager = subprocess.Popen(
39662
50f46b771921 py3: partially fix pager spawning on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 39313
diff changeset
  1189
                procutil.tonativestr(command), shell=shell, bufsize=-1,
37120
a8a902d7176e procutil: bulk-replace function calls to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37119
diff changeset
  1190
                close_fds=procutil.closefds, stdin=subprocess.PIPE,
37119
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1191
                stdout=procutil.stdout, stderr=procutil.stderr,
39662
50f46b771921 py3: partially fix pager spawning on Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 39313
diff changeset
  1192
                env=procutil.tonativeenv(procutil.shellenviron(env)))
31478
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1193
        except OSError as e:
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1194
            if e.errno == errno.ENOENT and not shell:
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1195
                self.warn(_("missing pager command '%s', skipping pager\n")
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1196
                          % command)
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1197
                return False
31478
9335dc6b2a9c pager: avoid shell=True on subprocess.Popen for better errors (issue5491)
Augie Fackler <augie@google.com>
parents: 31472
diff changeset
  1198
            raise
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1199
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1200
        # back up original file descriptors
37119
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1201
        stdoutfd = os.dup(procutil.stdout.fileno())
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1202
        stderrfd = os.dup(procutil.stderr.fileno())
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1203
37119
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1204
        os.dup2(pager.stdin.fileno(), procutil.stdout.fileno())
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1205
        if self._isatty(procutil.stderr):
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1206
            os.dup2(pager.stdin.fileno(), procutil.stderr.fileno())
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1207
31958
de5c9d0e02ea atexit: switch to home-grown implementation
Bryan O'Sullivan <bryano@fb.com>
parents: 31956
diff changeset
  1208
        @self.atexit
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1209
        def killpager():
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1210
            if util.safehasattr(signal, "SIGINT"):
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1211
                signal.signal(signal.SIGINT, signal.SIG_IGN)
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1212
            # restore original fds, closing pager.stdin copies in the process
37119
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1213
            os.dup2(stdoutfd, procutil.stdout.fileno())
d4a2e0d5d042 procutil: bulk-replace util.std* to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37084
diff changeset
  1214
            os.dup2(stderrfd, procutil.stderr.fileno())
30992
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1215
            pager.stdin.close()
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1216
            pager.wait()
61b4122019d3 pager: move pager-initiating code into core
Augie Fackler <augie@google.com>
parents: 30980
diff changeset
  1217
31690
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1218
        return True
2d11d278279a ui: defer setting pager related properties until the pager has spawned
Matt Harbison <matt_harbison@yahoo.com>
parents: 31688
diff changeset
  1219
34882
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
  1220
    @property
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
  1221
    def _exithandlers(self):
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
  1222
        return _reqexithandlers
e9f320a40b44 ui: move request exit handlers to global state
Saurabh Singh <singhsrb@fb.com>
parents: 34858
diff changeset
  1223
31956
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1224
    def atexit(self, func, *args, **kwargs):
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1225
        '''register a function to run after dispatching a request
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1226
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1227
        Handlers do not stay registered across request boundaries.'''
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1228
        self._exithandlers.append((func, args, kwargs))
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1229
        return func
c13ff31818b0 ui: add special-purpose atexit functionality
Bryan O'Sullivan <bryano@fb.com>
parents: 31954
diff changeset
  1230
28542
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1231
    def interface(self, feature):
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1232
        """what interface to use for interactive console features?
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1233
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1234
        The interface is controlled by the value of `ui.interface` but also by
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1235
        the value of feature-specific configuration. For example:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1236
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1237
        ui.interface.histedit = text
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1238
        ui.interface.chunkselector = curses
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1239
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1240
        Here the features are "histedit" and "chunkselector".
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1241
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1242
        The configuration above means that the default interfaces for commands
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1243
        is curses, the interface for histedit is text and the interface for
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1244
        selecting chunk is crecord (the best curses interface available).
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1245
30332
318a24b52eeb spelling: fixes of non-dictionary words
Mads Kiilerich <madski@unity3d.com>
parents: 30314
diff changeset
  1246
        Consider the following example:
28542
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1247
        ui.interface = curses
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1248
        ui.interface.histedit = text
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1249
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1250
        Then histedit will use the text interface and chunkselector will use
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1251
        the default curses interface (crecord at the moment).
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1252
        """
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1253
        alldefaults = frozenset(["text", "curses"])
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1254
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1255
        featureinterfaces = {
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1256
            "chunkselector": [
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1257
                "text",
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1258
                "curses",
40602
c36175456350 histedit: import chistedit curses UI from hg-experimental
Augie Fackler <augie@google.com>
parents: 40594
diff changeset
  1259
            ],
c36175456350 histedit: import chistedit curses UI from hg-experimental
Augie Fackler <augie@google.com>
parents: 40594
diff changeset
  1260
            "histedit": [
c36175456350 histedit: import chistedit curses UI from hg-experimental
Augie Fackler <augie@google.com>
parents: 40594
diff changeset
  1261
                "text",
c36175456350 histedit: import chistedit curses UI from hg-experimental
Augie Fackler <augie@google.com>
parents: 40594
diff changeset
  1262
                "curses",
c36175456350 histedit: import chistedit curses UI from hg-experimental
Augie Fackler <augie@google.com>
parents: 40594
diff changeset
  1263
            ],
28542
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1264
        }
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1265
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1266
        # Feature-specific interface
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1267
        if feature not in featureinterfaces.keys():
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1268
            # Programming error, not user error
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1269
            raise ValueError("Unknown feature requested %s" % feature)
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1270
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1271
        availableinterfaces = frozenset(featureinterfaces[feature])
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1272
        if alldefaults > availableinterfaces:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1273
            # Programming error, not user error. We need a use case to
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1274
            # define the right thing to do here.
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1275
            raise ValueError(
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1276
                "Feature %s does not handle all default interfaces" %
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1277
                feature)
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1278
38726
d79f3afb079e curses: use "text" interface if TERM=dumb
Kyle Lippincott <spectral@google.com>
parents: 38652
diff changeset
  1279
        if self.plain() or encoding.environ.get('TERM') == 'dumb':
28542
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1280
            return "text"
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1281
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1282
        # Default interface for all the features
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1283
        defaultinterface = "text"
33499
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
  1284
        i = self.config("ui", "interface")
28542
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1285
        if i in alldefaults:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1286
            defaultinterface = i
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1287
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1288
        choseninterface = defaultinterface
34616
c0dabec35019 configitems: register the 'ui.interface.chunkselector' config
Boris Feld <boris.feld@octobus.net>
parents: 34568
diff changeset
  1289
        f = self.config("ui", "interface.%s" % feature)
28542
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1290
        if f in availableinterfaces:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1291
            choseninterface = f
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1292
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1293
        if i is not None and defaultinterface != i:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1294
            if f is not None:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1295
                self.warn(_("invalid value for ui.interface: %s\n") %
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1296
                          (i,))
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1297
            else:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1298
                self.warn(_("invalid value for ui.interface: %s (using %s)\n") %
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1299
                         (i, choseninterface))
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1300
        if f is not None and choseninterface != f:
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1301
            self.warn(_("invalid value for ui.interface.%s: %s (using %s)\n") %
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1302
                      (feature, f, choseninterface))
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1303
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1304
        return choseninterface
71e12fc53b80 ui: add new config flag for interface selection
Simon Farnsworth <simonfar@fb.com>
parents: 28498
diff changeset
  1305
8208
32a2a1e244f1 ui: make interactive a method
Matt Mackall <mpm@selenic.com>
parents: 8206
diff changeset
  1306
    def interactive(self):
11325
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1307
        '''is interactive input allowed?
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1308
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1309
        An interactive session is a session where input can be reasonably read
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1310
        from `sys.stdin'. If this function returns false, any attempt to read
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1311
        from stdin should fail with an error, unless a sensible default has been
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1312
        specified.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1313
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1314
        Interactiveness is triggered by the value of the `ui.interactive'
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1315
        configuration variable or - if it is unset - when `sys.stdin' points
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1316
        to a terminal device.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1317
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1318
        This function refers to input only; for output, see `ui.formatted()'.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1319
        '''
33061
c41cbe98822c configitems: register 'ui.interactive'
Pierre-Yves David <pierre-yves.david@octobus.net>
parents: 33060
diff changeset
  1320
        i = self.configbool("ui", "interactive")
8538
6419bc7b3d9c ui: honor interactive=off even if isatty()
Patrick Mezard <pmezard@gmail.com>
parents: 8527
diff changeset
  1321
        if i is None:
14515
76f295eaed86 util: add helper function isatty(fd) to check for tty-ness
Idan Kamara <idankk86@gmail.com>
parents: 14373
diff changeset
  1322
            # some environments replace stdin without implementing isatty
76f295eaed86 util: add helper function isatty(fd) to check for tty-ness
Idan Kamara <idankk86@gmail.com>
parents: 14373
diff changeset
  1323
            # usually those are non-interactive
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1324
            return self._isatty(self._fin)
10077
89617aacb495 make ui.interactive() return false in case stdin lacks isatty
Ronny Pfannschmidt <Ronny.Pfannschmidt@gmx.de>
parents: 9887
diff changeset
  1325
8538
6419bc7b3d9c ui: honor interactive=off even if isatty()
Patrick Mezard <pmezard@gmail.com>
parents: 8527
diff changeset
  1326
        return i
8208
32a2a1e244f1 ui: make interactive a method
Matt Mackall <mpm@selenic.com>
parents: 8206
diff changeset
  1327
12689
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1328
    def termwidth(self):
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1329
        '''how wide is the terminal in columns?
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1330
        '''
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
  1331
        if 'COLUMNS' in encoding.environ:
12689
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1332
            try:
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
  1333
                return int(encoding.environ['COLUMNS'])
12689
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1334
            except ValueError:
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1335
                pass
30314
365812902904 scmutil: extend termwidth() to return terminal height, renamed to termsize()
Yuya Nishihara <yuya@tcha.org>
parents: 30310
diff changeset
  1336
        return scmutil.termsize(self)[0]
12689
c52c629ce19e termwidth: move to ui.ui from util
Augie Fackler <durin42@gmail.com>
parents: 12665
diff changeset
  1337
11324
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1338
    def formatted(self):
11325
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1339
        '''should formatted output be used?
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1340
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1341
        It is often desirable to format the output to suite the output medium.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1342
        Examples of this are truncating long lines or colorizing messages.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1343
        However, this is not often not desirable when piping output into other
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1344
        utilities, e.g. `grep'.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1345
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1346
        Formatted output is triggered by the value of the `ui.formatted'
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1347
        configuration variable or - if it is unset - when `sys.stdout' points
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1348
        to a terminal device. Please note that `ui.formatted' should be
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1349
        considered an implementation detail; it is not intended for use outside
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1350
        Mercurial or its extensions.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1351
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1352
        This function refers to output only; for input, see `ui.interactive()'.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1353
        This function always returns false when in plain mode, see `ui.plain()'.
22a737306ba5 ui: document the formatted(), interactive() & plain() functions.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11324
diff changeset
  1354
        '''
11324
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1355
        if self.plain():
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1356
            return False
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1357
33499
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
  1358
        i = self.configbool("ui", "formatted")
11324
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1359
        if i is None:
14515
76f295eaed86 util: add helper function isatty(fd) to check for tty-ness
Idan Kamara <idankk86@gmail.com>
parents: 14373
diff changeset
  1360
            # some environments replace stdout without implementing isatty
76f295eaed86 util: add helper function isatty(fd) to check for tty-ness
Idan Kamara <idankk86@gmail.com>
parents: 14373
diff changeset
  1361
            # usually those are non-interactive
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1362
            return self._isatty(self._fout)
11324
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1363
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1364
        return i
cdf6d861b207 ui: add ui.formatted configuration variable and accessor function.
Dan Villiom Podlaski Christiansen <danchr@gmail.com>
parents: 11311
diff changeset
  1365
35956
fd54846e1f8e ui: write prompt text in ui.prompt(), not in ui._readline()
Yuya Nishihara <yuya@tcha.org>
parents: 35923
diff changeset
  1366
    def _readline(self):
36795
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1367
        # Replacing stdin/stdout temporarily is a hard problem on Python 3
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1368
        # because they have to be text streams with *no buffering*. Instead,
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1369
        # we use rawinput() only if call_readline() will be invoked by
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1370
        # PyOS_Readline(), so no I/O will be made at Python layer.
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1371
        usereadline = (self._isatty(self._fin) and self._isatty(self._fout)
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1372
                       and procutil.isstdin(self._fin)
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1373
                       and procutil.isstdout(self._fout))
36794
fa53a1d1f16e ui: do not try readline support if fin/fout aren't standard streams
Yuya Nishihara <yuya@tcha.org>
parents: 36791
diff changeset
  1374
        if usereadline:
5036
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1375
            try:
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1376
                # magically add command line editing support, where
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1377
                # available
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1378
                import readline
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1379
                # force demandimport to really load the module
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1380
                readline.read_history_file
7496
0a27d0db256d issue1419: catch strange readline import error on windows
Brendan Cully <brendan@kublai.com>
parents: 7320
diff changeset
  1381
                # windows sometimes raises something other than ImportError
0a27d0db256d issue1419: catch strange readline import error on windows
Brendan Cully <brendan@kublai.com>
parents: 7320
diff changeset
  1382
            except Exception:
36794
fa53a1d1f16e ui: do not try readline support if fin/fout aren't standard streams
Yuya Nishihara <yuya@tcha.org>
parents: 36791
diff changeset
  1383
                usereadline = False
14614
afccc64eea73 ui: use I/O descriptors internally
Idan Kamara <idankk86@gmail.com>
parents: 14612
diff changeset
  1384
22291
3b39e1522d8f ui: add brief comment why raw_input() needs dummy ' ' prompt string
Yuya Nishihara <yuya@tcha.org>
parents: 22205
diff changeset
  1385
        # prompt ' ' must exist; otherwise readline may delete entire line
3b39e1522d8f ui: add brief comment why raw_input() needs dummy ' ' prompt string
Yuya Nishihara <yuya@tcha.org>
parents: 22205
diff changeset
  1386
        # - http://bugs.python.org/issue12833
30978
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1387
        with self.timeblockedsection('stdio'):
36795
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1388
            if usereadline:
36791
30742c216abb ui: inline util.bytesinput() into ui._readline()
Yuya Nishihara <yuya@tcha.org>
parents: 36784
diff changeset
  1389
                line = encoding.strtolocal(pycompat.rawinput(r' '))
36796
aa0fc12743c7 ui: adjust Windows workaround to new _readline() code
Yuya Nishihara <yuya@tcha.org>
parents: 36795
diff changeset
  1390
                # When stdin is in binary mode on Windows, it can cause
aa0fc12743c7 ui: adjust Windows workaround to new _readline() code
Yuya Nishihara <yuya@tcha.org>
parents: 36795
diff changeset
  1391
                # raw_input() to emit an extra trailing carriage return
aa0fc12743c7 ui: adjust Windows workaround to new _readline() code
Yuya Nishihara <yuya@tcha.org>
parents: 36795
diff changeset
  1392
                if pycompat.oslinesep == b'\r\n' and line.endswith(b'\r'):
aa0fc12743c7 ui: adjust Windows workaround to new _readline() code
Yuya Nishihara <yuya@tcha.org>
parents: 36795
diff changeset
  1393
                    line = line[:-1]
36795
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1394
            else:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1395
                self._fout.write(b' ')
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1396
                self._fout.flush()
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1397
                line = self._fin.readline()
36795
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1398
                if not line:
9b513888ea23 ui: do not use rawinput() when we have to replace sys.stdin/stdout
Yuya Nishihara <yuya@tcha.org>
parents: 36794
diff changeset
  1399
                    raise EOFError
36834
1527f40de3b3 ui: remove any combinations of CR|LF from prompt response
Yuya Nishihara <yuya@tcha.org>
parents: 36796
diff changeset
  1400
                line = line.rstrip(pycompat.oslinesep)
14614
afccc64eea73 ui: use I/O descriptors internally
Idan Kamara <idankk86@gmail.com>
parents: 14612
diff changeset
  1401
5613
2e76e5a23c2b workaround for raw_input() on Windows
Steve Borho <steve@borho.org>
parents: 5337
diff changeset
  1402
        return line
5036
ca0d02222d6a ui: get readline and prompt to behave better depending on interactivity
Bryan O'Sullivan <bos@serpentine.com>
parents: 4729
diff changeset
  1403
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1404
    def prompt(self, msg, default="y"):
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1405
        """Prompt user with msg, read response.
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1406
        If ui is not interactive, the default is returned.
5751
bc475d1f74ca prompt: kill matchflags
Kirill Smelkov <kirr@mns.spb.ru>
parents: 5709
diff changeset
  1407
        """
40592
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1408
        return self._prompt(msg, default=default)
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1409
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1410
    def _prompt(self, msg, **opts):
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1411
        default = opts[r'default']
8208
32a2a1e244f1 ui: make interactive a method
Matt Mackall <mpm@selenic.com>
parents: 8206
diff changeset
  1412
        if not self.interactive():
40592
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1413
            self._writemsg(self._fmsgout, msg, ' ', type='prompt', **opts)
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1414
            self._writemsg(self._fmsgout, default or '', "\n",
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1415
                           type='promptecho')
7320
8dca507e56ce ui: log non-interactive default response to stdout when verbose
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents: 6862
diff changeset
  1416
            return default
40592
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1417
        self._writemsgnobuf(self._fmsgout, msg, type='prompt', **opts)
35956
fd54846e1f8e ui: write prompt text in ui.prompt(), not in ui._readline()
Yuya Nishihara <yuya@tcha.org>
parents: 35923
diff changeset
  1418
        self.flush()
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1419
        try:
35956
fd54846e1f8e ui: write prompt text in ui.prompt(), not in ui._readline()
Yuya Nishihara <yuya@tcha.org>
parents: 35923
diff changeset
  1420
            r = self._readline()
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1421
            if not r:
22589
9ab18a912c44 ui: show prompt choice if input is not a tty but is forced to be interactive
Mads Kiilerich <madski@unity3d.com>
parents: 22419
diff changeset
  1422
                r = default
23053
5ba11ab48fcf ui: separate option to show prompt echo, enabled only in tests (issue4417)
Yuya Nishihara <yuya@tcha.org>
parents: 22837
diff changeset
  1423
            if self.configbool('ui', 'promptecho'):
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1424
                self._writemsg(self._fmsgout, r, "\n", type='promptecho')
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1425
            return r
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1426
        except EOFError:
26896
5e46123e6c35 error: add structured exception for EOF at prompt
Siddharth Agarwal <sid0@fb.com>
parents: 26820
diff changeset
  1427
            raise error.ResponseExpected()
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1428
20265
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1429
    @staticmethod
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1430
    def extractchoices(prompt):
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1431
        """Extract prompt message and list of choices from specified prompt.
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1432
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1433
        This returns tuple "(message, choices)", and "choices" is the
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1434
        list of tuple "(response character, text without &)".
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1435
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
  1436
        >>> ui.extractchoices(b"awake? $$ &Yes $$ &No")
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1437
        ('awake? ', [('y', 'Yes'), ('n', 'No')])
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
  1438
        >>> ui.extractchoices(b"line\\nbreak? $$ &Yes $$ &No")
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1439
        ('line\\nbreak? ', [('y', 'Yes'), ('n', 'No')])
34131
0fa781320203 doctest: bulk-replace string literals with b'' for Python 3
Yuya Nishihara <yuya@tcha.org>
parents: 34054
diff changeset
  1440
        >>> ui.extractchoices(b"want lots of $$money$$?$$Ye&s$$N&o")
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1441
        ('want lots of $$money$$?', [('s', 'Yes'), ('o', 'No')])
20265
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1442
        """
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1443
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1444
        # Sadly, the prompt string may have been built with a filename
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1445
        # containing "$$" so let's try to find the first valid-looking
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1446
        # prompt to start parsing. Sadly, we also can't rely on
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1447
        # choices containing spaces, ASCII, or basically anything
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1448
        # except an ampersand followed by a character.
33096
d9962854a4a2 py3: add b'' to make the regex pattern bytes
Pulkit Goyal <7895pulkit@gmail.com>
parents: 33061
diff changeset
  1449
        m = re.match(br'(?s)(.+?)\$\$([^\$]*&[^ \$].*)', prompt)
27392
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1450
        msg = m.group(1)
00aa37c65e0a ui: try to handle $$ more robustly in prompts (issue4970)
Matt Mackall <mpm@selenic.com>
parents: 26820
diff changeset
  1451
        choices = [p.strip(' ') for p in m.group(2).split('$$')]
33714
d880a6bcef2f ui: refactor extractchoices so it doesn't break on Python 3
Augie Fackler <augie@google.com>
parents: 33687
diff changeset
  1452
        def choicetuple(s):
d880a6bcef2f ui: refactor extractchoices so it doesn't break on Python 3
Augie Fackler <augie@google.com>
parents: 33687
diff changeset
  1453
            ampidx = s.index('&')
d880a6bcef2f ui: refactor extractchoices so it doesn't break on Python 3
Augie Fackler <augie@google.com>
parents: 33687
diff changeset
  1454
            return s[ampidx + 1:ampidx + 2].lower(), s.replace('&', '', 1)
d880a6bcef2f ui: refactor extractchoices so it doesn't break on Python 3
Augie Fackler <augie@google.com>
parents: 33687
diff changeset
  1455
        return (msg, [choicetuple(s) for s in choices])
20265
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1456
19226
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1457
    def promptchoice(self, prompt, default=0):
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1458
        """Prompt user with a message, read response, and ensure it matches
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1459
        one of the provided choices. The prompt is formatted as follows:
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1460
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1461
           "would you like fries with that (Yn)? $$ &Yes $$ &No"
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1462
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1463
        The index of the choice is returned. Responses are case
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1464
        insensitive. If ui is not interactive, the default is
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1465
        returned.
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1466
        """
19226
c58b6ab4c26f ui: merge prompt text components into a singe string
Matt Mackall <mpm@selenic.com>
parents: 19195
diff changeset
  1467
20265
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1468
        msg, choices = self.extractchoices(prompt)
e5803150ea1d ui: add "extractchoices()" to share the logic to extract choices from prompt
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 19886
diff changeset
  1469
        resps = [r for r, t in choices]
5671
b5605d88dc27 Make ui.prompt repeat on "unrecognized response" again (issue897)
Thomas Arendsen Hein <thomas@intevation.de>
parents: 5337
diff changeset
  1470
        while True:
40592
83e571ea06a9 commandserver: attach prompt default and choices to message
Yuya Nishihara <yuya@tcha.org>
parents: 40590
diff changeset
  1471
            r = self._prompt(msg, default=resps[default], choices=choices)
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1472
            if r.lower() in resps:
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1473
                return resps.index(r.lower())
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  1474
            # TODO: shouldn't it be a warning?
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1475
            self._writemsg(self._fmsgout, _("unrecognized response\n"))
9048
86b4a9b0ddda ui: extract choice from prompt
Simon Heimberg <simohe@besonet.ch>
parents: 8940
diff changeset
  1476
2281
7761597b5da3 prompt user for http authentication info
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 2206
diff changeset
  1477
    def getpass(self, prompt=None, default=None):
10282
08a0f04b56bd many, many trivial check-code fixups
Matt Mackall <mpm@selenic.com>
parents: 10264
diff changeset
  1478
        if not self.interactive():
08a0f04b56bd many, many trivial check-code fixups
Matt Mackall <mpm@selenic.com>
parents: 10264
diff changeset
  1479
            return default
7798
57fee79e5588 catch CTRL-D at password prompt
Steve Borho <steve@borho.org>
parents: 7600
diff changeset
  1480
        try:
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1481
            self._writemsg(self._fmsgerr, prompt or _('password: '),
40593
6f0941f4a184 commandserver: make getpass() request distinct from normal prompt
Yuya Nishihara <yuya@tcha.org>
parents: 40592
diff changeset
  1482
                           type='prompt', password=True)
21195
9336bc7dca8e cmdserver: forcibly use L channel to read password input (issue3161)
Yuya Nishihara <yuya@tcha.org>
parents: 21132
diff changeset
  1483
            # disable getpass() only if explicitly specified. it's still valid
9336bc7dca8e cmdserver: forcibly use L channel to read password input (issue3161)
Yuya Nishihara <yuya@tcha.org>
parents: 21132
diff changeset
  1484
            # to interact with tty even if fin is not a tty.
30978
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1485
            with self.timeblockedsection('stdio'):
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1486
                if self.configbool('ui', 'nontty'):
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1487
                    l = self._fin.readline()
30978
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1488
                    if not l:
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1489
                        raise EOFError
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1490
                    return l.rstrip('\n')
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1491
                else:
fdecd24ca4dc ui: log time spent blocked on stdio
Simon Farnsworth <simonfar@fb.com>
parents: 30976
diff changeset
  1492
                    return getpass.getpass('')
7798
57fee79e5588 catch CTRL-D at password prompt
Steve Borho <steve@borho.org>
parents: 7600
diff changeset
  1493
        except EOFError:
26896
5e46123e6c35 error: add structured exception for EOF at prompt
Siddharth Agarwal <sid0@fb.com>
parents: 26820
diff changeset
  1494
            raise error.ResponseExpected()
38768
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1495
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1496
    def status(self, *msg, **opts):
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1497
        '''write status message to output (if ui.quiet is False)
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1498
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1499
        This adds an output label of "ui.status".
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1500
        '''
10282
08a0f04b56bd many, many trivial check-code fixups
Matt Mackall <mpm@selenic.com>
parents: 10264
diff changeset
  1501
        if not self.quiet:
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1502
            self._writemsg(self._fmsgout, type='status', *msg, **opts)
38768
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1503
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1504
    def warn(self, *msg, **opts):
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1505
        '''write warning message to output (stderr)
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1506
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1507
        This adds an output label of "ui.warning".
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1508
        '''
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1509
        self._writemsg(self._fmsgerr, type='warning', *msg, **opts)
38768
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1510
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1511
    def error(self, *msg, **opts):
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1512
        '''write error message to output (stderr)
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1513
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1514
        This adds an output label of "ui.error".
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1515
        '''
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1516
        self._writemsg(self._fmsgerr, type='error', *msg, **opts)
38768
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1517
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1518
    def note(self, *msg, **opts):
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1519
        '''write note to output (if ui.verbose is True)
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1520
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1521
        This adds an output label of "ui.note".
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1522
        '''
10282
08a0f04b56bd many, many trivial check-code fixups
Matt Mackall <mpm@selenic.com>
parents: 10264
diff changeset
  1523
        if self.verbose:
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1524
            self._writemsg(self._fmsgout, type='note', *msg, **opts)
38768
afc4ad706f9c dispatch: making all hg abortions be output with a specific label
Rodrigo Damazio Bovendorp <rdamazio@google.com>
parents: 38767
diff changeset
  1525
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1526
    def debug(self, *msg, **opts):
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1527
        '''write debug message to output (if ui.debugflag is True)
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1528
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1529
        This adds an output label of "ui.debug".
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1530
        '''
10282
08a0f04b56bd many, many trivial check-code fixups
Matt Mackall <mpm@selenic.com>
parents: 10264
diff changeset
  1531
        if self.debugflag:
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  1532
            self._writemsg(self._fmsgout, type='debug', *msg, **opts)
40759
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1533
            self.log(b'debug', b'%s', b''.join(msg))
26750
9f9ec4abe700 cmdutil: make in-memory changes visible to external editor (issue4378)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 26587
diff changeset
  1534
30835
bcad61a1f9a7 ui: add a parameter to set the temporary directory for edit
Sean Farley <sean@farley.io>
parents: 30832
diff changeset
  1535
    def edit(self, text, user, extra=None, editform=None, pending=None,
34029
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1536
             repopath=None, action=None):
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1537
        if action is None:
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1538
            self.develwarn('action is None but will soon be a required '
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1539
                           'parameter to ui.edit()')
28635
87f92d6f0bc3 edit: allow to configure the suffix of the temporary filename
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 28633
diff changeset
  1540
        extra_defaults = {
87f92d6f0bc3 edit: allow to configure the suffix of the temporary filename
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 28633
diff changeset
  1541
            'prefix': 'editor',
87f92d6f0bc3 edit: allow to configure the suffix of the temporary filename
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 28633
diff changeset
  1542
            'suffix': '.txt',
87f92d6f0bc3 edit: allow to configure the suffix of the temporary filename
Jordi Gutiérrez Hermoso <jordigh@octave.org>
parents: 28633
diff changeset
  1543
        }
27153
3553e40d0770 ui: allow open editor with custom filename
Mykola Nikishov <mn@mn.com.ua>
parents: 27110
diff changeset
  1544
        if extra is not None:
34029
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1545
            if extra.get('suffix') is not None:
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1546
                self.develwarn('extra.suffix is not None but will soon be '
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1547
                               'ignored by ui.edit()')
27153
3553e40d0770 ui: allow open editor with custom filename
Mykola Nikishov <mn@mn.com.ua>
parents: 27110
diff changeset
  1548
            extra_defaults.update(extra)
3553e40d0770 ui: allow open editor with custom filename
Mykola Nikishov <mn@mn.com.ua>
parents: 27110
diff changeset
  1549
        extra = extra_defaults
30835
bcad61a1f9a7 ui: add a parameter to set the temporary directory for edit
Sean Farley <sean@farley.io>
parents: 30832
diff changeset
  1550
34054
3c82b14d2838 editor: file created for diff action should have .diff suffix
Michael Bolin <mbolin@fb.com>
parents: 34029
diff changeset
  1551
        if action == 'diff':
3c82b14d2838 editor: file created for diff action should have .diff suffix
Michael Bolin <mbolin@fb.com>
parents: 34029
diff changeset
  1552
            suffix = '.diff'
3c82b14d2838 editor: file created for diff action should have .diff suffix
Michael Bolin <mbolin@fb.com>
parents: 34029
diff changeset
  1553
        elif action:
34029
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1554
            suffix = '.%s.hg.txt' % action
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1555
        else:
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1556
            suffix = extra['suffix']
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1557
30848
7080652af6e6 ui: rename tmpdir parameter to more specific repopath
Sean Farley <sean@farley.io>
parents: 30835
diff changeset
  1558
        rdir = None
30835
bcad61a1f9a7 ui: add a parameter to set the temporary directory for edit
Sean Farley <sean@farley.io>
parents: 30832
diff changeset
  1559
        if self.configbool('experimental', 'editortmpinhg'):
30848
7080652af6e6 ui: rename tmpdir parameter to more specific repopath
Sean Farley <sean@farley.io>
parents: 30835
diff changeset
  1560
            rdir = repopath
38164
aac4be30e250 py3: wrap tempfile.mkstemp() to use bytes path
Yuya Nishihara <yuya@tcha.org>
parents: 38101
diff changeset
  1561
        (fd, name) = pycompat.mkstemp(prefix='hg-' + extra['prefix'] + '-',
34029
6e6452bc441d editor: use an unambiguous path suffix for editor files
Michael Bolin <mbolin@fb.com>
parents: 34021
diff changeset
  1562
                                      suffix=suffix,
30848
7080652af6e6 ui: rename tmpdir parameter to more specific repopath
Sean Farley <sean@farley.io>
parents: 30835
diff changeset
  1563
                                      dir=rdir)
1984
df7436f439a0 Improved ui.edit():
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1983
diff changeset
  1564
        try:
31778
ac69675fff1c ui: use bytes IO and convert EOL manually in ui.editor()
Yuya Nishihara <yuya@tcha.org>
parents: 31775
diff changeset
  1565
            f = os.fdopen(fd, r'wb')
ac69675fff1c ui: use bytes IO and convert EOL manually in ui.editor()
Yuya Nishihara <yuya@tcha.org>
parents: 31775
diff changeset
  1566
            f.write(util.tonativeeol(text))
1984
df7436f439a0 Improved ui.edit():
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1983
diff changeset
  1567
            f.close()
df7436f439a0 Improved ui.edit():
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1983
diff changeset
  1568
20605
a8aa699a812a ui: edit(): rebase, graft: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20603
diff changeset
  1569
            environ = {'HGUSER': user}
20606
be140ebd506b ui: edit(): transplant: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20605
diff changeset
  1570
            if 'transplant_source' in extra:
be140ebd506b ui: edit(): transplant: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20605
diff changeset
  1571
                environ.update({'HGREVISION': hex(extra['transplant_source'])})
24687
28d76bc069db editor: prefer 'intermediate-source' extra to use for HGREVISION environment variable
Alexander Drozdov <al.drozdov@gmail.com>
parents: 24663
diff changeset
  1572
            for label in ('intermediate-source', 'source', 'rebase_source'):
20605
a8aa699a812a ui: edit(): rebase, graft: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20603
diff changeset
  1573
                if label in extra:
a8aa699a812a ui: edit(): rebase, graft: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20603
diff changeset
  1574
                    environ.update({'HGREVISION': extra[label]})
a8aa699a812a ui: edit(): rebase, graft: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20603
diff changeset
  1575
                    break
22205
9fa429723f26 ui: invoke editor for committing with HGEDITFORM environment variable
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 21955
diff changeset
  1576
            if editform:
9fa429723f26 ui: invoke editor for committing with HGEDITFORM environment variable
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 21955
diff changeset
  1577
                environ.update({'HGEDITFORM': editform})
26750
9f9ec4abe700 cmdutil: make in-memory changes visible to external editor (issue4378)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 26587
diff changeset
  1578
            if pending:
9f9ec4abe700 cmdutil: make in-memory changes visible to external editor (issue4378)
FUJIWARA Katsunori <foozy@lares.dti.ne.jp>
parents: 26587
diff changeset
  1579
                environ.update({'HG_PENDING': pending})
20605
a8aa699a812a ui: edit(): rebase, graft: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20603
diff changeset
  1580
5660
3c80ecdc1bcd Use VISUAL in addition to EDITOR when choosing the editor to use.
Osku Salerma <osku@iki.fi>
parents: 5613
diff changeset
  1581
            editor = self.geteditor()
207
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
  1582
23269
d9d8d2e0f701 ui: introduce util.system() wrapper to make sure ui.fout is used
Yuya Nishihara <yuya@tcha.org>
parents: 23139
diff changeset
  1583
            self.system("%s \"%s\"" % (editor, name),
20605
a8aa699a812a ui: edit(): rebase, graft: set HGREVISION environment variable for an editor
Alexander Drozdov <al.drozdov@gmail.com>
parents: 20603
diff changeset
  1584
                        environ=environ,
30980
60b5db2ab586 ui: give editor() a tag of its own
Simon Farnsworth <simonfar@fb.com>
parents: 30979
diff changeset
  1585
                        onerr=error.Abort, errprefix=_("edit failed"),
60b5db2ab586 ui: give editor() a tag of its own
Simon Farnsworth <simonfar@fb.com>
parents: 30979
diff changeset
  1586
                        blockedtag='editor')
608
d2994b5298fb Add username/merge/editor to .hgrc
Matt Mackall <mpm@selenic.com>
parents: 565
diff changeset
  1587
31778
ac69675fff1c ui: use bytes IO and convert EOL manually in ui.editor()
Yuya Nishihara <yuya@tcha.org>
parents: 31775
diff changeset
  1588
            f = open(name, r'rb')
ac69675fff1c ui: use bytes IO and convert EOL manually in ui.editor()
Yuya Nishihara <yuya@tcha.org>
parents: 31775
diff changeset
  1589
            t = util.fromnativeeol(f.read())
1984
df7436f439a0 Improved ui.edit():
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1983
diff changeset
  1590
            f.close()
df7436f439a0 Improved ui.edit():
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1983
diff changeset
  1591
        finally:
df7436f439a0 Improved ui.edit():
Thomas Arendsen Hein <thomas@intevation.de>
parents: 1983
diff changeset
  1592
            os.unlink(name)
662
b55a78595ef6 Pass username to hgeditor, remove temporary file
Radoslaw "AstralStorm" Szkodzinski <astralstorm@gorzow.mm.pl>
parents: 613
diff changeset
  1593
207
ec327cf0d3a9 Move ui class to its own module
mpm@selenic.com
parents:
diff changeset
  1594
        return t
2200
9f43b6e24232 move mail sending code into core, so extensions can share it.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 2166
diff changeset
  1595
30979
fd598149112b ui: time calls to ui.system
Simon Farnsworth <simonfar@fb.com>
parents: 30978
diff changeset
  1596
    def system(self, cmd, environ=None, cwd=None, onerr=None, errprefix=None,
fd598149112b ui: time calls to ui.system
Simon Farnsworth <simonfar@fb.com>
parents: 30978
diff changeset
  1597
               blockedtag=None):
23269
d9d8d2e0f701 ui: introduce util.system() wrapper to make sure ui.fout is used
Yuya Nishihara <yuya@tcha.org>
parents: 23139
diff changeset
  1598
        '''execute shell command with appropriate output stream. command
d9d8d2e0f701 ui: introduce util.system() wrapper to make sure ui.fout is used
Yuya Nishihara <yuya@tcha.org>
parents: 23139
diff changeset
  1599
        output will be redirected if fout is not stdout.
31108
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1600
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1601
        if command fails and onerr is None, return status, else raise onerr
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1602
        object as exception.
23269
d9d8d2e0f701 ui: introduce util.system() wrapper to make sure ui.fout is used
Yuya Nishihara <yuya@tcha.org>
parents: 23139
diff changeset
  1603
        '''
30979
fd598149112b ui: time calls to ui.system
Simon Farnsworth <simonfar@fb.com>
parents: 30978
diff changeset
  1604
        if blockedtag is None:
31535
d0f95ecca2ad ui: restrict length of autogenerated blocked tags
Simon Farnsworth <simonfar@fb.com>
parents: 31532
diff changeset
  1605
            # Long cmds tend to be because of an absolute path on cmd. Keep
d0f95ecca2ad ui: restrict length of autogenerated blocked tags
Simon Farnsworth <simonfar@fb.com>
parents: 31532
diff changeset
  1606
            # the tail end instead
d0f95ecca2ad ui: restrict length of autogenerated blocked tags
Simon Farnsworth <simonfar@fb.com>
parents: 31532
diff changeset
  1607
            cmdsuffix = cmd.translate(None, _keepalnum)[-85:]
d0f95ecca2ad ui: restrict length of autogenerated blocked tags
Simon Farnsworth <simonfar@fb.com>
parents: 31532
diff changeset
  1608
            blockedtag = 'unknown_system_' + cmdsuffix
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1609
        out = self._fout
25149
3f0744eeaeaf cleanup: use __builtins__.any instead of util.any
Augie Fackler <augie@google.com>
parents: 25125
diff changeset
  1610
        if any(s[1] for s in self._bufferstates):
24848
2f88821856eb ui: allow capture of subprocess output
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 24687
diff changeset
  1611
            out = self
30979
fd598149112b ui: time calls to ui.system
Simon Farnsworth <simonfar@fb.com>
parents: 30978
diff changeset
  1612
        with self.timeblockedsection(blockedtag):
31108
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1613
            rc = self._runsystem(cmd, environ=environ, cwd=cwd, out=out)
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1614
        if rc and onerr:
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1615
            errmsg = '%s %s' % (os.path.basename(cmd.split(None, 1)[0]),
37463
bbd240f81ac5 procutil: make explainexit() simply return a message (API)
Yuya Nishihara <yuya@tcha.org>
parents: 37134
diff changeset
  1616
                                procutil.explainexit(rc))
31108
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1617
            if errprefix:
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1618
                errmsg = '%s: %s' % (errprefix, errmsg)
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1619
            raise onerr(errmsg)
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1620
        return rc
31107
fbce78c58f1e chg: refactor ui.system() to be partly overridden
Yuya Nishihara <yuya@tcha.org>
parents: 31106
diff changeset
  1621
31108
3f8f53190d6a chg: deduplicate error handling of ui.system()
Yuya Nishihara <yuya@tcha.org>
parents: 31107
diff changeset
  1622
    def _runsystem(self, cmd, environ, cwd, out):
31107
fbce78c58f1e chg: refactor ui.system() to be partly overridden
Yuya Nishihara <yuya@tcha.org>
parents: 31106
diff changeset
  1623
        """actually execute the given shell command (can be overridden by
fbce78c58f1e chg: refactor ui.system() to be partly overridden
Yuya Nishihara <yuya@tcha.org>
parents: 31106
diff changeset
  1624
        extensions like chg)"""
37120
a8a902d7176e procutil: bulk-replace function calls to point to new module
Yuya Nishihara <yuya@tcha.org>
parents: 37119
diff changeset
  1625
        return procutil.system(cmd, environ=environ, cwd=cwd, out=out)
23269
d9d8d2e0f701 ui: introduce util.system() wrapper to make sure ui.fout is used
Yuya Nishihara <yuya@tcha.org>
parents: 23139
diff changeset
  1626
18966
5572f688e0a9 ui: add 'force' parameter to traceback() to override the current print setting
Matt Harbison <matt_harbison@yahoo.com>
parents: 18965
diff changeset
  1627
    def traceback(self, exc=None, force=False):
5572f688e0a9 ui: add 'force' parameter to traceback() to override the current print setting
Matt Harbison <matt_harbison@yahoo.com>
parents: 18965
diff changeset
  1628
        '''print exception traceback if traceback printing enabled or forced.
2335
f0680b2d1d64 add ui.print_exc(), make all traceback printing central.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 2293
diff changeset
  1629
        only to call in exception handler. returns true if traceback
f0680b2d1d64 add ui.print_exc(), make all traceback printing central.
Vadim Gelfer <vadim.gelfer@gmail.com>
parents: 2293
diff changeset
  1630
        printed.'''
18966
5572f688e0a9 ui: add 'force' parameter to traceback() to override the current print setting
Matt Harbison <matt_harbison@yahoo.com>
parents: 18965
diff changeset
  1631
        if self.tracebackflag or force:
18965
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1632
            if exc is None:
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1633
                exc = sys.exc_info()
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1634
            cause = getattr(exc[1], 'cause', None)
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1635
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1636
            if cause is not None:
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1637
                causetb = traceback.format_tb(cause[2])
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1638
                exctb = traceback.format_tb(exc[2])
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1639
                exconly = traceback.format_exception_only(cause[0], cause[1])
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1640
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1641
                # exclude frame where 'exc' was chained and rethrown from exctb
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1642
                self.write_err('Traceback (most recent call last):\n',
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1643
                               ''.join(exctb[:-1]),
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1644
                               ''.join(causetb),
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1645
                               ''.join(exconly))
0062508b1900 ui: add support for fully printing chained exception stacks in ui.traceback()
Matt Harbison <matt_harbison@yahoo.com>
parents: 18669
diff changeset
  1646
            else:
25568
c1ff82daed62 ui: flush stderr after printing a non-chained exception for Windows
Matt Harbison <matt_harbison@yahoo.com>
parents: 25519
diff changeset
  1647
                output = traceback.format_exception(exc[0], exc[1], exc[2])
35897
4b1c04082cdc py3: replace "if ispy3" by encoding.strtolocal()
Yuya Nishihara <yuya@tcha.org>
parents: 35889
diff changeset
  1648
                self.write_err(encoding.strtolocal(r''.join(output)))
18966
5572f688e0a9 ui: add 'force' parameter to traceback() to override the current print setting
Matt Harbison <matt_harbison@yahoo.com>
parents: 18965
diff changeset
  1649
        return self.tracebackflag or force
5660
3c80ecdc1bcd Use VISUAL in addition to EDITOR when choosing the editor to use.
Osku Salerma <osku@iki.fi>
parents: 5613
diff changeset
  1650
3c80ecdc1bcd Use VISUAL in addition to EDITOR when choosing the editor to use.
Osku Salerma <osku@iki.fi>
parents: 5613
diff changeset
  1651
    def geteditor(self):
3c80ecdc1bcd Use VISUAL in addition to EDITOR when choosing the editor to use.
Osku Salerma <osku@iki.fi>
parents: 5613
diff changeset
  1652
        '''return editor to use'''
30641
16b5df5792a8 py3: replace sys.platform with pycompat.sysplatform (part 1 of 2)
Pulkit Goyal <7895pulkit@gmail.com>
parents: 30637
diff changeset
  1653
        if pycompat.sysplatform == 'plan9':
16383
f5dd179bfa4a plan9: initial support for plan 9 from bell labs
Steven Stallion <sstallion@gmail.com>
parents: 16373
diff changeset
  1654
            # vi is the MIPS instruction simulator on Plan 9. We
f5dd179bfa4a plan9: initial support for plan 9 from bell labs
Steven Stallion <sstallion@gmail.com>
parents: 16373
diff changeset
  1655
            # instead default to E to plumb commit messages to
f5dd179bfa4a plan9: initial support for plan 9 from bell labs
Steven Stallion <sstallion@gmail.com>
parents: 16373
diff changeset
  1656
            # avoid confusion.
f5dd179bfa4a plan9: initial support for plan 9 from bell labs
Steven Stallion <sstallion@gmail.com>
parents: 16373
diff changeset
  1657
            editor = 'E'
f5dd179bfa4a plan9: initial support for plan 9 from bell labs
Steven Stallion <sstallion@gmail.com>
parents: 16373
diff changeset
  1658
        else:
f5dd179bfa4a plan9: initial support for plan 9 from bell labs
Steven Stallion <sstallion@gmail.com>
parents: 16373
diff changeset
  1659
            editor = 'vi'
30277
e9fca89c6d58 py3: use encoding.environ in ui.py
Pulkit Goyal <7895pulkit@gmail.com>
parents: 29978
diff changeset
  1660
        return (encoding.environ.get("HGEDITOR") or
31687
5bea95a1d353 ui: simplify geteditor
Jun Wu <quark@fb.com>
parents: 31685
diff changeset
  1661
                self.config("ui", "editor", editor))
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1662
25499
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1663
    @util.propertycache
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1664
    def _progbar(self):
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1665
        """setup the progbar singleton to the ui object"""
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1666
        if (self.quiet or self.debugflag
33499
0407a51b9d8c codemod: register core configitems using a script
Jun Wu <quark@fb.com>
parents: 33471
diff changeset
  1667
                or self.configbool('progress', 'disable')
25499
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1668
                or not progress.shouldprint(self)):
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1669
            return None
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1670
        return getprogbar(self)
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1671
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1672
    def _progclear(self):
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1673
        """clear progress bar output if any. use it before any output"""
34351
0e4bed5c5c38 ui: check for progress singleton when clearing progress bar (issue5684)
Mark Thomas <mbthomas@fb.com>
parents: 33755
diff changeset
  1674
        if not haveprogbar(): # nothing loaded yet
25499
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1675
            return
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1676
        if self._progbar is not None and self._progbar.printed:
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1677
            self._progbar.clear()
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1678
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1679
    def progress(self, topic, pos, item="", unit="", total=None):
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1680
        '''show a progress message
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1681
28598
c30d5ca4945b progress: update comment to reflect implementation
timeless <timeless@mozdev.org>
parents: 28542
diff changeset
  1682
        By default a textual progress bar will be displayed if an operation
c30d5ca4945b progress: update comment to reflect implementation
timeless <timeless@mozdev.org>
parents: 28542
diff changeset
  1683
        takes too long. 'topic' is the current operation, 'item' is a
17424
e7cfe3587ea4 fix trivial spelling errors
Mads Kiilerich <mads@kiilerich.com>
parents: 17059
diff changeset
  1684
        non-numeric marker of the current position (i.e. the currently
e7cfe3587ea4 fix trivial spelling errors
Mads Kiilerich <mads@kiilerich.com>
parents: 17059
diff changeset
  1685
        in-process file), 'pos' is the current numeric position (i.e.
9398
3fb8c6dbeeec ui: fix NameError in ui.progress due to unit/units typo
Brodie Rao <me+hg@dackz.net>
parents: 9312
diff changeset
  1686
        revision, bytes, etc.), unit is a corresponding unit label,
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1687
        and total is the highest expected pos.
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1688
10425
f8a9de664a1c ui.progress: clarify termination requirement
Augie Fackler <durin42@gmail.com>
parents: 10383
diff changeset
  1689
        Multiple nested topics may be active at a time.
f8a9de664a1c ui.progress: clarify termination requirement
Augie Fackler <durin42@gmail.com>
parents: 10383
diff changeset
  1690
f8a9de664a1c ui.progress: clarify termination requirement
Augie Fackler <durin42@gmail.com>
parents: 10383
diff changeset
  1691
        All topics should be marked closed by setting pos to None at
f8a9de664a1c ui.progress: clarify termination requirement
Augie Fackler <durin42@gmail.com>
parents: 10383
diff changeset
  1692
        termination.
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1693
        '''
40594
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1694
        if getattr(self._fmsgerr, 'structured', False):
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1695
            # channel for machine-readable output with metadata, just send
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1696
            # raw information
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1697
            # TODO: consider porting some useful information (e.g. estimated
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1698
            # time) from progbar. we might want to support update delay to
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1699
            # reduce the cost of transferring progress messages.
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1700
            self._fmsgerr.write(None, type=b'progress', topic=topic, pos=pos,
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1701
                                item=item, unit=unit, total=total)
234c2d8c9e48 commandserver: send raw progress information to message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40593
diff changeset
  1702
        elif self._progbar is not None:
25499
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1703
            self._progbar.progress(topic, pos, item=item, unit=unit,
0fa964d6fd48 progress: move all logic altering the ui object logic in mercurial.ui
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25498
diff changeset
  1704
                                   total=total)
41063
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1705
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1706
            # Looking up progress.debug in tight loops is expensive. The value
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1707
            # is cached on the progbar object and we can avoid the lookup in
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1708
            # the common case where a progbar is active.
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1709
            if pos is None or not self._progbar.debug:
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1710
                return
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1711
6603de284b0a progress: avoid ui.configbool() lookup when progress bar is active
Gregory Szorc <gregory.szorc@gmail.com>
parents: 40994
diff changeset
  1712
        # Keep this logic in sync with above.
25125
bd625cd4e5e7 progress: get the extremely verbose output out of default debug
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 24883
diff changeset
  1713
        if pos is None or not self.configbool('progress', 'debug'):
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1714
            return
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1715
9398
3fb8c6dbeeec ui: fix NameError in ui.progress due to unit/units typo
Brodie Rao <me+hg@dackz.net>
parents: 9312
diff changeset
  1716
        if unit:
3fb8c6dbeeec ui: fix NameError in ui.progress due to unit/units typo
Brodie Rao <me+hg@dackz.net>
parents: 9312
diff changeset
  1717
            unit = ' ' + unit
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1718
        if item:
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1719
            item = ' ' + item
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1720
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1721
        if total:
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1722
            pct = 100.0 * pos / total
34271
a254c669b475 ui: fix progress debug log format strings to work on Python 3
Augie Fackler <augie@google.com>
parents: 34208
diff changeset
  1723
            self.debug('%s:%s %d/%d%s (%4.2f%%)\n'
9398
3fb8c6dbeeec ui: fix NameError in ui.progress due to unit/units typo
Brodie Rao <me+hg@dackz.net>
parents: 9312
diff changeset
  1724
                     % (topic, item, pos, total, unit, pct))
9153
6adc899c98d0 Add ui.progress API
Matt Mackall <mpm@selenic.com>
parents: 9048
diff changeset
  1725
        else:
34271
a254c669b475 ui: fix progress debug log format strings to work on Python 3
Augie Fackler <augie@google.com>
parents: 34208
diff changeset
  1726
            self.debug('%s:%s %d%s\n' % (topic, item, pos, unit))
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1727
38345
bec1212eceaa progress: create helper class for incrementing progress
Martin von Zweigbergk <martinvonz@google.com>
parents: 38164
diff changeset
  1728
    def makeprogress(self, topic, unit="", total=None):
bec1212eceaa progress: create helper class for incrementing progress
Martin von Zweigbergk <martinvonz@google.com>
parents: 38164
diff changeset
  1729
        '''exists only so low-level modules won't need to import scmutil'''
bec1212eceaa progress: create helper class for incrementing progress
Martin von Zweigbergk <martinvonz@google.com>
parents: 38164
diff changeset
  1730
        return scmutil.progress(self, topic, unit, total)
bec1212eceaa progress: create helper class for incrementing progress
Martin von Zweigbergk <martinvonz@google.com>
parents: 38164
diff changeset
  1731
40730
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1732
    def getlogger(self, name):
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1733
        """Returns a logger of the given name; or None if not registered"""
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1734
        return self._loggers.get(name)
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1735
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1736
    def setlogger(self, name, logger):
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1737
        """Install logger which can be identified later by the given name
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1738
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1739
        More than one loggers can be registered. Use extension or module
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1740
        name to uniquely identify the logger instance.
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1741
        """
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1742
        self._loggers[name] = logger
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1743
40760
ffd574c144d2 ui: pass in formatted message to logger.log()
Yuya Nishihara <yuya@tcha.org>
parents: 40759
diff changeset
  1744
    def log(self, event, msgfmt, *msgargs, **opts):
11984
2db0fccc8143 ui: add logging hook
Matt Mackall <mpm@selenic.com>
parents: 11970
diff changeset
  1745
        '''hook for logging facility extensions
2db0fccc8143 ui: add logging hook
Matt Mackall <mpm@selenic.com>
parents: 11970
diff changeset
  1746
40678
c72a81bc2e82 ui: unify argument name of ui.log()
Yuya Nishihara <yuya@tcha.org>
parents: 40602
diff changeset
  1747
        event should be a readily-identifiable subsystem, which will
11984
2db0fccc8143 ui: add logging hook
Matt Mackall <mpm@selenic.com>
parents: 11970
diff changeset
  1748
        allow filtering.
26235
6c962145f523 ui: improve docs on ui.log
Augie Fackler <augie@google.com>
parents: 26189
diff changeset
  1749
40760
ffd574c144d2 ui: pass in formatted message to logger.log()
Yuya Nishihara <yuya@tcha.org>
parents: 40759
diff changeset
  1750
        msgfmt should be a newline-terminated format string to log, and
ffd574c144d2 ui: pass in formatted message to logger.log()
Yuya Nishihara <yuya@tcha.org>
parents: 40759
diff changeset
  1751
        *msgargs are %-formatted into it.
26235
6c962145f523 ui: improve docs on ui.log
Augie Fackler <augie@google.com>
parents: 26189
diff changeset
  1752
6c962145f523 ui: improve docs on ui.log
Augie Fackler <augie@google.com>
parents: 26189
diff changeset
  1753
        **opts currently has no defined meanings.
11984
2db0fccc8143 ui: add logging hook
Matt Mackall <mpm@selenic.com>
parents: 11970
diff changeset
  1754
        '''
40730
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1755
        if not self._loggers:
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1756
            return
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1757
        activeloggers = [l for l in self._loggers.itervalues()
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1758
                         if l.tracked(event)]
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1759
        if not activeloggers:
55b053af7196 ui: manage logger instances and event filtering by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40678
diff changeset
  1760
            return
40760
ffd574c144d2 ui: pass in formatted message to logger.log()
Yuya Nishihara <yuya@tcha.org>
parents: 40759
diff changeset
  1761
        msg = msgfmt % msgargs
40761
691c68bc1222 ui: pass in bytes opts dict to logger.log()
Yuya Nishihara <yuya@tcha.org>
parents: 40760
diff changeset
  1762
        opts = pycompat.byteskwargs(opts)
40759
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1763
        # guard against recursion from e.g. ui.debug()
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1764
        registeredloggers = self._loggers
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1765
        self._loggers = {}
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1766
        try:
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1767
            for logger in activeloggers:
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1768
                logger.log(self, event, msg, opts)
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1769
        finally:
fdc6eb1d650d blackbox: send debug message to logger by core ui
Yuya Nishihara <yuya@tcha.org>
parents: 40730
diff changeset
  1770
            self._loggers = registeredloggers
11984
2db0fccc8143 ui: add logging hook
Matt Mackall <mpm@selenic.com>
parents: 11970
diff changeset
  1771
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1772
    def label(self, msg, label):
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1773
        '''style msg based on supplied label
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1774
31087
894bdcdc75df color: move the 'colorlabel' call to the core 'ui' class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31083
diff changeset
  1775
        If some color mode is enabled, this will add the necessary control
894bdcdc75df color: move the 'colorlabel' call to the core 'ui' class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31083
diff changeset
  1776
        characters to apply such color. In addition, 'debug' color mode adds
894bdcdc75df color: move the 'colorlabel' call to the core 'ui' class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31083
diff changeset
  1777
        markup showing which label affects a piece of text.
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1778
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1779
        ui.write(s, 'label') is equivalent to
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1780
        ui.write(ui.label(s, 'label')).
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1781
        '''
31087
894bdcdc75df color: move the 'colorlabel' call to the core 'ui' class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31083
diff changeset
  1782
        if self._colormode is not None:
894bdcdc75df color: move the 'colorlabel' call to the core 'ui' class
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 31083
diff changeset
  1783
            return color.colorlabel(self, msg, label)
10815
32b213b9b22c ui: add ui.write() output labeling API
Brodie Rao <brodie@bitheap.org>
parents: 10567
diff changeset
  1784
        return msg
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1785
29095
3f33831a9202 develwarn: move config gating inside the develwarn function
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 29082
diff changeset
  1786
    def develwarn(self, msg, stacklevel=1, config=None):
27274
82910fdc216f ui: add a 'stacklevel' argument to 'develwarn'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27266
diff changeset
  1787
        """issue a developer warning message
82910fdc216f ui: add a 'stacklevel' argument to 'develwarn'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27266
diff changeset
  1788
82910fdc216f ui: add a 'stacklevel' argument to 'develwarn'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27266
diff changeset
  1789
        Use 'stacklevel' to report the offender some layers further up in the
82910fdc216f ui: add a 'stacklevel' argument to 'develwarn'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27266
diff changeset
  1790
        stack.
82910fdc216f ui: add a 'stacklevel' argument to 'develwarn'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27266
diff changeset
  1791
        """
29095
3f33831a9202 develwarn: move config gating inside the develwarn function
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 29082
diff changeset
  1792
        if not self.configbool('devel', 'all-warnings'):
35127
fa2395db68c6 develwarn: do not emit warning if "config" is unspecified
Kyle Lippincott <spectral@google.com>
parents: 35067
diff changeset
  1793
            if config is None or not self.configbool('devel', config):
29095
3f33831a9202 develwarn: move config gating inside the develwarn function
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 29082
diff changeset
  1794
                return
25629
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1795
        msg = 'devel-warn: ' + msg
27274
82910fdc216f ui: add a 'stacklevel' argument to 'develwarn'
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27266
diff changeset
  1796
        stacklevel += 1 # get in develwarn
25629
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1797
        if self.tracebackflag:
40543
7bffbbe03e90 ui: hide fin/fout/ferr attributes behind @property functions
Yuya Nishihara <yuya@tcha.org>
parents: 40542
diff changeset
  1798
            util.debugstacktrace(msg, stacklevel, self._ferr, self._fout)
28498
d09be0b8a3c6 ui: log devel warnings
timeless <timeless@mozdev.org>
parents: 28218
diff changeset
  1799
            self.log('develwarn', '%s at:\n%s' %
d09be0b8a3c6 ui: log devel warnings
timeless <timeless@mozdev.org>
parents: 28218
diff changeset
  1800
                     (msg, ''.join(util.getstackframes(stacklevel))))
25629
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1801
        else:
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1802
            curframe = inspect.currentframe()
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1803
            calframe = inspect.getouterframes(curframe, 2)
36127
df1760b58fda ui: convert stack traces to sysbytes before logging
Augie Fackler <augie@google.com>
parents: 36126
diff changeset
  1804
            fname, lineno, fmsg = calframe[stacklevel][1:4]
df1760b58fda ui: convert stack traces to sysbytes before logging
Augie Fackler <augie@google.com>
parents: 36126
diff changeset
  1805
            fname, fmsg = pycompat.sysbytes(fname), pycompat.sysbytes(fmsg)
df1760b58fda ui: convert stack traces to sysbytes before logging
Augie Fackler <augie@google.com>
parents: 36126
diff changeset
  1806
            self.write_err('%s at: %s:%d (%s)\n'
df1760b58fda ui: convert stack traces to sysbytes before logging
Augie Fackler <augie@google.com>
parents: 36126
diff changeset
  1807
                           % (msg, fname, lineno, fmsg))
df1760b58fda ui: convert stack traces to sysbytes before logging
Augie Fackler <augie@google.com>
parents: 36126
diff changeset
  1808
            self.log('develwarn', '%s at: %s:%d (%s)\n',
df1760b58fda ui: convert stack traces to sysbytes before logging
Augie Fackler <augie@google.com>
parents: 36126
diff changeset
  1809
                     msg, fname, lineno, fmsg)
29762
96bd27eb23f0 ui: drop values returned by inspect.*frame*() to avoid cycles
Jun Wu <quark@fb.com>
parents: 29413
diff changeset
  1810
            curframe = calframe = None  # avoid cycles
25629
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1811
35923
efbd04238029 cmdutil: convert _revertprefetch() to a generic stored file hook (API)
Matt Harbison <matt_harbison@yahoo.com>
parents: 35911
diff changeset
  1812
    def deprecwarn(self, msg, version, stacklevel=2):
27275
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1813
        """issue a deprecation warning
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1814
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1815
        - msg: message explaining what is deprecated and how to upgrade,
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1816
        - version: last version where the API will be supported,
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1817
        """
29082
77de985d7c91 deprecation: gate deprecation warning behind devel configuration
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 28962
diff changeset
  1818
        if not (self.configbool('devel', 'all-warnings')
77de985d7c91 deprecation: gate deprecation warning behind devel configuration
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 28962
diff changeset
  1819
                or self.configbool('devel', 'deprec-warn')):
77de985d7c91 deprecation: gate deprecation warning behind devel configuration
Pierre-Yves David <pierre-yves.david@ens-lyon.org>
parents: 28962
diff changeset
  1820
            return
27275
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1821
        msg += ("\n(compatibility will be dropped after Mercurial-%s,"
f2cd240f2f7c ui: add a 'deprecwarn' helper to issue deprecation warnings
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 27274
diff changeset
  1822
                " update your code.)") % version
35923
efbd04238029 cmdutil: convert _revertprefetch() to a generic stored file hook (API)
Matt Harbison <matt_harbison@yahoo.com>
parents: 35911
diff changeset
  1823
        self.develwarn(msg, stacklevel=stacklevel, config='deprec-warn')
25629
52e5f68d8363 devel-warn: move the develwarn function as a method of the ui object
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25568
diff changeset
  1824
30832
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
  1825
    def exportableenviron(self):
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
  1826
        """The environment variables that are safe to export, e.g. through
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
  1827
        hgweb.
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
  1828
        """
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
  1829
        return self._exportableenviron
da5fa0f13a41 ui: introduce an experimental dict of exportable environment variables
Matt Harbison <matt_harbison@yahoo.com>
parents: 30814
diff changeset
  1830
30480
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1831
    @contextlib.contextmanager
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1832
    def configoverride(self, overrides, source=""):
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1833
        """Context manager for temporary config overrides
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1834
        `overrides` must be a dict of the following structure:
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1835
        {(section, name) : value}"""
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1836
        backups = {}
30537
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1837
        try:
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1838
            for (section, name), value in overrides.items():
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1839
                backups[(section, name)] = self.backupconfig(section, name)
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1840
                self.setconfig(section, name, value, source)
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1841
            yield
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1842
        finally:
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1843
            for __, backup in backups.items():
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1844
                self.restoreconfig(backup)
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1845
            # just restoring ui.quiet config to the previous value is not enough
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1846
            # as it does not update ui.quiet class member
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1847
            if ('ui', 'quiet') in overrides:
4b0e6677eed1 ui: use try..finally in configoverride
Gregory Szorc <gregory.szorc@gmail.com>
parents: 30519
diff changeset
  1848
                self.fixconfig(section='ui')
30480
b0a8337ba9af ui: add configoverride context manager
Kostia Balytskyi <ikostia@fb.com>
parents: 30473
diff changeset
  1849
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1850
class paths(dict):
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1851
    """Represents a collection of paths and their configs.
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1852
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1853
    Data is initially derived from ui instances and the config files they have
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1854
    loaded.
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1855
    """
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1856
    def __init__(self, ui):
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1857
        dict.__init__(self)
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1858
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1859
        for name, loc in ui.configitems('paths', ignoresub=True):
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1860
            # No location is the same as not existing.
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1861
            if not loc:
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1862
                continue
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1863
            loc, sub = ui.configsuboptions('paths', name)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1864
            self[name] = path(ui, name, rawloc=loc, suboptions=sub)
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1865
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1866
    def getpath(self, name, default=None):
27561
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1867
        """Return a ``path`` from a string, falling back to default.
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1868
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1869
        ``name`` can be a named path or locations. Locations are filesystem
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1870
        paths or URIs.
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1871
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1872
        Returns None if ``name`` is not a registered path, a URI, or a local
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1873
        path to a repo.
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1874
        """
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1875
        # Only fall back to default if no path was requested.
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1876
        if name is None:
27561
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1877
            if not default:
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1878
                default = ()
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1879
            elif not isinstance(default, (tuple, list)):
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1880
                default = (default,)
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1881
            for k in default:
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1882
                try:
27561
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1883
                    return self[k]
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1884
                except KeyError:
27561
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1885
                    continue
723413ee000e paths: make getpath() accept multiple defaults
Yuya Nishihara <yuya@tcha.org>
parents: 27500
diff changeset
  1886
            return None
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1887
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1888
        # Most likely empty string.
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1889
        # This may need to raise in the future.
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1890
        if not name:
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1891
            return None
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1892
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1893
        try:
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1894
            return self[name]
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1895
        except KeyError:
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1896
            # Try to resolve as a local path or URI.
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1897
            try:
27265
47539ea08bdb ui: pass ui instance to path.__init__
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27264
diff changeset
  1898
                # We don't pass sub-options in, so no need to pass ui instance.
47539ea08bdb ui: pass ui instance to path.__init__
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27264
diff changeset
  1899
                return path(None, None, rawloc=name)
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1900
            except ValueError:
26189
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1901
                raise error.RepoError(_('repository %s does not exist') %
663fbc336e22 ui: change default path fallback mechanism (issue4796)
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26076
diff changeset
  1902
                                        name)
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1903
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1904
_pathsuboptions = {}
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1905
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1906
def pathsuboption(option, attr):
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1907
    """Decorator used to declare a path sub-option.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1908
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1909
    Arguments are the sub-option name and the attribute it should set on
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1910
    ``path`` instances.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1911
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1912
    The decorated function will receive as arguments a ``ui`` instance,
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1913
    ``path`` instance, and the string value of this option from the config.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1914
    The function should return the value that will be set on the ``path``
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1915
    instance.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1916
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1917
    This decorator can be used to perform additional verification of
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1918
    sub-options and to change the type of sub-options.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1919
    """
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1920
    def register(func):
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1921
        _pathsuboptions[option] = (attr, func)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1922
        return func
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1923
    return register
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1924
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1925
@pathsuboption('pushurl', 'pushloc')
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1926
def pushurlpathoption(ui, path, value):
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1927
    u = util.url(value)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1928
    # Actually require a URL.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1929
    if not u.scheme:
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1930
        ui.warn(_('(paths.%s:pushurl not a URL; ignoring)\n') % path.name)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1931
        return None
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1932
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1933
    # Don't support the #foo syntax in the push URL to declare branch to
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1934
    # push.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1935
    if u.fragment:
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1936
        ui.warn(_('("#fragment" in paths.%s:pushurl not supported; '
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1937
                  'ignoring)\n') % path.name)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1938
        u.fragment = None
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1939
36731
8988c34bd018 py3: don't use str() to stringify pushloc
Yuya Nishihara <yuya@tcha.org>
parents: 36607
diff changeset
  1940
    return bytes(u)
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1941
29413
31d3ab7985b8 ui: path option to declare which revisions to push by default
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29412
diff changeset
  1942
@pathsuboption('pushrev', 'pushrev')
31d3ab7985b8 ui: path option to declare which revisions to push by default
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29412
diff changeset
  1943
def pushrevpathoption(ui, path, value):
31d3ab7985b8 ui: path option to declare which revisions to push by default
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29412
diff changeset
  1944
    return value
31d3ab7985b8 ui: path option to declare which revisions to push by default
Gregory Szorc <gregory.szorc@gmail.com>
parents: 29412
diff changeset
  1945
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1946
class path(object):
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1947
    """Represents an individual path and its configuration."""
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1948
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1949
    def __init__(self, ui, name, rawloc=None, suboptions=None):
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1950
        """Construct a path from its config options.
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1951
27265
47539ea08bdb ui: pass ui instance to path.__init__
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27264
diff changeset
  1952
        ``ui`` is the ``ui`` instance the path is coming from.
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1953
        ``name`` is the symbolic name of the path.
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1954
        ``rawloc`` is the raw location, as defined in the config.
26064
1b1ab6ff58c4 ui: capture push location on path instances
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26056
diff changeset
  1955
        ``pushloc`` is the raw locations pushes should be made to.
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1956
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1957
        If ``name`` is not defined, we require that the location be a) a local
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1958
        filesystem path with a .hg directory or b) a URL. If not,
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1959
        ``ValueError`` is raised.
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1960
        """
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1961
        if not rawloc:
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1962
            raise ValueError('rawloc must be defined')
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1963
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1964
        # Locations may define branches via syntax <base>#<branch>.
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1965
        u = util.url(rawloc)
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1966
        branch = None
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1967
        if u.fragment:
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1968
            branch = u.fragment
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1969
            u.fragment = None
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1970
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1971
        self.url = u
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1972
        self.branch = branch
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1973
24250
9c32eea2ca04 ui: represent paths as classes
Gregory Szorc <gregory.szorc@gmail.com>
parents: 23269
diff changeset
  1974
        self.name = name
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1975
        self.rawloc = rawloc
31350
2eee8ad77726 ui: portably bytestring-ify url object
Augie Fackler <augie@google.com>
parents: 31341
diff changeset
  1976
        self.loc = '%s' % u
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1977
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1978
        # When given a raw location but not a symbolic name, validate the
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1979
        # location is valid.
26076
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  1980
        if not name and not u.scheme and not self._isvalidlocalpath(self.loc):
26056
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1981
            raise ValueError('location is not a URL or path to a local '
5f2a4fc3c4fa ui: move URL and path detection into path API
Gregory Szorc <gregory.szorc@gmail.com>
parents: 25989
diff changeset
  1982
                             'repo: %s' % rawloc)
25498
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  1983
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1984
        suboptions = suboptions or {}
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1985
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1986
        # Now process the sub-options. If a sub-option is registered, its
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1987
        # attribute will always be present. The value will be None if there
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1988
        # was no valid sub-option.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1989
        for suboption, (attr, func) in _pathsuboptions.iteritems():
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1990
            if suboption not in suboptions:
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1991
                setattr(self, attr, None)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1992
                continue
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1993
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1994
            value = func(ui, self, suboptions[suboption])
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1995
            setattr(self, attr, value)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  1996
26076
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  1997
    def _isvalidlocalpath(self, path):
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  1998
        """Returns True if the given path is a potentially valid repository.
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  1999
        This is its own function so that extensions can change the definition of
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  2000
        'valid' in this case (like when pulling from a git repo into a hg
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  2001
        one)."""
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  2002
        return os.path.isdir(os.path.join(path, '.hg'))
cebf7e48365e paths: move path validation logic to its own function
Durham Goode <durham@fb.com>
parents: 26064
diff changeset
  2003
26064
1b1ab6ff58c4 ui: capture push location on path instances
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26056
diff changeset
  2004
    @property
27266
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2005
    def suboptions(self):
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2006
        """Return sub-options and their values for this path.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2007
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2008
        This is intended to be used for presentation purposes.
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2009
        """
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2010
        d = {}
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2011
        for subopt, (attr, _func) in _pathsuboptions.iteritems():
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2012
            value = getattr(self, attr)
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2013
            if value is not None:
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2014
                d[subopt] = value
4dccc37b87bd ui: support declaring path push urls as sub-options
Gregory Szorc <gregory.szorc@gmail.com>
parents: 27265
diff changeset
  2015
        return d
26064
1b1ab6ff58c4 ui: capture push location on path instances
Gregory Szorc <gregory.szorc@gmail.com>
parents: 26056
diff changeset
  2016
25498
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2017
# we instantiate one globally shared progress bar to avoid
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2018
# competing progress bars when multiple UI objects get created
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2019
_progresssingleton = None
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2020
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2021
def getprogbar(ui):
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2022
    global _progresssingleton
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2023
    if _progresssingleton is None:
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2024
        # passing 'ui' object to the singleton is fishy,
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2025
        # this is how the extension used to work but feel free to rework it.
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2026
        _progresssingleton = progress.progbar(ui)
7a5335ed7e1a progress: move the singleton logic to the ui module
Pierre-Yves David <pierre-yves.david@fb.com>
parents: 25363
diff changeset
  2027
    return _progresssingleton
34351
0e4bed5c5c38 ui: check for progress singleton when clearing progress bar (issue5684)
Mark Thomas <mbthomas@fb.com>
parents: 33755
diff changeset
  2028
0e4bed5c5c38 ui: check for progress singleton when clearing progress bar (issue5684)
Mark Thomas <mbthomas@fb.com>
parents: 33755
diff changeset
  2029
def haveprogbar():
0e4bed5c5c38 ui: check for progress singleton when clearing progress bar (issue5684)
Mark Thomas <mbthomas@fb.com>
parents: 33755
diff changeset
  2030
    return _progresssingleton is not None
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2031
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2032
def _selectmsgdests(ui):
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2033
    name = ui.config(b'ui', b'message-output')
40589
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2034
    if name == b'channel':
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2035
        if ui.fmsg:
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2036
            return ui.fmsg, ui.fmsg
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2037
        else:
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2038
            # fall back to ferr if channel isn't ready so that status/error
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2039
            # messages can be printed
054d0fcba2c4 commandserver: add experimental option to use separate message channel
Yuya Nishihara <yuya@tcha.org>
parents: 40587
diff changeset
  2040
            return ui.ferr, ui.ferr
40547
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2041
    if name == b'stdio':
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2042
        return ui.fout, ui.ferr
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2043
    if name == b'stderr':
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2044
        return ui.ferr, ui.ferr
840cd57cde32 ui: add config knob to redirect status messages to stderr (API)
Yuya Nishihara <yuya@tcha.org>
parents: 40543
diff changeset
  2045
    raise error.Abort(b'invalid ui.message-output destination: %s' % name)
40590
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2046
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2047
def _writemsgwith(write, dest, *args, **opts):
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2048
    """Write ui message with the given ui._write*() function
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2049
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2050
    The specified message type is translated to 'ui.<type>' label if the dest
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2051
    isn't a structured channel, so that the message will be colorized.
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2052
    """
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2053
    # TODO: maybe change 'type' to a mandatory option
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2054
    if r'type' in opts and not getattr(dest, 'structured', False):
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2055
        opts[r'label'] = opts.get(r'label', '') + ' ui.%s' % opts.pop(r'type')
83dd8c63a0c6 ui: extract helpers to write message with type or label
Yuya Nishihara <yuya@tcha.org>
parents: 40589
diff changeset
  2056
    write(dest, *args, **opts)