##// END OF EJS Templates
ui: remove labeled argument from popbuffer...
Gregory Szorc -
r27109:a93d53f7 default
parent child Browse files
Show More
@@ -1,689 +1,689 b''
1 # color.py color output for Mercurial commands
1 # color.py color output for Mercurial commands
2 #
2 #
3 # Copyright (C) 2007 Kevin Christen <kevin.christen@gmail.com>
3 # Copyright (C) 2007 Kevin Christen <kevin.christen@gmail.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''colorize output from some commands
8 '''colorize output from some commands
9
9
10 The color extension colorizes output from several Mercurial commands.
10 The color extension colorizes output from several Mercurial commands.
11 For example, the diff command shows additions in green and deletions
11 For example, the diff command shows additions in green and deletions
12 in red, while the status command shows modified files in magenta. Many
12 in red, while the status command shows modified files in magenta. Many
13 other commands have analogous colors. It is possible to customize
13 other commands have analogous colors. It is possible to customize
14 these colors.
14 these colors.
15
15
16 Effects
16 Effects
17 -------
17 -------
18
18
19 Other effects in addition to color, like bold and underlined text, are
19 Other effects in addition to color, like bold and underlined text, are
20 also available. By default, the terminfo database is used to find the
20 also available. By default, the terminfo database is used to find the
21 terminal codes used to change color and effect. If terminfo is not
21 terminal codes used to change color and effect. If terminfo is not
22 available, then effects are rendered with the ECMA-48 SGR control
22 available, then effects are rendered with the ECMA-48 SGR control
23 function (aka ANSI escape codes).
23 function (aka ANSI escape codes).
24
24
25 The available effects in terminfo mode are 'blink', 'bold', 'dim',
25 The available effects in terminfo mode are 'blink', 'bold', 'dim',
26 'inverse', 'invisible', 'italic', 'standout', and 'underline'; in
26 'inverse', 'invisible', 'italic', 'standout', and 'underline'; in
27 ECMA-48 mode, the options are 'bold', 'inverse', 'italic', and
27 ECMA-48 mode, the options are 'bold', 'inverse', 'italic', and
28 'underline'. How each is rendered depends on the terminal emulator.
28 'underline'. How each is rendered depends on the terminal emulator.
29 Some may not be available for a given terminal type, and will be
29 Some may not be available for a given terminal type, and will be
30 silently ignored.
30 silently ignored.
31
31
32 Labels
32 Labels
33 ------
33 ------
34
34
35 Text receives color effects depending on the labels that it has. Many
35 Text receives color effects depending on the labels that it has. Many
36 default Mercurial commands emit labelled text. You can also define
36 default Mercurial commands emit labelled text. You can also define
37 your own labels in templates using the label function, see :hg:`help
37 your own labels in templates using the label function, see :hg:`help
38 templates`. A single portion of text may have more than one label. In
38 templates`. A single portion of text may have more than one label. In
39 that case, effects given to the last label will override any other
39 that case, effects given to the last label will override any other
40 effects. This includes the special "none" effect, which nullifies
40 effects. This includes the special "none" effect, which nullifies
41 other effects.
41 other effects.
42
42
43 Labels are normally invisible. In order to see these labels and their
43 Labels are normally invisible. In order to see these labels and their
44 position in the text, use the global --color=debug option. The same
44 position in the text, use the global --color=debug option. The same
45 anchor text may be associated to multiple labels, e.g.
45 anchor text may be associated to multiple labels, e.g.
46
46
47 [log.changeset changeset.secret|changeset: 22611:6f0a53c8f587]
47 [log.changeset changeset.secret|changeset: 22611:6f0a53c8f587]
48
48
49 The following are the default effects for some default labels. Default
49 The following are the default effects for some default labels. Default
50 effects may be overridden from your configuration file::
50 effects may be overridden from your configuration file::
51
51
52 [color]
52 [color]
53 status.modified = blue bold underline red_background
53 status.modified = blue bold underline red_background
54 status.added = green bold
54 status.added = green bold
55 status.removed = red bold blue_background
55 status.removed = red bold blue_background
56 status.deleted = cyan bold underline
56 status.deleted = cyan bold underline
57 status.unknown = magenta bold underline
57 status.unknown = magenta bold underline
58 status.ignored = black bold
58 status.ignored = black bold
59
59
60 # 'none' turns off all effects
60 # 'none' turns off all effects
61 status.clean = none
61 status.clean = none
62 status.copied = none
62 status.copied = none
63
63
64 qseries.applied = blue bold underline
64 qseries.applied = blue bold underline
65 qseries.unapplied = black bold
65 qseries.unapplied = black bold
66 qseries.missing = red bold
66 qseries.missing = red bold
67
67
68 diff.diffline = bold
68 diff.diffline = bold
69 diff.extended = cyan bold
69 diff.extended = cyan bold
70 diff.file_a = red bold
70 diff.file_a = red bold
71 diff.file_b = green bold
71 diff.file_b = green bold
72 diff.hunk = magenta
72 diff.hunk = magenta
73 diff.deleted = red
73 diff.deleted = red
74 diff.inserted = green
74 diff.inserted = green
75 diff.changed = white
75 diff.changed = white
76 diff.tab =
76 diff.tab =
77 diff.trailingwhitespace = bold red_background
77 diff.trailingwhitespace = bold red_background
78
78
79 # Blank so it inherits the style of the surrounding label
79 # Blank so it inherits the style of the surrounding label
80 changeset.public =
80 changeset.public =
81 changeset.draft =
81 changeset.draft =
82 changeset.secret =
82 changeset.secret =
83
83
84 resolve.unresolved = red bold
84 resolve.unresolved = red bold
85 resolve.resolved = green bold
85 resolve.resolved = green bold
86
86
87 bookmarks.active = green
87 bookmarks.active = green
88
88
89 branches.active = none
89 branches.active = none
90 branches.closed = black bold
90 branches.closed = black bold
91 branches.current = green
91 branches.current = green
92 branches.inactive = none
92 branches.inactive = none
93
93
94 tags.normal = green
94 tags.normal = green
95 tags.local = black bold
95 tags.local = black bold
96
96
97 rebase.rebased = blue
97 rebase.rebased = blue
98 rebase.remaining = red bold
98 rebase.remaining = red bold
99
99
100 shelve.age = cyan
100 shelve.age = cyan
101 shelve.newest = green bold
101 shelve.newest = green bold
102 shelve.name = blue bold
102 shelve.name = blue bold
103
103
104 histedit.remaining = red bold
104 histedit.remaining = red bold
105
105
106 Custom colors
106 Custom colors
107 -------------
107 -------------
108
108
109 Because there are only eight standard colors, this module allows you
109 Because there are only eight standard colors, this module allows you
110 to define color names for other color slots which might be available
110 to define color names for other color slots which might be available
111 for your terminal type, assuming terminfo mode. For instance::
111 for your terminal type, assuming terminfo mode. For instance::
112
112
113 color.brightblue = 12
113 color.brightblue = 12
114 color.pink = 207
114 color.pink = 207
115 color.orange = 202
115 color.orange = 202
116
116
117 to set 'brightblue' to color slot 12 (useful for 16 color terminals
117 to set 'brightblue' to color slot 12 (useful for 16 color terminals
118 that have brighter colors defined in the upper eight) and, 'pink' and
118 that have brighter colors defined in the upper eight) and, 'pink' and
119 'orange' to colors in 256-color xterm's default color cube. These
119 'orange' to colors in 256-color xterm's default color cube. These
120 defined colors may then be used as any of the pre-defined eight,
120 defined colors may then be used as any of the pre-defined eight,
121 including appending '_background' to set the background to that color.
121 including appending '_background' to set the background to that color.
122
122
123 Modes
123 Modes
124 -----
124 -----
125
125
126 By default, the color extension will use ANSI mode (or win32 mode on
126 By default, the color extension will use ANSI mode (or win32 mode on
127 Windows) if it detects a terminal. To override auto mode (to enable
127 Windows) if it detects a terminal. To override auto mode (to enable
128 terminfo mode, for example), set the following configuration option::
128 terminfo mode, for example), set the following configuration option::
129
129
130 [color]
130 [color]
131 mode = terminfo
131 mode = terminfo
132
132
133 Any value other than 'ansi', 'win32', 'terminfo', or 'auto' will
133 Any value other than 'ansi', 'win32', 'terminfo', or 'auto' will
134 disable color.
134 disable color.
135
135
136 Note that on some systems, terminfo mode may cause problems when using
136 Note that on some systems, terminfo mode may cause problems when using
137 color with the pager extension and less -R. less with the -R option
137 color with the pager extension and less -R. less with the -R option
138 will only display ECMA-48 color codes, and terminfo mode may sometimes
138 will only display ECMA-48 color codes, and terminfo mode may sometimes
139 emit codes that less doesn't understand. You can work around this by
139 emit codes that less doesn't understand. You can work around this by
140 either using ansi mode (or auto mode), or by using less -r (which will
140 either using ansi mode (or auto mode), or by using less -r (which will
141 pass through all terminal control codes, not just color control
141 pass through all terminal control codes, not just color control
142 codes).
142 codes).
143
143
144 On some systems (such as MSYS in Windows), the terminal may support
144 On some systems (such as MSYS in Windows), the terminal may support
145 a different color mode than the pager (activated via the "pager"
145 a different color mode than the pager (activated via the "pager"
146 extension). It is possible to define separate modes depending on whether
146 extension). It is possible to define separate modes depending on whether
147 the pager is active::
147 the pager is active::
148
148
149 [color]
149 [color]
150 mode = auto
150 mode = auto
151 pagermode = ansi
151 pagermode = ansi
152
152
153 If ``pagermode`` is not defined, the ``mode`` will be used.
153 If ``pagermode`` is not defined, the ``mode`` will be used.
154 '''
154 '''
155
155
156 import os
156 import os
157
157
158 from mercurial import cmdutil, commands, dispatch, extensions, subrepo, util
158 from mercurial import cmdutil, commands, dispatch, extensions, subrepo, util
159 from mercurial import ui as uimod
159 from mercurial import ui as uimod
160 from mercurial import templater, error
160 from mercurial import templater, error
161 from mercurial.i18n import _
161 from mercurial.i18n import _
162
162
163 cmdtable = {}
163 cmdtable = {}
164 command = cmdutil.command(cmdtable)
164 command = cmdutil.command(cmdtable)
165 # Note for extension authors: ONLY specify testedwith = 'internal' for
165 # Note for extension authors: ONLY specify testedwith = 'internal' for
166 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
166 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
167 # be specifying the version(s) of Mercurial they are tested with, or
167 # be specifying the version(s) of Mercurial they are tested with, or
168 # leave the attribute unspecified.
168 # leave the attribute unspecified.
169 testedwith = 'internal'
169 testedwith = 'internal'
170
170
171 # start and stop parameters for effects
171 # start and stop parameters for effects
172 _effects = {'none': 0, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
172 _effects = {'none': 0, 'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
173 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 'bold': 1,
173 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37, 'bold': 1,
174 'italic': 3, 'underline': 4, 'inverse': 7, 'dim': 2,
174 'italic': 3, 'underline': 4, 'inverse': 7, 'dim': 2,
175 'black_background': 40, 'red_background': 41,
175 'black_background': 40, 'red_background': 41,
176 'green_background': 42, 'yellow_background': 43,
176 'green_background': 42, 'yellow_background': 43,
177 'blue_background': 44, 'purple_background': 45,
177 'blue_background': 44, 'purple_background': 45,
178 'cyan_background': 46, 'white_background': 47}
178 'cyan_background': 46, 'white_background': 47}
179
179
180 def _terminfosetup(ui, mode):
180 def _terminfosetup(ui, mode):
181 '''Initialize terminfo data and the terminal if we're in terminfo mode.'''
181 '''Initialize terminfo data and the terminal if we're in terminfo mode.'''
182
182
183 global _terminfo_params
183 global _terminfo_params
184 # If we failed to load curses, we go ahead and return.
184 # If we failed to load curses, we go ahead and return.
185 if not _terminfo_params:
185 if not _terminfo_params:
186 return
186 return
187 # Otherwise, see what the config file says.
187 # Otherwise, see what the config file says.
188 if mode not in ('auto', 'terminfo'):
188 if mode not in ('auto', 'terminfo'):
189 return
189 return
190
190
191 _terminfo_params.update((key[6:], (False, int(val)))
191 _terminfo_params.update((key[6:], (False, int(val)))
192 for key, val in ui.configitems('color')
192 for key, val in ui.configitems('color')
193 if key.startswith('color.'))
193 if key.startswith('color.'))
194
194
195 try:
195 try:
196 curses.setupterm()
196 curses.setupterm()
197 except curses.error as e:
197 except curses.error as e:
198 _terminfo_params = {}
198 _terminfo_params = {}
199 return
199 return
200
200
201 for key, (b, e) in _terminfo_params.items():
201 for key, (b, e) in _terminfo_params.items():
202 if not b:
202 if not b:
203 continue
203 continue
204 if not curses.tigetstr(e):
204 if not curses.tigetstr(e):
205 # Most terminals don't support dim, invis, etc, so don't be
205 # Most terminals don't support dim, invis, etc, so don't be
206 # noisy and use ui.debug().
206 # noisy and use ui.debug().
207 ui.debug("no terminfo entry for %s\n" % e)
207 ui.debug("no terminfo entry for %s\n" % e)
208 del _terminfo_params[key]
208 del _terminfo_params[key]
209 if not curses.tigetstr('setaf') or not curses.tigetstr('setab'):
209 if not curses.tigetstr('setaf') or not curses.tigetstr('setab'):
210 # Only warn about missing terminfo entries if we explicitly asked for
210 # Only warn about missing terminfo entries if we explicitly asked for
211 # terminfo mode.
211 # terminfo mode.
212 if mode == "terminfo":
212 if mode == "terminfo":
213 ui.warn(_("no terminfo entry for setab/setaf: reverting to "
213 ui.warn(_("no terminfo entry for setab/setaf: reverting to "
214 "ECMA-48 color\n"))
214 "ECMA-48 color\n"))
215 _terminfo_params = {}
215 _terminfo_params = {}
216
216
217 def _modesetup(ui, coloropt):
217 def _modesetup(ui, coloropt):
218 global _terminfo_params
218 global _terminfo_params
219
219
220 if coloropt == 'debug':
220 if coloropt == 'debug':
221 return 'debug'
221 return 'debug'
222
222
223 auto = (coloropt == 'auto')
223 auto = (coloropt == 'auto')
224 always = not auto and util.parsebool(coloropt)
224 always = not auto and util.parsebool(coloropt)
225 if not always and not auto:
225 if not always and not auto:
226 return None
226 return None
227
227
228 formatted = always or (os.environ.get('TERM') != 'dumb' and ui.formatted())
228 formatted = always or (os.environ.get('TERM') != 'dumb' and ui.formatted())
229
229
230 mode = ui.config('color', 'mode', 'auto')
230 mode = ui.config('color', 'mode', 'auto')
231
231
232 # If pager is active, color.pagermode overrides color.mode.
232 # If pager is active, color.pagermode overrides color.mode.
233 if getattr(ui, 'pageractive', False):
233 if getattr(ui, 'pageractive', False):
234 mode = ui.config('color', 'pagermode', mode)
234 mode = ui.config('color', 'pagermode', mode)
235
235
236 realmode = mode
236 realmode = mode
237 if mode == 'auto':
237 if mode == 'auto':
238 if os.name == 'nt':
238 if os.name == 'nt':
239 term = os.environ.get('TERM')
239 term = os.environ.get('TERM')
240 # TERM won't be defined in a vanilla cmd.exe environment.
240 # TERM won't be defined in a vanilla cmd.exe environment.
241
241
242 # UNIX-like environments on Windows such as Cygwin and MSYS will
242 # UNIX-like environments on Windows such as Cygwin and MSYS will
243 # set TERM. They appear to make a best effort attempt at setting it
243 # set TERM. They appear to make a best effort attempt at setting it
244 # to something appropriate. However, not all environments with TERM
244 # to something appropriate. However, not all environments with TERM
245 # defined support ANSI. Since "ansi" could result in terminal
245 # defined support ANSI. Since "ansi" could result in terminal
246 # gibberish, we error on the side of selecting "win32". However, if
246 # gibberish, we error on the side of selecting "win32". However, if
247 # w32effects is not defined, we almost certainly don't support
247 # w32effects is not defined, we almost certainly don't support
248 # "win32", so don't even try.
248 # "win32", so don't even try.
249 if (term and 'xterm' in term) or not w32effects:
249 if (term and 'xterm' in term) or not w32effects:
250 realmode = 'ansi'
250 realmode = 'ansi'
251 else:
251 else:
252 realmode = 'win32'
252 realmode = 'win32'
253 else:
253 else:
254 realmode = 'ansi'
254 realmode = 'ansi'
255
255
256 def modewarn():
256 def modewarn():
257 # only warn if color.mode was explicitly set and we're in
257 # only warn if color.mode was explicitly set and we're in
258 # an interactive terminal
258 # an interactive terminal
259 if mode == realmode and ui.interactive():
259 if mode == realmode and ui.interactive():
260 ui.warn(_('warning: failed to set color mode to %s\n') % mode)
260 ui.warn(_('warning: failed to set color mode to %s\n') % mode)
261
261
262 if realmode == 'win32':
262 if realmode == 'win32':
263 _terminfo_params = {}
263 _terminfo_params = {}
264 if not w32effects:
264 if not w32effects:
265 modewarn()
265 modewarn()
266 return None
266 return None
267 _effects.update(w32effects)
267 _effects.update(w32effects)
268 elif realmode == 'ansi':
268 elif realmode == 'ansi':
269 _terminfo_params = {}
269 _terminfo_params = {}
270 elif realmode == 'terminfo':
270 elif realmode == 'terminfo':
271 _terminfosetup(ui, mode)
271 _terminfosetup(ui, mode)
272 if not _terminfo_params:
272 if not _terminfo_params:
273 ## FIXME Shouldn't we return None in this case too?
273 ## FIXME Shouldn't we return None in this case too?
274 modewarn()
274 modewarn()
275 realmode = 'ansi'
275 realmode = 'ansi'
276 else:
276 else:
277 return None
277 return None
278
278
279 if always or (auto and formatted):
279 if always or (auto and formatted):
280 return realmode
280 return realmode
281 return None
281 return None
282
282
283 try:
283 try:
284 import curses
284 import curses
285 # Mapping from effect name to terminfo attribute name or color number.
285 # Mapping from effect name to terminfo attribute name or color number.
286 # This will also force-load the curses module.
286 # This will also force-load the curses module.
287 _terminfo_params = {'none': (True, 'sgr0'),
287 _terminfo_params = {'none': (True, 'sgr0'),
288 'standout': (True, 'smso'),
288 'standout': (True, 'smso'),
289 'underline': (True, 'smul'),
289 'underline': (True, 'smul'),
290 'reverse': (True, 'rev'),
290 'reverse': (True, 'rev'),
291 'inverse': (True, 'rev'),
291 'inverse': (True, 'rev'),
292 'blink': (True, 'blink'),
292 'blink': (True, 'blink'),
293 'dim': (True, 'dim'),
293 'dim': (True, 'dim'),
294 'bold': (True, 'bold'),
294 'bold': (True, 'bold'),
295 'invisible': (True, 'invis'),
295 'invisible': (True, 'invis'),
296 'italic': (True, 'sitm'),
296 'italic': (True, 'sitm'),
297 'black': (False, curses.COLOR_BLACK),
297 'black': (False, curses.COLOR_BLACK),
298 'red': (False, curses.COLOR_RED),
298 'red': (False, curses.COLOR_RED),
299 'green': (False, curses.COLOR_GREEN),
299 'green': (False, curses.COLOR_GREEN),
300 'yellow': (False, curses.COLOR_YELLOW),
300 'yellow': (False, curses.COLOR_YELLOW),
301 'blue': (False, curses.COLOR_BLUE),
301 'blue': (False, curses.COLOR_BLUE),
302 'magenta': (False, curses.COLOR_MAGENTA),
302 'magenta': (False, curses.COLOR_MAGENTA),
303 'cyan': (False, curses.COLOR_CYAN),
303 'cyan': (False, curses.COLOR_CYAN),
304 'white': (False, curses.COLOR_WHITE)}
304 'white': (False, curses.COLOR_WHITE)}
305 except ImportError:
305 except ImportError:
306 _terminfo_params = {}
306 _terminfo_params = {}
307
307
308 _styles = {'grep.match': 'red bold',
308 _styles = {'grep.match': 'red bold',
309 'grep.linenumber': 'green',
309 'grep.linenumber': 'green',
310 'grep.rev': 'green',
310 'grep.rev': 'green',
311 'grep.change': 'green',
311 'grep.change': 'green',
312 'grep.sep': 'cyan',
312 'grep.sep': 'cyan',
313 'grep.filename': 'magenta',
313 'grep.filename': 'magenta',
314 'grep.user': 'magenta',
314 'grep.user': 'magenta',
315 'grep.date': 'magenta',
315 'grep.date': 'magenta',
316 'bookmarks.active': 'green',
316 'bookmarks.active': 'green',
317 'branches.active': 'none',
317 'branches.active': 'none',
318 'branches.closed': 'black bold',
318 'branches.closed': 'black bold',
319 'branches.current': 'green',
319 'branches.current': 'green',
320 'branches.inactive': 'none',
320 'branches.inactive': 'none',
321 'diff.changed': 'white',
321 'diff.changed': 'white',
322 'diff.deleted': 'red',
322 'diff.deleted': 'red',
323 'diff.diffline': 'bold',
323 'diff.diffline': 'bold',
324 'diff.extended': 'cyan bold',
324 'diff.extended': 'cyan bold',
325 'diff.file_a': 'red bold',
325 'diff.file_a': 'red bold',
326 'diff.file_b': 'green bold',
326 'diff.file_b': 'green bold',
327 'diff.hunk': 'magenta',
327 'diff.hunk': 'magenta',
328 'diff.inserted': 'green',
328 'diff.inserted': 'green',
329 'diff.tab': '',
329 'diff.tab': '',
330 'diff.trailingwhitespace': 'bold red_background',
330 'diff.trailingwhitespace': 'bold red_background',
331 'changeset.public' : '',
331 'changeset.public' : '',
332 'changeset.draft' : '',
332 'changeset.draft' : '',
333 'changeset.secret' : '',
333 'changeset.secret' : '',
334 'diffstat.deleted': 'red',
334 'diffstat.deleted': 'red',
335 'diffstat.inserted': 'green',
335 'diffstat.inserted': 'green',
336 'histedit.remaining': 'red bold',
336 'histedit.remaining': 'red bold',
337 'ui.prompt': 'yellow',
337 'ui.prompt': 'yellow',
338 'log.changeset': 'yellow',
338 'log.changeset': 'yellow',
339 'patchbomb.finalsummary': '',
339 'patchbomb.finalsummary': '',
340 'patchbomb.from': 'magenta',
340 'patchbomb.from': 'magenta',
341 'patchbomb.to': 'cyan',
341 'patchbomb.to': 'cyan',
342 'patchbomb.subject': 'green',
342 'patchbomb.subject': 'green',
343 'patchbomb.diffstats': '',
343 'patchbomb.diffstats': '',
344 'rebase.rebased': 'blue',
344 'rebase.rebased': 'blue',
345 'rebase.remaining': 'red bold',
345 'rebase.remaining': 'red bold',
346 'resolve.resolved': 'green bold',
346 'resolve.resolved': 'green bold',
347 'resolve.unresolved': 'red bold',
347 'resolve.unresolved': 'red bold',
348 'shelve.age': 'cyan',
348 'shelve.age': 'cyan',
349 'shelve.newest': 'green bold',
349 'shelve.newest': 'green bold',
350 'shelve.name': 'blue bold',
350 'shelve.name': 'blue bold',
351 'status.added': 'green bold',
351 'status.added': 'green bold',
352 'status.clean': 'none',
352 'status.clean': 'none',
353 'status.copied': 'none',
353 'status.copied': 'none',
354 'status.deleted': 'cyan bold underline',
354 'status.deleted': 'cyan bold underline',
355 'status.ignored': 'black bold',
355 'status.ignored': 'black bold',
356 'status.modified': 'blue bold',
356 'status.modified': 'blue bold',
357 'status.removed': 'red bold',
357 'status.removed': 'red bold',
358 'status.unknown': 'magenta bold underline',
358 'status.unknown': 'magenta bold underline',
359 'tags.normal': 'green',
359 'tags.normal': 'green',
360 'tags.local': 'black bold'}
360 'tags.local': 'black bold'}
361
361
362
362
363 def _effect_str(effect):
363 def _effect_str(effect):
364 '''Helper function for render_effects().'''
364 '''Helper function for render_effects().'''
365
365
366 bg = False
366 bg = False
367 if effect.endswith('_background'):
367 if effect.endswith('_background'):
368 bg = True
368 bg = True
369 effect = effect[:-11]
369 effect = effect[:-11]
370 attr, val = _terminfo_params[effect]
370 attr, val = _terminfo_params[effect]
371 if attr:
371 if attr:
372 return curses.tigetstr(val)
372 return curses.tigetstr(val)
373 elif bg:
373 elif bg:
374 return curses.tparm(curses.tigetstr('setab'), val)
374 return curses.tparm(curses.tigetstr('setab'), val)
375 else:
375 else:
376 return curses.tparm(curses.tigetstr('setaf'), val)
376 return curses.tparm(curses.tigetstr('setaf'), val)
377
377
378 def render_effects(text, effects):
378 def render_effects(text, effects):
379 'Wrap text in commands to turn on each effect.'
379 'Wrap text in commands to turn on each effect.'
380 if not text:
380 if not text:
381 return text
381 return text
382 if not _terminfo_params:
382 if not _terminfo_params:
383 start = [str(_effects[e]) for e in ['none'] + effects.split()]
383 start = [str(_effects[e]) for e in ['none'] + effects.split()]
384 start = '\033[' + ';'.join(start) + 'm'
384 start = '\033[' + ';'.join(start) + 'm'
385 stop = '\033[' + str(_effects['none']) + 'm'
385 stop = '\033[' + str(_effects['none']) + 'm'
386 else:
386 else:
387 start = ''.join(_effect_str(effect)
387 start = ''.join(_effect_str(effect)
388 for effect in ['none'] + effects.split())
388 for effect in ['none'] + effects.split())
389 stop = _effect_str('none')
389 stop = _effect_str('none')
390 return ''.join([start, text, stop])
390 return ''.join([start, text, stop])
391
391
392 def extstyles():
392 def extstyles():
393 for name, ext in extensions.extensions():
393 for name, ext in extensions.extensions():
394 _styles.update(getattr(ext, 'colortable', {}))
394 _styles.update(getattr(ext, 'colortable', {}))
395
395
396 def valideffect(effect):
396 def valideffect(effect):
397 'Determine if the effect is valid or not.'
397 'Determine if the effect is valid or not.'
398 good = False
398 good = False
399 if not _terminfo_params and effect in _effects:
399 if not _terminfo_params and effect in _effects:
400 good = True
400 good = True
401 elif effect in _terminfo_params or effect[:-11] in _terminfo_params:
401 elif effect in _terminfo_params or effect[:-11] in _terminfo_params:
402 good = True
402 good = True
403 return good
403 return good
404
404
405 def configstyles(ui):
405 def configstyles(ui):
406 for status, cfgeffects in ui.configitems('color'):
406 for status, cfgeffects in ui.configitems('color'):
407 if '.' not in status or status.startswith('color.'):
407 if '.' not in status or status.startswith('color.'):
408 continue
408 continue
409 cfgeffects = ui.configlist('color', status)
409 cfgeffects = ui.configlist('color', status)
410 if cfgeffects:
410 if cfgeffects:
411 good = []
411 good = []
412 for e in cfgeffects:
412 for e in cfgeffects:
413 if valideffect(e):
413 if valideffect(e):
414 good.append(e)
414 good.append(e)
415 else:
415 else:
416 ui.warn(_("ignoring unknown color/effect %r "
416 ui.warn(_("ignoring unknown color/effect %r "
417 "(configured in color.%s)\n")
417 "(configured in color.%s)\n")
418 % (e, status))
418 % (e, status))
419 _styles[status] = ' '.join(good)
419 _styles[status] = ' '.join(good)
420
420
421 class colorui(uimod.ui):
421 class colorui(uimod.ui):
422 def popbuffer(self, labeled=False):
422 def popbuffer(self):
423 if self._colormode is None:
423 if self._colormode is None:
424 return super(colorui, self).popbuffer(labeled)
424 return super(colorui, self).popbuffer()
425
425
426 self._bufferstates.pop()
426 self._bufferstates.pop()
427 return ''.join(self._buffers.pop())
427 return ''.join(self._buffers.pop())
428
428
429 _colormode = 'ansi'
429 _colormode = 'ansi'
430 def write(self, *args, **opts):
430 def write(self, *args, **opts):
431 if self._colormode is None:
431 if self._colormode is None:
432 return super(colorui, self).write(*args, **opts)
432 return super(colorui, self).write(*args, **opts)
433
433
434 label = opts.get('label', '')
434 label = opts.get('label', '')
435 if self._buffers:
435 if self._buffers:
436 if self._bufferapplylabels:
436 if self._bufferapplylabels:
437 self._buffers[-1].extend(self.label(str(a), label)
437 self._buffers[-1].extend(self.label(str(a), label)
438 for a in args)
438 for a in args)
439 else:
439 else:
440 self._buffers[-1].extend(str(a) for a in args)
440 self._buffers[-1].extend(str(a) for a in args)
441 elif self._colormode == 'win32':
441 elif self._colormode == 'win32':
442 for a in args:
442 for a in args:
443 win32print(a, super(colorui, self).write, **opts)
443 win32print(a, super(colorui, self).write, **opts)
444 else:
444 else:
445 return super(colorui, self).write(
445 return super(colorui, self).write(
446 *[self.label(str(a), label) for a in args], **opts)
446 *[self.label(str(a), label) for a in args], **opts)
447
447
448 def write_err(self, *args, **opts):
448 def write_err(self, *args, **opts):
449 if self._colormode is None:
449 if self._colormode is None:
450 return super(colorui, self).write_err(*args, **opts)
450 return super(colorui, self).write_err(*args, **opts)
451
451
452 label = opts.get('label', '')
452 label = opts.get('label', '')
453 if self._bufferstates and self._bufferstates[-1][0]:
453 if self._bufferstates and self._bufferstates[-1][0]:
454 return self.write(*args, **opts)
454 return self.write(*args, **opts)
455 if self._colormode == 'win32':
455 if self._colormode == 'win32':
456 for a in args:
456 for a in args:
457 win32print(a, super(colorui, self).write_err, **opts)
457 win32print(a, super(colorui, self).write_err, **opts)
458 else:
458 else:
459 return super(colorui, self).write_err(
459 return super(colorui, self).write_err(
460 *[self.label(str(a), label) for a in args], **opts)
460 *[self.label(str(a), label) for a in args], **opts)
461
461
462 def showlabel(self, msg, label):
462 def showlabel(self, msg, label):
463 if label and msg:
463 if label and msg:
464 if msg[-1] == '\n':
464 if msg[-1] == '\n':
465 return "[%s|%s]\n" % (label, msg[:-1])
465 return "[%s|%s]\n" % (label, msg[:-1])
466 else:
466 else:
467 return "[%s|%s]" % (label, msg)
467 return "[%s|%s]" % (label, msg)
468 else:
468 else:
469 return msg
469 return msg
470
470
471 def label(self, msg, label):
471 def label(self, msg, label):
472 if self._colormode is None:
472 if self._colormode is None:
473 return super(colorui, self).label(msg, label)
473 return super(colorui, self).label(msg, label)
474
474
475 if self._colormode == 'debug':
475 if self._colormode == 'debug':
476 return self.showlabel(msg, label)
476 return self.showlabel(msg, label)
477
477
478 effects = []
478 effects = []
479 for l in label.split():
479 for l in label.split():
480 s = _styles.get(l, '')
480 s = _styles.get(l, '')
481 if s:
481 if s:
482 effects.append(s)
482 effects.append(s)
483 elif valideffect(l):
483 elif valideffect(l):
484 effects.append(l)
484 effects.append(l)
485 effects = ' '.join(effects)
485 effects = ' '.join(effects)
486 if effects:
486 if effects:
487 return '\n'.join([render_effects(s, effects)
487 return '\n'.join([render_effects(s, effects)
488 for s in msg.split('\n')])
488 for s in msg.split('\n')])
489 return msg
489 return msg
490
490
491 def templatelabel(context, mapping, args):
491 def templatelabel(context, mapping, args):
492 if len(args) != 2:
492 if len(args) != 2:
493 # i18n: "label" is a keyword
493 # i18n: "label" is a keyword
494 raise error.ParseError(_("label expects two arguments"))
494 raise error.ParseError(_("label expects two arguments"))
495
495
496 # add known effects to the mapping so symbols like 'red', 'bold',
496 # add known effects to the mapping so symbols like 'red', 'bold',
497 # etc. don't need to be quoted
497 # etc. don't need to be quoted
498 mapping.update(dict([(k, k) for k in _effects]))
498 mapping.update(dict([(k, k) for k in _effects]))
499
499
500 thing = args[1][0](context, mapping, args[1][1])
500 thing = args[1][0](context, mapping, args[1][1])
501
501
502 # apparently, repo could be a string that is the favicon?
502 # apparently, repo could be a string that is the favicon?
503 repo = mapping.get('repo', '')
503 repo = mapping.get('repo', '')
504 if isinstance(repo, str):
504 if isinstance(repo, str):
505 return thing
505 return thing
506
506
507 label = args[0][0](context, mapping, args[0][1])
507 label = args[0][0](context, mapping, args[0][1])
508
508
509 thing = templater.stringify(thing)
509 thing = templater.stringify(thing)
510 label = templater.stringify(label)
510 label = templater.stringify(label)
511
511
512 return repo.ui.label(thing, label)
512 return repo.ui.label(thing, label)
513
513
514 def uisetup(ui):
514 def uisetup(ui):
515 if ui.plain():
515 if ui.plain():
516 return
516 return
517 if not isinstance(ui, colorui):
517 if not isinstance(ui, colorui):
518 colorui.__bases__ = (ui.__class__,)
518 colorui.__bases__ = (ui.__class__,)
519 ui.__class__ = colorui
519 ui.__class__ = colorui
520 def colorcmd(orig, ui_, opts, cmd, cmdfunc):
520 def colorcmd(orig, ui_, opts, cmd, cmdfunc):
521 mode = _modesetup(ui_, opts['color'])
521 mode = _modesetup(ui_, opts['color'])
522 colorui._colormode = mode
522 colorui._colormode = mode
523 if mode and mode != 'debug':
523 if mode and mode != 'debug':
524 extstyles()
524 extstyles()
525 configstyles(ui_)
525 configstyles(ui_)
526 return orig(ui_, opts, cmd, cmdfunc)
526 return orig(ui_, opts, cmd, cmdfunc)
527 def colorgit(orig, gitsub, commands, env=None, stream=False, cwd=None):
527 def colorgit(orig, gitsub, commands, env=None, stream=False, cwd=None):
528 if gitsub.ui._colormode and len(commands) and commands[0] == "diff":
528 if gitsub.ui._colormode and len(commands) and commands[0] == "diff":
529 # insert the argument in the front,
529 # insert the argument in the front,
530 # the end of git diff arguments is used for paths
530 # the end of git diff arguments is used for paths
531 commands.insert(1, '--color')
531 commands.insert(1, '--color')
532 return orig(gitsub, commands, env, stream, cwd)
532 return orig(gitsub, commands, env, stream, cwd)
533 extensions.wrapfunction(dispatch, '_runcommand', colorcmd)
533 extensions.wrapfunction(dispatch, '_runcommand', colorcmd)
534 extensions.wrapfunction(subrepo.gitsubrepo, '_gitnodir', colorgit)
534 extensions.wrapfunction(subrepo.gitsubrepo, '_gitnodir', colorgit)
535 templatelabel.__doc__ = templater.funcs['label'].__doc__
535 templatelabel.__doc__ = templater.funcs['label'].__doc__
536 templater.funcs['label'] = templatelabel
536 templater.funcs['label'] = templatelabel
537
537
538 def extsetup(ui):
538 def extsetup(ui):
539 commands.globalopts.append(
539 commands.globalopts.append(
540 ('', 'color', 'auto',
540 ('', 'color', 'auto',
541 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
541 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
542 # and should not be translated
542 # and should not be translated
543 _("when to colorize (boolean, always, auto, never, or debug)"),
543 _("when to colorize (boolean, always, auto, never, or debug)"),
544 _('TYPE')))
544 _('TYPE')))
545
545
546 @command('debugcolor', [], 'hg debugcolor')
546 @command('debugcolor', [], 'hg debugcolor')
547 def debugcolor(ui, repo, **opts):
547 def debugcolor(ui, repo, **opts):
548 global _styles
548 global _styles
549 _styles = {}
549 _styles = {}
550 for effect in _effects.keys():
550 for effect in _effects.keys():
551 _styles[effect] = effect
551 _styles[effect] = effect
552 ui.write(('color mode: %s\n') % ui._colormode)
552 ui.write(('color mode: %s\n') % ui._colormode)
553 ui.write(_('available colors:\n'))
553 ui.write(_('available colors:\n'))
554 for label, colors in _styles.items():
554 for label, colors in _styles.items():
555 ui.write(('%s\n') % colors, label=label)
555 ui.write(('%s\n') % colors, label=label)
556
556
557 if os.name != 'nt':
557 if os.name != 'nt':
558 w32effects = None
558 w32effects = None
559 else:
559 else:
560 import re, ctypes
560 import re, ctypes
561
561
562 _kernel32 = ctypes.windll.kernel32
562 _kernel32 = ctypes.windll.kernel32
563
563
564 _WORD = ctypes.c_ushort
564 _WORD = ctypes.c_ushort
565
565
566 _INVALID_HANDLE_VALUE = -1
566 _INVALID_HANDLE_VALUE = -1
567
567
568 class _COORD(ctypes.Structure):
568 class _COORD(ctypes.Structure):
569 _fields_ = [('X', ctypes.c_short),
569 _fields_ = [('X', ctypes.c_short),
570 ('Y', ctypes.c_short)]
570 ('Y', ctypes.c_short)]
571
571
572 class _SMALL_RECT(ctypes.Structure):
572 class _SMALL_RECT(ctypes.Structure):
573 _fields_ = [('Left', ctypes.c_short),
573 _fields_ = [('Left', ctypes.c_short),
574 ('Top', ctypes.c_short),
574 ('Top', ctypes.c_short),
575 ('Right', ctypes.c_short),
575 ('Right', ctypes.c_short),
576 ('Bottom', ctypes.c_short)]
576 ('Bottom', ctypes.c_short)]
577
577
578 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
578 class _CONSOLE_SCREEN_BUFFER_INFO(ctypes.Structure):
579 _fields_ = [('dwSize', _COORD),
579 _fields_ = [('dwSize', _COORD),
580 ('dwCursorPosition', _COORD),
580 ('dwCursorPosition', _COORD),
581 ('wAttributes', _WORD),
581 ('wAttributes', _WORD),
582 ('srWindow', _SMALL_RECT),
582 ('srWindow', _SMALL_RECT),
583 ('dwMaximumWindowSize', _COORD)]
583 ('dwMaximumWindowSize', _COORD)]
584
584
585 _STD_OUTPUT_HANDLE = 0xfffffff5L # (DWORD)-11
585 _STD_OUTPUT_HANDLE = 0xfffffff5L # (DWORD)-11
586 _STD_ERROR_HANDLE = 0xfffffff4L # (DWORD)-12
586 _STD_ERROR_HANDLE = 0xfffffff4L # (DWORD)-12
587
587
588 _FOREGROUND_BLUE = 0x0001
588 _FOREGROUND_BLUE = 0x0001
589 _FOREGROUND_GREEN = 0x0002
589 _FOREGROUND_GREEN = 0x0002
590 _FOREGROUND_RED = 0x0004
590 _FOREGROUND_RED = 0x0004
591 _FOREGROUND_INTENSITY = 0x0008
591 _FOREGROUND_INTENSITY = 0x0008
592
592
593 _BACKGROUND_BLUE = 0x0010
593 _BACKGROUND_BLUE = 0x0010
594 _BACKGROUND_GREEN = 0x0020
594 _BACKGROUND_GREEN = 0x0020
595 _BACKGROUND_RED = 0x0040
595 _BACKGROUND_RED = 0x0040
596 _BACKGROUND_INTENSITY = 0x0080
596 _BACKGROUND_INTENSITY = 0x0080
597
597
598 _COMMON_LVB_REVERSE_VIDEO = 0x4000
598 _COMMON_LVB_REVERSE_VIDEO = 0x4000
599 _COMMON_LVB_UNDERSCORE = 0x8000
599 _COMMON_LVB_UNDERSCORE = 0x8000
600
600
601 # http://msdn.microsoft.com/en-us/library/ms682088%28VS.85%29.aspx
601 # http://msdn.microsoft.com/en-us/library/ms682088%28VS.85%29.aspx
602 w32effects = {
602 w32effects = {
603 'none': -1,
603 'none': -1,
604 'black': 0,
604 'black': 0,
605 'red': _FOREGROUND_RED,
605 'red': _FOREGROUND_RED,
606 'green': _FOREGROUND_GREEN,
606 'green': _FOREGROUND_GREEN,
607 'yellow': _FOREGROUND_RED | _FOREGROUND_GREEN,
607 'yellow': _FOREGROUND_RED | _FOREGROUND_GREEN,
608 'blue': _FOREGROUND_BLUE,
608 'blue': _FOREGROUND_BLUE,
609 'magenta': _FOREGROUND_BLUE | _FOREGROUND_RED,
609 'magenta': _FOREGROUND_BLUE | _FOREGROUND_RED,
610 'cyan': _FOREGROUND_BLUE | _FOREGROUND_GREEN,
610 'cyan': _FOREGROUND_BLUE | _FOREGROUND_GREEN,
611 'white': _FOREGROUND_RED | _FOREGROUND_GREEN | _FOREGROUND_BLUE,
611 'white': _FOREGROUND_RED | _FOREGROUND_GREEN | _FOREGROUND_BLUE,
612 'bold': _FOREGROUND_INTENSITY,
612 'bold': _FOREGROUND_INTENSITY,
613 'black_background': 0x100, # unused value > 0x0f
613 'black_background': 0x100, # unused value > 0x0f
614 'red_background': _BACKGROUND_RED,
614 'red_background': _BACKGROUND_RED,
615 'green_background': _BACKGROUND_GREEN,
615 'green_background': _BACKGROUND_GREEN,
616 'yellow_background': _BACKGROUND_RED | _BACKGROUND_GREEN,
616 'yellow_background': _BACKGROUND_RED | _BACKGROUND_GREEN,
617 'blue_background': _BACKGROUND_BLUE,
617 'blue_background': _BACKGROUND_BLUE,
618 'purple_background': _BACKGROUND_BLUE | _BACKGROUND_RED,
618 'purple_background': _BACKGROUND_BLUE | _BACKGROUND_RED,
619 'cyan_background': _BACKGROUND_BLUE | _BACKGROUND_GREEN,
619 'cyan_background': _BACKGROUND_BLUE | _BACKGROUND_GREEN,
620 'white_background': (_BACKGROUND_RED | _BACKGROUND_GREEN |
620 'white_background': (_BACKGROUND_RED | _BACKGROUND_GREEN |
621 _BACKGROUND_BLUE),
621 _BACKGROUND_BLUE),
622 'bold_background': _BACKGROUND_INTENSITY,
622 'bold_background': _BACKGROUND_INTENSITY,
623 'underline': _COMMON_LVB_UNDERSCORE, # double-byte charsets only
623 'underline': _COMMON_LVB_UNDERSCORE, # double-byte charsets only
624 'inverse': _COMMON_LVB_REVERSE_VIDEO, # double-byte charsets only
624 'inverse': _COMMON_LVB_REVERSE_VIDEO, # double-byte charsets only
625 }
625 }
626
626
627 passthrough = set([_FOREGROUND_INTENSITY,
627 passthrough = set([_FOREGROUND_INTENSITY,
628 _BACKGROUND_INTENSITY,
628 _BACKGROUND_INTENSITY,
629 _COMMON_LVB_UNDERSCORE,
629 _COMMON_LVB_UNDERSCORE,
630 _COMMON_LVB_REVERSE_VIDEO])
630 _COMMON_LVB_REVERSE_VIDEO])
631
631
632 stdout = _kernel32.GetStdHandle(
632 stdout = _kernel32.GetStdHandle(
633 _STD_OUTPUT_HANDLE) # don't close the handle returned
633 _STD_OUTPUT_HANDLE) # don't close the handle returned
634 if stdout is None or stdout == _INVALID_HANDLE_VALUE:
634 if stdout is None or stdout == _INVALID_HANDLE_VALUE:
635 w32effects = None
635 w32effects = None
636 else:
636 else:
637 csbi = _CONSOLE_SCREEN_BUFFER_INFO()
637 csbi = _CONSOLE_SCREEN_BUFFER_INFO()
638 if not _kernel32.GetConsoleScreenBufferInfo(
638 if not _kernel32.GetConsoleScreenBufferInfo(
639 stdout, ctypes.byref(csbi)):
639 stdout, ctypes.byref(csbi)):
640 # stdout may not support GetConsoleScreenBufferInfo()
640 # stdout may not support GetConsoleScreenBufferInfo()
641 # when called from subprocess or redirected
641 # when called from subprocess or redirected
642 w32effects = None
642 w32effects = None
643 else:
643 else:
644 origattr = csbi.wAttributes
644 origattr = csbi.wAttributes
645 ansire = re.compile('\033\[([^m]*)m([^\033]*)(.*)',
645 ansire = re.compile('\033\[([^m]*)m([^\033]*)(.*)',
646 re.MULTILINE | re.DOTALL)
646 re.MULTILINE | re.DOTALL)
647
647
648 def win32print(text, orig, **opts):
648 def win32print(text, orig, **opts):
649 label = opts.get('label', '')
649 label = opts.get('label', '')
650 attr = origattr
650 attr = origattr
651
651
652 def mapcolor(val, attr):
652 def mapcolor(val, attr):
653 if val == -1:
653 if val == -1:
654 return origattr
654 return origattr
655 elif val in passthrough:
655 elif val in passthrough:
656 return attr | val
656 return attr | val
657 elif val > 0x0f:
657 elif val > 0x0f:
658 return (val & 0x70) | (attr & 0x8f)
658 return (val & 0x70) | (attr & 0x8f)
659 else:
659 else:
660 return (val & 0x07) | (attr & 0xf8)
660 return (val & 0x07) | (attr & 0xf8)
661
661
662 # determine console attributes based on labels
662 # determine console attributes based on labels
663 for l in label.split():
663 for l in label.split():
664 style = _styles.get(l, '')
664 style = _styles.get(l, '')
665 for effect in style.split():
665 for effect in style.split():
666 try:
666 try:
667 attr = mapcolor(w32effects[effect], attr)
667 attr = mapcolor(w32effects[effect], attr)
668 except KeyError:
668 except KeyError:
669 # w32effects could not have certain attributes so we skip
669 # w32effects could not have certain attributes so we skip
670 # them if not found
670 # them if not found
671 pass
671 pass
672 # hack to ensure regexp finds data
672 # hack to ensure regexp finds data
673 if not text.startswith('\033['):
673 if not text.startswith('\033['):
674 text = '\033[m' + text
674 text = '\033[m' + text
675
675
676 # Look for ANSI-like codes embedded in text
676 # Look for ANSI-like codes embedded in text
677 m = re.match(ansire, text)
677 m = re.match(ansire, text)
678
678
679 try:
679 try:
680 while m:
680 while m:
681 for sattr in m.group(1).split(';'):
681 for sattr in m.group(1).split(';'):
682 if sattr:
682 if sattr:
683 attr = mapcolor(int(sattr), attr)
683 attr = mapcolor(int(sattr), attr)
684 _kernel32.SetConsoleTextAttribute(stdout, attr)
684 _kernel32.SetConsoleTextAttribute(stdout, attr)
685 orig(m.group(2), **opts)
685 orig(m.group(2), **opts)
686 m = re.match(ansire, m.group(3))
686 m = re.match(ansire, m.group(3))
687 finally:
687 finally:
688 # Explicitly reset original attributes
688 # Explicitly reset original attributes
689 _kernel32.SetConsoleTextAttribute(stdout, origattr)
689 _kernel32.SetConsoleTextAttribute(stdout, origattr)
@@ -1,3403 +1,3403 b''
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import os, sys, errno, re, tempfile, cStringIO, shutil
10 import os, sys, errno, re, tempfile, cStringIO, shutil
11 import util, scmutil, templater, patch, error, templatekw, revlog, copies
11 import util, scmutil, templater, patch, error, templatekw, revlog, copies
12 import match as matchmod
12 import match as matchmod
13 import repair, graphmod, revset, phases, obsolete, pathutil
13 import repair, graphmod, revset, phases, obsolete, pathutil
14 import changelog
14 import changelog
15 import bookmarks
15 import bookmarks
16 import encoding
16 import encoding
17 import formatter
17 import formatter
18 import crecord as crecordmod
18 import crecord as crecordmod
19 import lock as lockmod
19 import lock as lockmod
20
20
21 def ishunk(x):
21 def ishunk(x):
22 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
22 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
23 return isinstance(x, hunkclasses)
23 return isinstance(x, hunkclasses)
24
24
25 def newandmodified(chunks, originalchunks):
25 def newandmodified(chunks, originalchunks):
26 newlyaddedandmodifiedfiles = set()
26 newlyaddedandmodifiedfiles = set()
27 for chunk in chunks:
27 for chunk in chunks:
28 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
28 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
29 originalchunks:
29 originalchunks:
30 newlyaddedandmodifiedfiles.add(chunk.header.filename())
30 newlyaddedandmodifiedfiles.add(chunk.header.filename())
31 return newlyaddedandmodifiedfiles
31 return newlyaddedandmodifiedfiles
32
32
33 def parsealiases(cmd):
33 def parsealiases(cmd):
34 return cmd.lstrip("^").split("|")
34 return cmd.lstrip("^").split("|")
35
35
36 def setupwrapcolorwrite(ui):
36 def setupwrapcolorwrite(ui):
37 # wrap ui.write so diff output can be labeled/colorized
37 # wrap ui.write so diff output can be labeled/colorized
38 def wrapwrite(orig, *args, **kw):
38 def wrapwrite(orig, *args, **kw):
39 label = kw.pop('label', '')
39 label = kw.pop('label', '')
40 for chunk, l in patch.difflabel(lambda: args):
40 for chunk, l in patch.difflabel(lambda: args):
41 orig(chunk, label=label + l)
41 orig(chunk, label=label + l)
42
42
43 oldwrite = ui.write
43 oldwrite = ui.write
44 def wrap(*args, **kwargs):
44 def wrap(*args, **kwargs):
45 return wrapwrite(oldwrite, *args, **kwargs)
45 return wrapwrite(oldwrite, *args, **kwargs)
46 setattr(ui, 'write', wrap)
46 setattr(ui, 'write', wrap)
47 return oldwrite
47 return oldwrite
48
48
49 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
49 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
50 if usecurses:
50 if usecurses:
51 if testfile:
51 if testfile:
52 recordfn = crecordmod.testdecorator(testfile,
52 recordfn = crecordmod.testdecorator(testfile,
53 crecordmod.testchunkselector)
53 crecordmod.testchunkselector)
54 else:
54 else:
55 recordfn = crecordmod.chunkselector
55 recordfn = crecordmod.chunkselector
56
56
57 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
57 return crecordmod.filterpatch(ui, originalhunks, recordfn, operation)
58
58
59 else:
59 else:
60 return patch.filterpatch(ui, originalhunks, operation)
60 return patch.filterpatch(ui, originalhunks, operation)
61
61
62 def recordfilter(ui, originalhunks, operation=None):
62 def recordfilter(ui, originalhunks, operation=None):
63 """ Prompts the user to filter the originalhunks and return a list of
63 """ Prompts the user to filter the originalhunks and return a list of
64 selected hunks.
64 selected hunks.
65 *operation* is used for ui purposes to indicate the user
65 *operation* is used for ui purposes to indicate the user
66 what kind of filtering they are doing: reverting, committing, shelving, etc.
66 what kind of filtering they are doing: reverting, committing, shelving, etc.
67 *operation* has to be a translated string.
67 *operation* has to be a translated string.
68 """
68 """
69 usecurses = ui.configbool('experimental', 'crecord', False)
69 usecurses = ui.configbool('experimental', 'crecord', False)
70 testfile = ui.config('experimental', 'crecordtest', None)
70 testfile = ui.config('experimental', 'crecordtest', None)
71 oldwrite = setupwrapcolorwrite(ui)
71 oldwrite = setupwrapcolorwrite(ui)
72 try:
72 try:
73 newchunks = filterchunks(ui, originalhunks, usecurses, testfile,
73 newchunks = filterchunks(ui, originalhunks, usecurses, testfile,
74 operation)
74 operation)
75 finally:
75 finally:
76 ui.write = oldwrite
76 ui.write = oldwrite
77 return newchunks
77 return newchunks
78
78
79 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
79 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
80 filterfn, *pats, **opts):
80 filterfn, *pats, **opts):
81 import merge as mergemod
81 import merge as mergemod
82
82
83 if not ui.interactive():
83 if not ui.interactive():
84 if cmdsuggest:
84 if cmdsuggest:
85 msg = _('running non-interactively, use %s instead') % cmdsuggest
85 msg = _('running non-interactively, use %s instead') % cmdsuggest
86 else:
86 else:
87 msg = _('running non-interactively')
87 msg = _('running non-interactively')
88 raise error.Abort(msg)
88 raise error.Abort(msg)
89
89
90 # make sure username is set before going interactive
90 # make sure username is set before going interactive
91 if not opts.get('user'):
91 if not opts.get('user'):
92 ui.username() # raise exception, username not provided
92 ui.username() # raise exception, username not provided
93
93
94 def recordfunc(ui, repo, message, match, opts):
94 def recordfunc(ui, repo, message, match, opts):
95 """This is generic record driver.
95 """This is generic record driver.
96
96
97 Its job is to interactively filter local changes, and
97 Its job is to interactively filter local changes, and
98 accordingly prepare working directory into a state in which the
98 accordingly prepare working directory into a state in which the
99 job can be delegated to a non-interactive commit command such as
99 job can be delegated to a non-interactive commit command such as
100 'commit' or 'qrefresh'.
100 'commit' or 'qrefresh'.
101
101
102 After the actual job is done by non-interactive command, the
102 After the actual job is done by non-interactive command, the
103 working directory is restored to its original state.
103 working directory is restored to its original state.
104
104
105 In the end we'll record interesting changes, and everything else
105 In the end we'll record interesting changes, and everything else
106 will be left in place, so the user can continue working.
106 will be left in place, so the user can continue working.
107 """
107 """
108
108
109 checkunfinished(repo, commit=True)
109 checkunfinished(repo, commit=True)
110 merge = len(repo[None].parents()) > 1
110 merge = len(repo[None].parents()) > 1
111 if merge:
111 if merge:
112 raise error.Abort(_('cannot partially commit a merge '
112 raise error.Abort(_('cannot partially commit a merge '
113 '(use "hg commit" instead)'))
113 '(use "hg commit" instead)'))
114
114
115 status = repo.status(match=match)
115 status = repo.status(match=match)
116 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
116 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True)
117 diffopts.nodates = True
117 diffopts.nodates = True
118 diffopts.git = True
118 diffopts.git = True
119 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
119 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
120 originalchunks = patch.parsepatch(originaldiff)
120 originalchunks = patch.parsepatch(originaldiff)
121
121
122 # 1. filter patch, so we have intending-to apply subset of it
122 # 1. filter patch, so we have intending-to apply subset of it
123 try:
123 try:
124 chunks = filterfn(ui, originalchunks)
124 chunks = filterfn(ui, originalchunks)
125 except patch.PatchError as err:
125 except patch.PatchError as err:
126 raise error.Abort(_('error parsing patch: %s') % err)
126 raise error.Abort(_('error parsing patch: %s') % err)
127
127
128 # We need to keep a backup of files that have been newly added and
128 # We need to keep a backup of files that have been newly added and
129 # modified during the recording process because there is a previous
129 # modified during the recording process because there is a previous
130 # version without the edit in the workdir
130 # version without the edit in the workdir
131 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
131 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
132 contenders = set()
132 contenders = set()
133 for h in chunks:
133 for h in chunks:
134 try:
134 try:
135 contenders.update(set(h.files()))
135 contenders.update(set(h.files()))
136 except AttributeError:
136 except AttributeError:
137 pass
137 pass
138
138
139 changed = status.modified + status.added + status.removed
139 changed = status.modified + status.added + status.removed
140 newfiles = [f for f in changed if f in contenders]
140 newfiles = [f for f in changed if f in contenders]
141 if not newfiles:
141 if not newfiles:
142 ui.status(_('no changes to record\n'))
142 ui.status(_('no changes to record\n'))
143 return 0
143 return 0
144
144
145 modified = set(status.modified)
145 modified = set(status.modified)
146
146
147 # 2. backup changed files, so we can restore them in the end
147 # 2. backup changed files, so we can restore them in the end
148
148
149 if backupall:
149 if backupall:
150 tobackup = changed
150 tobackup = changed
151 else:
151 else:
152 tobackup = [f for f in newfiles if f in modified or f in \
152 tobackup = [f for f in newfiles if f in modified or f in \
153 newlyaddedandmodifiedfiles]
153 newlyaddedandmodifiedfiles]
154 backups = {}
154 backups = {}
155 if tobackup:
155 if tobackup:
156 backupdir = repo.join('record-backups')
156 backupdir = repo.join('record-backups')
157 try:
157 try:
158 os.mkdir(backupdir)
158 os.mkdir(backupdir)
159 except OSError as err:
159 except OSError as err:
160 if err.errno != errno.EEXIST:
160 if err.errno != errno.EEXIST:
161 raise
161 raise
162 try:
162 try:
163 # backup continues
163 # backup continues
164 for f in tobackup:
164 for f in tobackup:
165 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
165 fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
166 dir=backupdir)
166 dir=backupdir)
167 os.close(fd)
167 os.close(fd)
168 ui.debug('backup %r as %r\n' % (f, tmpname))
168 ui.debug('backup %r as %r\n' % (f, tmpname))
169 util.copyfile(repo.wjoin(f), tmpname)
169 util.copyfile(repo.wjoin(f), tmpname)
170 shutil.copystat(repo.wjoin(f), tmpname)
170 shutil.copystat(repo.wjoin(f), tmpname)
171 backups[f] = tmpname
171 backups[f] = tmpname
172
172
173 fp = cStringIO.StringIO()
173 fp = cStringIO.StringIO()
174 for c in chunks:
174 for c in chunks:
175 fname = c.filename()
175 fname = c.filename()
176 if fname in backups:
176 if fname in backups:
177 c.write(fp)
177 c.write(fp)
178 dopatch = fp.tell()
178 dopatch = fp.tell()
179 fp.seek(0)
179 fp.seek(0)
180
180
181 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
181 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
182 # 3a. apply filtered patch to clean repo (clean)
182 # 3a. apply filtered patch to clean repo (clean)
183 if backups:
183 if backups:
184 # Equivalent to hg.revert
184 # Equivalent to hg.revert
185 choices = lambda key: key in backups
185 choices = lambda key: key in backups
186 mergemod.update(repo, repo.dirstate.p1(),
186 mergemod.update(repo, repo.dirstate.p1(),
187 False, True, choices)
187 False, True, choices)
188
188
189 # 3b. (apply)
189 # 3b. (apply)
190 if dopatch:
190 if dopatch:
191 try:
191 try:
192 ui.debug('applying patch\n')
192 ui.debug('applying patch\n')
193 ui.debug(fp.getvalue())
193 ui.debug(fp.getvalue())
194 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
194 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
195 except patch.PatchError as err:
195 except patch.PatchError as err:
196 raise error.Abort(str(err))
196 raise error.Abort(str(err))
197 del fp
197 del fp
198
198
199 # 4. We prepared working directory according to filtered
199 # 4. We prepared working directory according to filtered
200 # patch. Now is the time to delegate the job to
200 # patch. Now is the time to delegate the job to
201 # commit/qrefresh or the like!
201 # commit/qrefresh or the like!
202
202
203 # Make all of the pathnames absolute.
203 # Make all of the pathnames absolute.
204 newfiles = [repo.wjoin(nf) for nf in newfiles]
204 newfiles = [repo.wjoin(nf) for nf in newfiles]
205 return commitfunc(ui, repo, *newfiles, **opts)
205 return commitfunc(ui, repo, *newfiles, **opts)
206 finally:
206 finally:
207 # 5. finally restore backed-up files
207 # 5. finally restore backed-up files
208 try:
208 try:
209 dirstate = repo.dirstate
209 dirstate = repo.dirstate
210 for realname, tmpname in backups.iteritems():
210 for realname, tmpname in backups.iteritems():
211 ui.debug('restoring %r to %r\n' % (tmpname, realname))
211 ui.debug('restoring %r to %r\n' % (tmpname, realname))
212
212
213 if dirstate[realname] == 'n':
213 if dirstate[realname] == 'n':
214 # without normallookup, restoring timestamp
214 # without normallookup, restoring timestamp
215 # may cause partially committed files
215 # may cause partially committed files
216 # to be treated as unmodified
216 # to be treated as unmodified
217 dirstate.normallookup(realname)
217 dirstate.normallookup(realname)
218
218
219 util.copyfile(tmpname, repo.wjoin(realname))
219 util.copyfile(tmpname, repo.wjoin(realname))
220 # Our calls to copystat() here and above are a
220 # Our calls to copystat() here and above are a
221 # hack to trick any editors that have f open that
221 # hack to trick any editors that have f open that
222 # we haven't modified them.
222 # we haven't modified them.
223 #
223 #
224 # Also note that this racy as an editor could
224 # Also note that this racy as an editor could
225 # notice the file's mtime before we've finished
225 # notice the file's mtime before we've finished
226 # writing it.
226 # writing it.
227 shutil.copystat(tmpname, repo.wjoin(realname))
227 shutil.copystat(tmpname, repo.wjoin(realname))
228 os.unlink(tmpname)
228 os.unlink(tmpname)
229 if tobackup:
229 if tobackup:
230 os.rmdir(backupdir)
230 os.rmdir(backupdir)
231 except OSError:
231 except OSError:
232 pass
232 pass
233
233
234 def recordinwlock(ui, repo, message, match, opts):
234 def recordinwlock(ui, repo, message, match, opts):
235 wlock = repo.wlock()
235 wlock = repo.wlock()
236 try:
236 try:
237 return recordfunc(ui, repo, message, match, opts)
237 return recordfunc(ui, repo, message, match, opts)
238 finally:
238 finally:
239 wlock.release()
239 wlock.release()
240
240
241 return commit(ui, repo, recordinwlock, pats, opts)
241 return commit(ui, repo, recordinwlock, pats, opts)
242
242
243 def findpossible(cmd, table, strict=False):
243 def findpossible(cmd, table, strict=False):
244 """
244 """
245 Return cmd -> (aliases, command table entry)
245 Return cmd -> (aliases, command table entry)
246 for each matching command.
246 for each matching command.
247 Return debug commands (or their aliases) only if no normal command matches.
247 Return debug commands (or their aliases) only if no normal command matches.
248 """
248 """
249 choice = {}
249 choice = {}
250 debugchoice = {}
250 debugchoice = {}
251
251
252 if cmd in table:
252 if cmd in table:
253 # short-circuit exact matches, "log" alias beats "^log|history"
253 # short-circuit exact matches, "log" alias beats "^log|history"
254 keys = [cmd]
254 keys = [cmd]
255 else:
255 else:
256 keys = table.keys()
256 keys = table.keys()
257
257
258 allcmds = []
258 allcmds = []
259 for e in keys:
259 for e in keys:
260 aliases = parsealiases(e)
260 aliases = parsealiases(e)
261 allcmds.extend(aliases)
261 allcmds.extend(aliases)
262 found = None
262 found = None
263 if cmd in aliases:
263 if cmd in aliases:
264 found = cmd
264 found = cmd
265 elif not strict:
265 elif not strict:
266 for a in aliases:
266 for a in aliases:
267 if a.startswith(cmd):
267 if a.startswith(cmd):
268 found = a
268 found = a
269 break
269 break
270 if found is not None:
270 if found is not None:
271 if aliases[0].startswith("debug") or found.startswith("debug"):
271 if aliases[0].startswith("debug") or found.startswith("debug"):
272 debugchoice[found] = (aliases, table[e])
272 debugchoice[found] = (aliases, table[e])
273 else:
273 else:
274 choice[found] = (aliases, table[e])
274 choice[found] = (aliases, table[e])
275
275
276 if not choice and debugchoice:
276 if not choice and debugchoice:
277 choice = debugchoice
277 choice = debugchoice
278
278
279 return choice, allcmds
279 return choice, allcmds
280
280
281 def findcmd(cmd, table, strict=True):
281 def findcmd(cmd, table, strict=True):
282 """Return (aliases, command table entry) for command string."""
282 """Return (aliases, command table entry) for command string."""
283 choice, allcmds = findpossible(cmd, table, strict)
283 choice, allcmds = findpossible(cmd, table, strict)
284
284
285 if cmd in choice:
285 if cmd in choice:
286 return choice[cmd]
286 return choice[cmd]
287
287
288 if len(choice) > 1:
288 if len(choice) > 1:
289 clist = choice.keys()
289 clist = choice.keys()
290 clist.sort()
290 clist.sort()
291 raise error.AmbiguousCommand(cmd, clist)
291 raise error.AmbiguousCommand(cmd, clist)
292
292
293 if choice:
293 if choice:
294 return choice.values()[0]
294 return choice.values()[0]
295
295
296 raise error.UnknownCommand(cmd, allcmds)
296 raise error.UnknownCommand(cmd, allcmds)
297
297
298 def findrepo(p):
298 def findrepo(p):
299 while not os.path.isdir(os.path.join(p, ".hg")):
299 while not os.path.isdir(os.path.join(p, ".hg")):
300 oldp, p = p, os.path.dirname(p)
300 oldp, p = p, os.path.dirname(p)
301 if p == oldp:
301 if p == oldp:
302 return None
302 return None
303
303
304 return p
304 return p
305
305
306 def bailifchanged(repo, merge=True):
306 def bailifchanged(repo, merge=True):
307 if merge and repo.dirstate.p2() != nullid:
307 if merge and repo.dirstate.p2() != nullid:
308 raise error.Abort(_('outstanding uncommitted merge'))
308 raise error.Abort(_('outstanding uncommitted merge'))
309 modified, added, removed, deleted = repo.status()[:4]
309 modified, added, removed, deleted = repo.status()[:4]
310 if modified or added or removed or deleted:
310 if modified or added or removed or deleted:
311 raise error.Abort(_('uncommitted changes'))
311 raise error.Abort(_('uncommitted changes'))
312 ctx = repo[None]
312 ctx = repo[None]
313 for s in sorted(ctx.substate):
313 for s in sorted(ctx.substate):
314 ctx.sub(s).bailifchanged()
314 ctx.sub(s).bailifchanged()
315
315
316 def logmessage(ui, opts):
316 def logmessage(ui, opts):
317 """ get the log message according to -m and -l option """
317 """ get the log message according to -m and -l option """
318 message = opts.get('message')
318 message = opts.get('message')
319 logfile = opts.get('logfile')
319 logfile = opts.get('logfile')
320
320
321 if message and logfile:
321 if message and logfile:
322 raise error.Abort(_('options --message and --logfile are mutually '
322 raise error.Abort(_('options --message and --logfile are mutually '
323 'exclusive'))
323 'exclusive'))
324 if not message and logfile:
324 if not message and logfile:
325 try:
325 try:
326 if logfile == '-':
326 if logfile == '-':
327 message = ui.fin.read()
327 message = ui.fin.read()
328 else:
328 else:
329 message = '\n'.join(util.readfile(logfile).splitlines())
329 message = '\n'.join(util.readfile(logfile).splitlines())
330 except IOError as inst:
330 except IOError as inst:
331 raise error.Abort(_("can't read commit message '%s': %s") %
331 raise error.Abort(_("can't read commit message '%s': %s") %
332 (logfile, inst.strerror))
332 (logfile, inst.strerror))
333 return message
333 return message
334
334
335 def mergeeditform(ctxorbool, baseformname):
335 def mergeeditform(ctxorbool, baseformname):
336 """return appropriate editform name (referencing a committemplate)
336 """return appropriate editform name (referencing a committemplate)
337
337
338 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
338 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
339 merging is committed.
339 merging is committed.
340
340
341 This returns baseformname with '.merge' appended if it is a merge,
341 This returns baseformname with '.merge' appended if it is a merge,
342 otherwise '.normal' is appended.
342 otherwise '.normal' is appended.
343 """
343 """
344 if isinstance(ctxorbool, bool):
344 if isinstance(ctxorbool, bool):
345 if ctxorbool:
345 if ctxorbool:
346 return baseformname + ".merge"
346 return baseformname + ".merge"
347 elif 1 < len(ctxorbool.parents()):
347 elif 1 < len(ctxorbool.parents()):
348 return baseformname + ".merge"
348 return baseformname + ".merge"
349
349
350 return baseformname + ".normal"
350 return baseformname + ".normal"
351
351
352 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
352 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
353 editform='', **opts):
353 editform='', **opts):
354 """get appropriate commit message editor according to '--edit' option
354 """get appropriate commit message editor according to '--edit' option
355
355
356 'finishdesc' is a function to be called with edited commit message
356 'finishdesc' is a function to be called with edited commit message
357 (= 'description' of the new changeset) just after editing, but
357 (= 'description' of the new changeset) just after editing, but
358 before checking empty-ness. It should return actual text to be
358 before checking empty-ness. It should return actual text to be
359 stored into history. This allows to change description before
359 stored into history. This allows to change description before
360 storing.
360 storing.
361
361
362 'extramsg' is a extra message to be shown in the editor instead of
362 'extramsg' is a extra message to be shown in the editor instead of
363 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
363 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
364 is automatically added.
364 is automatically added.
365
365
366 'editform' is a dot-separated list of names, to distinguish
366 'editform' is a dot-separated list of names, to distinguish
367 the purpose of commit text editing.
367 the purpose of commit text editing.
368
368
369 'getcommiteditor' returns 'commitforceeditor' regardless of
369 'getcommiteditor' returns 'commitforceeditor' regardless of
370 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
370 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
371 they are specific for usage in MQ.
371 they are specific for usage in MQ.
372 """
372 """
373 if edit or finishdesc or extramsg:
373 if edit or finishdesc or extramsg:
374 return lambda r, c, s: commitforceeditor(r, c, s,
374 return lambda r, c, s: commitforceeditor(r, c, s,
375 finishdesc=finishdesc,
375 finishdesc=finishdesc,
376 extramsg=extramsg,
376 extramsg=extramsg,
377 editform=editform)
377 editform=editform)
378 elif editform:
378 elif editform:
379 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
379 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
380 else:
380 else:
381 return commiteditor
381 return commiteditor
382
382
383 def loglimit(opts):
383 def loglimit(opts):
384 """get the log limit according to option -l/--limit"""
384 """get the log limit according to option -l/--limit"""
385 limit = opts.get('limit')
385 limit = opts.get('limit')
386 if limit:
386 if limit:
387 try:
387 try:
388 limit = int(limit)
388 limit = int(limit)
389 except ValueError:
389 except ValueError:
390 raise error.Abort(_('limit must be a positive integer'))
390 raise error.Abort(_('limit must be a positive integer'))
391 if limit <= 0:
391 if limit <= 0:
392 raise error.Abort(_('limit must be positive'))
392 raise error.Abort(_('limit must be positive'))
393 else:
393 else:
394 limit = None
394 limit = None
395 return limit
395 return limit
396
396
397 def makefilename(repo, pat, node, desc=None,
397 def makefilename(repo, pat, node, desc=None,
398 total=None, seqno=None, revwidth=None, pathname=None):
398 total=None, seqno=None, revwidth=None, pathname=None):
399 node_expander = {
399 node_expander = {
400 'H': lambda: hex(node),
400 'H': lambda: hex(node),
401 'R': lambda: str(repo.changelog.rev(node)),
401 'R': lambda: str(repo.changelog.rev(node)),
402 'h': lambda: short(node),
402 'h': lambda: short(node),
403 'm': lambda: re.sub('[^\w]', '_', str(desc))
403 'm': lambda: re.sub('[^\w]', '_', str(desc))
404 }
404 }
405 expander = {
405 expander = {
406 '%': lambda: '%',
406 '%': lambda: '%',
407 'b': lambda: os.path.basename(repo.root),
407 'b': lambda: os.path.basename(repo.root),
408 }
408 }
409
409
410 try:
410 try:
411 if node:
411 if node:
412 expander.update(node_expander)
412 expander.update(node_expander)
413 if node:
413 if node:
414 expander['r'] = (lambda:
414 expander['r'] = (lambda:
415 str(repo.changelog.rev(node)).zfill(revwidth or 0))
415 str(repo.changelog.rev(node)).zfill(revwidth or 0))
416 if total is not None:
416 if total is not None:
417 expander['N'] = lambda: str(total)
417 expander['N'] = lambda: str(total)
418 if seqno is not None:
418 if seqno is not None:
419 expander['n'] = lambda: str(seqno)
419 expander['n'] = lambda: str(seqno)
420 if total is not None and seqno is not None:
420 if total is not None and seqno is not None:
421 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
421 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
422 if pathname is not None:
422 if pathname is not None:
423 expander['s'] = lambda: os.path.basename(pathname)
423 expander['s'] = lambda: os.path.basename(pathname)
424 expander['d'] = lambda: os.path.dirname(pathname) or '.'
424 expander['d'] = lambda: os.path.dirname(pathname) or '.'
425 expander['p'] = lambda: pathname
425 expander['p'] = lambda: pathname
426
426
427 newname = []
427 newname = []
428 patlen = len(pat)
428 patlen = len(pat)
429 i = 0
429 i = 0
430 while i < patlen:
430 while i < patlen:
431 c = pat[i]
431 c = pat[i]
432 if c == '%':
432 if c == '%':
433 i += 1
433 i += 1
434 c = pat[i]
434 c = pat[i]
435 c = expander[c]()
435 c = expander[c]()
436 newname.append(c)
436 newname.append(c)
437 i += 1
437 i += 1
438 return ''.join(newname)
438 return ''.join(newname)
439 except KeyError as inst:
439 except KeyError as inst:
440 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
440 raise error.Abort(_("invalid format spec '%%%s' in output filename") %
441 inst.args[0])
441 inst.args[0])
442
442
443 def makefileobj(repo, pat, node=None, desc=None, total=None,
443 def makefileobj(repo, pat, node=None, desc=None, total=None,
444 seqno=None, revwidth=None, mode='wb', modemap=None,
444 seqno=None, revwidth=None, mode='wb', modemap=None,
445 pathname=None):
445 pathname=None):
446
446
447 writable = mode not in ('r', 'rb')
447 writable = mode not in ('r', 'rb')
448
448
449 if not pat or pat == '-':
449 if not pat or pat == '-':
450 if writable:
450 if writable:
451 fp = repo.ui.fout
451 fp = repo.ui.fout
452 else:
452 else:
453 fp = repo.ui.fin
453 fp = repo.ui.fin
454 if util.safehasattr(fp, 'fileno'):
454 if util.safehasattr(fp, 'fileno'):
455 return os.fdopen(os.dup(fp.fileno()), mode)
455 return os.fdopen(os.dup(fp.fileno()), mode)
456 else:
456 else:
457 # if this fp can't be duped properly, return
457 # if this fp can't be duped properly, return
458 # a dummy object that can be closed
458 # a dummy object that can be closed
459 class wrappedfileobj(object):
459 class wrappedfileobj(object):
460 noop = lambda x: None
460 noop = lambda x: None
461 def __init__(self, f):
461 def __init__(self, f):
462 self.f = f
462 self.f = f
463 def __getattr__(self, attr):
463 def __getattr__(self, attr):
464 if attr == 'close':
464 if attr == 'close':
465 return self.noop
465 return self.noop
466 else:
466 else:
467 return getattr(self.f, attr)
467 return getattr(self.f, attr)
468
468
469 return wrappedfileobj(fp)
469 return wrappedfileobj(fp)
470 if util.safehasattr(pat, 'write') and writable:
470 if util.safehasattr(pat, 'write') and writable:
471 return pat
471 return pat
472 if util.safehasattr(pat, 'read') and 'r' in mode:
472 if util.safehasattr(pat, 'read') and 'r' in mode:
473 return pat
473 return pat
474 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
474 fn = makefilename(repo, pat, node, desc, total, seqno, revwidth, pathname)
475 if modemap is not None:
475 if modemap is not None:
476 mode = modemap.get(fn, mode)
476 mode = modemap.get(fn, mode)
477 if mode == 'wb':
477 if mode == 'wb':
478 modemap[fn] = 'ab'
478 modemap[fn] = 'ab'
479 return open(fn, mode)
479 return open(fn, mode)
480
480
481 def openrevlog(repo, cmd, file_, opts):
481 def openrevlog(repo, cmd, file_, opts):
482 """opens the changelog, manifest, a filelog or a given revlog"""
482 """opens the changelog, manifest, a filelog or a given revlog"""
483 cl = opts['changelog']
483 cl = opts['changelog']
484 mf = opts['manifest']
484 mf = opts['manifest']
485 dir = opts['dir']
485 dir = opts['dir']
486 msg = None
486 msg = None
487 if cl and mf:
487 if cl and mf:
488 msg = _('cannot specify --changelog and --manifest at the same time')
488 msg = _('cannot specify --changelog and --manifest at the same time')
489 elif cl and dir:
489 elif cl and dir:
490 msg = _('cannot specify --changelog and --dir at the same time')
490 msg = _('cannot specify --changelog and --dir at the same time')
491 elif cl or mf:
491 elif cl or mf:
492 if file_:
492 if file_:
493 msg = _('cannot specify filename with --changelog or --manifest')
493 msg = _('cannot specify filename with --changelog or --manifest')
494 elif not repo:
494 elif not repo:
495 msg = _('cannot specify --changelog or --manifest or --dir '
495 msg = _('cannot specify --changelog or --manifest or --dir '
496 'without a repository')
496 'without a repository')
497 if msg:
497 if msg:
498 raise error.Abort(msg)
498 raise error.Abort(msg)
499
499
500 r = None
500 r = None
501 if repo:
501 if repo:
502 if cl:
502 if cl:
503 r = repo.unfiltered().changelog
503 r = repo.unfiltered().changelog
504 elif dir:
504 elif dir:
505 if 'treemanifest' not in repo.requirements:
505 if 'treemanifest' not in repo.requirements:
506 raise error.Abort(_("--dir can only be used on repos with "
506 raise error.Abort(_("--dir can only be used on repos with "
507 "treemanifest enabled"))
507 "treemanifest enabled"))
508 dirlog = repo.dirlog(file_)
508 dirlog = repo.dirlog(file_)
509 if len(dirlog):
509 if len(dirlog):
510 r = dirlog
510 r = dirlog
511 elif mf:
511 elif mf:
512 r = repo.manifest
512 r = repo.manifest
513 elif file_:
513 elif file_:
514 filelog = repo.file(file_)
514 filelog = repo.file(file_)
515 if len(filelog):
515 if len(filelog):
516 r = filelog
516 r = filelog
517 if not r:
517 if not r:
518 if not file_:
518 if not file_:
519 raise error.CommandError(cmd, _('invalid arguments'))
519 raise error.CommandError(cmd, _('invalid arguments'))
520 if not os.path.isfile(file_):
520 if not os.path.isfile(file_):
521 raise error.Abort(_("revlog '%s' not found") % file_)
521 raise error.Abort(_("revlog '%s' not found") % file_)
522 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
522 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
523 file_[:-2] + ".i")
523 file_[:-2] + ".i")
524 return r
524 return r
525
525
526 def copy(ui, repo, pats, opts, rename=False):
526 def copy(ui, repo, pats, opts, rename=False):
527 # called with the repo lock held
527 # called with the repo lock held
528 #
528 #
529 # hgsep => pathname that uses "/" to separate directories
529 # hgsep => pathname that uses "/" to separate directories
530 # ossep => pathname that uses os.sep to separate directories
530 # ossep => pathname that uses os.sep to separate directories
531 cwd = repo.getcwd()
531 cwd = repo.getcwd()
532 targets = {}
532 targets = {}
533 after = opts.get("after")
533 after = opts.get("after")
534 dryrun = opts.get("dry_run")
534 dryrun = opts.get("dry_run")
535 wctx = repo[None]
535 wctx = repo[None]
536
536
537 def walkpat(pat):
537 def walkpat(pat):
538 srcs = []
538 srcs = []
539 if after:
539 if after:
540 badstates = '?'
540 badstates = '?'
541 else:
541 else:
542 badstates = '?r'
542 badstates = '?r'
543 m = scmutil.match(repo[None], [pat], opts, globbed=True)
543 m = scmutil.match(repo[None], [pat], opts, globbed=True)
544 for abs in repo.walk(m):
544 for abs in repo.walk(m):
545 state = repo.dirstate[abs]
545 state = repo.dirstate[abs]
546 rel = m.rel(abs)
546 rel = m.rel(abs)
547 exact = m.exact(abs)
547 exact = m.exact(abs)
548 if state in badstates:
548 if state in badstates:
549 if exact and state == '?':
549 if exact and state == '?':
550 ui.warn(_('%s: not copying - file is not managed\n') % rel)
550 ui.warn(_('%s: not copying - file is not managed\n') % rel)
551 if exact and state == 'r':
551 if exact and state == 'r':
552 ui.warn(_('%s: not copying - file has been marked for'
552 ui.warn(_('%s: not copying - file has been marked for'
553 ' remove\n') % rel)
553 ' remove\n') % rel)
554 continue
554 continue
555 # abs: hgsep
555 # abs: hgsep
556 # rel: ossep
556 # rel: ossep
557 srcs.append((abs, rel, exact))
557 srcs.append((abs, rel, exact))
558 return srcs
558 return srcs
559
559
560 # abssrc: hgsep
560 # abssrc: hgsep
561 # relsrc: ossep
561 # relsrc: ossep
562 # otarget: ossep
562 # otarget: ossep
563 def copyfile(abssrc, relsrc, otarget, exact):
563 def copyfile(abssrc, relsrc, otarget, exact):
564 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
564 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
565 if '/' in abstarget:
565 if '/' in abstarget:
566 # We cannot normalize abstarget itself, this would prevent
566 # We cannot normalize abstarget itself, this would prevent
567 # case only renames, like a => A.
567 # case only renames, like a => A.
568 abspath, absname = abstarget.rsplit('/', 1)
568 abspath, absname = abstarget.rsplit('/', 1)
569 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
569 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
570 reltarget = repo.pathto(abstarget, cwd)
570 reltarget = repo.pathto(abstarget, cwd)
571 target = repo.wjoin(abstarget)
571 target = repo.wjoin(abstarget)
572 src = repo.wjoin(abssrc)
572 src = repo.wjoin(abssrc)
573 state = repo.dirstate[abstarget]
573 state = repo.dirstate[abstarget]
574
574
575 scmutil.checkportable(ui, abstarget)
575 scmutil.checkportable(ui, abstarget)
576
576
577 # check for collisions
577 # check for collisions
578 prevsrc = targets.get(abstarget)
578 prevsrc = targets.get(abstarget)
579 if prevsrc is not None:
579 if prevsrc is not None:
580 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
580 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
581 (reltarget, repo.pathto(abssrc, cwd),
581 (reltarget, repo.pathto(abssrc, cwd),
582 repo.pathto(prevsrc, cwd)))
582 repo.pathto(prevsrc, cwd)))
583 return
583 return
584
584
585 # check for overwrites
585 # check for overwrites
586 exists = os.path.lexists(target)
586 exists = os.path.lexists(target)
587 samefile = False
587 samefile = False
588 if exists and abssrc != abstarget:
588 if exists and abssrc != abstarget:
589 if (repo.dirstate.normalize(abssrc) ==
589 if (repo.dirstate.normalize(abssrc) ==
590 repo.dirstate.normalize(abstarget)):
590 repo.dirstate.normalize(abstarget)):
591 if not rename:
591 if not rename:
592 ui.warn(_("%s: can't copy - same file\n") % reltarget)
592 ui.warn(_("%s: can't copy - same file\n") % reltarget)
593 return
593 return
594 exists = False
594 exists = False
595 samefile = True
595 samefile = True
596
596
597 if not after and exists or after and state in 'mn':
597 if not after and exists or after and state in 'mn':
598 if not opts['force']:
598 if not opts['force']:
599 ui.warn(_('%s: not overwriting - file exists\n') %
599 ui.warn(_('%s: not overwriting - file exists\n') %
600 reltarget)
600 reltarget)
601 return
601 return
602
602
603 if after:
603 if after:
604 if not exists:
604 if not exists:
605 if rename:
605 if rename:
606 ui.warn(_('%s: not recording move - %s does not exist\n') %
606 ui.warn(_('%s: not recording move - %s does not exist\n') %
607 (relsrc, reltarget))
607 (relsrc, reltarget))
608 else:
608 else:
609 ui.warn(_('%s: not recording copy - %s does not exist\n') %
609 ui.warn(_('%s: not recording copy - %s does not exist\n') %
610 (relsrc, reltarget))
610 (relsrc, reltarget))
611 return
611 return
612 elif not dryrun:
612 elif not dryrun:
613 try:
613 try:
614 if exists:
614 if exists:
615 os.unlink(target)
615 os.unlink(target)
616 targetdir = os.path.dirname(target) or '.'
616 targetdir = os.path.dirname(target) or '.'
617 if not os.path.isdir(targetdir):
617 if not os.path.isdir(targetdir):
618 os.makedirs(targetdir)
618 os.makedirs(targetdir)
619 if samefile:
619 if samefile:
620 tmp = target + "~hgrename"
620 tmp = target + "~hgrename"
621 os.rename(src, tmp)
621 os.rename(src, tmp)
622 os.rename(tmp, target)
622 os.rename(tmp, target)
623 else:
623 else:
624 util.copyfile(src, target)
624 util.copyfile(src, target)
625 srcexists = True
625 srcexists = True
626 except IOError as inst:
626 except IOError as inst:
627 if inst.errno == errno.ENOENT:
627 if inst.errno == errno.ENOENT:
628 ui.warn(_('%s: deleted in working directory\n') % relsrc)
628 ui.warn(_('%s: deleted in working directory\n') % relsrc)
629 srcexists = False
629 srcexists = False
630 else:
630 else:
631 ui.warn(_('%s: cannot copy - %s\n') %
631 ui.warn(_('%s: cannot copy - %s\n') %
632 (relsrc, inst.strerror))
632 (relsrc, inst.strerror))
633 return True # report a failure
633 return True # report a failure
634
634
635 if ui.verbose or not exact:
635 if ui.verbose or not exact:
636 if rename:
636 if rename:
637 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
637 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
638 else:
638 else:
639 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
639 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
640
640
641 targets[abstarget] = abssrc
641 targets[abstarget] = abssrc
642
642
643 # fix up dirstate
643 # fix up dirstate
644 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
644 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
645 dryrun=dryrun, cwd=cwd)
645 dryrun=dryrun, cwd=cwd)
646 if rename and not dryrun:
646 if rename and not dryrun:
647 if not after and srcexists and not samefile:
647 if not after and srcexists and not samefile:
648 util.unlinkpath(repo.wjoin(abssrc))
648 util.unlinkpath(repo.wjoin(abssrc))
649 wctx.forget([abssrc])
649 wctx.forget([abssrc])
650
650
651 # pat: ossep
651 # pat: ossep
652 # dest ossep
652 # dest ossep
653 # srcs: list of (hgsep, hgsep, ossep, bool)
653 # srcs: list of (hgsep, hgsep, ossep, bool)
654 # return: function that takes hgsep and returns ossep
654 # return: function that takes hgsep and returns ossep
655 def targetpathfn(pat, dest, srcs):
655 def targetpathfn(pat, dest, srcs):
656 if os.path.isdir(pat):
656 if os.path.isdir(pat):
657 abspfx = pathutil.canonpath(repo.root, cwd, pat)
657 abspfx = pathutil.canonpath(repo.root, cwd, pat)
658 abspfx = util.localpath(abspfx)
658 abspfx = util.localpath(abspfx)
659 if destdirexists:
659 if destdirexists:
660 striplen = len(os.path.split(abspfx)[0])
660 striplen = len(os.path.split(abspfx)[0])
661 else:
661 else:
662 striplen = len(abspfx)
662 striplen = len(abspfx)
663 if striplen:
663 if striplen:
664 striplen += len(os.sep)
664 striplen += len(os.sep)
665 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
665 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
666 elif destdirexists:
666 elif destdirexists:
667 res = lambda p: os.path.join(dest,
667 res = lambda p: os.path.join(dest,
668 os.path.basename(util.localpath(p)))
668 os.path.basename(util.localpath(p)))
669 else:
669 else:
670 res = lambda p: dest
670 res = lambda p: dest
671 return res
671 return res
672
672
673 # pat: ossep
673 # pat: ossep
674 # dest ossep
674 # dest ossep
675 # srcs: list of (hgsep, hgsep, ossep, bool)
675 # srcs: list of (hgsep, hgsep, ossep, bool)
676 # return: function that takes hgsep and returns ossep
676 # return: function that takes hgsep and returns ossep
677 def targetpathafterfn(pat, dest, srcs):
677 def targetpathafterfn(pat, dest, srcs):
678 if matchmod.patkind(pat):
678 if matchmod.patkind(pat):
679 # a mercurial pattern
679 # a mercurial pattern
680 res = lambda p: os.path.join(dest,
680 res = lambda p: os.path.join(dest,
681 os.path.basename(util.localpath(p)))
681 os.path.basename(util.localpath(p)))
682 else:
682 else:
683 abspfx = pathutil.canonpath(repo.root, cwd, pat)
683 abspfx = pathutil.canonpath(repo.root, cwd, pat)
684 if len(abspfx) < len(srcs[0][0]):
684 if len(abspfx) < len(srcs[0][0]):
685 # A directory. Either the target path contains the last
685 # A directory. Either the target path contains the last
686 # component of the source path or it does not.
686 # component of the source path or it does not.
687 def evalpath(striplen):
687 def evalpath(striplen):
688 score = 0
688 score = 0
689 for s in srcs:
689 for s in srcs:
690 t = os.path.join(dest, util.localpath(s[0])[striplen:])
690 t = os.path.join(dest, util.localpath(s[0])[striplen:])
691 if os.path.lexists(t):
691 if os.path.lexists(t):
692 score += 1
692 score += 1
693 return score
693 return score
694
694
695 abspfx = util.localpath(abspfx)
695 abspfx = util.localpath(abspfx)
696 striplen = len(abspfx)
696 striplen = len(abspfx)
697 if striplen:
697 if striplen:
698 striplen += len(os.sep)
698 striplen += len(os.sep)
699 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
699 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
700 score = evalpath(striplen)
700 score = evalpath(striplen)
701 striplen1 = len(os.path.split(abspfx)[0])
701 striplen1 = len(os.path.split(abspfx)[0])
702 if striplen1:
702 if striplen1:
703 striplen1 += len(os.sep)
703 striplen1 += len(os.sep)
704 if evalpath(striplen1) > score:
704 if evalpath(striplen1) > score:
705 striplen = striplen1
705 striplen = striplen1
706 res = lambda p: os.path.join(dest,
706 res = lambda p: os.path.join(dest,
707 util.localpath(p)[striplen:])
707 util.localpath(p)[striplen:])
708 else:
708 else:
709 # a file
709 # a file
710 if destdirexists:
710 if destdirexists:
711 res = lambda p: os.path.join(dest,
711 res = lambda p: os.path.join(dest,
712 os.path.basename(util.localpath(p)))
712 os.path.basename(util.localpath(p)))
713 else:
713 else:
714 res = lambda p: dest
714 res = lambda p: dest
715 return res
715 return res
716
716
717 pats = scmutil.expandpats(pats)
717 pats = scmutil.expandpats(pats)
718 if not pats:
718 if not pats:
719 raise error.Abort(_('no source or destination specified'))
719 raise error.Abort(_('no source or destination specified'))
720 if len(pats) == 1:
720 if len(pats) == 1:
721 raise error.Abort(_('no destination specified'))
721 raise error.Abort(_('no destination specified'))
722 dest = pats.pop()
722 dest = pats.pop()
723 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
723 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
724 if not destdirexists:
724 if not destdirexists:
725 if len(pats) > 1 or matchmod.patkind(pats[0]):
725 if len(pats) > 1 or matchmod.patkind(pats[0]):
726 raise error.Abort(_('with multiple sources, destination must be an '
726 raise error.Abort(_('with multiple sources, destination must be an '
727 'existing directory'))
727 'existing directory'))
728 if util.endswithsep(dest):
728 if util.endswithsep(dest):
729 raise error.Abort(_('destination %s is not a directory') % dest)
729 raise error.Abort(_('destination %s is not a directory') % dest)
730
730
731 tfn = targetpathfn
731 tfn = targetpathfn
732 if after:
732 if after:
733 tfn = targetpathafterfn
733 tfn = targetpathafterfn
734 copylist = []
734 copylist = []
735 for pat in pats:
735 for pat in pats:
736 srcs = walkpat(pat)
736 srcs = walkpat(pat)
737 if not srcs:
737 if not srcs:
738 continue
738 continue
739 copylist.append((tfn(pat, dest, srcs), srcs))
739 copylist.append((tfn(pat, dest, srcs), srcs))
740 if not copylist:
740 if not copylist:
741 raise error.Abort(_('no files to copy'))
741 raise error.Abort(_('no files to copy'))
742
742
743 errors = 0
743 errors = 0
744 for targetpath, srcs in copylist:
744 for targetpath, srcs in copylist:
745 for abssrc, relsrc, exact in srcs:
745 for abssrc, relsrc, exact in srcs:
746 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
746 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
747 errors += 1
747 errors += 1
748
748
749 if errors:
749 if errors:
750 ui.warn(_('(consider using --after)\n'))
750 ui.warn(_('(consider using --after)\n'))
751
751
752 return errors != 0
752 return errors != 0
753
753
754 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
754 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
755 runargs=None, appendpid=False):
755 runargs=None, appendpid=False):
756 '''Run a command as a service.'''
756 '''Run a command as a service.'''
757
757
758 def writepid(pid):
758 def writepid(pid):
759 if opts['pid_file']:
759 if opts['pid_file']:
760 if appendpid:
760 if appendpid:
761 mode = 'a'
761 mode = 'a'
762 else:
762 else:
763 mode = 'w'
763 mode = 'w'
764 fp = open(opts['pid_file'], mode)
764 fp = open(opts['pid_file'], mode)
765 fp.write(str(pid) + '\n')
765 fp.write(str(pid) + '\n')
766 fp.close()
766 fp.close()
767
767
768 if opts['daemon'] and not opts['daemon_pipefds']:
768 if opts['daemon'] and not opts['daemon_pipefds']:
769 # Signal child process startup with file removal
769 # Signal child process startup with file removal
770 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
770 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
771 os.close(lockfd)
771 os.close(lockfd)
772 try:
772 try:
773 if not runargs:
773 if not runargs:
774 runargs = util.hgcmd() + sys.argv[1:]
774 runargs = util.hgcmd() + sys.argv[1:]
775 runargs.append('--daemon-pipefds=%s' % lockpath)
775 runargs.append('--daemon-pipefds=%s' % lockpath)
776 # Don't pass --cwd to the child process, because we've already
776 # Don't pass --cwd to the child process, because we've already
777 # changed directory.
777 # changed directory.
778 for i in xrange(1, len(runargs)):
778 for i in xrange(1, len(runargs)):
779 if runargs[i].startswith('--cwd='):
779 if runargs[i].startswith('--cwd='):
780 del runargs[i]
780 del runargs[i]
781 break
781 break
782 elif runargs[i].startswith('--cwd'):
782 elif runargs[i].startswith('--cwd'):
783 del runargs[i:i + 2]
783 del runargs[i:i + 2]
784 break
784 break
785 def condfn():
785 def condfn():
786 return not os.path.exists(lockpath)
786 return not os.path.exists(lockpath)
787 pid = util.rundetached(runargs, condfn)
787 pid = util.rundetached(runargs, condfn)
788 if pid < 0:
788 if pid < 0:
789 raise error.Abort(_('child process failed to start'))
789 raise error.Abort(_('child process failed to start'))
790 writepid(pid)
790 writepid(pid)
791 finally:
791 finally:
792 try:
792 try:
793 os.unlink(lockpath)
793 os.unlink(lockpath)
794 except OSError as e:
794 except OSError as e:
795 if e.errno != errno.ENOENT:
795 if e.errno != errno.ENOENT:
796 raise
796 raise
797 if parentfn:
797 if parentfn:
798 return parentfn(pid)
798 return parentfn(pid)
799 else:
799 else:
800 return
800 return
801
801
802 if initfn:
802 if initfn:
803 initfn()
803 initfn()
804
804
805 if not opts['daemon']:
805 if not opts['daemon']:
806 writepid(os.getpid())
806 writepid(os.getpid())
807
807
808 if opts['daemon_pipefds']:
808 if opts['daemon_pipefds']:
809 lockpath = opts['daemon_pipefds']
809 lockpath = opts['daemon_pipefds']
810 try:
810 try:
811 os.setsid()
811 os.setsid()
812 except AttributeError:
812 except AttributeError:
813 pass
813 pass
814 os.unlink(lockpath)
814 os.unlink(lockpath)
815 util.hidewindow()
815 util.hidewindow()
816 sys.stdout.flush()
816 sys.stdout.flush()
817 sys.stderr.flush()
817 sys.stderr.flush()
818
818
819 nullfd = os.open(os.devnull, os.O_RDWR)
819 nullfd = os.open(os.devnull, os.O_RDWR)
820 logfilefd = nullfd
820 logfilefd = nullfd
821 if logfile:
821 if logfile:
822 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
822 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
823 os.dup2(nullfd, 0)
823 os.dup2(nullfd, 0)
824 os.dup2(logfilefd, 1)
824 os.dup2(logfilefd, 1)
825 os.dup2(logfilefd, 2)
825 os.dup2(logfilefd, 2)
826 if nullfd not in (0, 1, 2):
826 if nullfd not in (0, 1, 2):
827 os.close(nullfd)
827 os.close(nullfd)
828 if logfile and logfilefd not in (0, 1, 2):
828 if logfile and logfilefd not in (0, 1, 2):
829 os.close(logfilefd)
829 os.close(logfilefd)
830
830
831 if runfn:
831 if runfn:
832 return runfn()
832 return runfn()
833
833
834 ## facility to let extension process additional data into an import patch
834 ## facility to let extension process additional data into an import patch
835 # list of identifier to be executed in order
835 # list of identifier to be executed in order
836 extrapreimport = [] # run before commit
836 extrapreimport = [] # run before commit
837 extrapostimport = [] # run after commit
837 extrapostimport = [] # run after commit
838 # mapping from identifier to actual import function
838 # mapping from identifier to actual import function
839 #
839 #
840 # 'preimport' are run before the commit is made and are provided the following
840 # 'preimport' are run before the commit is made and are provided the following
841 # arguments:
841 # arguments:
842 # - repo: the localrepository instance,
842 # - repo: the localrepository instance,
843 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
843 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
844 # - extra: the future extra dictionary of the changeset, please mutate it,
844 # - extra: the future extra dictionary of the changeset, please mutate it,
845 # - opts: the import options.
845 # - opts: the import options.
846 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
846 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
847 # mutation of in memory commit and more. Feel free to rework the code to get
847 # mutation of in memory commit and more. Feel free to rework the code to get
848 # there.
848 # there.
849 extrapreimportmap = {}
849 extrapreimportmap = {}
850 # 'postimport' are run after the commit is made and are provided the following
850 # 'postimport' are run after the commit is made and are provided the following
851 # argument:
851 # argument:
852 # - ctx: the changectx created by import.
852 # - ctx: the changectx created by import.
853 extrapostimportmap = {}
853 extrapostimportmap = {}
854
854
855 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
855 def tryimportone(ui, repo, hunk, parents, opts, msgs, updatefunc):
856 """Utility function used by commands.import to import a single patch
856 """Utility function used by commands.import to import a single patch
857
857
858 This function is explicitly defined here to help the evolve extension to
858 This function is explicitly defined here to help the evolve extension to
859 wrap this part of the import logic.
859 wrap this part of the import logic.
860
860
861 The API is currently a bit ugly because it a simple code translation from
861 The API is currently a bit ugly because it a simple code translation from
862 the import command. Feel free to make it better.
862 the import command. Feel free to make it better.
863
863
864 :hunk: a patch (as a binary string)
864 :hunk: a patch (as a binary string)
865 :parents: nodes that will be parent of the created commit
865 :parents: nodes that will be parent of the created commit
866 :opts: the full dict of option passed to the import command
866 :opts: the full dict of option passed to the import command
867 :msgs: list to save commit message to.
867 :msgs: list to save commit message to.
868 (used in case we need to save it when failing)
868 (used in case we need to save it when failing)
869 :updatefunc: a function that update a repo to a given node
869 :updatefunc: a function that update a repo to a given node
870 updatefunc(<repo>, <node>)
870 updatefunc(<repo>, <node>)
871 """
871 """
872 # avoid cycle context -> subrepo -> cmdutil
872 # avoid cycle context -> subrepo -> cmdutil
873 import context
873 import context
874 extractdata = patch.extract(ui, hunk)
874 extractdata = patch.extract(ui, hunk)
875 tmpname = extractdata.get('filename')
875 tmpname = extractdata.get('filename')
876 message = extractdata.get('message')
876 message = extractdata.get('message')
877 user = extractdata.get('user')
877 user = extractdata.get('user')
878 date = extractdata.get('date')
878 date = extractdata.get('date')
879 branch = extractdata.get('branch')
879 branch = extractdata.get('branch')
880 nodeid = extractdata.get('nodeid')
880 nodeid = extractdata.get('nodeid')
881 p1 = extractdata.get('p1')
881 p1 = extractdata.get('p1')
882 p2 = extractdata.get('p2')
882 p2 = extractdata.get('p2')
883
883
884 update = not opts.get('bypass')
884 update = not opts.get('bypass')
885 strip = opts["strip"]
885 strip = opts["strip"]
886 prefix = opts["prefix"]
886 prefix = opts["prefix"]
887 sim = float(opts.get('similarity') or 0)
887 sim = float(opts.get('similarity') or 0)
888 if not tmpname:
888 if not tmpname:
889 return (None, None, False)
889 return (None, None, False)
890 msg = _('applied to working directory')
890 msg = _('applied to working directory')
891
891
892 rejects = False
892 rejects = False
893
893
894 try:
894 try:
895 cmdline_message = logmessage(ui, opts)
895 cmdline_message = logmessage(ui, opts)
896 if cmdline_message:
896 if cmdline_message:
897 # pickup the cmdline msg
897 # pickup the cmdline msg
898 message = cmdline_message
898 message = cmdline_message
899 elif message:
899 elif message:
900 # pickup the patch msg
900 # pickup the patch msg
901 message = message.strip()
901 message = message.strip()
902 else:
902 else:
903 # launch the editor
903 # launch the editor
904 message = None
904 message = None
905 ui.debug('message:\n%s\n' % message)
905 ui.debug('message:\n%s\n' % message)
906
906
907 if len(parents) == 1:
907 if len(parents) == 1:
908 parents.append(repo[nullid])
908 parents.append(repo[nullid])
909 if opts.get('exact'):
909 if opts.get('exact'):
910 if not nodeid or not p1:
910 if not nodeid or not p1:
911 raise error.Abort(_('not a Mercurial patch'))
911 raise error.Abort(_('not a Mercurial patch'))
912 p1 = repo[p1]
912 p1 = repo[p1]
913 p2 = repo[p2 or nullid]
913 p2 = repo[p2 or nullid]
914 elif p2:
914 elif p2:
915 try:
915 try:
916 p1 = repo[p1]
916 p1 = repo[p1]
917 p2 = repo[p2]
917 p2 = repo[p2]
918 # Without any options, consider p2 only if the
918 # Without any options, consider p2 only if the
919 # patch is being applied on top of the recorded
919 # patch is being applied on top of the recorded
920 # first parent.
920 # first parent.
921 if p1 != parents[0]:
921 if p1 != parents[0]:
922 p1 = parents[0]
922 p1 = parents[0]
923 p2 = repo[nullid]
923 p2 = repo[nullid]
924 except error.RepoError:
924 except error.RepoError:
925 p1, p2 = parents
925 p1, p2 = parents
926 if p2.node() == nullid:
926 if p2.node() == nullid:
927 ui.warn(_("warning: import the patch as a normal revision\n"
927 ui.warn(_("warning: import the patch as a normal revision\n"
928 "(use --exact to import the patch as a merge)\n"))
928 "(use --exact to import the patch as a merge)\n"))
929 else:
929 else:
930 p1, p2 = parents
930 p1, p2 = parents
931
931
932 n = None
932 n = None
933 if update:
933 if update:
934 if p1 != parents[0]:
934 if p1 != parents[0]:
935 updatefunc(repo, p1.node())
935 updatefunc(repo, p1.node())
936 if p2 != parents[1]:
936 if p2 != parents[1]:
937 repo.setparents(p1.node(), p2.node())
937 repo.setparents(p1.node(), p2.node())
938
938
939 if opts.get('exact') or opts.get('import_branch'):
939 if opts.get('exact') or opts.get('import_branch'):
940 repo.dirstate.setbranch(branch or 'default')
940 repo.dirstate.setbranch(branch or 'default')
941
941
942 partial = opts.get('partial', False)
942 partial = opts.get('partial', False)
943 files = set()
943 files = set()
944 try:
944 try:
945 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
945 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
946 files=files, eolmode=None, similarity=sim / 100.0)
946 files=files, eolmode=None, similarity=sim / 100.0)
947 except patch.PatchError as e:
947 except patch.PatchError as e:
948 if not partial:
948 if not partial:
949 raise error.Abort(str(e))
949 raise error.Abort(str(e))
950 if partial:
950 if partial:
951 rejects = True
951 rejects = True
952
952
953 files = list(files)
953 files = list(files)
954 if opts.get('no_commit'):
954 if opts.get('no_commit'):
955 if message:
955 if message:
956 msgs.append(message)
956 msgs.append(message)
957 else:
957 else:
958 if opts.get('exact') or p2:
958 if opts.get('exact') or p2:
959 # If you got here, you either use --force and know what
959 # If you got here, you either use --force and know what
960 # you are doing or used --exact or a merge patch while
960 # you are doing or used --exact or a merge patch while
961 # being updated to its first parent.
961 # being updated to its first parent.
962 m = None
962 m = None
963 else:
963 else:
964 m = scmutil.matchfiles(repo, files or [])
964 m = scmutil.matchfiles(repo, files or [])
965 editform = mergeeditform(repo[None], 'import.normal')
965 editform = mergeeditform(repo[None], 'import.normal')
966 if opts.get('exact'):
966 if opts.get('exact'):
967 editor = None
967 editor = None
968 else:
968 else:
969 editor = getcommiteditor(editform=editform, **opts)
969 editor = getcommiteditor(editform=editform, **opts)
970 allowemptyback = repo.ui.backupconfig('ui', 'allowemptycommit')
970 allowemptyback = repo.ui.backupconfig('ui', 'allowemptycommit')
971 extra = {}
971 extra = {}
972 for idfunc in extrapreimport:
972 for idfunc in extrapreimport:
973 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
973 extrapreimportmap[idfunc](repo, extractdata, extra, opts)
974 try:
974 try:
975 if partial:
975 if partial:
976 repo.ui.setconfig('ui', 'allowemptycommit', True)
976 repo.ui.setconfig('ui', 'allowemptycommit', True)
977 n = repo.commit(message, opts.get('user') or user,
977 n = repo.commit(message, opts.get('user') or user,
978 opts.get('date') or date, match=m,
978 opts.get('date') or date, match=m,
979 editor=editor, extra=extra)
979 editor=editor, extra=extra)
980 for idfunc in extrapostimport:
980 for idfunc in extrapostimport:
981 extrapostimportmap[idfunc](repo[n])
981 extrapostimportmap[idfunc](repo[n])
982 finally:
982 finally:
983 repo.ui.restoreconfig(allowemptyback)
983 repo.ui.restoreconfig(allowemptyback)
984 else:
984 else:
985 if opts.get('exact') or opts.get('import_branch'):
985 if opts.get('exact') or opts.get('import_branch'):
986 branch = branch or 'default'
986 branch = branch or 'default'
987 else:
987 else:
988 branch = p1.branch()
988 branch = p1.branch()
989 store = patch.filestore()
989 store = patch.filestore()
990 try:
990 try:
991 files = set()
991 files = set()
992 try:
992 try:
993 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
993 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
994 files, eolmode=None)
994 files, eolmode=None)
995 except patch.PatchError as e:
995 except patch.PatchError as e:
996 raise error.Abort(str(e))
996 raise error.Abort(str(e))
997 if opts.get('exact'):
997 if opts.get('exact'):
998 editor = None
998 editor = None
999 else:
999 else:
1000 editor = getcommiteditor(editform='import.bypass')
1000 editor = getcommiteditor(editform='import.bypass')
1001 memctx = context.makememctx(repo, (p1.node(), p2.node()),
1001 memctx = context.makememctx(repo, (p1.node(), p2.node()),
1002 message,
1002 message,
1003 opts.get('user') or user,
1003 opts.get('user') or user,
1004 opts.get('date') or date,
1004 opts.get('date') or date,
1005 branch, files, store,
1005 branch, files, store,
1006 editor=editor)
1006 editor=editor)
1007 n = memctx.commit()
1007 n = memctx.commit()
1008 finally:
1008 finally:
1009 store.close()
1009 store.close()
1010 if opts.get('exact') and opts.get('no_commit'):
1010 if opts.get('exact') and opts.get('no_commit'):
1011 # --exact with --no-commit is still useful in that it does merge
1011 # --exact with --no-commit is still useful in that it does merge
1012 # and branch bits
1012 # and branch bits
1013 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1013 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1014 elif opts.get('exact') and hex(n) != nodeid:
1014 elif opts.get('exact') and hex(n) != nodeid:
1015 raise error.Abort(_('patch is damaged or loses information'))
1015 raise error.Abort(_('patch is damaged or loses information'))
1016 if n:
1016 if n:
1017 # i18n: refers to a short changeset id
1017 # i18n: refers to a short changeset id
1018 msg = _('created %s') % short(n)
1018 msg = _('created %s') % short(n)
1019 return (msg, n, rejects)
1019 return (msg, n, rejects)
1020 finally:
1020 finally:
1021 os.unlink(tmpname)
1021 os.unlink(tmpname)
1022
1022
1023 # facility to let extensions include additional data in an exported patch
1023 # facility to let extensions include additional data in an exported patch
1024 # list of identifiers to be executed in order
1024 # list of identifiers to be executed in order
1025 extraexport = []
1025 extraexport = []
1026 # mapping from identifier to actual export function
1026 # mapping from identifier to actual export function
1027 # function as to return a string to be added to the header or None
1027 # function as to return a string to be added to the header or None
1028 # it is given two arguments (sequencenumber, changectx)
1028 # it is given two arguments (sequencenumber, changectx)
1029 extraexportmap = {}
1029 extraexportmap = {}
1030
1030
1031 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
1031 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
1032 opts=None, match=None):
1032 opts=None, match=None):
1033 '''export changesets as hg patches.'''
1033 '''export changesets as hg patches.'''
1034
1034
1035 total = len(revs)
1035 total = len(revs)
1036 revwidth = max([len(str(rev)) for rev in revs])
1036 revwidth = max([len(str(rev)) for rev in revs])
1037 filemode = {}
1037 filemode = {}
1038
1038
1039 def single(rev, seqno, fp):
1039 def single(rev, seqno, fp):
1040 ctx = repo[rev]
1040 ctx = repo[rev]
1041 node = ctx.node()
1041 node = ctx.node()
1042 parents = [p.node() for p in ctx.parents() if p]
1042 parents = [p.node() for p in ctx.parents() if p]
1043 branch = ctx.branch()
1043 branch = ctx.branch()
1044 if switch_parent:
1044 if switch_parent:
1045 parents.reverse()
1045 parents.reverse()
1046
1046
1047 if parents:
1047 if parents:
1048 prev = parents[0]
1048 prev = parents[0]
1049 else:
1049 else:
1050 prev = nullid
1050 prev = nullid
1051
1051
1052 shouldclose = False
1052 shouldclose = False
1053 if not fp and len(template) > 0:
1053 if not fp and len(template) > 0:
1054 desc_lines = ctx.description().rstrip().split('\n')
1054 desc_lines = ctx.description().rstrip().split('\n')
1055 desc = desc_lines[0] #Commit always has a first line.
1055 desc = desc_lines[0] #Commit always has a first line.
1056 fp = makefileobj(repo, template, node, desc=desc, total=total,
1056 fp = makefileobj(repo, template, node, desc=desc, total=total,
1057 seqno=seqno, revwidth=revwidth, mode='wb',
1057 seqno=seqno, revwidth=revwidth, mode='wb',
1058 modemap=filemode)
1058 modemap=filemode)
1059 if fp != template:
1059 if fp != template:
1060 shouldclose = True
1060 shouldclose = True
1061 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
1061 if fp and fp != sys.stdout and util.safehasattr(fp, 'name'):
1062 repo.ui.note("%s\n" % fp.name)
1062 repo.ui.note("%s\n" % fp.name)
1063
1063
1064 if not fp:
1064 if not fp:
1065 write = repo.ui.write
1065 write = repo.ui.write
1066 else:
1066 else:
1067 def write(s, **kw):
1067 def write(s, **kw):
1068 fp.write(s)
1068 fp.write(s)
1069
1069
1070 write("# HG changeset patch\n")
1070 write("# HG changeset patch\n")
1071 write("# User %s\n" % ctx.user())
1071 write("# User %s\n" % ctx.user())
1072 write("# Date %d %d\n" % ctx.date())
1072 write("# Date %d %d\n" % ctx.date())
1073 write("# %s\n" % util.datestr(ctx.date()))
1073 write("# %s\n" % util.datestr(ctx.date()))
1074 if branch and branch != 'default':
1074 if branch and branch != 'default':
1075 write("# Branch %s\n" % branch)
1075 write("# Branch %s\n" % branch)
1076 write("# Node ID %s\n" % hex(node))
1076 write("# Node ID %s\n" % hex(node))
1077 write("# Parent %s\n" % hex(prev))
1077 write("# Parent %s\n" % hex(prev))
1078 if len(parents) > 1:
1078 if len(parents) > 1:
1079 write("# Parent %s\n" % hex(parents[1]))
1079 write("# Parent %s\n" % hex(parents[1]))
1080
1080
1081 for headerid in extraexport:
1081 for headerid in extraexport:
1082 header = extraexportmap[headerid](seqno, ctx)
1082 header = extraexportmap[headerid](seqno, ctx)
1083 if header is not None:
1083 if header is not None:
1084 write('# %s\n' % header)
1084 write('# %s\n' % header)
1085 write(ctx.description().rstrip())
1085 write(ctx.description().rstrip())
1086 write("\n\n")
1086 write("\n\n")
1087
1087
1088 for chunk, label in patch.diffui(repo, prev, node, match, opts=opts):
1088 for chunk, label in patch.diffui(repo, prev, node, match, opts=opts):
1089 write(chunk, label=label)
1089 write(chunk, label=label)
1090
1090
1091 if shouldclose:
1091 if shouldclose:
1092 fp.close()
1092 fp.close()
1093
1093
1094 for seqno, rev in enumerate(revs):
1094 for seqno, rev in enumerate(revs):
1095 single(rev, seqno + 1, fp)
1095 single(rev, seqno + 1, fp)
1096
1096
1097 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1097 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
1098 changes=None, stat=False, fp=None, prefix='',
1098 changes=None, stat=False, fp=None, prefix='',
1099 root='', listsubrepos=False):
1099 root='', listsubrepos=False):
1100 '''show diff or diffstat.'''
1100 '''show diff or diffstat.'''
1101 if fp is None:
1101 if fp is None:
1102 write = ui.write
1102 write = ui.write
1103 else:
1103 else:
1104 def write(s, **kw):
1104 def write(s, **kw):
1105 fp.write(s)
1105 fp.write(s)
1106
1106
1107 if root:
1107 if root:
1108 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1108 relroot = pathutil.canonpath(repo.root, repo.getcwd(), root)
1109 else:
1109 else:
1110 relroot = ''
1110 relroot = ''
1111 if relroot != '':
1111 if relroot != '':
1112 # XXX relative roots currently don't work if the root is within a
1112 # XXX relative roots currently don't work if the root is within a
1113 # subrepo
1113 # subrepo
1114 uirelroot = match.uipath(relroot)
1114 uirelroot = match.uipath(relroot)
1115 relroot += '/'
1115 relroot += '/'
1116 for matchroot in match.files():
1116 for matchroot in match.files():
1117 if not matchroot.startswith(relroot):
1117 if not matchroot.startswith(relroot):
1118 ui.warn(_('warning: %s not inside relative root %s\n') % (
1118 ui.warn(_('warning: %s not inside relative root %s\n') % (
1119 match.uipath(matchroot), uirelroot))
1119 match.uipath(matchroot), uirelroot))
1120
1120
1121 if stat:
1121 if stat:
1122 diffopts = diffopts.copy(context=0)
1122 diffopts = diffopts.copy(context=0)
1123 width = 80
1123 width = 80
1124 if not ui.plain():
1124 if not ui.plain():
1125 width = ui.termwidth()
1125 width = ui.termwidth()
1126 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1126 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
1127 prefix=prefix, relroot=relroot)
1127 prefix=prefix, relroot=relroot)
1128 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1128 for chunk, label in patch.diffstatui(util.iterlines(chunks),
1129 width=width,
1129 width=width,
1130 git=diffopts.git):
1130 git=diffopts.git):
1131 write(chunk, label=label)
1131 write(chunk, label=label)
1132 else:
1132 else:
1133 for chunk, label in patch.diffui(repo, node1, node2, match,
1133 for chunk, label in patch.diffui(repo, node1, node2, match,
1134 changes, diffopts, prefix=prefix,
1134 changes, diffopts, prefix=prefix,
1135 relroot=relroot):
1135 relroot=relroot):
1136 write(chunk, label=label)
1136 write(chunk, label=label)
1137
1137
1138 if listsubrepos:
1138 if listsubrepos:
1139 ctx1 = repo[node1]
1139 ctx1 = repo[node1]
1140 ctx2 = repo[node2]
1140 ctx2 = repo[node2]
1141 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1141 for subpath, sub in scmutil.itersubrepos(ctx1, ctx2):
1142 tempnode2 = node2
1142 tempnode2 = node2
1143 try:
1143 try:
1144 if node2 is not None:
1144 if node2 is not None:
1145 tempnode2 = ctx2.substate[subpath][1]
1145 tempnode2 = ctx2.substate[subpath][1]
1146 except KeyError:
1146 except KeyError:
1147 # A subrepo that existed in node1 was deleted between node1 and
1147 # A subrepo that existed in node1 was deleted between node1 and
1148 # node2 (inclusive). Thus, ctx2's substate won't contain that
1148 # node2 (inclusive). Thus, ctx2's substate won't contain that
1149 # subpath. The best we can do is to ignore it.
1149 # subpath. The best we can do is to ignore it.
1150 tempnode2 = None
1150 tempnode2 = None
1151 submatch = matchmod.narrowmatcher(subpath, match)
1151 submatch = matchmod.narrowmatcher(subpath, match)
1152 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1152 sub.diff(ui, diffopts, tempnode2, submatch, changes=changes,
1153 stat=stat, fp=fp, prefix=prefix)
1153 stat=stat, fp=fp, prefix=prefix)
1154
1154
1155 class changeset_printer(object):
1155 class changeset_printer(object):
1156 '''show changeset information when templating not requested.'''
1156 '''show changeset information when templating not requested.'''
1157
1157
1158 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1158 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1159 self.ui = ui
1159 self.ui = ui
1160 self.repo = repo
1160 self.repo = repo
1161 self.buffered = buffered
1161 self.buffered = buffered
1162 self.matchfn = matchfn
1162 self.matchfn = matchfn
1163 self.diffopts = diffopts
1163 self.diffopts = diffopts
1164 self.header = {}
1164 self.header = {}
1165 self.hunk = {}
1165 self.hunk = {}
1166 self.lastheader = None
1166 self.lastheader = None
1167 self.footer = None
1167 self.footer = None
1168
1168
1169 def flush(self, ctx):
1169 def flush(self, ctx):
1170 rev = ctx.rev()
1170 rev = ctx.rev()
1171 if rev in self.header:
1171 if rev in self.header:
1172 h = self.header[rev]
1172 h = self.header[rev]
1173 if h != self.lastheader:
1173 if h != self.lastheader:
1174 self.lastheader = h
1174 self.lastheader = h
1175 self.ui.write(h)
1175 self.ui.write(h)
1176 del self.header[rev]
1176 del self.header[rev]
1177 if rev in self.hunk:
1177 if rev in self.hunk:
1178 self.ui.write(self.hunk[rev])
1178 self.ui.write(self.hunk[rev])
1179 del self.hunk[rev]
1179 del self.hunk[rev]
1180 return 1
1180 return 1
1181 return 0
1181 return 0
1182
1182
1183 def close(self):
1183 def close(self):
1184 if self.footer:
1184 if self.footer:
1185 self.ui.write(self.footer)
1185 self.ui.write(self.footer)
1186
1186
1187 def show(self, ctx, copies=None, matchfn=None, **props):
1187 def show(self, ctx, copies=None, matchfn=None, **props):
1188 if self.buffered:
1188 if self.buffered:
1189 self.ui.pushbuffer(labeled=True)
1189 self.ui.pushbuffer(labeled=True)
1190 self._show(ctx, copies, matchfn, props)
1190 self._show(ctx, copies, matchfn, props)
1191 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
1191 self.hunk[ctx.rev()] = self.ui.popbuffer()
1192 else:
1192 else:
1193 self._show(ctx, copies, matchfn, props)
1193 self._show(ctx, copies, matchfn, props)
1194
1194
1195 def _show(self, ctx, copies, matchfn, props):
1195 def _show(self, ctx, copies, matchfn, props):
1196 '''show a single changeset or file revision'''
1196 '''show a single changeset or file revision'''
1197 changenode = ctx.node()
1197 changenode = ctx.node()
1198 rev = ctx.rev()
1198 rev = ctx.rev()
1199 if self.ui.debugflag:
1199 if self.ui.debugflag:
1200 hexfunc = hex
1200 hexfunc = hex
1201 else:
1201 else:
1202 hexfunc = short
1202 hexfunc = short
1203 # as of now, wctx.node() and wctx.rev() return None, but we want to
1203 # as of now, wctx.node() and wctx.rev() return None, but we want to
1204 # show the same values as {node} and {rev} templatekw
1204 # show the same values as {node} and {rev} templatekw
1205 revnode = (scmutil.intrev(rev), hexfunc(bin(ctx.hex())))
1205 revnode = (scmutil.intrev(rev), hexfunc(bin(ctx.hex())))
1206
1206
1207 if self.ui.quiet:
1207 if self.ui.quiet:
1208 self.ui.write("%d:%s\n" % revnode, label='log.node')
1208 self.ui.write("%d:%s\n" % revnode, label='log.node')
1209 return
1209 return
1210
1210
1211 date = util.datestr(ctx.date())
1211 date = util.datestr(ctx.date())
1212
1212
1213 # i18n: column positioning for "hg log"
1213 # i18n: column positioning for "hg log"
1214 self.ui.write(_("changeset: %d:%s\n") % revnode,
1214 self.ui.write(_("changeset: %d:%s\n") % revnode,
1215 label='log.changeset changeset.%s' % ctx.phasestr())
1215 label='log.changeset changeset.%s' % ctx.phasestr())
1216
1216
1217 # branches are shown first before any other names due to backwards
1217 # branches are shown first before any other names due to backwards
1218 # compatibility
1218 # compatibility
1219 branch = ctx.branch()
1219 branch = ctx.branch()
1220 # don't show the default branch name
1220 # don't show the default branch name
1221 if branch != 'default':
1221 if branch != 'default':
1222 # i18n: column positioning for "hg log"
1222 # i18n: column positioning for "hg log"
1223 self.ui.write(_("branch: %s\n") % branch,
1223 self.ui.write(_("branch: %s\n") % branch,
1224 label='log.branch')
1224 label='log.branch')
1225
1225
1226 for name, ns in self.repo.names.iteritems():
1226 for name, ns in self.repo.names.iteritems():
1227 # branches has special logic already handled above, so here we just
1227 # branches has special logic already handled above, so here we just
1228 # skip it
1228 # skip it
1229 if name == 'branches':
1229 if name == 'branches':
1230 continue
1230 continue
1231 # we will use the templatename as the color name since those two
1231 # we will use the templatename as the color name since those two
1232 # should be the same
1232 # should be the same
1233 for name in ns.names(self.repo, changenode):
1233 for name in ns.names(self.repo, changenode):
1234 self.ui.write(ns.logfmt % name,
1234 self.ui.write(ns.logfmt % name,
1235 label='log.%s' % ns.colorname)
1235 label='log.%s' % ns.colorname)
1236 if self.ui.debugflag:
1236 if self.ui.debugflag:
1237 # i18n: column positioning for "hg log"
1237 # i18n: column positioning for "hg log"
1238 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1238 self.ui.write(_("phase: %s\n") % ctx.phasestr(),
1239 label='log.phase')
1239 label='log.phase')
1240 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1240 for pctx in scmutil.meaningfulparents(self.repo, ctx):
1241 label = 'log.parent changeset.%s' % pctx.phasestr()
1241 label = 'log.parent changeset.%s' % pctx.phasestr()
1242 # i18n: column positioning for "hg log"
1242 # i18n: column positioning for "hg log"
1243 self.ui.write(_("parent: %d:%s\n")
1243 self.ui.write(_("parent: %d:%s\n")
1244 % (pctx.rev(), hexfunc(pctx.node())),
1244 % (pctx.rev(), hexfunc(pctx.node())),
1245 label=label)
1245 label=label)
1246
1246
1247 if self.ui.debugflag and rev is not None:
1247 if self.ui.debugflag and rev is not None:
1248 mnode = ctx.manifestnode()
1248 mnode = ctx.manifestnode()
1249 # i18n: column positioning for "hg log"
1249 # i18n: column positioning for "hg log"
1250 self.ui.write(_("manifest: %d:%s\n") %
1250 self.ui.write(_("manifest: %d:%s\n") %
1251 (self.repo.manifest.rev(mnode), hex(mnode)),
1251 (self.repo.manifest.rev(mnode), hex(mnode)),
1252 label='ui.debug log.manifest')
1252 label='ui.debug log.manifest')
1253 # i18n: column positioning for "hg log"
1253 # i18n: column positioning for "hg log"
1254 self.ui.write(_("user: %s\n") % ctx.user(),
1254 self.ui.write(_("user: %s\n") % ctx.user(),
1255 label='log.user')
1255 label='log.user')
1256 # i18n: column positioning for "hg log"
1256 # i18n: column positioning for "hg log"
1257 self.ui.write(_("date: %s\n") % date,
1257 self.ui.write(_("date: %s\n") % date,
1258 label='log.date')
1258 label='log.date')
1259
1259
1260 if self.ui.debugflag:
1260 if self.ui.debugflag:
1261 files = ctx.p1().status(ctx)[:3]
1261 files = ctx.p1().status(ctx)[:3]
1262 for key, value in zip([# i18n: column positioning for "hg log"
1262 for key, value in zip([# i18n: column positioning for "hg log"
1263 _("files:"),
1263 _("files:"),
1264 # i18n: column positioning for "hg log"
1264 # i18n: column positioning for "hg log"
1265 _("files+:"),
1265 _("files+:"),
1266 # i18n: column positioning for "hg log"
1266 # i18n: column positioning for "hg log"
1267 _("files-:")], files):
1267 _("files-:")], files):
1268 if value:
1268 if value:
1269 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1269 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
1270 label='ui.debug log.files')
1270 label='ui.debug log.files')
1271 elif ctx.files() and self.ui.verbose:
1271 elif ctx.files() and self.ui.verbose:
1272 # i18n: column positioning for "hg log"
1272 # i18n: column positioning for "hg log"
1273 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1273 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
1274 label='ui.note log.files')
1274 label='ui.note log.files')
1275 if copies and self.ui.verbose:
1275 if copies and self.ui.verbose:
1276 copies = ['%s (%s)' % c for c in copies]
1276 copies = ['%s (%s)' % c for c in copies]
1277 # i18n: column positioning for "hg log"
1277 # i18n: column positioning for "hg log"
1278 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1278 self.ui.write(_("copies: %s\n") % ' '.join(copies),
1279 label='ui.note log.copies')
1279 label='ui.note log.copies')
1280
1280
1281 extra = ctx.extra()
1281 extra = ctx.extra()
1282 if extra and self.ui.debugflag:
1282 if extra and self.ui.debugflag:
1283 for key, value in sorted(extra.items()):
1283 for key, value in sorted(extra.items()):
1284 # i18n: column positioning for "hg log"
1284 # i18n: column positioning for "hg log"
1285 self.ui.write(_("extra: %s=%s\n")
1285 self.ui.write(_("extra: %s=%s\n")
1286 % (key, value.encode('string_escape')),
1286 % (key, value.encode('string_escape')),
1287 label='ui.debug log.extra')
1287 label='ui.debug log.extra')
1288
1288
1289 description = ctx.description().strip()
1289 description = ctx.description().strip()
1290 if description:
1290 if description:
1291 if self.ui.verbose:
1291 if self.ui.verbose:
1292 self.ui.write(_("description:\n"),
1292 self.ui.write(_("description:\n"),
1293 label='ui.note log.description')
1293 label='ui.note log.description')
1294 self.ui.write(description,
1294 self.ui.write(description,
1295 label='ui.note log.description')
1295 label='ui.note log.description')
1296 self.ui.write("\n\n")
1296 self.ui.write("\n\n")
1297 else:
1297 else:
1298 # i18n: column positioning for "hg log"
1298 # i18n: column positioning for "hg log"
1299 self.ui.write(_("summary: %s\n") %
1299 self.ui.write(_("summary: %s\n") %
1300 description.splitlines()[0],
1300 description.splitlines()[0],
1301 label='log.summary')
1301 label='log.summary')
1302 self.ui.write("\n")
1302 self.ui.write("\n")
1303
1303
1304 self.showpatch(ctx, matchfn)
1304 self.showpatch(ctx, matchfn)
1305
1305
1306 def showpatch(self, ctx, matchfn):
1306 def showpatch(self, ctx, matchfn):
1307 if not matchfn:
1307 if not matchfn:
1308 matchfn = self.matchfn
1308 matchfn = self.matchfn
1309 if matchfn:
1309 if matchfn:
1310 stat = self.diffopts.get('stat')
1310 stat = self.diffopts.get('stat')
1311 diff = self.diffopts.get('patch')
1311 diff = self.diffopts.get('patch')
1312 diffopts = patch.diffallopts(self.ui, self.diffopts)
1312 diffopts = patch.diffallopts(self.ui, self.diffopts)
1313 node = ctx.node()
1313 node = ctx.node()
1314 prev = ctx.p1()
1314 prev = ctx.p1()
1315 if stat:
1315 if stat:
1316 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1316 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1317 match=matchfn, stat=True)
1317 match=matchfn, stat=True)
1318 if diff:
1318 if diff:
1319 if stat:
1319 if stat:
1320 self.ui.write("\n")
1320 self.ui.write("\n")
1321 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1321 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1322 match=matchfn, stat=False)
1322 match=matchfn, stat=False)
1323 self.ui.write("\n")
1323 self.ui.write("\n")
1324
1324
1325 class jsonchangeset(changeset_printer):
1325 class jsonchangeset(changeset_printer):
1326 '''format changeset information.'''
1326 '''format changeset information.'''
1327
1327
1328 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1328 def __init__(self, ui, repo, matchfn, diffopts, buffered):
1329 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1329 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1330 self.cache = {}
1330 self.cache = {}
1331 self._first = True
1331 self._first = True
1332
1332
1333 def close(self):
1333 def close(self):
1334 if not self._first:
1334 if not self._first:
1335 self.ui.write("\n]\n")
1335 self.ui.write("\n]\n")
1336 else:
1336 else:
1337 self.ui.write("[]\n")
1337 self.ui.write("[]\n")
1338
1338
1339 def _show(self, ctx, copies, matchfn, props):
1339 def _show(self, ctx, copies, matchfn, props):
1340 '''show a single changeset or file revision'''
1340 '''show a single changeset or file revision'''
1341 rev = ctx.rev()
1341 rev = ctx.rev()
1342 if rev is None:
1342 if rev is None:
1343 jrev = jnode = 'null'
1343 jrev = jnode = 'null'
1344 else:
1344 else:
1345 jrev = str(rev)
1345 jrev = str(rev)
1346 jnode = '"%s"' % hex(ctx.node())
1346 jnode = '"%s"' % hex(ctx.node())
1347 j = encoding.jsonescape
1347 j = encoding.jsonescape
1348
1348
1349 if self._first:
1349 if self._first:
1350 self.ui.write("[\n {")
1350 self.ui.write("[\n {")
1351 self._first = False
1351 self._first = False
1352 else:
1352 else:
1353 self.ui.write(",\n {")
1353 self.ui.write(",\n {")
1354
1354
1355 if self.ui.quiet:
1355 if self.ui.quiet:
1356 self.ui.write('\n "rev": %s' % jrev)
1356 self.ui.write('\n "rev": %s' % jrev)
1357 self.ui.write(',\n "node": %s' % jnode)
1357 self.ui.write(',\n "node": %s' % jnode)
1358 self.ui.write('\n }')
1358 self.ui.write('\n }')
1359 return
1359 return
1360
1360
1361 self.ui.write('\n "rev": %s' % jrev)
1361 self.ui.write('\n "rev": %s' % jrev)
1362 self.ui.write(',\n "node": %s' % jnode)
1362 self.ui.write(',\n "node": %s' % jnode)
1363 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1363 self.ui.write(',\n "branch": "%s"' % j(ctx.branch()))
1364 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1364 self.ui.write(',\n "phase": "%s"' % ctx.phasestr())
1365 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1365 self.ui.write(',\n "user": "%s"' % j(ctx.user()))
1366 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1366 self.ui.write(',\n "date": [%d, %d]' % ctx.date())
1367 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1367 self.ui.write(',\n "desc": "%s"' % j(ctx.description()))
1368
1368
1369 self.ui.write(',\n "bookmarks": [%s]' %
1369 self.ui.write(',\n "bookmarks": [%s]' %
1370 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1370 ", ".join('"%s"' % j(b) for b in ctx.bookmarks()))
1371 self.ui.write(',\n "tags": [%s]' %
1371 self.ui.write(',\n "tags": [%s]' %
1372 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1372 ", ".join('"%s"' % j(t) for t in ctx.tags()))
1373 self.ui.write(',\n "parents": [%s]' %
1373 self.ui.write(',\n "parents": [%s]' %
1374 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1374 ", ".join('"%s"' % c.hex() for c in ctx.parents()))
1375
1375
1376 if self.ui.debugflag:
1376 if self.ui.debugflag:
1377 if rev is None:
1377 if rev is None:
1378 jmanifestnode = 'null'
1378 jmanifestnode = 'null'
1379 else:
1379 else:
1380 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1380 jmanifestnode = '"%s"' % hex(ctx.manifestnode())
1381 self.ui.write(',\n "manifest": %s' % jmanifestnode)
1381 self.ui.write(',\n "manifest": %s' % jmanifestnode)
1382
1382
1383 self.ui.write(',\n "extra": {%s}' %
1383 self.ui.write(',\n "extra": {%s}' %
1384 ", ".join('"%s": "%s"' % (j(k), j(v))
1384 ", ".join('"%s": "%s"' % (j(k), j(v))
1385 for k, v in ctx.extra().items()))
1385 for k, v in ctx.extra().items()))
1386
1386
1387 files = ctx.p1().status(ctx)
1387 files = ctx.p1().status(ctx)
1388 self.ui.write(',\n "modified": [%s]' %
1388 self.ui.write(',\n "modified": [%s]' %
1389 ", ".join('"%s"' % j(f) for f in files[0]))
1389 ", ".join('"%s"' % j(f) for f in files[0]))
1390 self.ui.write(',\n "added": [%s]' %
1390 self.ui.write(',\n "added": [%s]' %
1391 ", ".join('"%s"' % j(f) for f in files[1]))
1391 ", ".join('"%s"' % j(f) for f in files[1]))
1392 self.ui.write(',\n "removed": [%s]' %
1392 self.ui.write(',\n "removed": [%s]' %
1393 ", ".join('"%s"' % j(f) for f in files[2]))
1393 ", ".join('"%s"' % j(f) for f in files[2]))
1394
1394
1395 elif self.ui.verbose:
1395 elif self.ui.verbose:
1396 self.ui.write(',\n "files": [%s]' %
1396 self.ui.write(',\n "files": [%s]' %
1397 ", ".join('"%s"' % j(f) for f in ctx.files()))
1397 ", ".join('"%s"' % j(f) for f in ctx.files()))
1398
1398
1399 if copies:
1399 if copies:
1400 self.ui.write(',\n "copies": {%s}' %
1400 self.ui.write(',\n "copies": {%s}' %
1401 ", ".join('"%s": "%s"' % (j(k), j(v))
1401 ", ".join('"%s": "%s"' % (j(k), j(v))
1402 for k, v in copies))
1402 for k, v in copies))
1403
1403
1404 matchfn = self.matchfn
1404 matchfn = self.matchfn
1405 if matchfn:
1405 if matchfn:
1406 stat = self.diffopts.get('stat')
1406 stat = self.diffopts.get('stat')
1407 diff = self.diffopts.get('patch')
1407 diff = self.diffopts.get('patch')
1408 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1408 diffopts = patch.difffeatureopts(self.ui, self.diffopts, git=True)
1409 node, prev = ctx.node(), ctx.p1().node()
1409 node, prev = ctx.node(), ctx.p1().node()
1410 if stat:
1410 if stat:
1411 self.ui.pushbuffer()
1411 self.ui.pushbuffer()
1412 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1412 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1413 match=matchfn, stat=True)
1413 match=matchfn, stat=True)
1414 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1414 self.ui.write(',\n "diffstat": "%s"' % j(self.ui.popbuffer()))
1415 if diff:
1415 if diff:
1416 self.ui.pushbuffer()
1416 self.ui.pushbuffer()
1417 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1417 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
1418 match=matchfn, stat=False)
1418 match=matchfn, stat=False)
1419 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1419 self.ui.write(',\n "diff": "%s"' % j(self.ui.popbuffer()))
1420
1420
1421 self.ui.write("\n }")
1421 self.ui.write("\n }")
1422
1422
1423 class changeset_templater(changeset_printer):
1423 class changeset_templater(changeset_printer):
1424 '''format changeset information.'''
1424 '''format changeset information.'''
1425
1425
1426 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1426 def __init__(self, ui, repo, matchfn, diffopts, tmpl, mapfile, buffered):
1427 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1427 changeset_printer.__init__(self, ui, repo, matchfn, diffopts, buffered)
1428 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1428 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
1429 defaulttempl = {
1429 defaulttempl = {
1430 'parent': '{rev}:{node|formatnode} ',
1430 'parent': '{rev}:{node|formatnode} ',
1431 'manifest': '{rev}:{node|formatnode}',
1431 'manifest': '{rev}:{node|formatnode}',
1432 'file_copy': '{name} ({source})',
1432 'file_copy': '{name} ({source})',
1433 'extra': '{key}={value|stringescape}'
1433 'extra': '{key}={value|stringescape}'
1434 }
1434 }
1435 # filecopy is preserved for compatibility reasons
1435 # filecopy is preserved for compatibility reasons
1436 defaulttempl['filecopy'] = defaulttempl['file_copy']
1436 defaulttempl['filecopy'] = defaulttempl['file_copy']
1437 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1437 self.t = templater.templater(mapfile, {'formatnode': formatnode},
1438 cache=defaulttempl)
1438 cache=defaulttempl)
1439 if tmpl:
1439 if tmpl:
1440 self.t.cache['changeset'] = tmpl
1440 self.t.cache['changeset'] = tmpl
1441
1441
1442 self.cache = {}
1442 self.cache = {}
1443
1443
1444 # find correct templates for current mode
1444 # find correct templates for current mode
1445 tmplmodes = [
1445 tmplmodes = [
1446 (True, None),
1446 (True, None),
1447 (self.ui.verbose, 'verbose'),
1447 (self.ui.verbose, 'verbose'),
1448 (self.ui.quiet, 'quiet'),
1448 (self.ui.quiet, 'quiet'),
1449 (self.ui.debugflag, 'debug'),
1449 (self.ui.debugflag, 'debug'),
1450 ]
1450 ]
1451
1451
1452 self._parts = {'header': '', 'footer': '', 'changeset': 'changeset',
1452 self._parts = {'header': '', 'footer': '', 'changeset': 'changeset',
1453 'docheader': '', 'docfooter': ''}
1453 'docheader': '', 'docfooter': ''}
1454 for mode, postfix in tmplmodes:
1454 for mode, postfix in tmplmodes:
1455 for t in self._parts:
1455 for t in self._parts:
1456 cur = t
1456 cur = t
1457 if postfix:
1457 if postfix:
1458 cur += "_" + postfix
1458 cur += "_" + postfix
1459 if mode and cur in self.t:
1459 if mode and cur in self.t:
1460 self._parts[t] = cur
1460 self._parts[t] = cur
1461
1461
1462 if self._parts['docheader']:
1462 if self._parts['docheader']:
1463 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1463 self.ui.write(templater.stringify(self.t(self._parts['docheader'])))
1464
1464
1465 def close(self):
1465 def close(self):
1466 if self._parts['docfooter']:
1466 if self._parts['docfooter']:
1467 if not self.footer:
1467 if not self.footer:
1468 self.footer = ""
1468 self.footer = ""
1469 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1469 self.footer += templater.stringify(self.t(self._parts['docfooter']))
1470 return super(changeset_templater, self).close()
1470 return super(changeset_templater, self).close()
1471
1471
1472 def _show(self, ctx, copies, matchfn, props):
1472 def _show(self, ctx, copies, matchfn, props):
1473 '''show a single changeset or file revision'''
1473 '''show a single changeset or file revision'''
1474 props = props.copy()
1474 props = props.copy()
1475 props.update(templatekw.keywords)
1475 props.update(templatekw.keywords)
1476 props['templ'] = self.t
1476 props['templ'] = self.t
1477 props['ctx'] = ctx
1477 props['ctx'] = ctx
1478 props['repo'] = self.repo
1478 props['repo'] = self.repo
1479 props['revcache'] = {'copies': copies}
1479 props['revcache'] = {'copies': copies}
1480 props['cache'] = self.cache
1480 props['cache'] = self.cache
1481
1481
1482 try:
1482 try:
1483 # write header
1483 # write header
1484 if self._parts['header']:
1484 if self._parts['header']:
1485 h = templater.stringify(self.t(self._parts['header'], **props))
1485 h = templater.stringify(self.t(self._parts['header'], **props))
1486 if self.buffered:
1486 if self.buffered:
1487 self.header[ctx.rev()] = h
1487 self.header[ctx.rev()] = h
1488 else:
1488 else:
1489 if self.lastheader != h:
1489 if self.lastheader != h:
1490 self.lastheader = h
1490 self.lastheader = h
1491 self.ui.write(h)
1491 self.ui.write(h)
1492
1492
1493 # write changeset metadata, then patch if requested
1493 # write changeset metadata, then patch if requested
1494 key = self._parts['changeset']
1494 key = self._parts['changeset']
1495 self.ui.write(templater.stringify(self.t(key, **props)))
1495 self.ui.write(templater.stringify(self.t(key, **props)))
1496 self.showpatch(ctx, matchfn)
1496 self.showpatch(ctx, matchfn)
1497
1497
1498 if self._parts['footer']:
1498 if self._parts['footer']:
1499 if not self.footer:
1499 if not self.footer:
1500 self.footer = templater.stringify(
1500 self.footer = templater.stringify(
1501 self.t(self._parts['footer'], **props))
1501 self.t(self._parts['footer'], **props))
1502 except KeyError as inst:
1502 except KeyError as inst:
1503 msg = _("%s: no key named '%s'")
1503 msg = _("%s: no key named '%s'")
1504 raise error.Abort(msg % (self.t.mapfile, inst.args[0]))
1504 raise error.Abort(msg % (self.t.mapfile, inst.args[0]))
1505 except SyntaxError as inst:
1505 except SyntaxError as inst:
1506 raise error.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1506 raise error.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
1507
1507
1508 def gettemplate(ui, tmpl, style):
1508 def gettemplate(ui, tmpl, style):
1509 """
1509 """
1510 Find the template matching the given template spec or style.
1510 Find the template matching the given template spec or style.
1511 """
1511 """
1512
1512
1513 # ui settings
1513 # ui settings
1514 if not tmpl and not style: # template are stronger than style
1514 if not tmpl and not style: # template are stronger than style
1515 tmpl = ui.config('ui', 'logtemplate')
1515 tmpl = ui.config('ui', 'logtemplate')
1516 if tmpl:
1516 if tmpl:
1517 try:
1517 try:
1518 tmpl = templater.unquotestring(tmpl)
1518 tmpl = templater.unquotestring(tmpl)
1519 except SyntaxError:
1519 except SyntaxError:
1520 pass
1520 pass
1521 return tmpl, None
1521 return tmpl, None
1522 else:
1522 else:
1523 style = util.expandpath(ui.config('ui', 'style', ''))
1523 style = util.expandpath(ui.config('ui', 'style', ''))
1524
1524
1525 if not tmpl and style:
1525 if not tmpl and style:
1526 mapfile = style
1526 mapfile = style
1527 if not os.path.split(mapfile)[0]:
1527 if not os.path.split(mapfile)[0]:
1528 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1528 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1529 or templater.templatepath(mapfile))
1529 or templater.templatepath(mapfile))
1530 if mapname:
1530 if mapname:
1531 mapfile = mapname
1531 mapfile = mapname
1532 return None, mapfile
1532 return None, mapfile
1533
1533
1534 if not tmpl:
1534 if not tmpl:
1535 return None, None
1535 return None, None
1536
1536
1537 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1537 return formatter.lookuptemplate(ui, 'changeset', tmpl)
1538
1538
1539 def show_changeset(ui, repo, opts, buffered=False):
1539 def show_changeset(ui, repo, opts, buffered=False):
1540 """show one changeset using template or regular display.
1540 """show one changeset using template or regular display.
1541
1541
1542 Display format will be the first non-empty hit of:
1542 Display format will be the first non-empty hit of:
1543 1. option 'template'
1543 1. option 'template'
1544 2. option 'style'
1544 2. option 'style'
1545 3. [ui] setting 'logtemplate'
1545 3. [ui] setting 'logtemplate'
1546 4. [ui] setting 'style'
1546 4. [ui] setting 'style'
1547 If all of these values are either the unset or the empty string,
1547 If all of these values are either the unset or the empty string,
1548 regular display via changeset_printer() is done.
1548 regular display via changeset_printer() is done.
1549 """
1549 """
1550 # options
1550 # options
1551 matchfn = None
1551 matchfn = None
1552 if opts.get('patch') or opts.get('stat'):
1552 if opts.get('patch') or opts.get('stat'):
1553 matchfn = scmutil.matchall(repo)
1553 matchfn = scmutil.matchall(repo)
1554
1554
1555 if opts.get('template') == 'json':
1555 if opts.get('template') == 'json':
1556 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1556 return jsonchangeset(ui, repo, matchfn, opts, buffered)
1557
1557
1558 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1558 tmpl, mapfile = gettemplate(ui, opts.get('template'), opts.get('style'))
1559
1559
1560 if not tmpl and not mapfile:
1560 if not tmpl and not mapfile:
1561 return changeset_printer(ui, repo, matchfn, opts, buffered)
1561 return changeset_printer(ui, repo, matchfn, opts, buffered)
1562
1562
1563 try:
1563 try:
1564 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1564 t = changeset_templater(ui, repo, matchfn, opts, tmpl, mapfile,
1565 buffered)
1565 buffered)
1566 except SyntaxError as inst:
1566 except SyntaxError as inst:
1567 raise error.Abort(inst.args[0])
1567 raise error.Abort(inst.args[0])
1568 return t
1568 return t
1569
1569
1570 def showmarker(ui, marker):
1570 def showmarker(ui, marker):
1571 """utility function to display obsolescence marker in a readable way
1571 """utility function to display obsolescence marker in a readable way
1572
1572
1573 To be used by debug function."""
1573 To be used by debug function."""
1574 ui.write(hex(marker.precnode()))
1574 ui.write(hex(marker.precnode()))
1575 for repl in marker.succnodes():
1575 for repl in marker.succnodes():
1576 ui.write(' ')
1576 ui.write(' ')
1577 ui.write(hex(repl))
1577 ui.write(hex(repl))
1578 ui.write(' %X ' % marker.flags())
1578 ui.write(' %X ' % marker.flags())
1579 parents = marker.parentnodes()
1579 parents = marker.parentnodes()
1580 if parents is not None:
1580 if parents is not None:
1581 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1581 ui.write('{%s} ' % ', '.join(hex(p) for p in parents))
1582 ui.write('(%s) ' % util.datestr(marker.date()))
1582 ui.write('(%s) ' % util.datestr(marker.date()))
1583 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1583 ui.write('{%s}' % (', '.join('%r: %r' % t for t in
1584 sorted(marker.metadata().items())
1584 sorted(marker.metadata().items())
1585 if t[0] != 'date')))
1585 if t[0] != 'date')))
1586 ui.write('\n')
1586 ui.write('\n')
1587
1587
1588 def finddate(ui, repo, date):
1588 def finddate(ui, repo, date):
1589 """Find the tipmost changeset that matches the given date spec"""
1589 """Find the tipmost changeset that matches the given date spec"""
1590
1590
1591 df = util.matchdate(date)
1591 df = util.matchdate(date)
1592 m = scmutil.matchall(repo)
1592 m = scmutil.matchall(repo)
1593 results = {}
1593 results = {}
1594
1594
1595 def prep(ctx, fns):
1595 def prep(ctx, fns):
1596 d = ctx.date()
1596 d = ctx.date()
1597 if df(d[0]):
1597 if df(d[0]):
1598 results[ctx.rev()] = d
1598 results[ctx.rev()] = d
1599
1599
1600 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1600 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1601 rev = ctx.rev()
1601 rev = ctx.rev()
1602 if rev in results:
1602 if rev in results:
1603 ui.status(_("found revision %s from %s\n") %
1603 ui.status(_("found revision %s from %s\n") %
1604 (rev, util.datestr(results[rev])))
1604 (rev, util.datestr(results[rev])))
1605 return str(rev)
1605 return str(rev)
1606
1606
1607 raise error.Abort(_("revision matching date not found"))
1607 raise error.Abort(_("revision matching date not found"))
1608
1608
1609 def increasingwindows(windowsize=8, sizelimit=512):
1609 def increasingwindows(windowsize=8, sizelimit=512):
1610 while True:
1610 while True:
1611 yield windowsize
1611 yield windowsize
1612 if windowsize < sizelimit:
1612 if windowsize < sizelimit:
1613 windowsize *= 2
1613 windowsize *= 2
1614
1614
1615 class FileWalkError(Exception):
1615 class FileWalkError(Exception):
1616 pass
1616 pass
1617
1617
1618 def walkfilerevs(repo, match, follow, revs, fncache):
1618 def walkfilerevs(repo, match, follow, revs, fncache):
1619 '''Walks the file history for the matched files.
1619 '''Walks the file history for the matched files.
1620
1620
1621 Returns the changeset revs that are involved in the file history.
1621 Returns the changeset revs that are involved in the file history.
1622
1622
1623 Throws FileWalkError if the file history can't be walked using
1623 Throws FileWalkError if the file history can't be walked using
1624 filelogs alone.
1624 filelogs alone.
1625 '''
1625 '''
1626 wanted = set()
1626 wanted = set()
1627 copies = []
1627 copies = []
1628 minrev, maxrev = min(revs), max(revs)
1628 minrev, maxrev = min(revs), max(revs)
1629 def filerevgen(filelog, last):
1629 def filerevgen(filelog, last):
1630 """
1630 """
1631 Only files, no patterns. Check the history of each file.
1631 Only files, no patterns. Check the history of each file.
1632
1632
1633 Examines filelog entries within minrev, maxrev linkrev range
1633 Examines filelog entries within minrev, maxrev linkrev range
1634 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1634 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1635 tuples in backwards order
1635 tuples in backwards order
1636 """
1636 """
1637 cl_count = len(repo)
1637 cl_count = len(repo)
1638 revs = []
1638 revs = []
1639 for j in xrange(0, last + 1):
1639 for j in xrange(0, last + 1):
1640 linkrev = filelog.linkrev(j)
1640 linkrev = filelog.linkrev(j)
1641 if linkrev < minrev:
1641 if linkrev < minrev:
1642 continue
1642 continue
1643 # only yield rev for which we have the changelog, it can
1643 # only yield rev for which we have the changelog, it can
1644 # happen while doing "hg log" during a pull or commit
1644 # happen while doing "hg log" during a pull or commit
1645 if linkrev >= cl_count:
1645 if linkrev >= cl_count:
1646 break
1646 break
1647
1647
1648 parentlinkrevs = []
1648 parentlinkrevs = []
1649 for p in filelog.parentrevs(j):
1649 for p in filelog.parentrevs(j):
1650 if p != nullrev:
1650 if p != nullrev:
1651 parentlinkrevs.append(filelog.linkrev(p))
1651 parentlinkrevs.append(filelog.linkrev(p))
1652 n = filelog.node(j)
1652 n = filelog.node(j)
1653 revs.append((linkrev, parentlinkrevs,
1653 revs.append((linkrev, parentlinkrevs,
1654 follow and filelog.renamed(n)))
1654 follow and filelog.renamed(n)))
1655
1655
1656 return reversed(revs)
1656 return reversed(revs)
1657 def iterfiles():
1657 def iterfiles():
1658 pctx = repo['.']
1658 pctx = repo['.']
1659 for filename in match.files():
1659 for filename in match.files():
1660 if follow:
1660 if follow:
1661 if filename not in pctx:
1661 if filename not in pctx:
1662 raise error.Abort(_('cannot follow file not in parent '
1662 raise error.Abort(_('cannot follow file not in parent '
1663 'revision: "%s"') % filename)
1663 'revision: "%s"') % filename)
1664 yield filename, pctx[filename].filenode()
1664 yield filename, pctx[filename].filenode()
1665 else:
1665 else:
1666 yield filename, None
1666 yield filename, None
1667 for filename_node in copies:
1667 for filename_node in copies:
1668 yield filename_node
1668 yield filename_node
1669
1669
1670 for file_, node in iterfiles():
1670 for file_, node in iterfiles():
1671 filelog = repo.file(file_)
1671 filelog = repo.file(file_)
1672 if not len(filelog):
1672 if not len(filelog):
1673 if node is None:
1673 if node is None:
1674 # A zero count may be a directory or deleted file, so
1674 # A zero count may be a directory or deleted file, so
1675 # try to find matching entries on the slow path.
1675 # try to find matching entries on the slow path.
1676 if follow:
1676 if follow:
1677 raise error.Abort(
1677 raise error.Abort(
1678 _('cannot follow nonexistent file: "%s"') % file_)
1678 _('cannot follow nonexistent file: "%s"') % file_)
1679 raise FileWalkError("Cannot walk via filelog")
1679 raise FileWalkError("Cannot walk via filelog")
1680 else:
1680 else:
1681 continue
1681 continue
1682
1682
1683 if node is None:
1683 if node is None:
1684 last = len(filelog) - 1
1684 last = len(filelog) - 1
1685 else:
1685 else:
1686 last = filelog.rev(node)
1686 last = filelog.rev(node)
1687
1687
1688 # keep track of all ancestors of the file
1688 # keep track of all ancestors of the file
1689 ancestors = set([filelog.linkrev(last)])
1689 ancestors = set([filelog.linkrev(last)])
1690
1690
1691 # iterate from latest to oldest revision
1691 # iterate from latest to oldest revision
1692 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1692 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1693 if not follow:
1693 if not follow:
1694 if rev > maxrev:
1694 if rev > maxrev:
1695 continue
1695 continue
1696 else:
1696 else:
1697 # Note that last might not be the first interesting
1697 # Note that last might not be the first interesting
1698 # rev to us:
1698 # rev to us:
1699 # if the file has been changed after maxrev, we'll
1699 # if the file has been changed after maxrev, we'll
1700 # have linkrev(last) > maxrev, and we still need
1700 # have linkrev(last) > maxrev, and we still need
1701 # to explore the file graph
1701 # to explore the file graph
1702 if rev not in ancestors:
1702 if rev not in ancestors:
1703 continue
1703 continue
1704 # XXX insert 1327 fix here
1704 # XXX insert 1327 fix here
1705 if flparentlinkrevs:
1705 if flparentlinkrevs:
1706 ancestors.update(flparentlinkrevs)
1706 ancestors.update(flparentlinkrevs)
1707
1707
1708 fncache.setdefault(rev, []).append(file_)
1708 fncache.setdefault(rev, []).append(file_)
1709 wanted.add(rev)
1709 wanted.add(rev)
1710 if copied:
1710 if copied:
1711 copies.append(copied)
1711 copies.append(copied)
1712
1712
1713 return wanted
1713 return wanted
1714
1714
1715 class _followfilter(object):
1715 class _followfilter(object):
1716 def __init__(self, repo, onlyfirst=False):
1716 def __init__(self, repo, onlyfirst=False):
1717 self.repo = repo
1717 self.repo = repo
1718 self.startrev = nullrev
1718 self.startrev = nullrev
1719 self.roots = set()
1719 self.roots = set()
1720 self.onlyfirst = onlyfirst
1720 self.onlyfirst = onlyfirst
1721
1721
1722 def match(self, rev):
1722 def match(self, rev):
1723 def realparents(rev):
1723 def realparents(rev):
1724 if self.onlyfirst:
1724 if self.onlyfirst:
1725 return self.repo.changelog.parentrevs(rev)[0:1]
1725 return self.repo.changelog.parentrevs(rev)[0:1]
1726 else:
1726 else:
1727 return filter(lambda x: x != nullrev,
1727 return filter(lambda x: x != nullrev,
1728 self.repo.changelog.parentrevs(rev))
1728 self.repo.changelog.parentrevs(rev))
1729
1729
1730 if self.startrev == nullrev:
1730 if self.startrev == nullrev:
1731 self.startrev = rev
1731 self.startrev = rev
1732 return True
1732 return True
1733
1733
1734 if rev > self.startrev:
1734 if rev > self.startrev:
1735 # forward: all descendants
1735 # forward: all descendants
1736 if not self.roots:
1736 if not self.roots:
1737 self.roots.add(self.startrev)
1737 self.roots.add(self.startrev)
1738 for parent in realparents(rev):
1738 for parent in realparents(rev):
1739 if parent in self.roots:
1739 if parent in self.roots:
1740 self.roots.add(rev)
1740 self.roots.add(rev)
1741 return True
1741 return True
1742 else:
1742 else:
1743 # backwards: all parents
1743 # backwards: all parents
1744 if not self.roots:
1744 if not self.roots:
1745 self.roots.update(realparents(self.startrev))
1745 self.roots.update(realparents(self.startrev))
1746 if rev in self.roots:
1746 if rev in self.roots:
1747 self.roots.remove(rev)
1747 self.roots.remove(rev)
1748 self.roots.update(realparents(rev))
1748 self.roots.update(realparents(rev))
1749 return True
1749 return True
1750
1750
1751 return False
1751 return False
1752
1752
1753 def walkchangerevs(repo, match, opts, prepare):
1753 def walkchangerevs(repo, match, opts, prepare):
1754 '''Iterate over files and the revs in which they changed.
1754 '''Iterate over files and the revs in which they changed.
1755
1755
1756 Callers most commonly need to iterate backwards over the history
1756 Callers most commonly need to iterate backwards over the history
1757 in which they are interested. Doing so has awful (quadratic-looking)
1757 in which they are interested. Doing so has awful (quadratic-looking)
1758 performance, so we use iterators in a "windowed" way.
1758 performance, so we use iterators in a "windowed" way.
1759
1759
1760 We walk a window of revisions in the desired order. Within the
1760 We walk a window of revisions in the desired order. Within the
1761 window, we first walk forwards to gather data, then in the desired
1761 window, we first walk forwards to gather data, then in the desired
1762 order (usually backwards) to display it.
1762 order (usually backwards) to display it.
1763
1763
1764 This function returns an iterator yielding contexts. Before
1764 This function returns an iterator yielding contexts. Before
1765 yielding each context, the iterator will first call the prepare
1765 yielding each context, the iterator will first call the prepare
1766 function on each context in the window in forward order.'''
1766 function on each context in the window in forward order.'''
1767
1767
1768 follow = opts.get('follow') or opts.get('follow_first')
1768 follow = opts.get('follow') or opts.get('follow_first')
1769 revs = _logrevs(repo, opts)
1769 revs = _logrevs(repo, opts)
1770 if not revs:
1770 if not revs:
1771 return []
1771 return []
1772 wanted = set()
1772 wanted = set()
1773 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1773 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1774 opts.get('removed'))
1774 opts.get('removed'))
1775 fncache = {}
1775 fncache = {}
1776 change = repo.changectx
1776 change = repo.changectx
1777
1777
1778 # First step is to fill wanted, the set of revisions that we want to yield.
1778 # First step is to fill wanted, the set of revisions that we want to yield.
1779 # When it does not induce extra cost, we also fill fncache for revisions in
1779 # When it does not induce extra cost, we also fill fncache for revisions in
1780 # wanted: a cache of filenames that were changed (ctx.files()) and that
1780 # wanted: a cache of filenames that were changed (ctx.files()) and that
1781 # match the file filtering conditions.
1781 # match the file filtering conditions.
1782
1782
1783 if match.always():
1783 if match.always():
1784 # No files, no patterns. Display all revs.
1784 # No files, no patterns. Display all revs.
1785 wanted = revs
1785 wanted = revs
1786 elif not slowpath:
1786 elif not slowpath:
1787 # We only have to read through the filelog to find wanted revisions
1787 # We only have to read through the filelog to find wanted revisions
1788
1788
1789 try:
1789 try:
1790 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1790 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1791 except FileWalkError:
1791 except FileWalkError:
1792 slowpath = True
1792 slowpath = True
1793
1793
1794 # We decided to fall back to the slowpath because at least one
1794 # We decided to fall back to the slowpath because at least one
1795 # of the paths was not a file. Check to see if at least one of them
1795 # of the paths was not a file. Check to see if at least one of them
1796 # existed in history, otherwise simply return
1796 # existed in history, otherwise simply return
1797 for path in match.files():
1797 for path in match.files():
1798 if path == '.' or path in repo.store:
1798 if path == '.' or path in repo.store:
1799 break
1799 break
1800 else:
1800 else:
1801 return []
1801 return []
1802
1802
1803 if slowpath:
1803 if slowpath:
1804 # We have to read the changelog to match filenames against
1804 # We have to read the changelog to match filenames against
1805 # changed files
1805 # changed files
1806
1806
1807 if follow:
1807 if follow:
1808 raise error.Abort(_('can only follow copies/renames for explicit '
1808 raise error.Abort(_('can only follow copies/renames for explicit '
1809 'filenames'))
1809 'filenames'))
1810
1810
1811 # The slow path checks files modified in every changeset.
1811 # The slow path checks files modified in every changeset.
1812 # This is really slow on large repos, so compute the set lazily.
1812 # This is really slow on large repos, so compute the set lazily.
1813 class lazywantedset(object):
1813 class lazywantedset(object):
1814 def __init__(self):
1814 def __init__(self):
1815 self.set = set()
1815 self.set = set()
1816 self.revs = set(revs)
1816 self.revs = set(revs)
1817
1817
1818 # No need to worry about locality here because it will be accessed
1818 # No need to worry about locality here because it will be accessed
1819 # in the same order as the increasing window below.
1819 # in the same order as the increasing window below.
1820 def __contains__(self, value):
1820 def __contains__(self, value):
1821 if value in self.set:
1821 if value in self.set:
1822 return True
1822 return True
1823 elif not value in self.revs:
1823 elif not value in self.revs:
1824 return False
1824 return False
1825 else:
1825 else:
1826 self.revs.discard(value)
1826 self.revs.discard(value)
1827 ctx = change(value)
1827 ctx = change(value)
1828 matches = filter(match, ctx.files())
1828 matches = filter(match, ctx.files())
1829 if matches:
1829 if matches:
1830 fncache[value] = matches
1830 fncache[value] = matches
1831 self.set.add(value)
1831 self.set.add(value)
1832 return True
1832 return True
1833 return False
1833 return False
1834
1834
1835 def discard(self, value):
1835 def discard(self, value):
1836 self.revs.discard(value)
1836 self.revs.discard(value)
1837 self.set.discard(value)
1837 self.set.discard(value)
1838
1838
1839 wanted = lazywantedset()
1839 wanted = lazywantedset()
1840
1840
1841 # it might be worthwhile to do this in the iterator if the rev range
1841 # it might be worthwhile to do this in the iterator if the rev range
1842 # is descending and the prune args are all within that range
1842 # is descending and the prune args are all within that range
1843 for rev in opts.get('prune', ()):
1843 for rev in opts.get('prune', ()):
1844 rev = repo[rev].rev()
1844 rev = repo[rev].rev()
1845 ff = _followfilter(repo)
1845 ff = _followfilter(repo)
1846 stop = min(revs[0], revs[-1])
1846 stop = min(revs[0], revs[-1])
1847 for x in xrange(rev, stop - 1, -1):
1847 for x in xrange(rev, stop - 1, -1):
1848 if ff.match(x):
1848 if ff.match(x):
1849 wanted = wanted - [x]
1849 wanted = wanted - [x]
1850
1850
1851 # Now that wanted is correctly initialized, we can iterate over the
1851 # Now that wanted is correctly initialized, we can iterate over the
1852 # revision range, yielding only revisions in wanted.
1852 # revision range, yielding only revisions in wanted.
1853 def iterate():
1853 def iterate():
1854 if follow and match.always():
1854 if follow and match.always():
1855 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1855 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1856 def want(rev):
1856 def want(rev):
1857 return ff.match(rev) and rev in wanted
1857 return ff.match(rev) and rev in wanted
1858 else:
1858 else:
1859 def want(rev):
1859 def want(rev):
1860 return rev in wanted
1860 return rev in wanted
1861
1861
1862 it = iter(revs)
1862 it = iter(revs)
1863 stopiteration = False
1863 stopiteration = False
1864 for windowsize in increasingwindows():
1864 for windowsize in increasingwindows():
1865 nrevs = []
1865 nrevs = []
1866 for i in xrange(windowsize):
1866 for i in xrange(windowsize):
1867 rev = next(it, None)
1867 rev = next(it, None)
1868 if rev is None:
1868 if rev is None:
1869 stopiteration = True
1869 stopiteration = True
1870 break
1870 break
1871 elif want(rev):
1871 elif want(rev):
1872 nrevs.append(rev)
1872 nrevs.append(rev)
1873 for rev in sorted(nrevs):
1873 for rev in sorted(nrevs):
1874 fns = fncache.get(rev)
1874 fns = fncache.get(rev)
1875 ctx = change(rev)
1875 ctx = change(rev)
1876 if not fns:
1876 if not fns:
1877 def fns_generator():
1877 def fns_generator():
1878 for f in ctx.files():
1878 for f in ctx.files():
1879 if match(f):
1879 if match(f):
1880 yield f
1880 yield f
1881 fns = fns_generator()
1881 fns = fns_generator()
1882 prepare(ctx, fns)
1882 prepare(ctx, fns)
1883 for rev in nrevs:
1883 for rev in nrevs:
1884 yield change(rev)
1884 yield change(rev)
1885
1885
1886 if stopiteration:
1886 if stopiteration:
1887 break
1887 break
1888
1888
1889 return iterate()
1889 return iterate()
1890
1890
1891 def _makefollowlogfilematcher(repo, files, followfirst):
1891 def _makefollowlogfilematcher(repo, files, followfirst):
1892 # When displaying a revision with --patch --follow FILE, we have
1892 # When displaying a revision with --patch --follow FILE, we have
1893 # to know which file of the revision must be diffed. With
1893 # to know which file of the revision must be diffed. With
1894 # --follow, we want the names of the ancestors of FILE in the
1894 # --follow, we want the names of the ancestors of FILE in the
1895 # revision, stored in "fcache". "fcache" is populated by
1895 # revision, stored in "fcache". "fcache" is populated by
1896 # reproducing the graph traversal already done by --follow revset
1896 # reproducing the graph traversal already done by --follow revset
1897 # and relating linkrevs to file names (which is not "correct" but
1897 # and relating linkrevs to file names (which is not "correct" but
1898 # good enough).
1898 # good enough).
1899 fcache = {}
1899 fcache = {}
1900 fcacheready = [False]
1900 fcacheready = [False]
1901 pctx = repo['.']
1901 pctx = repo['.']
1902
1902
1903 def populate():
1903 def populate():
1904 for fn in files:
1904 for fn in files:
1905 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1905 for i in ((pctx[fn],), pctx[fn].ancestors(followfirst=followfirst)):
1906 for c in i:
1906 for c in i:
1907 fcache.setdefault(c.linkrev(), set()).add(c.path())
1907 fcache.setdefault(c.linkrev(), set()).add(c.path())
1908
1908
1909 def filematcher(rev):
1909 def filematcher(rev):
1910 if not fcacheready[0]:
1910 if not fcacheready[0]:
1911 # Lazy initialization
1911 # Lazy initialization
1912 fcacheready[0] = True
1912 fcacheready[0] = True
1913 populate()
1913 populate()
1914 return scmutil.matchfiles(repo, fcache.get(rev, []))
1914 return scmutil.matchfiles(repo, fcache.get(rev, []))
1915
1915
1916 return filematcher
1916 return filematcher
1917
1917
1918 def _makenofollowlogfilematcher(repo, pats, opts):
1918 def _makenofollowlogfilematcher(repo, pats, opts):
1919 '''hook for extensions to override the filematcher for non-follow cases'''
1919 '''hook for extensions to override the filematcher for non-follow cases'''
1920 return None
1920 return None
1921
1921
1922 def _makelogrevset(repo, pats, opts, revs):
1922 def _makelogrevset(repo, pats, opts, revs):
1923 """Return (expr, filematcher) where expr is a revset string built
1923 """Return (expr, filematcher) where expr is a revset string built
1924 from log options and file patterns or None. If --stat or --patch
1924 from log options and file patterns or None. If --stat or --patch
1925 are not passed filematcher is None. Otherwise it is a callable
1925 are not passed filematcher is None. Otherwise it is a callable
1926 taking a revision number and returning a match objects filtering
1926 taking a revision number and returning a match objects filtering
1927 the files to be detailed when displaying the revision.
1927 the files to be detailed when displaying the revision.
1928 """
1928 """
1929 opt2revset = {
1929 opt2revset = {
1930 'no_merges': ('not merge()', None),
1930 'no_merges': ('not merge()', None),
1931 'only_merges': ('merge()', None),
1931 'only_merges': ('merge()', None),
1932 '_ancestors': ('ancestors(%(val)s)', None),
1932 '_ancestors': ('ancestors(%(val)s)', None),
1933 '_fancestors': ('_firstancestors(%(val)s)', None),
1933 '_fancestors': ('_firstancestors(%(val)s)', None),
1934 '_descendants': ('descendants(%(val)s)', None),
1934 '_descendants': ('descendants(%(val)s)', None),
1935 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1935 '_fdescendants': ('_firstdescendants(%(val)s)', None),
1936 '_matchfiles': ('_matchfiles(%(val)s)', None),
1936 '_matchfiles': ('_matchfiles(%(val)s)', None),
1937 'date': ('date(%(val)r)', None),
1937 'date': ('date(%(val)r)', None),
1938 'branch': ('branch(%(val)r)', ' or '),
1938 'branch': ('branch(%(val)r)', ' or '),
1939 '_patslog': ('filelog(%(val)r)', ' or '),
1939 '_patslog': ('filelog(%(val)r)', ' or '),
1940 '_patsfollow': ('follow(%(val)r)', ' or '),
1940 '_patsfollow': ('follow(%(val)r)', ' or '),
1941 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1941 '_patsfollowfirst': ('_followfirst(%(val)r)', ' or '),
1942 'keyword': ('keyword(%(val)r)', ' or '),
1942 'keyword': ('keyword(%(val)r)', ' or '),
1943 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1943 'prune': ('not (%(val)r or ancestors(%(val)r))', ' and '),
1944 'user': ('user(%(val)r)', ' or '),
1944 'user': ('user(%(val)r)', ' or '),
1945 }
1945 }
1946
1946
1947 opts = dict(opts)
1947 opts = dict(opts)
1948 # follow or not follow?
1948 # follow or not follow?
1949 follow = opts.get('follow') or opts.get('follow_first')
1949 follow = opts.get('follow') or opts.get('follow_first')
1950 if opts.get('follow_first'):
1950 if opts.get('follow_first'):
1951 followfirst = 1
1951 followfirst = 1
1952 else:
1952 else:
1953 followfirst = 0
1953 followfirst = 0
1954 # --follow with FILE behavior depends on revs...
1954 # --follow with FILE behavior depends on revs...
1955 it = iter(revs)
1955 it = iter(revs)
1956 startrev = it.next()
1956 startrev = it.next()
1957 followdescendants = startrev < next(it, startrev)
1957 followdescendants = startrev < next(it, startrev)
1958
1958
1959 # branch and only_branch are really aliases and must be handled at
1959 # branch and only_branch are really aliases and must be handled at
1960 # the same time
1960 # the same time
1961 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1961 opts['branch'] = opts.get('branch', []) + opts.get('only_branch', [])
1962 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1962 opts['branch'] = [repo.lookupbranch(b) for b in opts['branch']]
1963 # pats/include/exclude are passed to match.match() directly in
1963 # pats/include/exclude are passed to match.match() directly in
1964 # _matchfiles() revset but walkchangerevs() builds its matcher with
1964 # _matchfiles() revset but walkchangerevs() builds its matcher with
1965 # scmutil.match(). The difference is input pats are globbed on
1965 # scmutil.match(). The difference is input pats are globbed on
1966 # platforms without shell expansion (windows).
1966 # platforms without shell expansion (windows).
1967 wctx = repo[None]
1967 wctx = repo[None]
1968 match, pats = scmutil.matchandpats(wctx, pats, opts)
1968 match, pats = scmutil.matchandpats(wctx, pats, opts)
1969 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1969 slowpath = match.anypats() or ((match.isexact() or match.prefix()) and
1970 opts.get('removed'))
1970 opts.get('removed'))
1971 if not slowpath:
1971 if not slowpath:
1972 for f in match.files():
1972 for f in match.files():
1973 if follow and f not in wctx:
1973 if follow and f not in wctx:
1974 # If the file exists, it may be a directory, so let it
1974 # If the file exists, it may be a directory, so let it
1975 # take the slow path.
1975 # take the slow path.
1976 if os.path.exists(repo.wjoin(f)):
1976 if os.path.exists(repo.wjoin(f)):
1977 slowpath = True
1977 slowpath = True
1978 continue
1978 continue
1979 else:
1979 else:
1980 raise error.Abort(_('cannot follow file not in parent '
1980 raise error.Abort(_('cannot follow file not in parent '
1981 'revision: "%s"') % f)
1981 'revision: "%s"') % f)
1982 filelog = repo.file(f)
1982 filelog = repo.file(f)
1983 if not filelog:
1983 if not filelog:
1984 # A zero count may be a directory or deleted file, so
1984 # A zero count may be a directory or deleted file, so
1985 # try to find matching entries on the slow path.
1985 # try to find matching entries on the slow path.
1986 if follow:
1986 if follow:
1987 raise error.Abort(
1987 raise error.Abort(
1988 _('cannot follow nonexistent file: "%s"') % f)
1988 _('cannot follow nonexistent file: "%s"') % f)
1989 slowpath = True
1989 slowpath = True
1990
1990
1991 # We decided to fall back to the slowpath because at least one
1991 # We decided to fall back to the slowpath because at least one
1992 # of the paths was not a file. Check to see if at least one of them
1992 # of the paths was not a file. Check to see if at least one of them
1993 # existed in history - in that case, we'll continue down the
1993 # existed in history - in that case, we'll continue down the
1994 # slowpath; otherwise, we can turn off the slowpath
1994 # slowpath; otherwise, we can turn off the slowpath
1995 if slowpath:
1995 if slowpath:
1996 for path in match.files():
1996 for path in match.files():
1997 if path == '.' or path in repo.store:
1997 if path == '.' or path in repo.store:
1998 break
1998 break
1999 else:
1999 else:
2000 slowpath = False
2000 slowpath = False
2001
2001
2002 fpats = ('_patsfollow', '_patsfollowfirst')
2002 fpats = ('_patsfollow', '_patsfollowfirst')
2003 fnopats = (('_ancestors', '_fancestors'),
2003 fnopats = (('_ancestors', '_fancestors'),
2004 ('_descendants', '_fdescendants'))
2004 ('_descendants', '_fdescendants'))
2005 if slowpath:
2005 if slowpath:
2006 # See walkchangerevs() slow path.
2006 # See walkchangerevs() slow path.
2007 #
2007 #
2008 # pats/include/exclude cannot be represented as separate
2008 # pats/include/exclude cannot be represented as separate
2009 # revset expressions as their filtering logic applies at file
2009 # revset expressions as their filtering logic applies at file
2010 # level. For instance "-I a -X a" matches a revision touching
2010 # level. For instance "-I a -X a" matches a revision touching
2011 # "a" and "b" while "file(a) and not file(b)" does
2011 # "a" and "b" while "file(a) and not file(b)" does
2012 # not. Besides, filesets are evaluated against the working
2012 # not. Besides, filesets are evaluated against the working
2013 # directory.
2013 # directory.
2014 matchargs = ['r:', 'd:relpath']
2014 matchargs = ['r:', 'd:relpath']
2015 for p in pats:
2015 for p in pats:
2016 matchargs.append('p:' + p)
2016 matchargs.append('p:' + p)
2017 for p in opts.get('include', []):
2017 for p in opts.get('include', []):
2018 matchargs.append('i:' + p)
2018 matchargs.append('i:' + p)
2019 for p in opts.get('exclude', []):
2019 for p in opts.get('exclude', []):
2020 matchargs.append('x:' + p)
2020 matchargs.append('x:' + p)
2021 matchargs = ','.join(('%r' % p) for p in matchargs)
2021 matchargs = ','.join(('%r' % p) for p in matchargs)
2022 opts['_matchfiles'] = matchargs
2022 opts['_matchfiles'] = matchargs
2023 if follow:
2023 if follow:
2024 opts[fnopats[0][followfirst]] = '.'
2024 opts[fnopats[0][followfirst]] = '.'
2025 else:
2025 else:
2026 if follow:
2026 if follow:
2027 if pats:
2027 if pats:
2028 # follow() revset interprets its file argument as a
2028 # follow() revset interprets its file argument as a
2029 # manifest entry, so use match.files(), not pats.
2029 # manifest entry, so use match.files(), not pats.
2030 opts[fpats[followfirst]] = list(match.files())
2030 opts[fpats[followfirst]] = list(match.files())
2031 else:
2031 else:
2032 op = fnopats[followdescendants][followfirst]
2032 op = fnopats[followdescendants][followfirst]
2033 opts[op] = 'rev(%d)' % startrev
2033 opts[op] = 'rev(%d)' % startrev
2034 else:
2034 else:
2035 opts['_patslog'] = list(pats)
2035 opts['_patslog'] = list(pats)
2036
2036
2037 filematcher = None
2037 filematcher = None
2038 if opts.get('patch') or opts.get('stat'):
2038 if opts.get('patch') or opts.get('stat'):
2039 # When following files, track renames via a special matcher.
2039 # When following files, track renames via a special matcher.
2040 # If we're forced to take the slowpath it means we're following
2040 # If we're forced to take the slowpath it means we're following
2041 # at least one pattern/directory, so don't bother with rename tracking.
2041 # at least one pattern/directory, so don't bother with rename tracking.
2042 if follow and not match.always() and not slowpath:
2042 if follow and not match.always() and not slowpath:
2043 # _makefollowlogfilematcher expects its files argument to be
2043 # _makefollowlogfilematcher expects its files argument to be
2044 # relative to the repo root, so use match.files(), not pats.
2044 # relative to the repo root, so use match.files(), not pats.
2045 filematcher = _makefollowlogfilematcher(repo, match.files(),
2045 filematcher = _makefollowlogfilematcher(repo, match.files(),
2046 followfirst)
2046 followfirst)
2047 else:
2047 else:
2048 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2048 filematcher = _makenofollowlogfilematcher(repo, pats, opts)
2049 if filematcher is None:
2049 if filematcher is None:
2050 filematcher = lambda rev: match
2050 filematcher = lambda rev: match
2051
2051
2052 expr = []
2052 expr = []
2053 for op, val in sorted(opts.iteritems()):
2053 for op, val in sorted(opts.iteritems()):
2054 if not val:
2054 if not val:
2055 continue
2055 continue
2056 if op not in opt2revset:
2056 if op not in opt2revset:
2057 continue
2057 continue
2058 revop, andor = opt2revset[op]
2058 revop, andor = opt2revset[op]
2059 if '%(val)' not in revop:
2059 if '%(val)' not in revop:
2060 expr.append(revop)
2060 expr.append(revop)
2061 else:
2061 else:
2062 if not isinstance(val, list):
2062 if not isinstance(val, list):
2063 e = revop % {'val': val}
2063 e = revop % {'val': val}
2064 else:
2064 else:
2065 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2065 e = '(' + andor.join((revop % {'val': v}) for v in val) + ')'
2066 expr.append(e)
2066 expr.append(e)
2067
2067
2068 if expr:
2068 if expr:
2069 expr = '(' + ' and '.join(expr) + ')'
2069 expr = '(' + ' and '.join(expr) + ')'
2070 else:
2070 else:
2071 expr = None
2071 expr = None
2072 return expr, filematcher
2072 return expr, filematcher
2073
2073
2074 def _logrevs(repo, opts):
2074 def _logrevs(repo, opts):
2075 # Default --rev value depends on --follow but --follow behavior
2075 # Default --rev value depends on --follow but --follow behavior
2076 # depends on revisions resolved from --rev...
2076 # depends on revisions resolved from --rev...
2077 follow = opts.get('follow') or opts.get('follow_first')
2077 follow = opts.get('follow') or opts.get('follow_first')
2078 if opts.get('rev'):
2078 if opts.get('rev'):
2079 revs = scmutil.revrange(repo, opts['rev'])
2079 revs = scmutil.revrange(repo, opts['rev'])
2080 elif follow and repo.dirstate.p1() == nullid:
2080 elif follow and repo.dirstate.p1() == nullid:
2081 revs = revset.baseset()
2081 revs = revset.baseset()
2082 elif follow:
2082 elif follow:
2083 revs = repo.revs('reverse(:.)')
2083 revs = repo.revs('reverse(:.)')
2084 else:
2084 else:
2085 revs = revset.spanset(repo)
2085 revs = revset.spanset(repo)
2086 revs.reverse()
2086 revs.reverse()
2087 return revs
2087 return revs
2088
2088
2089 def getgraphlogrevs(repo, pats, opts):
2089 def getgraphlogrevs(repo, pats, opts):
2090 """Return (revs, expr, filematcher) where revs is an iterable of
2090 """Return (revs, expr, filematcher) where revs is an iterable of
2091 revision numbers, expr is a revset string built from log options
2091 revision numbers, expr is a revset string built from log options
2092 and file patterns or None, and used to filter 'revs'. If --stat or
2092 and file patterns or None, and used to filter 'revs'. If --stat or
2093 --patch are not passed filematcher is None. Otherwise it is a
2093 --patch are not passed filematcher is None. Otherwise it is a
2094 callable taking a revision number and returning a match objects
2094 callable taking a revision number and returning a match objects
2095 filtering the files to be detailed when displaying the revision.
2095 filtering the files to be detailed when displaying the revision.
2096 """
2096 """
2097 limit = loglimit(opts)
2097 limit = loglimit(opts)
2098 revs = _logrevs(repo, opts)
2098 revs = _logrevs(repo, opts)
2099 if not revs:
2099 if not revs:
2100 return revset.baseset(), None, None
2100 return revset.baseset(), None, None
2101 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2101 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2102 if opts.get('rev'):
2102 if opts.get('rev'):
2103 # User-specified revs might be unsorted, but don't sort before
2103 # User-specified revs might be unsorted, but don't sort before
2104 # _makelogrevset because it might depend on the order of revs
2104 # _makelogrevset because it might depend on the order of revs
2105 revs.sort(reverse=True)
2105 revs.sort(reverse=True)
2106 if expr:
2106 if expr:
2107 # Revset matchers often operate faster on revisions in changelog
2107 # Revset matchers often operate faster on revisions in changelog
2108 # order, because most filters deal with the changelog.
2108 # order, because most filters deal with the changelog.
2109 revs.reverse()
2109 revs.reverse()
2110 matcher = revset.match(repo.ui, expr)
2110 matcher = revset.match(repo.ui, expr)
2111 # Revset matches can reorder revisions. "A or B" typically returns
2111 # Revset matches can reorder revisions. "A or B" typically returns
2112 # returns the revision matching A then the revision matching B. Sort
2112 # returns the revision matching A then the revision matching B. Sort
2113 # again to fix that.
2113 # again to fix that.
2114 revs = matcher(repo, revs)
2114 revs = matcher(repo, revs)
2115 revs.sort(reverse=True)
2115 revs.sort(reverse=True)
2116 if limit is not None:
2116 if limit is not None:
2117 limitedrevs = []
2117 limitedrevs = []
2118 for idx, rev in enumerate(revs):
2118 for idx, rev in enumerate(revs):
2119 if idx >= limit:
2119 if idx >= limit:
2120 break
2120 break
2121 limitedrevs.append(rev)
2121 limitedrevs.append(rev)
2122 revs = revset.baseset(limitedrevs)
2122 revs = revset.baseset(limitedrevs)
2123
2123
2124 return revs, expr, filematcher
2124 return revs, expr, filematcher
2125
2125
2126 def getlogrevs(repo, pats, opts):
2126 def getlogrevs(repo, pats, opts):
2127 """Return (revs, expr, filematcher) where revs is an iterable of
2127 """Return (revs, expr, filematcher) where revs is an iterable of
2128 revision numbers, expr is a revset string built from log options
2128 revision numbers, expr is a revset string built from log options
2129 and file patterns or None, and used to filter 'revs'. If --stat or
2129 and file patterns or None, and used to filter 'revs'. If --stat or
2130 --patch are not passed filematcher is None. Otherwise it is a
2130 --patch are not passed filematcher is None. Otherwise it is a
2131 callable taking a revision number and returning a match objects
2131 callable taking a revision number and returning a match objects
2132 filtering the files to be detailed when displaying the revision.
2132 filtering the files to be detailed when displaying the revision.
2133 """
2133 """
2134 limit = loglimit(opts)
2134 limit = loglimit(opts)
2135 revs = _logrevs(repo, opts)
2135 revs = _logrevs(repo, opts)
2136 if not revs:
2136 if not revs:
2137 return revset.baseset([]), None, None
2137 return revset.baseset([]), None, None
2138 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2138 expr, filematcher = _makelogrevset(repo, pats, opts, revs)
2139 if expr:
2139 if expr:
2140 # Revset matchers often operate faster on revisions in changelog
2140 # Revset matchers often operate faster on revisions in changelog
2141 # order, because most filters deal with the changelog.
2141 # order, because most filters deal with the changelog.
2142 if not opts.get('rev'):
2142 if not opts.get('rev'):
2143 revs.reverse()
2143 revs.reverse()
2144 matcher = revset.match(repo.ui, expr)
2144 matcher = revset.match(repo.ui, expr)
2145 # Revset matches can reorder revisions. "A or B" typically returns
2145 # Revset matches can reorder revisions. "A or B" typically returns
2146 # returns the revision matching A then the revision matching B. Sort
2146 # returns the revision matching A then the revision matching B. Sort
2147 # again to fix that.
2147 # again to fix that.
2148 revs = matcher(repo, revs)
2148 revs = matcher(repo, revs)
2149 if not opts.get('rev'):
2149 if not opts.get('rev'):
2150 revs.sort(reverse=True)
2150 revs.sort(reverse=True)
2151 if limit is not None:
2151 if limit is not None:
2152 limitedrevs = []
2152 limitedrevs = []
2153 for idx, r in enumerate(revs):
2153 for idx, r in enumerate(revs):
2154 if limit <= idx:
2154 if limit <= idx:
2155 break
2155 break
2156 limitedrevs.append(r)
2156 limitedrevs.append(r)
2157 revs = revset.baseset(limitedrevs)
2157 revs = revset.baseset(limitedrevs)
2158
2158
2159 return revs, expr, filematcher
2159 return revs, expr, filematcher
2160
2160
2161 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
2161 def displaygraph(ui, dag, displayer, showparents, edgefn, getrenamed=None,
2162 filematcher=None):
2162 filematcher=None):
2163 seen, state = [], graphmod.asciistate()
2163 seen, state = [], graphmod.asciistate()
2164 for rev, type, ctx, parents in dag:
2164 for rev, type, ctx, parents in dag:
2165 char = 'o'
2165 char = 'o'
2166 if ctx.node() in showparents:
2166 if ctx.node() in showparents:
2167 char = '@'
2167 char = '@'
2168 elif ctx.obsolete():
2168 elif ctx.obsolete():
2169 char = 'x'
2169 char = 'x'
2170 elif ctx.closesbranch():
2170 elif ctx.closesbranch():
2171 char = '_'
2171 char = '_'
2172 copies = None
2172 copies = None
2173 if getrenamed and ctx.rev():
2173 if getrenamed and ctx.rev():
2174 copies = []
2174 copies = []
2175 for fn in ctx.files():
2175 for fn in ctx.files():
2176 rename = getrenamed(fn, ctx.rev())
2176 rename = getrenamed(fn, ctx.rev())
2177 if rename:
2177 if rename:
2178 copies.append((fn, rename[0]))
2178 copies.append((fn, rename[0]))
2179 revmatchfn = None
2179 revmatchfn = None
2180 if filematcher is not None:
2180 if filematcher is not None:
2181 revmatchfn = filematcher(ctx.rev())
2181 revmatchfn = filematcher(ctx.rev())
2182 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2182 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
2183 lines = displayer.hunk.pop(rev).split('\n')
2183 lines = displayer.hunk.pop(rev).split('\n')
2184 if not lines[-1]:
2184 if not lines[-1]:
2185 del lines[-1]
2185 del lines[-1]
2186 displayer.flush(ctx)
2186 displayer.flush(ctx)
2187 edges = edgefn(type, char, lines, seen, rev, parents)
2187 edges = edgefn(type, char, lines, seen, rev, parents)
2188 for type, char, lines, coldata in edges:
2188 for type, char, lines, coldata in edges:
2189 graphmod.ascii(ui, state, type, char, lines, coldata)
2189 graphmod.ascii(ui, state, type, char, lines, coldata)
2190 displayer.close()
2190 displayer.close()
2191
2191
2192 def graphlog(ui, repo, *pats, **opts):
2192 def graphlog(ui, repo, *pats, **opts):
2193 # Parameters are identical to log command ones
2193 # Parameters are identical to log command ones
2194 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2194 revs, expr, filematcher = getgraphlogrevs(repo, pats, opts)
2195 revdag = graphmod.dagwalker(repo, revs)
2195 revdag = graphmod.dagwalker(repo, revs)
2196
2196
2197 getrenamed = None
2197 getrenamed = None
2198 if opts.get('copies'):
2198 if opts.get('copies'):
2199 endrev = None
2199 endrev = None
2200 if opts.get('rev'):
2200 if opts.get('rev'):
2201 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2201 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
2202 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2202 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2203 displayer = show_changeset(ui, repo, opts, buffered=True)
2203 displayer = show_changeset(ui, repo, opts, buffered=True)
2204 showparents = [ctx.node() for ctx in repo[None].parents()]
2204 showparents = [ctx.node() for ctx in repo[None].parents()]
2205 displaygraph(ui, revdag, displayer, showparents,
2205 displaygraph(ui, revdag, displayer, showparents,
2206 graphmod.asciiedges, getrenamed, filematcher)
2206 graphmod.asciiedges, getrenamed, filematcher)
2207
2207
2208 def checkunsupportedgraphflags(pats, opts):
2208 def checkunsupportedgraphflags(pats, opts):
2209 for op in ["newest_first"]:
2209 for op in ["newest_first"]:
2210 if op in opts and opts[op]:
2210 if op in opts and opts[op]:
2211 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2211 raise error.Abort(_("-G/--graph option is incompatible with --%s")
2212 % op.replace("_", "-"))
2212 % op.replace("_", "-"))
2213
2213
2214 def graphrevs(repo, nodes, opts):
2214 def graphrevs(repo, nodes, opts):
2215 limit = loglimit(opts)
2215 limit = loglimit(opts)
2216 nodes.reverse()
2216 nodes.reverse()
2217 if limit is not None:
2217 if limit is not None:
2218 nodes = nodes[:limit]
2218 nodes = nodes[:limit]
2219 return graphmod.nodes(repo, nodes)
2219 return graphmod.nodes(repo, nodes)
2220
2220
2221 def add(ui, repo, match, prefix, explicitonly, **opts):
2221 def add(ui, repo, match, prefix, explicitonly, **opts):
2222 join = lambda f: os.path.join(prefix, f)
2222 join = lambda f: os.path.join(prefix, f)
2223 bad = []
2223 bad = []
2224
2224
2225 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2225 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2226 names = []
2226 names = []
2227 wctx = repo[None]
2227 wctx = repo[None]
2228 cca = None
2228 cca = None
2229 abort, warn = scmutil.checkportabilityalert(ui)
2229 abort, warn = scmutil.checkportabilityalert(ui)
2230 if abort or warn:
2230 if abort or warn:
2231 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2231 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2232
2232
2233 badmatch = matchmod.badmatch(match, badfn)
2233 badmatch = matchmod.badmatch(match, badfn)
2234 dirstate = repo.dirstate
2234 dirstate = repo.dirstate
2235 # We don't want to just call wctx.walk here, since it would return a lot of
2235 # We don't want to just call wctx.walk here, since it would return a lot of
2236 # clean files, which we aren't interested in and takes time.
2236 # clean files, which we aren't interested in and takes time.
2237 for f in sorted(dirstate.walk(badmatch, sorted(wctx.substate),
2237 for f in sorted(dirstate.walk(badmatch, sorted(wctx.substate),
2238 True, False, full=False)):
2238 True, False, full=False)):
2239 exact = match.exact(f)
2239 exact = match.exact(f)
2240 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2240 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2241 if cca:
2241 if cca:
2242 cca(f)
2242 cca(f)
2243 names.append(f)
2243 names.append(f)
2244 if ui.verbose or not exact:
2244 if ui.verbose or not exact:
2245 ui.status(_('adding %s\n') % match.rel(f))
2245 ui.status(_('adding %s\n') % match.rel(f))
2246
2246
2247 for subpath in sorted(wctx.substate):
2247 for subpath in sorted(wctx.substate):
2248 sub = wctx.sub(subpath)
2248 sub = wctx.sub(subpath)
2249 try:
2249 try:
2250 submatch = matchmod.narrowmatcher(subpath, match)
2250 submatch = matchmod.narrowmatcher(subpath, match)
2251 if opts.get('subrepos'):
2251 if opts.get('subrepos'):
2252 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2252 bad.extend(sub.add(ui, submatch, prefix, False, **opts))
2253 else:
2253 else:
2254 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2254 bad.extend(sub.add(ui, submatch, prefix, True, **opts))
2255 except error.LookupError:
2255 except error.LookupError:
2256 ui.status(_("skipping missing subrepository: %s\n")
2256 ui.status(_("skipping missing subrepository: %s\n")
2257 % join(subpath))
2257 % join(subpath))
2258
2258
2259 if not opts.get('dry_run'):
2259 if not opts.get('dry_run'):
2260 rejected = wctx.add(names, prefix)
2260 rejected = wctx.add(names, prefix)
2261 bad.extend(f for f in rejected if f in match.files())
2261 bad.extend(f for f in rejected if f in match.files())
2262 return bad
2262 return bad
2263
2263
2264 def forget(ui, repo, match, prefix, explicitonly):
2264 def forget(ui, repo, match, prefix, explicitonly):
2265 join = lambda f: os.path.join(prefix, f)
2265 join = lambda f: os.path.join(prefix, f)
2266 bad = []
2266 bad = []
2267 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2267 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2268 wctx = repo[None]
2268 wctx = repo[None]
2269 forgot = []
2269 forgot = []
2270
2270
2271 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2271 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2272 forget = sorted(s[0] + s[1] + s[3] + s[6])
2272 forget = sorted(s[0] + s[1] + s[3] + s[6])
2273 if explicitonly:
2273 if explicitonly:
2274 forget = [f for f in forget if match.exact(f)]
2274 forget = [f for f in forget if match.exact(f)]
2275
2275
2276 for subpath in sorted(wctx.substate):
2276 for subpath in sorted(wctx.substate):
2277 sub = wctx.sub(subpath)
2277 sub = wctx.sub(subpath)
2278 try:
2278 try:
2279 submatch = matchmod.narrowmatcher(subpath, match)
2279 submatch = matchmod.narrowmatcher(subpath, match)
2280 subbad, subforgot = sub.forget(submatch, prefix)
2280 subbad, subforgot = sub.forget(submatch, prefix)
2281 bad.extend([subpath + '/' + f for f in subbad])
2281 bad.extend([subpath + '/' + f for f in subbad])
2282 forgot.extend([subpath + '/' + f for f in subforgot])
2282 forgot.extend([subpath + '/' + f for f in subforgot])
2283 except error.LookupError:
2283 except error.LookupError:
2284 ui.status(_("skipping missing subrepository: %s\n")
2284 ui.status(_("skipping missing subrepository: %s\n")
2285 % join(subpath))
2285 % join(subpath))
2286
2286
2287 if not explicitonly:
2287 if not explicitonly:
2288 for f in match.files():
2288 for f in match.files():
2289 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2289 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2290 if f not in forgot:
2290 if f not in forgot:
2291 if repo.wvfs.exists(f):
2291 if repo.wvfs.exists(f):
2292 # Don't complain if the exact case match wasn't given.
2292 # Don't complain if the exact case match wasn't given.
2293 # But don't do this until after checking 'forgot', so
2293 # But don't do this until after checking 'forgot', so
2294 # that subrepo files aren't normalized, and this op is
2294 # that subrepo files aren't normalized, and this op is
2295 # purely from data cached by the status walk above.
2295 # purely from data cached by the status walk above.
2296 if repo.dirstate.normalize(f) in repo.dirstate:
2296 if repo.dirstate.normalize(f) in repo.dirstate:
2297 continue
2297 continue
2298 ui.warn(_('not removing %s: '
2298 ui.warn(_('not removing %s: '
2299 'file is already untracked\n')
2299 'file is already untracked\n')
2300 % match.rel(f))
2300 % match.rel(f))
2301 bad.append(f)
2301 bad.append(f)
2302
2302
2303 for f in forget:
2303 for f in forget:
2304 if ui.verbose or not match.exact(f):
2304 if ui.verbose or not match.exact(f):
2305 ui.status(_('removing %s\n') % match.rel(f))
2305 ui.status(_('removing %s\n') % match.rel(f))
2306
2306
2307 rejected = wctx.forget(forget, prefix)
2307 rejected = wctx.forget(forget, prefix)
2308 bad.extend(f for f in rejected if f in match.files())
2308 bad.extend(f for f in rejected if f in match.files())
2309 forgot.extend(f for f in forget if f not in rejected)
2309 forgot.extend(f for f in forget if f not in rejected)
2310 return bad, forgot
2310 return bad, forgot
2311
2311
2312 def files(ui, ctx, m, fm, fmt, subrepos):
2312 def files(ui, ctx, m, fm, fmt, subrepos):
2313 rev = ctx.rev()
2313 rev = ctx.rev()
2314 ret = 1
2314 ret = 1
2315 ds = ctx.repo().dirstate
2315 ds = ctx.repo().dirstate
2316
2316
2317 for f in ctx.matches(m):
2317 for f in ctx.matches(m):
2318 if rev is None and ds[f] == 'r':
2318 if rev is None and ds[f] == 'r':
2319 continue
2319 continue
2320 fm.startitem()
2320 fm.startitem()
2321 if ui.verbose:
2321 if ui.verbose:
2322 fc = ctx[f]
2322 fc = ctx[f]
2323 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2323 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2324 fm.data(abspath=f)
2324 fm.data(abspath=f)
2325 fm.write('path', fmt, m.rel(f))
2325 fm.write('path', fmt, m.rel(f))
2326 ret = 0
2326 ret = 0
2327
2327
2328 for subpath in sorted(ctx.substate):
2328 for subpath in sorted(ctx.substate):
2329 def matchessubrepo(subpath):
2329 def matchessubrepo(subpath):
2330 return (m.always() or m.exact(subpath)
2330 return (m.always() or m.exact(subpath)
2331 or any(f.startswith(subpath + '/') for f in m.files()))
2331 or any(f.startswith(subpath + '/') for f in m.files()))
2332
2332
2333 if subrepos or matchessubrepo(subpath):
2333 if subrepos or matchessubrepo(subpath):
2334 sub = ctx.sub(subpath)
2334 sub = ctx.sub(subpath)
2335 try:
2335 try:
2336 submatch = matchmod.narrowmatcher(subpath, m)
2336 submatch = matchmod.narrowmatcher(subpath, m)
2337 if sub.printfiles(ui, submatch, fm, fmt, subrepos) == 0:
2337 if sub.printfiles(ui, submatch, fm, fmt, subrepos) == 0:
2338 ret = 0
2338 ret = 0
2339 except error.LookupError:
2339 except error.LookupError:
2340 ui.status(_("skipping missing subrepository: %s\n")
2340 ui.status(_("skipping missing subrepository: %s\n")
2341 % m.abs(subpath))
2341 % m.abs(subpath))
2342
2342
2343 return ret
2343 return ret
2344
2344
2345 def remove(ui, repo, m, prefix, after, force, subrepos):
2345 def remove(ui, repo, m, prefix, after, force, subrepos):
2346 join = lambda f: os.path.join(prefix, f)
2346 join = lambda f: os.path.join(prefix, f)
2347 ret = 0
2347 ret = 0
2348 s = repo.status(match=m, clean=True)
2348 s = repo.status(match=m, clean=True)
2349 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2349 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2350
2350
2351 wctx = repo[None]
2351 wctx = repo[None]
2352
2352
2353 for subpath in sorted(wctx.substate):
2353 for subpath in sorted(wctx.substate):
2354 def matchessubrepo(matcher, subpath):
2354 def matchessubrepo(matcher, subpath):
2355 if matcher.exact(subpath):
2355 if matcher.exact(subpath):
2356 return True
2356 return True
2357 for f in matcher.files():
2357 for f in matcher.files():
2358 if f.startswith(subpath):
2358 if f.startswith(subpath):
2359 return True
2359 return True
2360 return False
2360 return False
2361
2361
2362 if subrepos or matchessubrepo(m, subpath):
2362 if subrepos or matchessubrepo(m, subpath):
2363 sub = wctx.sub(subpath)
2363 sub = wctx.sub(subpath)
2364 try:
2364 try:
2365 submatch = matchmod.narrowmatcher(subpath, m)
2365 submatch = matchmod.narrowmatcher(subpath, m)
2366 if sub.removefiles(submatch, prefix, after, force, subrepos):
2366 if sub.removefiles(submatch, prefix, after, force, subrepos):
2367 ret = 1
2367 ret = 1
2368 except error.LookupError:
2368 except error.LookupError:
2369 ui.status(_("skipping missing subrepository: %s\n")
2369 ui.status(_("skipping missing subrepository: %s\n")
2370 % join(subpath))
2370 % join(subpath))
2371
2371
2372 # warn about failure to delete explicit files/dirs
2372 # warn about failure to delete explicit files/dirs
2373 deleteddirs = util.dirs(deleted)
2373 deleteddirs = util.dirs(deleted)
2374 for f in m.files():
2374 for f in m.files():
2375 def insubrepo():
2375 def insubrepo():
2376 for subpath in wctx.substate:
2376 for subpath in wctx.substate:
2377 if f.startswith(subpath):
2377 if f.startswith(subpath):
2378 return True
2378 return True
2379 return False
2379 return False
2380
2380
2381 isdir = f in deleteddirs or wctx.hasdir(f)
2381 isdir = f in deleteddirs or wctx.hasdir(f)
2382 if f in repo.dirstate or isdir or f == '.' or insubrepo():
2382 if f in repo.dirstate or isdir or f == '.' or insubrepo():
2383 continue
2383 continue
2384
2384
2385 if repo.wvfs.exists(f):
2385 if repo.wvfs.exists(f):
2386 if repo.wvfs.isdir(f):
2386 if repo.wvfs.isdir(f):
2387 ui.warn(_('not removing %s: no tracked files\n')
2387 ui.warn(_('not removing %s: no tracked files\n')
2388 % m.rel(f))
2388 % m.rel(f))
2389 else:
2389 else:
2390 ui.warn(_('not removing %s: file is untracked\n')
2390 ui.warn(_('not removing %s: file is untracked\n')
2391 % m.rel(f))
2391 % m.rel(f))
2392 # missing files will generate a warning elsewhere
2392 # missing files will generate a warning elsewhere
2393 ret = 1
2393 ret = 1
2394
2394
2395 if force:
2395 if force:
2396 list = modified + deleted + clean + added
2396 list = modified + deleted + clean + added
2397 elif after:
2397 elif after:
2398 list = deleted
2398 list = deleted
2399 for f in modified + added + clean:
2399 for f in modified + added + clean:
2400 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
2400 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
2401 ret = 1
2401 ret = 1
2402 else:
2402 else:
2403 list = deleted + clean
2403 list = deleted + clean
2404 for f in modified:
2404 for f in modified:
2405 ui.warn(_('not removing %s: file is modified (use -f'
2405 ui.warn(_('not removing %s: file is modified (use -f'
2406 ' to force removal)\n') % m.rel(f))
2406 ' to force removal)\n') % m.rel(f))
2407 ret = 1
2407 ret = 1
2408 for f in added:
2408 for f in added:
2409 ui.warn(_('not removing %s: file has been marked for add'
2409 ui.warn(_('not removing %s: file has been marked for add'
2410 ' (use forget to undo)\n') % m.rel(f))
2410 ' (use forget to undo)\n') % m.rel(f))
2411 ret = 1
2411 ret = 1
2412
2412
2413 for f in sorted(list):
2413 for f in sorted(list):
2414 if ui.verbose or not m.exact(f):
2414 if ui.verbose or not m.exact(f):
2415 ui.status(_('removing %s\n') % m.rel(f))
2415 ui.status(_('removing %s\n') % m.rel(f))
2416
2416
2417 wlock = repo.wlock()
2417 wlock = repo.wlock()
2418 try:
2418 try:
2419 if not after:
2419 if not after:
2420 for f in list:
2420 for f in list:
2421 if f in added:
2421 if f in added:
2422 continue # we never unlink added files on remove
2422 continue # we never unlink added files on remove
2423 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
2423 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
2424 repo[None].forget(list)
2424 repo[None].forget(list)
2425 finally:
2425 finally:
2426 wlock.release()
2426 wlock.release()
2427
2427
2428 return ret
2428 return ret
2429
2429
2430 def cat(ui, repo, ctx, matcher, prefix, **opts):
2430 def cat(ui, repo, ctx, matcher, prefix, **opts):
2431 err = 1
2431 err = 1
2432
2432
2433 def write(path):
2433 def write(path):
2434 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2434 fp = makefileobj(repo, opts.get('output'), ctx.node(),
2435 pathname=os.path.join(prefix, path))
2435 pathname=os.path.join(prefix, path))
2436 data = ctx[path].data()
2436 data = ctx[path].data()
2437 if opts.get('decode'):
2437 if opts.get('decode'):
2438 data = repo.wwritedata(path, data)
2438 data = repo.wwritedata(path, data)
2439 fp.write(data)
2439 fp.write(data)
2440 fp.close()
2440 fp.close()
2441
2441
2442 # Automation often uses hg cat on single files, so special case it
2442 # Automation often uses hg cat on single files, so special case it
2443 # for performance to avoid the cost of parsing the manifest.
2443 # for performance to avoid the cost of parsing the manifest.
2444 if len(matcher.files()) == 1 and not matcher.anypats():
2444 if len(matcher.files()) == 1 and not matcher.anypats():
2445 file = matcher.files()[0]
2445 file = matcher.files()[0]
2446 mf = repo.manifest
2446 mf = repo.manifest
2447 mfnode = ctx.manifestnode()
2447 mfnode = ctx.manifestnode()
2448 if mfnode and mf.find(mfnode, file)[0]:
2448 if mfnode and mf.find(mfnode, file)[0]:
2449 write(file)
2449 write(file)
2450 return 0
2450 return 0
2451
2451
2452 # Don't warn about "missing" files that are really in subrepos
2452 # Don't warn about "missing" files that are really in subrepos
2453 def badfn(path, msg):
2453 def badfn(path, msg):
2454 for subpath in ctx.substate:
2454 for subpath in ctx.substate:
2455 if path.startswith(subpath):
2455 if path.startswith(subpath):
2456 return
2456 return
2457 matcher.bad(path, msg)
2457 matcher.bad(path, msg)
2458
2458
2459 for abs in ctx.walk(matchmod.badmatch(matcher, badfn)):
2459 for abs in ctx.walk(matchmod.badmatch(matcher, badfn)):
2460 write(abs)
2460 write(abs)
2461 err = 0
2461 err = 0
2462
2462
2463 for subpath in sorted(ctx.substate):
2463 for subpath in sorted(ctx.substate):
2464 sub = ctx.sub(subpath)
2464 sub = ctx.sub(subpath)
2465 try:
2465 try:
2466 submatch = matchmod.narrowmatcher(subpath, matcher)
2466 submatch = matchmod.narrowmatcher(subpath, matcher)
2467
2467
2468 if not sub.cat(submatch, os.path.join(prefix, sub._path),
2468 if not sub.cat(submatch, os.path.join(prefix, sub._path),
2469 **opts):
2469 **opts):
2470 err = 0
2470 err = 0
2471 except error.RepoLookupError:
2471 except error.RepoLookupError:
2472 ui.status(_("skipping missing subrepository: %s\n")
2472 ui.status(_("skipping missing subrepository: %s\n")
2473 % os.path.join(prefix, subpath))
2473 % os.path.join(prefix, subpath))
2474
2474
2475 return err
2475 return err
2476
2476
2477 def commit(ui, repo, commitfunc, pats, opts):
2477 def commit(ui, repo, commitfunc, pats, opts):
2478 '''commit the specified files or all outstanding changes'''
2478 '''commit the specified files or all outstanding changes'''
2479 date = opts.get('date')
2479 date = opts.get('date')
2480 if date:
2480 if date:
2481 opts['date'] = util.parsedate(date)
2481 opts['date'] = util.parsedate(date)
2482 message = logmessage(ui, opts)
2482 message = logmessage(ui, opts)
2483 matcher = scmutil.match(repo[None], pats, opts)
2483 matcher = scmutil.match(repo[None], pats, opts)
2484
2484
2485 # extract addremove carefully -- this function can be called from a command
2485 # extract addremove carefully -- this function can be called from a command
2486 # that doesn't support addremove
2486 # that doesn't support addremove
2487 if opts.get('addremove'):
2487 if opts.get('addremove'):
2488 if scmutil.addremove(repo, matcher, "", opts) != 0:
2488 if scmutil.addremove(repo, matcher, "", opts) != 0:
2489 raise error.Abort(
2489 raise error.Abort(
2490 _("failed to mark all new/missing files as added/removed"))
2490 _("failed to mark all new/missing files as added/removed"))
2491
2491
2492 return commitfunc(ui, repo, message, matcher, opts)
2492 return commitfunc(ui, repo, message, matcher, opts)
2493
2493
2494 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2494 def amend(ui, repo, commitfunc, old, extra, pats, opts):
2495 # avoid cycle context -> subrepo -> cmdutil
2495 # avoid cycle context -> subrepo -> cmdutil
2496 import context
2496 import context
2497
2497
2498 # amend will reuse the existing user if not specified, but the obsolete
2498 # amend will reuse the existing user if not specified, but the obsolete
2499 # marker creation requires that the current user's name is specified.
2499 # marker creation requires that the current user's name is specified.
2500 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2500 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2501 ui.username() # raise exception if username not set
2501 ui.username() # raise exception if username not set
2502
2502
2503 ui.note(_('amending changeset %s\n') % old)
2503 ui.note(_('amending changeset %s\n') % old)
2504 base = old.p1()
2504 base = old.p1()
2505 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2505 createmarkers = obsolete.isenabled(repo, obsolete.createmarkersopt)
2506
2506
2507 wlock = lock = newid = None
2507 wlock = lock = newid = None
2508 try:
2508 try:
2509 wlock = repo.wlock()
2509 wlock = repo.wlock()
2510 lock = repo.lock()
2510 lock = repo.lock()
2511 tr = repo.transaction('amend')
2511 tr = repo.transaction('amend')
2512 try:
2512 try:
2513 # See if we got a message from -m or -l, if not, open the editor
2513 # See if we got a message from -m or -l, if not, open the editor
2514 # with the message of the changeset to amend
2514 # with the message of the changeset to amend
2515 message = logmessage(ui, opts)
2515 message = logmessage(ui, opts)
2516 # ensure logfile does not conflict with later enforcement of the
2516 # ensure logfile does not conflict with later enforcement of the
2517 # message. potential logfile content has been processed by
2517 # message. potential logfile content has been processed by
2518 # `logmessage` anyway.
2518 # `logmessage` anyway.
2519 opts.pop('logfile')
2519 opts.pop('logfile')
2520 # First, do a regular commit to record all changes in the working
2520 # First, do a regular commit to record all changes in the working
2521 # directory (if there are any)
2521 # directory (if there are any)
2522 ui.callhooks = False
2522 ui.callhooks = False
2523 activebookmark = repo._activebookmark
2523 activebookmark = repo._activebookmark
2524 try:
2524 try:
2525 repo._activebookmark = None
2525 repo._activebookmark = None
2526 opts['message'] = 'temporary amend commit for %s' % old
2526 opts['message'] = 'temporary amend commit for %s' % old
2527 node = commit(ui, repo, commitfunc, pats, opts)
2527 node = commit(ui, repo, commitfunc, pats, opts)
2528 finally:
2528 finally:
2529 repo._activebookmark = activebookmark
2529 repo._activebookmark = activebookmark
2530 ui.callhooks = True
2530 ui.callhooks = True
2531 ctx = repo[node]
2531 ctx = repo[node]
2532
2532
2533 # Participating changesets:
2533 # Participating changesets:
2534 #
2534 #
2535 # node/ctx o - new (intermediate) commit that contains changes
2535 # node/ctx o - new (intermediate) commit that contains changes
2536 # | from working dir to go into amending commit
2536 # | from working dir to go into amending commit
2537 # | (or a workingctx if there were no changes)
2537 # | (or a workingctx if there were no changes)
2538 # |
2538 # |
2539 # old o - changeset to amend
2539 # old o - changeset to amend
2540 # |
2540 # |
2541 # base o - parent of amending changeset
2541 # base o - parent of amending changeset
2542
2542
2543 # Update extra dict from amended commit (e.g. to preserve graft
2543 # Update extra dict from amended commit (e.g. to preserve graft
2544 # source)
2544 # source)
2545 extra.update(old.extra())
2545 extra.update(old.extra())
2546
2546
2547 # Also update it from the intermediate commit or from the wctx
2547 # Also update it from the intermediate commit or from the wctx
2548 extra.update(ctx.extra())
2548 extra.update(ctx.extra())
2549
2549
2550 if len(old.parents()) > 1:
2550 if len(old.parents()) > 1:
2551 # ctx.files() isn't reliable for merges, so fall back to the
2551 # ctx.files() isn't reliable for merges, so fall back to the
2552 # slower repo.status() method
2552 # slower repo.status() method
2553 files = set([fn for st in repo.status(base, old)[:3]
2553 files = set([fn for st in repo.status(base, old)[:3]
2554 for fn in st])
2554 for fn in st])
2555 else:
2555 else:
2556 files = set(old.files())
2556 files = set(old.files())
2557
2557
2558 # Second, we use either the commit we just did, or if there were no
2558 # Second, we use either the commit we just did, or if there were no
2559 # changes the parent of the working directory as the version of the
2559 # changes the parent of the working directory as the version of the
2560 # files in the final amend commit
2560 # files in the final amend commit
2561 if node:
2561 if node:
2562 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2562 ui.note(_('copying changeset %s to %s\n') % (ctx, base))
2563
2563
2564 user = ctx.user()
2564 user = ctx.user()
2565 date = ctx.date()
2565 date = ctx.date()
2566 # Recompute copies (avoid recording a -> b -> a)
2566 # Recompute copies (avoid recording a -> b -> a)
2567 copied = copies.pathcopies(base, ctx)
2567 copied = copies.pathcopies(base, ctx)
2568 if old.p2:
2568 if old.p2:
2569 copied.update(copies.pathcopies(old.p2(), ctx))
2569 copied.update(copies.pathcopies(old.p2(), ctx))
2570
2570
2571 # Prune files which were reverted by the updates: if old
2571 # Prune files which were reverted by the updates: if old
2572 # introduced file X and our intermediate commit, node,
2572 # introduced file X and our intermediate commit, node,
2573 # renamed that file, then those two files are the same and
2573 # renamed that file, then those two files are the same and
2574 # we can discard X from our list of files. Likewise if X
2574 # we can discard X from our list of files. Likewise if X
2575 # was deleted, it's no longer relevant
2575 # was deleted, it's no longer relevant
2576 files.update(ctx.files())
2576 files.update(ctx.files())
2577
2577
2578 def samefile(f):
2578 def samefile(f):
2579 if f in ctx.manifest():
2579 if f in ctx.manifest():
2580 a = ctx.filectx(f)
2580 a = ctx.filectx(f)
2581 if f in base.manifest():
2581 if f in base.manifest():
2582 b = base.filectx(f)
2582 b = base.filectx(f)
2583 return (not a.cmp(b)
2583 return (not a.cmp(b)
2584 and a.flags() == b.flags())
2584 and a.flags() == b.flags())
2585 else:
2585 else:
2586 return False
2586 return False
2587 else:
2587 else:
2588 return f not in base.manifest()
2588 return f not in base.manifest()
2589 files = [f for f in files if not samefile(f)]
2589 files = [f for f in files if not samefile(f)]
2590
2590
2591 def filectxfn(repo, ctx_, path):
2591 def filectxfn(repo, ctx_, path):
2592 try:
2592 try:
2593 fctx = ctx[path]
2593 fctx = ctx[path]
2594 flags = fctx.flags()
2594 flags = fctx.flags()
2595 mctx = context.memfilectx(repo,
2595 mctx = context.memfilectx(repo,
2596 fctx.path(), fctx.data(),
2596 fctx.path(), fctx.data(),
2597 islink='l' in flags,
2597 islink='l' in flags,
2598 isexec='x' in flags,
2598 isexec='x' in flags,
2599 copied=copied.get(path))
2599 copied=copied.get(path))
2600 return mctx
2600 return mctx
2601 except KeyError:
2601 except KeyError:
2602 return None
2602 return None
2603 else:
2603 else:
2604 ui.note(_('copying changeset %s to %s\n') % (old, base))
2604 ui.note(_('copying changeset %s to %s\n') % (old, base))
2605
2605
2606 # Use version of files as in the old cset
2606 # Use version of files as in the old cset
2607 def filectxfn(repo, ctx_, path):
2607 def filectxfn(repo, ctx_, path):
2608 try:
2608 try:
2609 return old.filectx(path)
2609 return old.filectx(path)
2610 except KeyError:
2610 except KeyError:
2611 return None
2611 return None
2612
2612
2613 user = opts.get('user') or old.user()
2613 user = opts.get('user') or old.user()
2614 date = opts.get('date') or old.date()
2614 date = opts.get('date') or old.date()
2615 editform = mergeeditform(old, 'commit.amend')
2615 editform = mergeeditform(old, 'commit.amend')
2616 editor = getcommiteditor(editform=editform, **opts)
2616 editor = getcommiteditor(editform=editform, **opts)
2617 if not message:
2617 if not message:
2618 editor = getcommiteditor(edit=True, editform=editform)
2618 editor = getcommiteditor(edit=True, editform=editform)
2619 message = old.description()
2619 message = old.description()
2620
2620
2621 pureextra = extra.copy()
2621 pureextra = extra.copy()
2622 extra['amend_source'] = old.hex()
2622 extra['amend_source'] = old.hex()
2623
2623
2624 new = context.memctx(repo,
2624 new = context.memctx(repo,
2625 parents=[base.node(), old.p2().node()],
2625 parents=[base.node(), old.p2().node()],
2626 text=message,
2626 text=message,
2627 files=files,
2627 files=files,
2628 filectxfn=filectxfn,
2628 filectxfn=filectxfn,
2629 user=user,
2629 user=user,
2630 date=date,
2630 date=date,
2631 extra=extra,
2631 extra=extra,
2632 editor=editor)
2632 editor=editor)
2633
2633
2634 newdesc = changelog.stripdesc(new.description())
2634 newdesc = changelog.stripdesc(new.description())
2635 if ((not node)
2635 if ((not node)
2636 and newdesc == old.description()
2636 and newdesc == old.description()
2637 and user == old.user()
2637 and user == old.user()
2638 and date == old.date()
2638 and date == old.date()
2639 and pureextra == old.extra()):
2639 and pureextra == old.extra()):
2640 # nothing changed. continuing here would create a new node
2640 # nothing changed. continuing here would create a new node
2641 # anyway because of the amend_source noise.
2641 # anyway because of the amend_source noise.
2642 #
2642 #
2643 # This not what we expect from amend.
2643 # This not what we expect from amend.
2644 return old.node()
2644 return old.node()
2645
2645
2646 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2646 ph = repo.ui.config('phases', 'new-commit', phases.draft)
2647 try:
2647 try:
2648 if opts.get('secret'):
2648 if opts.get('secret'):
2649 commitphase = 'secret'
2649 commitphase = 'secret'
2650 else:
2650 else:
2651 commitphase = old.phase()
2651 commitphase = old.phase()
2652 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2652 repo.ui.setconfig('phases', 'new-commit', commitphase, 'amend')
2653 newid = repo.commitctx(new)
2653 newid = repo.commitctx(new)
2654 finally:
2654 finally:
2655 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2655 repo.ui.setconfig('phases', 'new-commit', ph, 'amend')
2656 if newid != old.node():
2656 if newid != old.node():
2657 # Reroute the working copy parent to the new changeset
2657 # Reroute the working copy parent to the new changeset
2658 repo.setparents(newid, nullid)
2658 repo.setparents(newid, nullid)
2659
2659
2660 # Move bookmarks from old parent to amend commit
2660 # Move bookmarks from old parent to amend commit
2661 bms = repo.nodebookmarks(old.node())
2661 bms = repo.nodebookmarks(old.node())
2662 if bms:
2662 if bms:
2663 marks = repo._bookmarks
2663 marks = repo._bookmarks
2664 for bm in bms:
2664 for bm in bms:
2665 ui.debug('moving bookmarks %r from %s to %s\n' %
2665 ui.debug('moving bookmarks %r from %s to %s\n' %
2666 (marks, old.hex(), hex(newid)))
2666 (marks, old.hex(), hex(newid)))
2667 marks[bm] = newid
2667 marks[bm] = newid
2668 marks.recordchange(tr)
2668 marks.recordchange(tr)
2669 #commit the whole amend process
2669 #commit the whole amend process
2670 if createmarkers:
2670 if createmarkers:
2671 # mark the new changeset as successor of the rewritten one
2671 # mark the new changeset as successor of the rewritten one
2672 new = repo[newid]
2672 new = repo[newid]
2673 obs = [(old, (new,))]
2673 obs = [(old, (new,))]
2674 if node:
2674 if node:
2675 obs.append((ctx, ()))
2675 obs.append((ctx, ()))
2676
2676
2677 obsolete.createmarkers(repo, obs)
2677 obsolete.createmarkers(repo, obs)
2678 tr.close()
2678 tr.close()
2679 finally:
2679 finally:
2680 tr.release()
2680 tr.release()
2681 if not createmarkers and newid != old.node():
2681 if not createmarkers and newid != old.node():
2682 # Strip the intermediate commit (if there was one) and the amended
2682 # Strip the intermediate commit (if there was one) and the amended
2683 # commit
2683 # commit
2684 if node:
2684 if node:
2685 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2685 ui.note(_('stripping intermediate changeset %s\n') % ctx)
2686 ui.note(_('stripping amended changeset %s\n') % old)
2686 ui.note(_('stripping amended changeset %s\n') % old)
2687 repair.strip(ui, repo, old.node(), topic='amend-backup')
2687 repair.strip(ui, repo, old.node(), topic='amend-backup')
2688 finally:
2688 finally:
2689 lockmod.release(lock, wlock)
2689 lockmod.release(lock, wlock)
2690 return newid
2690 return newid
2691
2691
2692 def commiteditor(repo, ctx, subs, editform=''):
2692 def commiteditor(repo, ctx, subs, editform=''):
2693 if ctx.description():
2693 if ctx.description():
2694 return ctx.description()
2694 return ctx.description()
2695 return commitforceeditor(repo, ctx, subs, editform=editform,
2695 return commitforceeditor(repo, ctx, subs, editform=editform,
2696 unchangedmessagedetection=True)
2696 unchangedmessagedetection=True)
2697
2697
2698 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2698 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2699 editform='', unchangedmessagedetection=False):
2699 editform='', unchangedmessagedetection=False):
2700 if not extramsg:
2700 if not extramsg:
2701 extramsg = _("Leave message empty to abort commit.")
2701 extramsg = _("Leave message empty to abort commit.")
2702
2702
2703 forms = [e for e in editform.split('.') if e]
2703 forms = [e for e in editform.split('.') if e]
2704 forms.insert(0, 'changeset')
2704 forms.insert(0, 'changeset')
2705 templatetext = None
2705 templatetext = None
2706 while forms:
2706 while forms:
2707 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2707 tmpl = repo.ui.config('committemplate', '.'.join(forms))
2708 if tmpl:
2708 if tmpl:
2709 templatetext = committext = buildcommittemplate(
2709 templatetext = committext = buildcommittemplate(
2710 repo, ctx, subs, extramsg, tmpl)
2710 repo, ctx, subs, extramsg, tmpl)
2711 break
2711 break
2712 forms.pop()
2712 forms.pop()
2713 else:
2713 else:
2714 committext = buildcommittext(repo, ctx, subs, extramsg)
2714 committext = buildcommittext(repo, ctx, subs, extramsg)
2715
2715
2716 # run editor in the repository root
2716 # run editor in the repository root
2717 olddir = os.getcwd()
2717 olddir = os.getcwd()
2718 os.chdir(repo.root)
2718 os.chdir(repo.root)
2719
2719
2720 # make in-memory changes visible to external process
2720 # make in-memory changes visible to external process
2721 tr = repo.currenttransaction()
2721 tr = repo.currenttransaction()
2722 repo.dirstate.write(tr)
2722 repo.dirstate.write(tr)
2723 pending = tr and tr.writepending() and repo.root
2723 pending = tr and tr.writepending() and repo.root
2724
2724
2725 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2725 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2726 editform=editform, pending=pending)
2726 editform=editform, pending=pending)
2727 text = re.sub("(?m)^HG:.*(\n|$)", "", editortext)
2727 text = re.sub("(?m)^HG:.*(\n|$)", "", editortext)
2728 os.chdir(olddir)
2728 os.chdir(olddir)
2729
2729
2730 if finishdesc:
2730 if finishdesc:
2731 text = finishdesc(text)
2731 text = finishdesc(text)
2732 if not text.strip():
2732 if not text.strip():
2733 raise error.Abort(_("empty commit message"))
2733 raise error.Abort(_("empty commit message"))
2734 if unchangedmessagedetection and editortext == templatetext:
2734 if unchangedmessagedetection and editortext == templatetext:
2735 raise error.Abort(_("commit message unchanged"))
2735 raise error.Abort(_("commit message unchanged"))
2736
2736
2737 return text
2737 return text
2738
2738
2739 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2739 def buildcommittemplate(repo, ctx, subs, extramsg, tmpl):
2740 ui = repo.ui
2740 ui = repo.ui
2741 tmpl, mapfile = gettemplate(ui, tmpl, None)
2741 tmpl, mapfile = gettemplate(ui, tmpl, None)
2742
2742
2743 try:
2743 try:
2744 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2744 t = changeset_templater(ui, repo, None, {}, tmpl, mapfile, False)
2745 except SyntaxError as inst:
2745 except SyntaxError as inst:
2746 raise error.Abort(inst.args[0])
2746 raise error.Abort(inst.args[0])
2747
2747
2748 for k, v in repo.ui.configitems('committemplate'):
2748 for k, v in repo.ui.configitems('committemplate'):
2749 if k != 'changeset':
2749 if k != 'changeset':
2750 t.t.cache[k] = v
2750 t.t.cache[k] = v
2751
2751
2752 if not extramsg:
2752 if not extramsg:
2753 extramsg = '' # ensure that extramsg is string
2753 extramsg = '' # ensure that extramsg is string
2754
2754
2755 ui.pushbuffer()
2755 ui.pushbuffer()
2756 t.show(ctx, extramsg=extramsg)
2756 t.show(ctx, extramsg=extramsg)
2757 return ui.popbuffer()
2757 return ui.popbuffer()
2758
2758
2759 def hgprefix(msg):
2759 def hgprefix(msg):
2760 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2760 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2761
2761
2762 def buildcommittext(repo, ctx, subs, extramsg):
2762 def buildcommittext(repo, ctx, subs, extramsg):
2763 edittext = []
2763 edittext = []
2764 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2764 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2765 if ctx.description():
2765 if ctx.description():
2766 edittext.append(ctx.description())
2766 edittext.append(ctx.description())
2767 edittext.append("")
2767 edittext.append("")
2768 edittext.append("") # Empty line between message and comments.
2768 edittext.append("") # Empty line between message and comments.
2769 edittext.append(hgprefix(_("Enter commit message."
2769 edittext.append(hgprefix(_("Enter commit message."
2770 " Lines beginning with 'HG:' are removed.")))
2770 " Lines beginning with 'HG:' are removed.")))
2771 edittext.append(hgprefix(extramsg))
2771 edittext.append(hgprefix(extramsg))
2772 edittext.append("HG: --")
2772 edittext.append("HG: --")
2773 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2773 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2774 if ctx.p2():
2774 if ctx.p2():
2775 edittext.append(hgprefix(_("branch merge")))
2775 edittext.append(hgprefix(_("branch merge")))
2776 if ctx.branch():
2776 if ctx.branch():
2777 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2777 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2778 if bookmarks.isactivewdirparent(repo):
2778 if bookmarks.isactivewdirparent(repo):
2779 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2779 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2780 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2780 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2781 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2781 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2782 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2782 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2783 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2783 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2784 if not added and not modified and not removed:
2784 if not added and not modified and not removed:
2785 edittext.append(hgprefix(_("no files changed")))
2785 edittext.append(hgprefix(_("no files changed")))
2786 edittext.append("")
2786 edittext.append("")
2787
2787
2788 return "\n".join(edittext)
2788 return "\n".join(edittext)
2789
2789
2790 def commitstatus(repo, node, branch, bheads=None, opts=None):
2790 def commitstatus(repo, node, branch, bheads=None, opts=None):
2791 if opts is None:
2791 if opts is None:
2792 opts = {}
2792 opts = {}
2793 ctx = repo[node]
2793 ctx = repo[node]
2794 parents = ctx.parents()
2794 parents = ctx.parents()
2795
2795
2796 if (not opts.get('amend') and bheads and node not in bheads and not
2796 if (not opts.get('amend') and bheads and node not in bheads and not
2797 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2797 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2798 repo.ui.status(_('created new head\n'))
2798 repo.ui.status(_('created new head\n'))
2799 # The message is not printed for initial roots. For the other
2799 # The message is not printed for initial roots. For the other
2800 # changesets, it is printed in the following situations:
2800 # changesets, it is printed in the following situations:
2801 #
2801 #
2802 # Par column: for the 2 parents with ...
2802 # Par column: for the 2 parents with ...
2803 # N: null or no parent
2803 # N: null or no parent
2804 # B: parent is on another named branch
2804 # B: parent is on another named branch
2805 # C: parent is a regular non head changeset
2805 # C: parent is a regular non head changeset
2806 # H: parent was a branch head of the current branch
2806 # H: parent was a branch head of the current branch
2807 # Msg column: whether we print "created new head" message
2807 # Msg column: whether we print "created new head" message
2808 # In the following, it is assumed that there already exists some
2808 # In the following, it is assumed that there already exists some
2809 # initial branch heads of the current branch, otherwise nothing is
2809 # initial branch heads of the current branch, otherwise nothing is
2810 # printed anyway.
2810 # printed anyway.
2811 #
2811 #
2812 # Par Msg Comment
2812 # Par Msg Comment
2813 # N N y additional topo root
2813 # N N y additional topo root
2814 #
2814 #
2815 # B N y additional branch root
2815 # B N y additional branch root
2816 # C N y additional topo head
2816 # C N y additional topo head
2817 # H N n usual case
2817 # H N n usual case
2818 #
2818 #
2819 # B B y weird additional branch root
2819 # B B y weird additional branch root
2820 # C B y branch merge
2820 # C B y branch merge
2821 # H B n merge with named branch
2821 # H B n merge with named branch
2822 #
2822 #
2823 # C C y additional head from merge
2823 # C C y additional head from merge
2824 # C H n merge with a head
2824 # C H n merge with a head
2825 #
2825 #
2826 # H H n head merge: head count decreases
2826 # H H n head merge: head count decreases
2827
2827
2828 if not opts.get('close_branch'):
2828 if not opts.get('close_branch'):
2829 for r in parents:
2829 for r in parents:
2830 if r.closesbranch() and r.branch() == branch:
2830 if r.closesbranch() and r.branch() == branch:
2831 repo.ui.status(_('reopening closed branch head %d\n') % r)
2831 repo.ui.status(_('reopening closed branch head %d\n') % r)
2832
2832
2833 if repo.ui.debugflag:
2833 if repo.ui.debugflag:
2834 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2834 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
2835 elif repo.ui.verbose:
2835 elif repo.ui.verbose:
2836 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2836 repo.ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
2837
2837
2838 def revert(ui, repo, ctx, parents, *pats, **opts):
2838 def revert(ui, repo, ctx, parents, *pats, **opts):
2839 parent, p2 = parents
2839 parent, p2 = parents
2840 node = ctx.node()
2840 node = ctx.node()
2841
2841
2842 mf = ctx.manifest()
2842 mf = ctx.manifest()
2843 if node == p2:
2843 if node == p2:
2844 parent = p2
2844 parent = p2
2845 if node == parent:
2845 if node == parent:
2846 pmf = mf
2846 pmf = mf
2847 else:
2847 else:
2848 pmf = None
2848 pmf = None
2849
2849
2850 # need all matching names in dirstate and manifest of target rev,
2850 # need all matching names in dirstate and manifest of target rev,
2851 # so have to walk both. do not print errors if files exist in one
2851 # so have to walk both. do not print errors if files exist in one
2852 # but not other. in both cases, filesets should be evaluated against
2852 # but not other. in both cases, filesets should be evaluated against
2853 # workingctx to get consistent result (issue4497). this means 'set:**'
2853 # workingctx to get consistent result (issue4497). this means 'set:**'
2854 # cannot be used to select missing files from target rev.
2854 # cannot be used to select missing files from target rev.
2855
2855
2856 # `names` is a mapping for all elements in working copy and target revision
2856 # `names` is a mapping for all elements in working copy and target revision
2857 # The mapping is in the form:
2857 # The mapping is in the form:
2858 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2858 # <asb path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2859 names = {}
2859 names = {}
2860
2860
2861 wlock = repo.wlock()
2861 wlock = repo.wlock()
2862 try:
2862 try:
2863 ## filling of the `names` mapping
2863 ## filling of the `names` mapping
2864 # walk dirstate to fill `names`
2864 # walk dirstate to fill `names`
2865
2865
2866 interactive = opts.get('interactive', False)
2866 interactive = opts.get('interactive', False)
2867 wctx = repo[None]
2867 wctx = repo[None]
2868 m = scmutil.match(wctx, pats, opts)
2868 m = scmutil.match(wctx, pats, opts)
2869
2869
2870 # we'll need this later
2870 # we'll need this later
2871 targetsubs = sorted(s for s in wctx.substate if m(s))
2871 targetsubs = sorted(s for s in wctx.substate if m(s))
2872
2872
2873 if not m.always():
2873 if not m.always():
2874 for abs in repo.walk(matchmod.badmatch(m, lambda x, y: False)):
2874 for abs in repo.walk(matchmod.badmatch(m, lambda x, y: False)):
2875 names[abs] = m.rel(abs), m.exact(abs)
2875 names[abs] = m.rel(abs), m.exact(abs)
2876
2876
2877 # walk target manifest to fill `names`
2877 # walk target manifest to fill `names`
2878
2878
2879 def badfn(path, msg):
2879 def badfn(path, msg):
2880 if path in names:
2880 if path in names:
2881 return
2881 return
2882 if path in ctx.substate:
2882 if path in ctx.substate:
2883 return
2883 return
2884 path_ = path + '/'
2884 path_ = path + '/'
2885 for f in names:
2885 for f in names:
2886 if f.startswith(path_):
2886 if f.startswith(path_):
2887 return
2887 return
2888 ui.warn("%s: %s\n" % (m.rel(path), msg))
2888 ui.warn("%s: %s\n" % (m.rel(path), msg))
2889
2889
2890 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2890 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2891 if abs not in names:
2891 if abs not in names:
2892 names[abs] = m.rel(abs), m.exact(abs)
2892 names[abs] = m.rel(abs), m.exact(abs)
2893
2893
2894 # Find status of all file in `names`.
2894 # Find status of all file in `names`.
2895 m = scmutil.matchfiles(repo, names)
2895 m = scmutil.matchfiles(repo, names)
2896
2896
2897 changes = repo.status(node1=node, match=m,
2897 changes = repo.status(node1=node, match=m,
2898 unknown=True, ignored=True, clean=True)
2898 unknown=True, ignored=True, clean=True)
2899 else:
2899 else:
2900 changes = repo.status(node1=node, match=m)
2900 changes = repo.status(node1=node, match=m)
2901 for kind in changes:
2901 for kind in changes:
2902 for abs in kind:
2902 for abs in kind:
2903 names[abs] = m.rel(abs), m.exact(abs)
2903 names[abs] = m.rel(abs), m.exact(abs)
2904
2904
2905 m = scmutil.matchfiles(repo, names)
2905 m = scmutil.matchfiles(repo, names)
2906
2906
2907 modified = set(changes.modified)
2907 modified = set(changes.modified)
2908 added = set(changes.added)
2908 added = set(changes.added)
2909 removed = set(changes.removed)
2909 removed = set(changes.removed)
2910 _deleted = set(changes.deleted)
2910 _deleted = set(changes.deleted)
2911 unknown = set(changes.unknown)
2911 unknown = set(changes.unknown)
2912 unknown.update(changes.ignored)
2912 unknown.update(changes.ignored)
2913 clean = set(changes.clean)
2913 clean = set(changes.clean)
2914 modadded = set()
2914 modadded = set()
2915
2915
2916 # split between files known in target manifest and the others
2916 # split between files known in target manifest and the others
2917 smf = set(mf)
2917 smf = set(mf)
2918
2918
2919 # determine the exact nature of the deleted changesets
2919 # determine the exact nature of the deleted changesets
2920 deladded = _deleted - smf
2920 deladded = _deleted - smf
2921 deleted = _deleted - deladded
2921 deleted = _deleted - deladded
2922
2922
2923 # We need to account for the state of the file in the dirstate,
2923 # We need to account for the state of the file in the dirstate,
2924 # even when we revert against something else than parent. This will
2924 # even when we revert against something else than parent. This will
2925 # slightly alter the behavior of revert (doing back up or not, delete
2925 # slightly alter the behavior of revert (doing back up or not, delete
2926 # or just forget etc).
2926 # or just forget etc).
2927 if parent == node:
2927 if parent == node:
2928 dsmodified = modified
2928 dsmodified = modified
2929 dsadded = added
2929 dsadded = added
2930 dsremoved = removed
2930 dsremoved = removed
2931 # store all local modifications, useful later for rename detection
2931 # store all local modifications, useful later for rename detection
2932 localchanges = dsmodified | dsadded
2932 localchanges = dsmodified | dsadded
2933 modified, added, removed = set(), set(), set()
2933 modified, added, removed = set(), set(), set()
2934 else:
2934 else:
2935 changes = repo.status(node1=parent, match=m)
2935 changes = repo.status(node1=parent, match=m)
2936 dsmodified = set(changes.modified)
2936 dsmodified = set(changes.modified)
2937 dsadded = set(changes.added)
2937 dsadded = set(changes.added)
2938 dsremoved = set(changes.removed)
2938 dsremoved = set(changes.removed)
2939 # store all local modifications, useful later for rename detection
2939 # store all local modifications, useful later for rename detection
2940 localchanges = dsmodified | dsadded
2940 localchanges = dsmodified | dsadded
2941
2941
2942 # only take into account for removes between wc and target
2942 # only take into account for removes between wc and target
2943 clean |= dsremoved - removed
2943 clean |= dsremoved - removed
2944 dsremoved &= removed
2944 dsremoved &= removed
2945 # distinct between dirstate remove and other
2945 # distinct between dirstate remove and other
2946 removed -= dsremoved
2946 removed -= dsremoved
2947
2947
2948 modadded = added & dsmodified
2948 modadded = added & dsmodified
2949 added -= modadded
2949 added -= modadded
2950
2950
2951 # tell newly modified apart.
2951 # tell newly modified apart.
2952 dsmodified &= modified
2952 dsmodified &= modified
2953 dsmodified |= modified & dsadded # dirstate added may needs backup
2953 dsmodified |= modified & dsadded # dirstate added may needs backup
2954 modified -= dsmodified
2954 modified -= dsmodified
2955
2955
2956 # We need to wait for some post-processing to update this set
2956 # We need to wait for some post-processing to update this set
2957 # before making the distinction. The dirstate will be used for
2957 # before making the distinction. The dirstate will be used for
2958 # that purpose.
2958 # that purpose.
2959 dsadded = added
2959 dsadded = added
2960
2960
2961 # in case of merge, files that are actually added can be reported as
2961 # in case of merge, files that are actually added can be reported as
2962 # modified, we need to post process the result
2962 # modified, we need to post process the result
2963 if p2 != nullid:
2963 if p2 != nullid:
2964 if pmf is None:
2964 if pmf is None:
2965 # only need parent manifest in the merge case,
2965 # only need parent manifest in the merge case,
2966 # so do not read by default
2966 # so do not read by default
2967 pmf = repo[parent].manifest()
2967 pmf = repo[parent].manifest()
2968 mergeadd = dsmodified - set(pmf)
2968 mergeadd = dsmodified - set(pmf)
2969 dsadded |= mergeadd
2969 dsadded |= mergeadd
2970 dsmodified -= mergeadd
2970 dsmodified -= mergeadd
2971
2971
2972 # if f is a rename, update `names` to also revert the source
2972 # if f is a rename, update `names` to also revert the source
2973 cwd = repo.getcwd()
2973 cwd = repo.getcwd()
2974 for f in localchanges:
2974 for f in localchanges:
2975 src = repo.dirstate.copied(f)
2975 src = repo.dirstate.copied(f)
2976 # XXX should we check for rename down to target node?
2976 # XXX should we check for rename down to target node?
2977 if src and src not in names and repo.dirstate[src] == 'r':
2977 if src and src not in names and repo.dirstate[src] == 'r':
2978 dsremoved.add(src)
2978 dsremoved.add(src)
2979 names[src] = (repo.pathto(src, cwd), True)
2979 names[src] = (repo.pathto(src, cwd), True)
2980
2980
2981 # distinguish between file to forget and the other
2981 # distinguish between file to forget and the other
2982 added = set()
2982 added = set()
2983 for abs in dsadded:
2983 for abs in dsadded:
2984 if repo.dirstate[abs] != 'a':
2984 if repo.dirstate[abs] != 'a':
2985 added.add(abs)
2985 added.add(abs)
2986 dsadded -= added
2986 dsadded -= added
2987
2987
2988 for abs in deladded:
2988 for abs in deladded:
2989 if repo.dirstate[abs] == 'a':
2989 if repo.dirstate[abs] == 'a':
2990 dsadded.add(abs)
2990 dsadded.add(abs)
2991 deladded -= dsadded
2991 deladded -= dsadded
2992
2992
2993 # For files marked as removed, we check if an unknown file is present at
2993 # For files marked as removed, we check if an unknown file is present at
2994 # the same path. If a such file exists it may need to be backed up.
2994 # the same path. If a such file exists it may need to be backed up.
2995 # Making the distinction at this stage helps have simpler backup
2995 # Making the distinction at this stage helps have simpler backup
2996 # logic.
2996 # logic.
2997 removunk = set()
2997 removunk = set()
2998 for abs in removed:
2998 for abs in removed:
2999 target = repo.wjoin(abs)
2999 target = repo.wjoin(abs)
3000 if os.path.lexists(target):
3000 if os.path.lexists(target):
3001 removunk.add(abs)
3001 removunk.add(abs)
3002 removed -= removunk
3002 removed -= removunk
3003
3003
3004 dsremovunk = set()
3004 dsremovunk = set()
3005 for abs in dsremoved:
3005 for abs in dsremoved:
3006 target = repo.wjoin(abs)
3006 target = repo.wjoin(abs)
3007 if os.path.lexists(target):
3007 if os.path.lexists(target):
3008 dsremovunk.add(abs)
3008 dsremovunk.add(abs)
3009 dsremoved -= dsremovunk
3009 dsremoved -= dsremovunk
3010
3010
3011 # action to be actually performed by revert
3011 # action to be actually performed by revert
3012 # (<list of file>, message>) tuple
3012 # (<list of file>, message>) tuple
3013 actions = {'revert': ([], _('reverting %s\n')),
3013 actions = {'revert': ([], _('reverting %s\n')),
3014 'add': ([], _('adding %s\n')),
3014 'add': ([], _('adding %s\n')),
3015 'remove': ([], _('removing %s\n')),
3015 'remove': ([], _('removing %s\n')),
3016 'drop': ([], _('removing %s\n')),
3016 'drop': ([], _('removing %s\n')),
3017 'forget': ([], _('forgetting %s\n')),
3017 'forget': ([], _('forgetting %s\n')),
3018 'undelete': ([], _('undeleting %s\n')),
3018 'undelete': ([], _('undeleting %s\n')),
3019 'noop': (None, _('no changes needed to %s\n')),
3019 'noop': (None, _('no changes needed to %s\n')),
3020 'unknown': (None, _('file not managed: %s\n')),
3020 'unknown': (None, _('file not managed: %s\n')),
3021 }
3021 }
3022
3022
3023 # "constant" that convey the backup strategy.
3023 # "constant" that convey the backup strategy.
3024 # All set to `discard` if `no-backup` is set do avoid checking
3024 # All set to `discard` if `no-backup` is set do avoid checking
3025 # no_backup lower in the code.
3025 # no_backup lower in the code.
3026 # These values are ordered for comparison purposes
3026 # These values are ordered for comparison purposes
3027 backup = 2 # unconditionally do backup
3027 backup = 2 # unconditionally do backup
3028 check = 1 # check if the existing file differs from target
3028 check = 1 # check if the existing file differs from target
3029 discard = 0 # never do backup
3029 discard = 0 # never do backup
3030 if opts.get('no_backup'):
3030 if opts.get('no_backup'):
3031 backup = check = discard
3031 backup = check = discard
3032
3032
3033 backupanddel = actions['remove']
3033 backupanddel = actions['remove']
3034 if not opts.get('no_backup'):
3034 if not opts.get('no_backup'):
3035 backupanddel = actions['drop']
3035 backupanddel = actions['drop']
3036
3036
3037 disptable = (
3037 disptable = (
3038 # dispatch table:
3038 # dispatch table:
3039 # file state
3039 # file state
3040 # action
3040 # action
3041 # make backup
3041 # make backup
3042
3042
3043 ## Sets that results that will change file on disk
3043 ## Sets that results that will change file on disk
3044 # Modified compared to target, no local change
3044 # Modified compared to target, no local change
3045 (modified, actions['revert'], discard),
3045 (modified, actions['revert'], discard),
3046 # Modified compared to target, but local file is deleted
3046 # Modified compared to target, but local file is deleted
3047 (deleted, actions['revert'], discard),
3047 (deleted, actions['revert'], discard),
3048 # Modified compared to target, local change
3048 # Modified compared to target, local change
3049 (dsmodified, actions['revert'], backup),
3049 (dsmodified, actions['revert'], backup),
3050 # Added since target
3050 # Added since target
3051 (added, actions['remove'], discard),
3051 (added, actions['remove'], discard),
3052 # Added in working directory
3052 # Added in working directory
3053 (dsadded, actions['forget'], discard),
3053 (dsadded, actions['forget'], discard),
3054 # Added since target, have local modification
3054 # Added since target, have local modification
3055 (modadded, backupanddel, backup),
3055 (modadded, backupanddel, backup),
3056 # Added since target but file is missing in working directory
3056 # Added since target but file is missing in working directory
3057 (deladded, actions['drop'], discard),
3057 (deladded, actions['drop'], discard),
3058 # Removed since target, before working copy parent
3058 # Removed since target, before working copy parent
3059 (removed, actions['add'], discard),
3059 (removed, actions['add'], discard),
3060 # Same as `removed` but an unknown file exists at the same path
3060 # Same as `removed` but an unknown file exists at the same path
3061 (removunk, actions['add'], check),
3061 (removunk, actions['add'], check),
3062 # Removed since targe, marked as such in working copy parent
3062 # Removed since targe, marked as such in working copy parent
3063 (dsremoved, actions['undelete'], discard),
3063 (dsremoved, actions['undelete'], discard),
3064 # Same as `dsremoved` but an unknown file exists at the same path
3064 # Same as `dsremoved` but an unknown file exists at the same path
3065 (dsremovunk, actions['undelete'], check),
3065 (dsremovunk, actions['undelete'], check),
3066 ## the following sets does not result in any file changes
3066 ## the following sets does not result in any file changes
3067 # File with no modification
3067 # File with no modification
3068 (clean, actions['noop'], discard),
3068 (clean, actions['noop'], discard),
3069 # Existing file, not tracked anywhere
3069 # Existing file, not tracked anywhere
3070 (unknown, actions['unknown'], discard),
3070 (unknown, actions['unknown'], discard),
3071 )
3071 )
3072
3072
3073 for abs, (rel, exact) in sorted(names.items()):
3073 for abs, (rel, exact) in sorted(names.items()):
3074 # target file to be touch on disk (relative to cwd)
3074 # target file to be touch on disk (relative to cwd)
3075 target = repo.wjoin(abs)
3075 target = repo.wjoin(abs)
3076 # search the entry in the dispatch table.
3076 # search the entry in the dispatch table.
3077 # if the file is in any of these sets, it was touched in the working
3077 # if the file is in any of these sets, it was touched in the working
3078 # directory parent and we are sure it needs to be reverted.
3078 # directory parent and we are sure it needs to be reverted.
3079 for table, (xlist, msg), dobackup in disptable:
3079 for table, (xlist, msg), dobackup in disptable:
3080 if abs not in table:
3080 if abs not in table:
3081 continue
3081 continue
3082 if xlist is not None:
3082 if xlist is not None:
3083 xlist.append(abs)
3083 xlist.append(abs)
3084 if dobackup and (backup <= dobackup
3084 if dobackup and (backup <= dobackup
3085 or wctx[abs].cmp(ctx[abs])):
3085 or wctx[abs].cmp(ctx[abs])):
3086 bakname = origpath(ui, repo, rel)
3086 bakname = origpath(ui, repo, rel)
3087 ui.note(_('saving current version of %s as %s\n') %
3087 ui.note(_('saving current version of %s as %s\n') %
3088 (rel, bakname))
3088 (rel, bakname))
3089 if not opts.get('dry_run'):
3089 if not opts.get('dry_run'):
3090 if interactive:
3090 if interactive:
3091 util.copyfile(target, bakname)
3091 util.copyfile(target, bakname)
3092 else:
3092 else:
3093 util.rename(target, bakname)
3093 util.rename(target, bakname)
3094 if ui.verbose or not exact:
3094 if ui.verbose or not exact:
3095 if not isinstance(msg, basestring):
3095 if not isinstance(msg, basestring):
3096 msg = msg(abs)
3096 msg = msg(abs)
3097 ui.status(msg % rel)
3097 ui.status(msg % rel)
3098 elif exact:
3098 elif exact:
3099 ui.warn(msg % rel)
3099 ui.warn(msg % rel)
3100 break
3100 break
3101
3101
3102 if not opts.get('dry_run'):
3102 if not opts.get('dry_run'):
3103 needdata = ('revert', 'add', 'undelete')
3103 needdata = ('revert', 'add', 'undelete')
3104 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3104 _revertprefetch(repo, ctx, *[actions[name][0] for name in needdata])
3105 _performrevert(repo, parents, ctx, actions, interactive)
3105 _performrevert(repo, parents, ctx, actions, interactive)
3106
3106
3107 if targetsubs:
3107 if targetsubs:
3108 # Revert the subrepos on the revert list
3108 # Revert the subrepos on the revert list
3109 for sub in targetsubs:
3109 for sub in targetsubs:
3110 try:
3110 try:
3111 wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
3111 wctx.sub(sub).revert(ctx.substate[sub], *pats, **opts)
3112 except KeyError:
3112 except KeyError:
3113 raise error.Abort("subrepository '%s' does not exist in %s!"
3113 raise error.Abort("subrepository '%s' does not exist in %s!"
3114 % (sub, short(ctx.node())))
3114 % (sub, short(ctx.node())))
3115 finally:
3115 finally:
3116 wlock.release()
3116 wlock.release()
3117
3117
3118 def origpath(ui, repo, filepath):
3118 def origpath(ui, repo, filepath):
3119 '''customize where .orig files are created
3119 '''customize where .orig files are created
3120
3120
3121 Fetch user defined path from config file: [ui] origbackuppath = <path>
3121 Fetch user defined path from config file: [ui] origbackuppath = <path>
3122 Fall back to default (filepath) if not specified
3122 Fall back to default (filepath) if not specified
3123 '''
3123 '''
3124 origbackuppath = ui.config('ui', 'origbackuppath', None)
3124 origbackuppath = ui.config('ui', 'origbackuppath', None)
3125 if origbackuppath is None:
3125 if origbackuppath is None:
3126 return filepath + ".orig"
3126 return filepath + ".orig"
3127
3127
3128 filepathfromroot = os.path.relpath(filepath, start=repo.root)
3128 filepathfromroot = os.path.relpath(filepath, start=repo.root)
3129 fullorigpath = repo.wjoin(origbackuppath, filepathfromroot)
3129 fullorigpath = repo.wjoin(origbackuppath, filepathfromroot)
3130
3130
3131 origbackupdir = repo.vfs.dirname(fullorigpath)
3131 origbackupdir = repo.vfs.dirname(fullorigpath)
3132 if not repo.vfs.exists(origbackupdir):
3132 if not repo.vfs.exists(origbackupdir):
3133 ui.note(_('creating directory: %s\n') % origbackupdir)
3133 ui.note(_('creating directory: %s\n') % origbackupdir)
3134 util.makedirs(origbackupdir)
3134 util.makedirs(origbackupdir)
3135
3135
3136 return fullorigpath + ".orig"
3136 return fullorigpath + ".orig"
3137
3137
3138 def _revertprefetch(repo, ctx, *files):
3138 def _revertprefetch(repo, ctx, *files):
3139 """Let extension changing the storage layer prefetch content"""
3139 """Let extension changing the storage layer prefetch content"""
3140 pass
3140 pass
3141
3141
3142 def _performrevert(repo, parents, ctx, actions, interactive=False):
3142 def _performrevert(repo, parents, ctx, actions, interactive=False):
3143 """function that actually perform all the actions computed for revert
3143 """function that actually perform all the actions computed for revert
3144
3144
3145 This is an independent function to let extension to plug in and react to
3145 This is an independent function to let extension to plug in and react to
3146 the imminent revert.
3146 the imminent revert.
3147
3147
3148 Make sure you have the working directory locked when calling this function.
3148 Make sure you have the working directory locked when calling this function.
3149 """
3149 """
3150 parent, p2 = parents
3150 parent, p2 = parents
3151 node = ctx.node()
3151 node = ctx.node()
3152 def checkout(f):
3152 def checkout(f):
3153 fc = ctx[f]
3153 fc = ctx[f]
3154 repo.wwrite(f, fc.data(), fc.flags())
3154 repo.wwrite(f, fc.data(), fc.flags())
3155
3155
3156 audit_path = pathutil.pathauditor(repo.root)
3156 audit_path = pathutil.pathauditor(repo.root)
3157 for f in actions['forget'][0]:
3157 for f in actions['forget'][0]:
3158 repo.dirstate.drop(f)
3158 repo.dirstate.drop(f)
3159 for f in actions['remove'][0]:
3159 for f in actions['remove'][0]:
3160 audit_path(f)
3160 audit_path(f)
3161 try:
3161 try:
3162 util.unlinkpath(repo.wjoin(f))
3162 util.unlinkpath(repo.wjoin(f))
3163 except OSError:
3163 except OSError:
3164 pass
3164 pass
3165 repo.dirstate.remove(f)
3165 repo.dirstate.remove(f)
3166 for f in actions['drop'][0]:
3166 for f in actions['drop'][0]:
3167 audit_path(f)
3167 audit_path(f)
3168 repo.dirstate.remove(f)
3168 repo.dirstate.remove(f)
3169
3169
3170 normal = None
3170 normal = None
3171 if node == parent:
3171 if node == parent:
3172 # We're reverting to our parent. If possible, we'd like status
3172 # We're reverting to our parent. If possible, we'd like status
3173 # to report the file as clean. We have to use normallookup for
3173 # to report the file as clean. We have to use normallookup for
3174 # merges to avoid losing information about merged/dirty files.
3174 # merges to avoid losing information about merged/dirty files.
3175 if p2 != nullid:
3175 if p2 != nullid:
3176 normal = repo.dirstate.normallookup
3176 normal = repo.dirstate.normallookup
3177 else:
3177 else:
3178 normal = repo.dirstate.normal
3178 normal = repo.dirstate.normal
3179
3179
3180 newlyaddedandmodifiedfiles = set()
3180 newlyaddedandmodifiedfiles = set()
3181 if interactive:
3181 if interactive:
3182 # Prompt the user for changes to revert
3182 # Prompt the user for changes to revert
3183 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3183 torevert = [repo.wjoin(f) for f in actions['revert'][0]]
3184 m = scmutil.match(ctx, torevert, {})
3184 m = scmutil.match(ctx, torevert, {})
3185 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3185 diffopts = patch.difffeatureopts(repo.ui, whitespace=True)
3186 diffopts.nodates = True
3186 diffopts.nodates = True
3187 diffopts.git = True
3187 diffopts.git = True
3188 reversehunks = repo.ui.configbool('experimental',
3188 reversehunks = repo.ui.configbool('experimental',
3189 'revertalternateinteractivemode',
3189 'revertalternateinteractivemode',
3190 True)
3190 True)
3191 if reversehunks:
3191 if reversehunks:
3192 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3192 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3193 else:
3193 else:
3194 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3194 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3195 originalchunks = patch.parsepatch(diff)
3195 originalchunks = patch.parsepatch(diff)
3196
3196
3197 try:
3197 try:
3198
3198
3199 chunks = recordfilter(repo.ui, originalchunks)
3199 chunks = recordfilter(repo.ui, originalchunks)
3200 if reversehunks:
3200 if reversehunks:
3201 chunks = patch.reversehunks(chunks)
3201 chunks = patch.reversehunks(chunks)
3202
3202
3203 except patch.PatchError as err:
3203 except patch.PatchError as err:
3204 raise error.Abort(_('error parsing patch: %s') % err)
3204 raise error.Abort(_('error parsing patch: %s') % err)
3205
3205
3206 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3206 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3207 # Apply changes
3207 # Apply changes
3208 fp = cStringIO.StringIO()
3208 fp = cStringIO.StringIO()
3209 for c in chunks:
3209 for c in chunks:
3210 c.write(fp)
3210 c.write(fp)
3211 dopatch = fp.tell()
3211 dopatch = fp.tell()
3212 fp.seek(0)
3212 fp.seek(0)
3213 if dopatch:
3213 if dopatch:
3214 try:
3214 try:
3215 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3215 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3216 except patch.PatchError as err:
3216 except patch.PatchError as err:
3217 raise error.Abort(str(err))
3217 raise error.Abort(str(err))
3218 del fp
3218 del fp
3219 else:
3219 else:
3220 for f in actions['revert'][0]:
3220 for f in actions['revert'][0]:
3221 checkout(f)
3221 checkout(f)
3222 if normal:
3222 if normal:
3223 normal(f)
3223 normal(f)
3224
3224
3225 for f in actions['add'][0]:
3225 for f in actions['add'][0]:
3226 # Don't checkout modified files, they are already created by the diff
3226 # Don't checkout modified files, they are already created by the diff
3227 if f not in newlyaddedandmodifiedfiles:
3227 if f not in newlyaddedandmodifiedfiles:
3228 checkout(f)
3228 checkout(f)
3229 repo.dirstate.add(f)
3229 repo.dirstate.add(f)
3230
3230
3231 normal = repo.dirstate.normallookup
3231 normal = repo.dirstate.normallookup
3232 if node == parent and p2 == nullid:
3232 if node == parent and p2 == nullid:
3233 normal = repo.dirstate.normal
3233 normal = repo.dirstate.normal
3234 for f in actions['undelete'][0]:
3234 for f in actions['undelete'][0]:
3235 checkout(f)
3235 checkout(f)
3236 normal(f)
3236 normal(f)
3237
3237
3238 copied = copies.pathcopies(repo[parent], ctx)
3238 copied = copies.pathcopies(repo[parent], ctx)
3239
3239
3240 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3240 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3241 if f in copied:
3241 if f in copied:
3242 repo.dirstate.copy(copied[f], f)
3242 repo.dirstate.copy(copied[f], f)
3243
3243
3244 def command(table):
3244 def command(table):
3245 """Returns a function object to be used as a decorator for making commands.
3245 """Returns a function object to be used as a decorator for making commands.
3246
3246
3247 This function receives a command table as its argument. The table should
3247 This function receives a command table as its argument. The table should
3248 be a dict.
3248 be a dict.
3249
3249
3250 The returned function can be used as a decorator for adding commands
3250 The returned function can be used as a decorator for adding commands
3251 to that command table. This function accepts multiple arguments to define
3251 to that command table. This function accepts multiple arguments to define
3252 a command.
3252 a command.
3253
3253
3254 The first argument is the command name.
3254 The first argument is the command name.
3255
3255
3256 The options argument is an iterable of tuples defining command arguments.
3256 The options argument is an iterable of tuples defining command arguments.
3257 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
3257 See ``mercurial.fancyopts.fancyopts()`` for the format of each tuple.
3258
3258
3259 The synopsis argument defines a short, one line summary of how to use the
3259 The synopsis argument defines a short, one line summary of how to use the
3260 command. This shows up in the help output.
3260 command. This shows up in the help output.
3261
3261
3262 The norepo argument defines whether the command does not require a
3262 The norepo argument defines whether the command does not require a
3263 local repository. Most commands operate against a repository, thus the
3263 local repository. Most commands operate against a repository, thus the
3264 default is False.
3264 default is False.
3265
3265
3266 The optionalrepo argument defines whether the command optionally requires
3266 The optionalrepo argument defines whether the command optionally requires
3267 a local repository.
3267 a local repository.
3268
3268
3269 The inferrepo argument defines whether to try to find a repository from the
3269 The inferrepo argument defines whether to try to find a repository from the
3270 command line arguments. If True, arguments will be examined for potential
3270 command line arguments. If True, arguments will be examined for potential
3271 repository locations. See ``findrepo()``. If a repository is found, it
3271 repository locations. See ``findrepo()``. If a repository is found, it
3272 will be used.
3272 will be used.
3273 """
3273 """
3274 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
3274 def cmd(name, options=(), synopsis=None, norepo=False, optionalrepo=False,
3275 inferrepo=False):
3275 inferrepo=False):
3276 def decorator(func):
3276 def decorator(func):
3277 if synopsis:
3277 if synopsis:
3278 table[name] = func, list(options), synopsis
3278 table[name] = func, list(options), synopsis
3279 else:
3279 else:
3280 table[name] = func, list(options)
3280 table[name] = func, list(options)
3281
3281
3282 if norepo:
3282 if norepo:
3283 # Avoid import cycle.
3283 # Avoid import cycle.
3284 import commands
3284 import commands
3285 commands.norepo += ' %s' % ' '.join(parsealiases(name))
3285 commands.norepo += ' %s' % ' '.join(parsealiases(name))
3286
3286
3287 if optionalrepo:
3287 if optionalrepo:
3288 import commands
3288 import commands
3289 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
3289 commands.optionalrepo += ' %s' % ' '.join(parsealiases(name))
3290
3290
3291 if inferrepo:
3291 if inferrepo:
3292 import commands
3292 import commands
3293 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
3293 commands.inferrepo += ' %s' % ' '.join(parsealiases(name))
3294
3294
3295 return func
3295 return func
3296 return decorator
3296 return decorator
3297
3297
3298 return cmd
3298 return cmd
3299
3299
3300 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3300 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3301 # commands.outgoing. "missing" is "missing" of the result of
3301 # commands.outgoing. "missing" is "missing" of the result of
3302 # "findcommonoutgoing()"
3302 # "findcommonoutgoing()"
3303 outgoinghooks = util.hooks()
3303 outgoinghooks = util.hooks()
3304
3304
3305 # a list of (ui, repo) functions called by commands.summary
3305 # a list of (ui, repo) functions called by commands.summary
3306 summaryhooks = util.hooks()
3306 summaryhooks = util.hooks()
3307
3307
3308 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3308 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3309 #
3309 #
3310 # functions should return tuple of booleans below, if 'changes' is None:
3310 # functions should return tuple of booleans below, if 'changes' is None:
3311 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3311 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3312 #
3312 #
3313 # otherwise, 'changes' is a tuple of tuples below:
3313 # otherwise, 'changes' is a tuple of tuples below:
3314 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3314 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3315 # - (desturl, destbranch, destpeer, outgoing)
3315 # - (desturl, destbranch, destpeer, outgoing)
3316 summaryremotehooks = util.hooks()
3316 summaryremotehooks = util.hooks()
3317
3317
3318 # A list of state files kept by multistep operations like graft.
3318 # A list of state files kept by multistep operations like graft.
3319 # Since graft cannot be aborted, it is considered 'clearable' by update.
3319 # Since graft cannot be aborted, it is considered 'clearable' by update.
3320 # note: bisect is intentionally excluded
3320 # note: bisect is intentionally excluded
3321 # (state file, clearable, allowcommit, error, hint)
3321 # (state file, clearable, allowcommit, error, hint)
3322 unfinishedstates = [
3322 unfinishedstates = [
3323 ('graftstate', True, False, _('graft in progress'),
3323 ('graftstate', True, False, _('graft in progress'),
3324 _("use 'hg graft --continue' or 'hg update' to abort")),
3324 _("use 'hg graft --continue' or 'hg update' to abort")),
3325 ('updatestate', True, False, _('last update was interrupted'),
3325 ('updatestate', True, False, _('last update was interrupted'),
3326 _("use 'hg update' to get a consistent checkout"))
3326 _("use 'hg update' to get a consistent checkout"))
3327 ]
3327 ]
3328
3328
3329 def checkunfinished(repo, commit=False):
3329 def checkunfinished(repo, commit=False):
3330 '''Look for an unfinished multistep operation, like graft, and abort
3330 '''Look for an unfinished multistep operation, like graft, and abort
3331 if found. It's probably good to check this right before
3331 if found. It's probably good to check this right before
3332 bailifchanged().
3332 bailifchanged().
3333 '''
3333 '''
3334 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3334 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3335 if commit and allowcommit:
3335 if commit and allowcommit:
3336 continue
3336 continue
3337 if repo.vfs.exists(f):
3337 if repo.vfs.exists(f):
3338 raise error.Abort(msg, hint=hint)
3338 raise error.Abort(msg, hint=hint)
3339
3339
3340 def clearunfinished(repo):
3340 def clearunfinished(repo):
3341 '''Check for unfinished operations (as above), and clear the ones
3341 '''Check for unfinished operations (as above), and clear the ones
3342 that are clearable.
3342 that are clearable.
3343 '''
3343 '''
3344 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3344 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3345 if not clearable and repo.vfs.exists(f):
3345 if not clearable and repo.vfs.exists(f):
3346 raise error.Abort(msg, hint=hint)
3346 raise error.Abort(msg, hint=hint)
3347 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3347 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3348 if clearable and repo.vfs.exists(f):
3348 if clearable and repo.vfs.exists(f):
3349 util.unlink(repo.join(f))
3349 util.unlink(repo.join(f))
3350
3350
3351 class dirstateguard(object):
3351 class dirstateguard(object):
3352 '''Restore dirstate at unexpected failure.
3352 '''Restore dirstate at unexpected failure.
3353
3353
3354 At the construction, this class does:
3354 At the construction, this class does:
3355
3355
3356 - write current ``repo.dirstate`` out, and
3356 - write current ``repo.dirstate`` out, and
3357 - save ``.hg/dirstate`` into the backup file
3357 - save ``.hg/dirstate`` into the backup file
3358
3358
3359 This restores ``.hg/dirstate`` from backup file, if ``release()``
3359 This restores ``.hg/dirstate`` from backup file, if ``release()``
3360 is invoked before ``close()``.
3360 is invoked before ``close()``.
3361
3361
3362 This just removes the backup file at ``close()`` before ``release()``.
3362 This just removes the backup file at ``close()`` before ``release()``.
3363 '''
3363 '''
3364
3364
3365 def __init__(self, repo, name):
3365 def __init__(self, repo, name):
3366 self._repo = repo
3366 self._repo = repo
3367 self._suffix = '.backup.%s.%d' % (name, id(self))
3367 self._suffix = '.backup.%s.%d' % (name, id(self))
3368 repo.dirstate._savebackup(repo.currenttransaction(), self._suffix)
3368 repo.dirstate._savebackup(repo.currenttransaction(), self._suffix)
3369 self._active = True
3369 self._active = True
3370 self._closed = False
3370 self._closed = False
3371
3371
3372 def __del__(self):
3372 def __del__(self):
3373 if self._active: # still active
3373 if self._active: # still active
3374 # this may occur, even if this class is used correctly:
3374 # this may occur, even if this class is used correctly:
3375 # for example, releasing other resources like transaction
3375 # for example, releasing other resources like transaction
3376 # may raise exception before ``dirstateguard.release`` in
3376 # may raise exception before ``dirstateguard.release`` in
3377 # ``release(tr, ....)``.
3377 # ``release(tr, ....)``.
3378 self._abort()
3378 self._abort()
3379
3379
3380 def close(self):
3380 def close(self):
3381 if not self._active: # already inactivated
3381 if not self._active: # already inactivated
3382 msg = (_("can't close already inactivated backup: dirstate%s")
3382 msg = (_("can't close already inactivated backup: dirstate%s")
3383 % self._suffix)
3383 % self._suffix)
3384 raise error.Abort(msg)
3384 raise error.Abort(msg)
3385
3385
3386 self._repo.dirstate._clearbackup(self._repo.currenttransaction(),
3386 self._repo.dirstate._clearbackup(self._repo.currenttransaction(),
3387 self._suffix)
3387 self._suffix)
3388 self._active = False
3388 self._active = False
3389 self._closed = True
3389 self._closed = True
3390
3390
3391 def _abort(self):
3391 def _abort(self):
3392 self._repo.dirstate._restorebackup(self._repo.currenttransaction(),
3392 self._repo.dirstate._restorebackup(self._repo.currenttransaction(),
3393 self._suffix)
3393 self._suffix)
3394 self._active = False
3394 self._active = False
3395
3395
3396 def release(self):
3396 def release(self):
3397 if not self._closed:
3397 if not self._closed:
3398 if not self._active: # already inactivated
3398 if not self._active: # already inactivated
3399 msg = (_("can't release already inactivated backup:"
3399 msg = (_("can't release already inactivated backup:"
3400 " dirstate%s")
3400 " dirstate%s")
3401 % self._suffix)
3401 % self._suffix)
3402 raise error.Abort(msg)
3402 raise error.Abort(msg)
3403 self._abort()
3403 self._abort()
@@ -1,1148 +1,1140 b''
1 # ui.py - user interface bits for mercurial
1 # ui.py - user interface bits for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import errno
10 import errno
11 import getpass
11 import getpass
12 import inspect
12 import inspect
13 import os
13 import os
14 import socket
14 import socket
15 import sys
15 import sys
16 import tempfile
16 import tempfile
17 import traceback
17 import traceback
18
18
19 from .i18n import _
19 from .i18n import _
20 from .node import hex
20 from .node import hex
21
21
22 from . import (
22 from . import (
23 config,
23 config,
24 error,
24 error,
25 formatter,
25 formatter,
26 progress,
26 progress,
27 scmutil,
27 scmutil,
28 util,
28 util,
29 )
29 )
30
30
31 samplehgrcs = {
31 samplehgrcs = {
32 'user':
32 'user':
33 """# example user config (see "hg help config" for more info)
33 """# example user config (see "hg help config" for more info)
34 [ui]
34 [ui]
35 # name and email, e.g.
35 # name and email, e.g.
36 # username = Jane Doe <jdoe@example.com>
36 # username = Jane Doe <jdoe@example.com>
37 username =
37 username =
38
38
39 [extensions]
39 [extensions]
40 # uncomment these lines to enable some popular extensions
40 # uncomment these lines to enable some popular extensions
41 # (see "hg help extensions" for more info)
41 # (see "hg help extensions" for more info)
42 #
42 #
43 # pager =
43 # pager =
44 # progress =
44 # progress =
45 # color =""",
45 # color =""",
46
46
47 'cloned':
47 'cloned':
48 """# example repository config (see "hg help config" for more info)
48 """# example repository config (see "hg help config" for more info)
49 [paths]
49 [paths]
50 default = %s
50 default = %s
51
51
52 # path aliases to other clones of this repo in URLs or filesystem paths
52 # path aliases to other clones of this repo in URLs or filesystem paths
53 # (see "hg help config.paths" for more info)
53 # (see "hg help config.paths" for more info)
54 #
54 #
55 # default-push = ssh://jdoe@example.net/hg/jdoes-fork
55 # default-push = ssh://jdoe@example.net/hg/jdoes-fork
56 # my-fork = ssh://jdoe@example.net/hg/jdoes-fork
56 # my-fork = ssh://jdoe@example.net/hg/jdoes-fork
57 # my-clone = /home/jdoe/jdoes-clone
57 # my-clone = /home/jdoe/jdoes-clone
58
58
59 [ui]
59 [ui]
60 # name and email (local to this repository, optional), e.g.
60 # name and email (local to this repository, optional), e.g.
61 # username = Jane Doe <jdoe@example.com>
61 # username = Jane Doe <jdoe@example.com>
62 """,
62 """,
63
63
64 'local':
64 'local':
65 """# example repository config (see "hg help config" for more info)
65 """# example repository config (see "hg help config" for more info)
66 [paths]
66 [paths]
67 # path aliases to other clones of this repo in URLs or filesystem paths
67 # path aliases to other clones of this repo in URLs or filesystem paths
68 # (see "hg help config.paths" for more info)
68 # (see "hg help config.paths" for more info)
69 #
69 #
70 # default = http://example.com/hg/example-repo
70 # default = http://example.com/hg/example-repo
71 # default-push = ssh://jdoe@example.net/hg/jdoes-fork
71 # default-push = ssh://jdoe@example.net/hg/jdoes-fork
72 # my-fork = ssh://jdoe@example.net/hg/jdoes-fork
72 # my-fork = ssh://jdoe@example.net/hg/jdoes-fork
73 # my-clone = /home/jdoe/jdoes-clone
73 # my-clone = /home/jdoe/jdoes-clone
74
74
75 [ui]
75 [ui]
76 # name and email (local to this repository, optional), e.g.
76 # name and email (local to this repository, optional), e.g.
77 # username = Jane Doe <jdoe@example.com>
77 # username = Jane Doe <jdoe@example.com>
78 """,
78 """,
79
79
80 'global':
80 'global':
81 """# example system-wide hg config (see "hg help config" for more info)
81 """# example system-wide hg config (see "hg help config" for more info)
82
82
83 [extensions]
83 [extensions]
84 # uncomment these lines to enable some popular extensions
84 # uncomment these lines to enable some popular extensions
85 # (see "hg help extensions" for more info)
85 # (see "hg help extensions" for more info)
86 #
86 #
87 # blackbox =
87 # blackbox =
88 # progress =
88 # progress =
89 # color =
89 # color =
90 # pager =""",
90 # pager =""",
91 }
91 }
92
92
93 class ui(object):
93 class ui(object):
94 def __init__(self, src=None):
94 def __init__(self, src=None):
95 # _buffers: used for temporary capture of output
95 # _buffers: used for temporary capture of output
96 self._buffers = []
96 self._buffers = []
97 # 3-tuple describing how each buffer in the stack behaves.
97 # 3-tuple describing how each buffer in the stack behaves.
98 # Values are (capture stderr, capture subprocesses, apply labels).
98 # Values are (capture stderr, capture subprocesses, apply labels).
99 self._bufferstates = []
99 self._bufferstates = []
100 # When a buffer is active, defines whether we are expanding labels.
100 # When a buffer is active, defines whether we are expanding labels.
101 # This exists to prevent an extra list lookup.
101 # This exists to prevent an extra list lookup.
102 self._bufferapplylabels = None
102 self._bufferapplylabels = None
103 self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
103 self.quiet = self.verbose = self.debugflag = self.tracebackflag = False
104 self._reportuntrusted = True
104 self._reportuntrusted = True
105 self._ocfg = config.config() # overlay
105 self._ocfg = config.config() # overlay
106 self._tcfg = config.config() # trusted
106 self._tcfg = config.config() # trusted
107 self._ucfg = config.config() # untrusted
107 self._ucfg = config.config() # untrusted
108 self._trustusers = set()
108 self._trustusers = set()
109 self._trustgroups = set()
109 self._trustgroups = set()
110 self.callhooks = True
110 self.callhooks = True
111
111
112 if src:
112 if src:
113 self.fout = src.fout
113 self.fout = src.fout
114 self.ferr = src.ferr
114 self.ferr = src.ferr
115 self.fin = src.fin
115 self.fin = src.fin
116
116
117 self._tcfg = src._tcfg.copy()
117 self._tcfg = src._tcfg.copy()
118 self._ucfg = src._ucfg.copy()
118 self._ucfg = src._ucfg.copy()
119 self._ocfg = src._ocfg.copy()
119 self._ocfg = src._ocfg.copy()
120 self._trustusers = src._trustusers.copy()
120 self._trustusers = src._trustusers.copy()
121 self._trustgroups = src._trustgroups.copy()
121 self._trustgroups = src._trustgroups.copy()
122 self.environ = src.environ
122 self.environ = src.environ
123 self.callhooks = src.callhooks
123 self.callhooks = src.callhooks
124 self.fixconfig()
124 self.fixconfig()
125 else:
125 else:
126 self.fout = sys.stdout
126 self.fout = sys.stdout
127 self.ferr = sys.stderr
127 self.ferr = sys.stderr
128 self.fin = sys.stdin
128 self.fin = sys.stdin
129
129
130 # shared read-only environment
130 # shared read-only environment
131 self.environ = os.environ
131 self.environ = os.environ
132 # we always trust global config files
132 # we always trust global config files
133 for f in scmutil.rcpath():
133 for f in scmutil.rcpath():
134 self.readconfig(f, trust=True)
134 self.readconfig(f, trust=True)
135
135
136 def copy(self):
136 def copy(self):
137 return self.__class__(self)
137 return self.__class__(self)
138
138
139 def formatter(self, topic, opts):
139 def formatter(self, topic, opts):
140 return formatter.formatter(self, topic, opts)
140 return formatter.formatter(self, topic, opts)
141
141
142 def _trusted(self, fp, f):
142 def _trusted(self, fp, f):
143 st = util.fstat(fp)
143 st = util.fstat(fp)
144 if util.isowner(st):
144 if util.isowner(st):
145 return True
145 return True
146
146
147 tusers, tgroups = self._trustusers, self._trustgroups
147 tusers, tgroups = self._trustusers, self._trustgroups
148 if '*' in tusers or '*' in tgroups:
148 if '*' in tusers or '*' in tgroups:
149 return True
149 return True
150
150
151 user = util.username(st.st_uid)
151 user = util.username(st.st_uid)
152 group = util.groupname(st.st_gid)
152 group = util.groupname(st.st_gid)
153 if user in tusers or group in tgroups or user == util.username():
153 if user in tusers or group in tgroups or user == util.username():
154 return True
154 return True
155
155
156 if self._reportuntrusted:
156 if self._reportuntrusted:
157 self.warn(_('not trusting file %s from untrusted '
157 self.warn(_('not trusting file %s from untrusted '
158 'user %s, group %s\n') % (f, user, group))
158 'user %s, group %s\n') % (f, user, group))
159 return False
159 return False
160
160
161 def readconfig(self, filename, root=None, trust=False,
161 def readconfig(self, filename, root=None, trust=False,
162 sections=None, remap=None):
162 sections=None, remap=None):
163 try:
163 try:
164 fp = open(filename)
164 fp = open(filename)
165 except IOError:
165 except IOError:
166 if not sections: # ignore unless we were looking for something
166 if not sections: # ignore unless we were looking for something
167 return
167 return
168 raise
168 raise
169
169
170 cfg = config.config()
170 cfg = config.config()
171 trusted = sections or trust or self._trusted(fp, filename)
171 trusted = sections or trust or self._trusted(fp, filename)
172
172
173 try:
173 try:
174 cfg.read(filename, fp, sections=sections, remap=remap)
174 cfg.read(filename, fp, sections=sections, remap=remap)
175 fp.close()
175 fp.close()
176 except error.ConfigError as inst:
176 except error.ConfigError as inst:
177 if trusted:
177 if trusted:
178 raise
178 raise
179 self.warn(_("ignored: %s\n") % str(inst))
179 self.warn(_("ignored: %s\n") % str(inst))
180
180
181 if self.plain():
181 if self.plain():
182 for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
182 for k in ('debug', 'fallbackencoding', 'quiet', 'slash',
183 'logtemplate', 'statuscopies', 'style',
183 'logtemplate', 'statuscopies', 'style',
184 'traceback', 'verbose'):
184 'traceback', 'verbose'):
185 if k in cfg['ui']:
185 if k in cfg['ui']:
186 del cfg['ui'][k]
186 del cfg['ui'][k]
187 for k, v in cfg.items('defaults'):
187 for k, v in cfg.items('defaults'):
188 del cfg['defaults'][k]
188 del cfg['defaults'][k]
189 # Don't remove aliases from the configuration if in the exceptionlist
189 # Don't remove aliases from the configuration if in the exceptionlist
190 if self.plain('alias'):
190 if self.plain('alias'):
191 for k, v in cfg.items('alias'):
191 for k, v in cfg.items('alias'):
192 del cfg['alias'][k]
192 del cfg['alias'][k]
193 if self.plain('revsetalias'):
193 if self.plain('revsetalias'):
194 for k, v in cfg.items('revsetalias'):
194 for k, v in cfg.items('revsetalias'):
195 del cfg['revsetalias'][k]
195 del cfg['revsetalias'][k]
196
196
197 if trusted:
197 if trusted:
198 self._tcfg.update(cfg)
198 self._tcfg.update(cfg)
199 self._tcfg.update(self._ocfg)
199 self._tcfg.update(self._ocfg)
200 self._ucfg.update(cfg)
200 self._ucfg.update(cfg)
201 self._ucfg.update(self._ocfg)
201 self._ucfg.update(self._ocfg)
202
202
203 if root is None:
203 if root is None:
204 root = os.path.expanduser('~')
204 root = os.path.expanduser('~')
205 self.fixconfig(root=root)
205 self.fixconfig(root=root)
206
206
207 def fixconfig(self, root=None, section=None):
207 def fixconfig(self, root=None, section=None):
208 if section in (None, 'paths'):
208 if section in (None, 'paths'):
209 # expand vars and ~
209 # expand vars and ~
210 # translate paths relative to root (or home) into absolute paths
210 # translate paths relative to root (or home) into absolute paths
211 root = root or os.getcwd()
211 root = root or os.getcwd()
212 for c in self._tcfg, self._ucfg, self._ocfg:
212 for c in self._tcfg, self._ucfg, self._ocfg:
213 for n, p in c.items('paths'):
213 for n, p in c.items('paths'):
214 if not p:
214 if not p:
215 continue
215 continue
216 if '%%' in p:
216 if '%%' in p:
217 self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
217 self.warn(_("(deprecated '%%' in path %s=%s from %s)\n")
218 % (n, p, self.configsource('paths', n)))
218 % (n, p, self.configsource('paths', n)))
219 p = p.replace('%%', '%')
219 p = p.replace('%%', '%')
220 p = util.expandpath(p)
220 p = util.expandpath(p)
221 if not util.hasscheme(p) and not os.path.isabs(p):
221 if not util.hasscheme(p) and not os.path.isabs(p):
222 p = os.path.normpath(os.path.join(root, p))
222 p = os.path.normpath(os.path.join(root, p))
223 c.set("paths", n, p)
223 c.set("paths", n, p)
224
224
225 if section in (None, 'ui'):
225 if section in (None, 'ui'):
226 # update ui options
226 # update ui options
227 self.debugflag = self.configbool('ui', 'debug')
227 self.debugflag = self.configbool('ui', 'debug')
228 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
228 self.verbose = self.debugflag or self.configbool('ui', 'verbose')
229 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
229 self.quiet = not self.debugflag and self.configbool('ui', 'quiet')
230 if self.verbose and self.quiet:
230 if self.verbose and self.quiet:
231 self.quiet = self.verbose = False
231 self.quiet = self.verbose = False
232 self._reportuntrusted = self.debugflag or self.configbool("ui",
232 self._reportuntrusted = self.debugflag or self.configbool("ui",
233 "report_untrusted", True)
233 "report_untrusted", True)
234 self.tracebackflag = self.configbool('ui', 'traceback', False)
234 self.tracebackflag = self.configbool('ui', 'traceback', False)
235
235
236 if section in (None, 'trusted'):
236 if section in (None, 'trusted'):
237 # update trust information
237 # update trust information
238 self._trustusers.update(self.configlist('trusted', 'users'))
238 self._trustusers.update(self.configlist('trusted', 'users'))
239 self._trustgroups.update(self.configlist('trusted', 'groups'))
239 self._trustgroups.update(self.configlist('trusted', 'groups'))
240
240
241 def backupconfig(self, section, item):
241 def backupconfig(self, section, item):
242 return (self._ocfg.backup(section, item),
242 return (self._ocfg.backup(section, item),
243 self._tcfg.backup(section, item),
243 self._tcfg.backup(section, item),
244 self._ucfg.backup(section, item),)
244 self._ucfg.backup(section, item),)
245 def restoreconfig(self, data):
245 def restoreconfig(self, data):
246 self._ocfg.restore(data[0])
246 self._ocfg.restore(data[0])
247 self._tcfg.restore(data[1])
247 self._tcfg.restore(data[1])
248 self._ucfg.restore(data[2])
248 self._ucfg.restore(data[2])
249
249
250 def setconfig(self, section, name, value, source=''):
250 def setconfig(self, section, name, value, source=''):
251 for cfg in (self._ocfg, self._tcfg, self._ucfg):
251 for cfg in (self._ocfg, self._tcfg, self._ucfg):
252 cfg.set(section, name, value, source)
252 cfg.set(section, name, value, source)
253 self.fixconfig(section=section)
253 self.fixconfig(section=section)
254
254
255 def _data(self, untrusted):
255 def _data(self, untrusted):
256 return untrusted and self._ucfg or self._tcfg
256 return untrusted and self._ucfg or self._tcfg
257
257
258 def configsource(self, section, name, untrusted=False):
258 def configsource(self, section, name, untrusted=False):
259 return self._data(untrusted).source(section, name) or 'none'
259 return self._data(untrusted).source(section, name) or 'none'
260
260
261 def config(self, section, name, default=None, untrusted=False):
261 def config(self, section, name, default=None, untrusted=False):
262 if isinstance(name, list):
262 if isinstance(name, list):
263 alternates = name
263 alternates = name
264 else:
264 else:
265 alternates = [name]
265 alternates = [name]
266
266
267 for n in alternates:
267 for n in alternates:
268 value = self._data(untrusted).get(section, n, None)
268 value = self._data(untrusted).get(section, n, None)
269 if value is not None:
269 if value is not None:
270 name = n
270 name = n
271 break
271 break
272 else:
272 else:
273 value = default
273 value = default
274
274
275 if self.debugflag and not untrusted and self._reportuntrusted:
275 if self.debugflag and not untrusted and self._reportuntrusted:
276 for n in alternates:
276 for n in alternates:
277 uvalue = self._ucfg.get(section, n)
277 uvalue = self._ucfg.get(section, n)
278 if uvalue is not None and uvalue != value:
278 if uvalue is not None and uvalue != value:
279 self.debug("ignoring untrusted configuration option "
279 self.debug("ignoring untrusted configuration option "
280 "%s.%s = %s\n" % (section, n, uvalue))
280 "%s.%s = %s\n" % (section, n, uvalue))
281 return value
281 return value
282
282
283 def configpath(self, section, name, default=None, untrusted=False):
283 def configpath(self, section, name, default=None, untrusted=False):
284 'get a path config item, expanded relative to repo root or config file'
284 'get a path config item, expanded relative to repo root or config file'
285 v = self.config(section, name, default, untrusted)
285 v = self.config(section, name, default, untrusted)
286 if v is None:
286 if v is None:
287 return None
287 return None
288 if not os.path.isabs(v) or "://" not in v:
288 if not os.path.isabs(v) or "://" not in v:
289 src = self.configsource(section, name, untrusted)
289 src = self.configsource(section, name, untrusted)
290 if ':' in src:
290 if ':' in src:
291 base = os.path.dirname(src.rsplit(':')[0])
291 base = os.path.dirname(src.rsplit(':')[0])
292 v = os.path.join(base, os.path.expanduser(v))
292 v = os.path.join(base, os.path.expanduser(v))
293 return v
293 return v
294
294
295 def configbool(self, section, name, default=False, untrusted=False):
295 def configbool(self, section, name, default=False, untrusted=False):
296 """parse a configuration element as a boolean
296 """parse a configuration element as a boolean
297
297
298 >>> u = ui(); s = 'foo'
298 >>> u = ui(); s = 'foo'
299 >>> u.setconfig(s, 'true', 'yes')
299 >>> u.setconfig(s, 'true', 'yes')
300 >>> u.configbool(s, 'true')
300 >>> u.configbool(s, 'true')
301 True
301 True
302 >>> u.setconfig(s, 'false', 'no')
302 >>> u.setconfig(s, 'false', 'no')
303 >>> u.configbool(s, 'false')
303 >>> u.configbool(s, 'false')
304 False
304 False
305 >>> u.configbool(s, 'unknown')
305 >>> u.configbool(s, 'unknown')
306 False
306 False
307 >>> u.configbool(s, 'unknown', True)
307 >>> u.configbool(s, 'unknown', True)
308 True
308 True
309 >>> u.setconfig(s, 'invalid', 'somevalue')
309 >>> u.setconfig(s, 'invalid', 'somevalue')
310 >>> u.configbool(s, 'invalid')
310 >>> u.configbool(s, 'invalid')
311 Traceback (most recent call last):
311 Traceback (most recent call last):
312 ...
312 ...
313 ConfigError: foo.invalid is not a boolean ('somevalue')
313 ConfigError: foo.invalid is not a boolean ('somevalue')
314 """
314 """
315
315
316 v = self.config(section, name, None, untrusted)
316 v = self.config(section, name, None, untrusted)
317 if v is None:
317 if v is None:
318 return default
318 return default
319 if isinstance(v, bool):
319 if isinstance(v, bool):
320 return v
320 return v
321 b = util.parsebool(v)
321 b = util.parsebool(v)
322 if b is None:
322 if b is None:
323 raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
323 raise error.ConfigError(_("%s.%s is not a boolean ('%s')")
324 % (section, name, v))
324 % (section, name, v))
325 return b
325 return b
326
326
327 def configint(self, section, name, default=None, untrusted=False):
327 def configint(self, section, name, default=None, untrusted=False):
328 """parse a configuration element as an integer
328 """parse a configuration element as an integer
329
329
330 >>> u = ui(); s = 'foo'
330 >>> u = ui(); s = 'foo'
331 >>> u.setconfig(s, 'int1', '42')
331 >>> u.setconfig(s, 'int1', '42')
332 >>> u.configint(s, 'int1')
332 >>> u.configint(s, 'int1')
333 42
333 42
334 >>> u.setconfig(s, 'int2', '-42')
334 >>> u.setconfig(s, 'int2', '-42')
335 >>> u.configint(s, 'int2')
335 >>> u.configint(s, 'int2')
336 -42
336 -42
337 >>> u.configint(s, 'unknown', 7)
337 >>> u.configint(s, 'unknown', 7)
338 7
338 7
339 >>> u.setconfig(s, 'invalid', 'somevalue')
339 >>> u.setconfig(s, 'invalid', 'somevalue')
340 >>> u.configint(s, 'invalid')
340 >>> u.configint(s, 'invalid')
341 Traceback (most recent call last):
341 Traceback (most recent call last):
342 ...
342 ...
343 ConfigError: foo.invalid is not an integer ('somevalue')
343 ConfigError: foo.invalid is not an integer ('somevalue')
344 """
344 """
345
345
346 v = self.config(section, name, None, untrusted)
346 v = self.config(section, name, None, untrusted)
347 if v is None:
347 if v is None:
348 return default
348 return default
349 try:
349 try:
350 return int(v)
350 return int(v)
351 except ValueError:
351 except ValueError:
352 raise error.ConfigError(_("%s.%s is not an integer ('%s')")
352 raise error.ConfigError(_("%s.%s is not an integer ('%s')")
353 % (section, name, v))
353 % (section, name, v))
354
354
355 def configbytes(self, section, name, default=0, untrusted=False):
355 def configbytes(self, section, name, default=0, untrusted=False):
356 """parse a configuration element as a quantity in bytes
356 """parse a configuration element as a quantity in bytes
357
357
358 Units can be specified as b (bytes), k or kb (kilobytes), m or
358 Units can be specified as b (bytes), k or kb (kilobytes), m or
359 mb (megabytes), g or gb (gigabytes).
359 mb (megabytes), g or gb (gigabytes).
360
360
361 >>> u = ui(); s = 'foo'
361 >>> u = ui(); s = 'foo'
362 >>> u.setconfig(s, 'val1', '42')
362 >>> u.setconfig(s, 'val1', '42')
363 >>> u.configbytes(s, 'val1')
363 >>> u.configbytes(s, 'val1')
364 42
364 42
365 >>> u.setconfig(s, 'val2', '42.5 kb')
365 >>> u.setconfig(s, 'val2', '42.5 kb')
366 >>> u.configbytes(s, 'val2')
366 >>> u.configbytes(s, 'val2')
367 43520
367 43520
368 >>> u.configbytes(s, 'unknown', '7 MB')
368 >>> u.configbytes(s, 'unknown', '7 MB')
369 7340032
369 7340032
370 >>> u.setconfig(s, 'invalid', 'somevalue')
370 >>> u.setconfig(s, 'invalid', 'somevalue')
371 >>> u.configbytes(s, 'invalid')
371 >>> u.configbytes(s, 'invalid')
372 Traceback (most recent call last):
372 Traceback (most recent call last):
373 ...
373 ...
374 ConfigError: foo.invalid is not a byte quantity ('somevalue')
374 ConfigError: foo.invalid is not a byte quantity ('somevalue')
375 """
375 """
376
376
377 value = self.config(section, name)
377 value = self.config(section, name)
378 if value is None:
378 if value is None:
379 if not isinstance(default, str):
379 if not isinstance(default, str):
380 return default
380 return default
381 value = default
381 value = default
382 try:
382 try:
383 return util.sizetoint(value)
383 return util.sizetoint(value)
384 except error.ParseError:
384 except error.ParseError:
385 raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
385 raise error.ConfigError(_("%s.%s is not a byte quantity ('%s')")
386 % (section, name, value))
386 % (section, name, value))
387
387
388 def configlist(self, section, name, default=None, untrusted=False):
388 def configlist(self, section, name, default=None, untrusted=False):
389 """parse a configuration element as a list of comma/space separated
389 """parse a configuration element as a list of comma/space separated
390 strings
390 strings
391
391
392 >>> u = ui(); s = 'foo'
392 >>> u = ui(); s = 'foo'
393 >>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
393 >>> u.setconfig(s, 'list1', 'this,is "a small" ,test')
394 >>> u.configlist(s, 'list1')
394 >>> u.configlist(s, 'list1')
395 ['this', 'is', 'a small', 'test']
395 ['this', 'is', 'a small', 'test']
396 """
396 """
397
397
398 def _parse_plain(parts, s, offset):
398 def _parse_plain(parts, s, offset):
399 whitespace = False
399 whitespace = False
400 while offset < len(s) and (s[offset].isspace() or s[offset] == ','):
400 while offset < len(s) and (s[offset].isspace() or s[offset] == ','):
401 whitespace = True
401 whitespace = True
402 offset += 1
402 offset += 1
403 if offset >= len(s):
403 if offset >= len(s):
404 return None, parts, offset
404 return None, parts, offset
405 if whitespace:
405 if whitespace:
406 parts.append('')
406 parts.append('')
407 if s[offset] == '"' and not parts[-1]:
407 if s[offset] == '"' and not parts[-1]:
408 return _parse_quote, parts, offset + 1
408 return _parse_quote, parts, offset + 1
409 elif s[offset] == '"' and parts[-1][-1] == '\\':
409 elif s[offset] == '"' and parts[-1][-1] == '\\':
410 parts[-1] = parts[-1][:-1] + s[offset]
410 parts[-1] = parts[-1][:-1] + s[offset]
411 return _parse_plain, parts, offset + 1
411 return _parse_plain, parts, offset + 1
412 parts[-1] += s[offset]
412 parts[-1] += s[offset]
413 return _parse_plain, parts, offset + 1
413 return _parse_plain, parts, offset + 1
414
414
415 def _parse_quote(parts, s, offset):
415 def _parse_quote(parts, s, offset):
416 if offset < len(s) and s[offset] == '"': # ""
416 if offset < len(s) and s[offset] == '"': # ""
417 parts.append('')
417 parts.append('')
418 offset += 1
418 offset += 1
419 while offset < len(s) and (s[offset].isspace() or
419 while offset < len(s) and (s[offset].isspace() or
420 s[offset] == ','):
420 s[offset] == ','):
421 offset += 1
421 offset += 1
422 return _parse_plain, parts, offset
422 return _parse_plain, parts, offset
423
423
424 while offset < len(s) and s[offset] != '"':
424 while offset < len(s) and s[offset] != '"':
425 if (s[offset] == '\\' and offset + 1 < len(s)
425 if (s[offset] == '\\' and offset + 1 < len(s)
426 and s[offset + 1] == '"'):
426 and s[offset + 1] == '"'):
427 offset += 1
427 offset += 1
428 parts[-1] += '"'
428 parts[-1] += '"'
429 else:
429 else:
430 parts[-1] += s[offset]
430 parts[-1] += s[offset]
431 offset += 1
431 offset += 1
432
432
433 if offset >= len(s):
433 if offset >= len(s):
434 real_parts = _configlist(parts[-1])
434 real_parts = _configlist(parts[-1])
435 if not real_parts:
435 if not real_parts:
436 parts[-1] = '"'
436 parts[-1] = '"'
437 else:
437 else:
438 real_parts[0] = '"' + real_parts[0]
438 real_parts[0] = '"' + real_parts[0]
439 parts = parts[:-1]
439 parts = parts[:-1]
440 parts.extend(real_parts)
440 parts.extend(real_parts)
441 return None, parts, offset
441 return None, parts, offset
442
442
443 offset += 1
443 offset += 1
444 while offset < len(s) and s[offset] in [' ', ',']:
444 while offset < len(s) and s[offset] in [' ', ',']:
445 offset += 1
445 offset += 1
446
446
447 if offset < len(s):
447 if offset < len(s):
448 if offset + 1 == len(s) and s[offset] == '"':
448 if offset + 1 == len(s) and s[offset] == '"':
449 parts[-1] += '"'
449 parts[-1] += '"'
450 offset += 1
450 offset += 1
451 else:
451 else:
452 parts.append('')
452 parts.append('')
453 else:
453 else:
454 return None, parts, offset
454 return None, parts, offset
455
455
456 return _parse_plain, parts, offset
456 return _parse_plain, parts, offset
457
457
458 def _configlist(s):
458 def _configlist(s):
459 s = s.rstrip(' ,')
459 s = s.rstrip(' ,')
460 if not s:
460 if not s:
461 return []
461 return []
462 parser, parts, offset = _parse_plain, [''], 0
462 parser, parts, offset = _parse_plain, [''], 0
463 while parser:
463 while parser:
464 parser, parts, offset = parser(parts, s, offset)
464 parser, parts, offset = parser(parts, s, offset)
465 return parts
465 return parts
466
466
467 result = self.config(section, name, untrusted=untrusted)
467 result = self.config(section, name, untrusted=untrusted)
468 if result is None:
468 if result is None:
469 result = default or []
469 result = default or []
470 if isinstance(result, basestring):
470 if isinstance(result, basestring):
471 result = _configlist(result.lstrip(' ,\n'))
471 result = _configlist(result.lstrip(' ,\n'))
472 if result is None:
472 if result is None:
473 result = default or []
473 result = default or []
474 return result
474 return result
475
475
476 def has_section(self, section, untrusted=False):
476 def has_section(self, section, untrusted=False):
477 '''tell whether section exists in config.'''
477 '''tell whether section exists in config.'''
478 return section in self._data(untrusted)
478 return section in self._data(untrusted)
479
479
480 def configitems(self, section, untrusted=False):
480 def configitems(self, section, untrusted=False):
481 items = self._data(untrusted).items(section)
481 items = self._data(untrusted).items(section)
482 if self.debugflag and not untrusted and self._reportuntrusted:
482 if self.debugflag and not untrusted and self._reportuntrusted:
483 for k, v in self._ucfg.items(section):
483 for k, v in self._ucfg.items(section):
484 if self._tcfg.get(section, k) != v:
484 if self._tcfg.get(section, k) != v:
485 self.debug("ignoring untrusted configuration option "
485 self.debug("ignoring untrusted configuration option "
486 "%s.%s = %s\n" % (section, k, v))
486 "%s.%s = %s\n" % (section, k, v))
487 return items
487 return items
488
488
489 def walkconfig(self, untrusted=False):
489 def walkconfig(self, untrusted=False):
490 cfg = self._data(untrusted)
490 cfg = self._data(untrusted)
491 for section in cfg.sections():
491 for section in cfg.sections():
492 for name, value in self.configitems(section, untrusted):
492 for name, value in self.configitems(section, untrusted):
493 yield section, name, value
493 yield section, name, value
494
494
495 def plain(self, feature=None):
495 def plain(self, feature=None):
496 '''is plain mode active?
496 '''is plain mode active?
497
497
498 Plain mode means that all configuration variables which affect
498 Plain mode means that all configuration variables which affect
499 the behavior and output of Mercurial should be
499 the behavior and output of Mercurial should be
500 ignored. Additionally, the output should be stable,
500 ignored. Additionally, the output should be stable,
501 reproducible and suitable for use in scripts or applications.
501 reproducible and suitable for use in scripts or applications.
502
502
503 The only way to trigger plain mode is by setting either the
503 The only way to trigger plain mode is by setting either the
504 `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
504 `HGPLAIN' or `HGPLAINEXCEPT' environment variables.
505
505
506 The return value can either be
506 The return value can either be
507 - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
507 - False if HGPLAIN is not set, or feature is in HGPLAINEXCEPT
508 - True otherwise
508 - True otherwise
509 '''
509 '''
510 if 'HGPLAIN' not in os.environ and 'HGPLAINEXCEPT' not in os.environ:
510 if 'HGPLAIN' not in os.environ and 'HGPLAINEXCEPT' not in os.environ:
511 return False
511 return False
512 exceptions = os.environ.get('HGPLAINEXCEPT', '').strip().split(',')
512 exceptions = os.environ.get('HGPLAINEXCEPT', '').strip().split(',')
513 if feature and exceptions:
513 if feature and exceptions:
514 return feature not in exceptions
514 return feature not in exceptions
515 return True
515 return True
516
516
517 def username(self):
517 def username(self):
518 """Return default username to be used in commits.
518 """Return default username to be used in commits.
519
519
520 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
520 Searched in this order: $HGUSER, [ui] section of hgrcs, $EMAIL
521 and stop searching if one of these is set.
521 and stop searching if one of these is set.
522 If not found and ui.askusername is True, ask the user, else use
522 If not found and ui.askusername is True, ask the user, else use
523 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
523 ($LOGNAME or $USER or $LNAME or $USERNAME) + "@full.hostname".
524 """
524 """
525 user = os.environ.get("HGUSER")
525 user = os.environ.get("HGUSER")
526 if user is None:
526 if user is None:
527 user = self.config("ui", ["username", "user"])
527 user = self.config("ui", ["username", "user"])
528 if user is not None:
528 if user is not None:
529 user = os.path.expandvars(user)
529 user = os.path.expandvars(user)
530 if user is None:
530 if user is None:
531 user = os.environ.get("EMAIL")
531 user = os.environ.get("EMAIL")
532 if user is None and self.configbool("ui", "askusername"):
532 if user is None and self.configbool("ui", "askusername"):
533 user = self.prompt(_("enter a commit username:"), default=None)
533 user = self.prompt(_("enter a commit username:"), default=None)
534 if user is None and not self.interactive():
534 if user is None and not self.interactive():
535 try:
535 try:
536 user = '%s@%s' % (util.getuser(), socket.getfqdn())
536 user = '%s@%s' % (util.getuser(), socket.getfqdn())
537 self.warn(_("no username found, using '%s' instead\n") % user)
537 self.warn(_("no username found, using '%s' instead\n") % user)
538 except KeyError:
538 except KeyError:
539 pass
539 pass
540 if not user:
540 if not user:
541 raise error.Abort(_('no username supplied'),
541 raise error.Abort(_('no username supplied'),
542 hint=_('use "hg config --edit" '
542 hint=_('use "hg config --edit" '
543 'to set your username'))
543 'to set your username'))
544 if "\n" in user:
544 if "\n" in user:
545 raise error.Abort(_("username %s contains a newline\n")
545 raise error.Abort(_("username %s contains a newline\n")
546 % repr(user))
546 % repr(user))
547 return user
547 return user
548
548
549 def shortuser(self, user):
549 def shortuser(self, user):
550 """Return a short representation of a user name or email address."""
550 """Return a short representation of a user name or email address."""
551 if not self.verbose:
551 if not self.verbose:
552 user = util.shortuser(user)
552 user = util.shortuser(user)
553 return user
553 return user
554
554
555 def expandpath(self, loc, default=None):
555 def expandpath(self, loc, default=None):
556 """Return repository location relative to cwd or from [paths]"""
556 """Return repository location relative to cwd or from [paths]"""
557 try:
557 try:
558 p = self.paths.getpath(loc)
558 p = self.paths.getpath(loc)
559 if p:
559 if p:
560 return p.rawloc
560 return p.rawloc
561 except error.RepoError:
561 except error.RepoError:
562 pass
562 pass
563
563
564 if default:
564 if default:
565 try:
565 try:
566 p = self.paths.getpath(default)
566 p = self.paths.getpath(default)
567 if p:
567 if p:
568 return p.rawloc
568 return p.rawloc
569 except error.RepoError:
569 except error.RepoError:
570 pass
570 pass
571
571
572 return loc
572 return loc
573
573
574 @util.propertycache
574 @util.propertycache
575 def paths(self):
575 def paths(self):
576 return paths(self)
576 return paths(self)
577
577
578 def pushbuffer(self, error=False, subproc=False, labeled=False):
578 def pushbuffer(self, error=False, subproc=False, labeled=False):
579 """install a buffer to capture standard output of the ui object
579 """install a buffer to capture standard output of the ui object
580
580
581 If error is True, the error output will be captured too.
581 If error is True, the error output will be captured too.
582
582
583 If subproc is True, output from subprocesses (typically hooks) will be
583 If subproc is True, output from subprocesses (typically hooks) will be
584 captured too.
584 captured too.
585
585
586 If labeled is True, any labels associated with buffered
586 If labeled is True, any labels associated with buffered
587 output will be handled. By default, this has no effect
587 output will be handled. By default, this has no effect
588 on the output returned, but extensions and GUI tools may
588 on the output returned, but extensions and GUI tools may
589 handle this argument and returned styled output. If output
589 handle this argument and returned styled output. If output
590 is being buffered so it can be captured and parsed or
590 is being buffered so it can be captured and parsed or
591 processed, labeled should not be set to True.
591 processed, labeled should not be set to True.
592 """
592 """
593 self._buffers.append([])
593 self._buffers.append([])
594 self._bufferstates.append((error, subproc, labeled))
594 self._bufferstates.append((error, subproc, labeled))
595 self._bufferapplylabels = labeled
595 self._bufferapplylabels = labeled
596
596
597 def popbuffer(self, labeled=False):
597 def popbuffer(self):
598 '''pop the last buffer and return the buffered output
598 '''pop the last buffer and return the buffered output'''
599
600 If labeled is True, any labels associated with buffered
601 output will be handled. By default, this has no effect
602 on the output returned, but extensions and GUI tools may
603 handle this argument and returned styled output. If output
604 is being buffered so it can be captured and parsed or
605 processed, labeled should not be set to True.
606 '''
607 self._bufferstates.pop()
599 self._bufferstates.pop()
608 if self._bufferstates:
600 if self._bufferstates:
609 self._bufferapplylabels = self._bufferstates[-1][2]
601 self._bufferapplylabels = self._bufferstates[-1][2]
610 else:
602 else:
611 self._bufferapplylabels = None
603 self._bufferapplylabels = None
612
604
613 return "".join(self._buffers.pop())
605 return "".join(self._buffers.pop())
614
606
615 def write(self, *args, **opts):
607 def write(self, *args, **opts):
616 '''write args to output
608 '''write args to output
617
609
618 By default, this method simply writes to the buffer or stdout,
610 By default, this method simply writes to the buffer or stdout,
619 but extensions or GUI tools may override this method,
611 but extensions or GUI tools may override this method,
620 write_err(), popbuffer(), and label() to style output from
612 write_err(), popbuffer(), and label() to style output from
621 various parts of hg.
613 various parts of hg.
622
614
623 An optional keyword argument, "label", can be passed in.
615 An optional keyword argument, "label", can be passed in.
624 This should be a string containing label names separated by
616 This should be a string containing label names separated by
625 space. Label names take the form of "topic.type". For example,
617 space. Label names take the form of "topic.type". For example,
626 ui.debug() issues a label of "ui.debug".
618 ui.debug() issues a label of "ui.debug".
627
619
628 When labeling output for a specific command, a label of
620 When labeling output for a specific command, a label of
629 "cmdname.type" is recommended. For example, status issues
621 "cmdname.type" is recommended. For example, status issues
630 a label of "status.modified" for modified files.
622 a label of "status.modified" for modified files.
631 '''
623 '''
632 if self._buffers:
624 if self._buffers:
633 self._buffers[-1].extend([str(a) for a in args])
625 self._buffers[-1].extend([str(a) for a in args])
634 else:
626 else:
635 self._progclear()
627 self._progclear()
636 for a in args:
628 for a in args:
637 self.fout.write(str(a))
629 self.fout.write(str(a))
638
630
639 def write_err(self, *args, **opts):
631 def write_err(self, *args, **opts):
640 self._progclear()
632 self._progclear()
641 try:
633 try:
642 if self._bufferstates and self._bufferstates[-1][0]:
634 if self._bufferstates and self._bufferstates[-1][0]:
643 return self.write(*args, **opts)
635 return self.write(*args, **opts)
644 if not getattr(self.fout, 'closed', False):
636 if not getattr(self.fout, 'closed', False):
645 self.fout.flush()
637 self.fout.flush()
646 for a in args:
638 for a in args:
647 self.ferr.write(str(a))
639 self.ferr.write(str(a))
648 # stderr may be buffered under win32 when redirected to files,
640 # stderr may be buffered under win32 when redirected to files,
649 # including stdout.
641 # including stdout.
650 if not getattr(self.ferr, 'closed', False):
642 if not getattr(self.ferr, 'closed', False):
651 self.ferr.flush()
643 self.ferr.flush()
652 except IOError as inst:
644 except IOError as inst:
653 if inst.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
645 if inst.errno not in (errno.EPIPE, errno.EIO, errno.EBADF):
654 raise
646 raise
655
647
656 def flush(self):
648 def flush(self):
657 try: self.fout.flush()
649 try: self.fout.flush()
658 except (IOError, ValueError): pass
650 except (IOError, ValueError): pass
659 try: self.ferr.flush()
651 try: self.ferr.flush()
660 except (IOError, ValueError): pass
652 except (IOError, ValueError): pass
661
653
662 def _isatty(self, fh):
654 def _isatty(self, fh):
663 if self.configbool('ui', 'nontty', False):
655 if self.configbool('ui', 'nontty', False):
664 return False
656 return False
665 return util.isatty(fh)
657 return util.isatty(fh)
666
658
667 def interactive(self):
659 def interactive(self):
668 '''is interactive input allowed?
660 '''is interactive input allowed?
669
661
670 An interactive session is a session where input can be reasonably read
662 An interactive session is a session where input can be reasonably read
671 from `sys.stdin'. If this function returns false, any attempt to read
663 from `sys.stdin'. If this function returns false, any attempt to read
672 from stdin should fail with an error, unless a sensible default has been
664 from stdin should fail with an error, unless a sensible default has been
673 specified.
665 specified.
674
666
675 Interactiveness is triggered by the value of the `ui.interactive'
667 Interactiveness is triggered by the value of the `ui.interactive'
676 configuration variable or - if it is unset - when `sys.stdin' points
668 configuration variable or - if it is unset - when `sys.stdin' points
677 to a terminal device.
669 to a terminal device.
678
670
679 This function refers to input only; for output, see `ui.formatted()'.
671 This function refers to input only; for output, see `ui.formatted()'.
680 '''
672 '''
681 i = self.configbool("ui", "interactive", None)
673 i = self.configbool("ui", "interactive", None)
682 if i is None:
674 if i is None:
683 # some environments replace stdin without implementing isatty
675 # some environments replace stdin without implementing isatty
684 # usually those are non-interactive
676 # usually those are non-interactive
685 return self._isatty(self.fin)
677 return self._isatty(self.fin)
686
678
687 return i
679 return i
688
680
689 def termwidth(self):
681 def termwidth(self):
690 '''how wide is the terminal in columns?
682 '''how wide is the terminal in columns?
691 '''
683 '''
692 if 'COLUMNS' in os.environ:
684 if 'COLUMNS' in os.environ:
693 try:
685 try:
694 return int(os.environ['COLUMNS'])
686 return int(os.environ['COLUMNS'])
695 except ValueError:
687 except ValueError:
696 pass
688 pass
697 return util.termwidth()
689 return util.termwidth()
698
690
699 def formatted(self):
691 def formatted(self):
700 '''should formatted output be used?
692 '''should formatted output be used?
701
693
702 It is often desirable to format the output to suite the output medium.
694 It is often desirable to format the output to suite the output medium.
703 Examples of this are truncating long lines or colorizing messages.
695 Examples of this are truncating long lines or colorizing messages.
704 However, this is not often not desirable when piping output into other
696 However, this is not often not desirable when piping output into other
705 utilities, e.g. `grep'.
697 utilities, e.g. `grep'.
706
698
707 Formatted output is triggered by the value of the `ui.formatted'
699 Formatted output is triggered by the value of the `ui.formatted'
708 configuration variable or - if it is unset - when `sys.stdout' points
700 configuration variable or - if it is unset - when `sys.stdout' points
709 to a terminal device. Please note that `ui.formatted' should be
701 to a terminal device. Please note that `ui.formatted' should be
710 considered an implementation detail; it is not intended for use outside
702 considered an implementation detail; it is not intended for use outside
711 Mercurial or its extensions.
703 Mercurial or its extensions.
712
704
713 This function refers to output only; for input, see `ui.interactive()'.
705 This function refers to output only; for input, see `ui.interactive()'.
714 This function always returns false when in plain mode, see `ui.plain()'.
706 This function always returns false when in plain mode, see `ui.plain()'.
715 '''
707 '''
716 if self.plain():
708 if self.plain():
717 return False
709 return False
718
710
719 i = self.configbool("ui", "formatted", None)
711 i = self.configbool("ui", "formatted", None)
720 if i is None:
712 if i is None:
721 # some environments replace stdout without implementing isatty
713 # some environments replace stdout without implementing isatty
722 # usually those are non-interactive
714 # usually those are non-interactive
723 return self._isatty(self.fout)
715 return self._isatty(self.fout)
724
716
725 return i
717 return i
726
718
727 def _readline(self, prompt=''):
719 def _readline(self, prompt=''):
728 if self._isatty(self.fin):
720 if self._isatty(self.fin):
729 try:
721 try:
730 # magically add command line editing support, where
722 # magically add command line editing support, where
731 # available
723 # available
732 import readline
724 import readline
733 # force demandimport to really load the module
725 # force demandimport to really load the module
734 readline.read_history_file
726 readline.read_history_file
735 # windows sometimes raises something other than ImportError
727 # windows sometimes raises something other than ImportError
736 except Exception:
728 except Exception:
737 pass
729 pass
738
730
739 # call write() so output goes through subclassed implementation
731 # call write() so output goes through subclassed implementation
740 # e.g. color extension on Windows
732 # e.g. color extension on Windows
741 self.write(prompt)
733 self.write(prompt)
742
734
743 # instead of trying to emulate raw_input, swap (self.fin,
735 # instead of trying to emulate raw_input, swap (self.fin,
744 # self.fout) with (sys.stdin, sys.stdout)
736 # self.fout) with (sys.stdin, sys.stdout)
745 oldin = sys.stdin
737 oldin = sys.stdin
746 oldout = sys.stdout
738 oldout = sys.stdout
747 sys.stdin = self.fin
739 sys.stdin = self.fin
748 sys.stdout = self.fout
740 sys.stdout = self.fout
749 # prompt ' ' must exist; otherwise readline may delete entire line
741 # prompt ' ' must exist; otherwise readline may delete entire line
750 # - http://bugs.python.org/issue12833
742 # - http://bugs.python.org/issue12833
751 line = raw_input(' ')
743 line = raw_input(' ')
752 sys.stdin = oldin
744 sys.stdin = oldin
753 sys.stdout = oldout
745 sys.stdout = oldout
754
746
755 # When stdin is in binary mode on Windows, it can cause
747 # When stdin is in binary mode on Windows, it can cause
756 # raw_input() to emit an extra trailing carriage return
748 # raw_input() to emit an extra trailing carriage return
757 if os.linesep == '\r\n' and line and line[-1] == '\r':
749 if os.linesep == '\r\n' and line and line[-1] == '\r':
758 line = line[:-1]
750 line = line[:-1]
759 return line
751 return line
760
752
761 def prompt(self, msg, default="y"):
753 def prompt(self, msg, default="y"):
762 """Prompt user with msg, read response.
754 """Prompt user with msg, read response.
763 If ui is not interactive, the default is returned.
755 If ui is not interactive, the default is returned.
764 """
756 """
765 if not self.interactive():
757 if not self.interactive():
766 self.write(msg, ' ', default, "\n")
758 self.write(msg, ' ', default, "\n")
767 return default
759 return default
768 try:
760 try:
769 r = self._readline(self.label(msg, 'ui.prompt'))
761 r = self._readline(self.label(msg, 'ui.prompt'))
770 if not r:
762 if not r:
771 r = default
763 r = default
772 if self.configbool('ui', 'promptecho'):
764 if self.configbool('ui', 'promptecho'):
773 self.write(r, "\n")
765 self.write(r, "\n")
774 return r
766 return r
775 except EOFError:
767 except EOFError:
776 raise error.ResponseExpected()
768 raise error.ResponseExpected()
777
769
778 @staticmethod
770 @staticmethod
779 def extractchoices(prompt):
771 def extractchoices(prompt):
780 """Extract prompt message and list of choices from specified prompt.
772 """Extract prompt message and list of choices from specified prompt.
781
773
782 This returns tuple "(message, choices)", and "choices" is the
774 This returns tuple "(message, choices)", and "choices" is the
783 list of tuple "(response character, text without &)".
775 list of tuple "(response character, text without &)".
784 """
776 """
785 parts = prompt.split('$$')
777 parts = prompt.split('$$')
786 msg = parts[0].rstrip(' ')
778 msg = parts[0].rstrip(' ')
787 choices = [p.strip(' ') for p in parts[1:]]
779 choices = [p.strip(' ') for p in parts[1:]]
788 return (msg,
780 return (msg,
789 [(s[s.index('&') + 1].lower(), s.replace('&', '', 1))
781 [(s[s.index('&') + 1].lower(), s.replace('&', '', 1))
790 for s in choices])
782 for s in choices])
791
783
792 def promptchoice(self, prompt, default=0):
784 def promptchoice(self, prompt, default=0):
793 """Prompt user with a message, read response, and ensure it matches
785 """Prompt user with a message, read response, and ensure it matches
794 one of the provided choices. The prompt is formatted as follows:
786 one of the provided choices. The prompt is formatted as follows:
795
787
796 "would you like fries with that (Yn)? $$ &Yes $$ &No"
788 "would you like fries with that (Yn)? $$ &Yes $$ &No"
797
789
798 The index of the choice is returned. Responses are case
790 The index of the choice is returned. Responses are case
799 insensitive. If ui is not interactive, the default is
791 insensitive. If ui is not interactive, the default is
800 returned.
792 returned.
801 """
793 """
802
794
803 msg, choices = self.extractchoices(prompt)
795 msg, choices = self.extractchoices(prompt)
804 resps = [r for r, t in choices]
796 resps = [r for r, t in choices]
805 while True:
797 while True:
806 r = self.prompt(msg, resps[default])
798 r = self.prompt(msg, resps[default])
807 if r.lower() in resps:
799 if r.lower() in resps:
808 return resps.index(r.lower())
800 return resps.index(r.lower())
809 self.write(_("unrecognized response\n"))
801 self.write(_("unrecognized response\n"))
810
802
811 def getpass(self, prompt=None, default=None):
803 def getpass(self, prompt=None, default=None):
812 if not self.interactive():
804 if not self.interactive():
813 return default
805 return default
814 try:
806 try:
815 self.write_err(self.label(prompt or _('password: '), 'ui.prompt'))
807 self.write_err(self.label(prompt or _('password: '), 'ui.prompt'))
816 # disable getpass() only if explicitly specified. it's still valid
808 # disable getpass() only if explicitly specified. it's still valid
817 # to interact with tty even if fin is not a tty.
809 # to interact with tty even if fin is not a tty.
818 if self.configbool('ui', 'nontty'):
810 if self.configbool('ui', 'nontty'):
819 return self.fin.readline().rstrip('\n')
811 return self.fin.readline().rstrip('\n')
820 else:
812 else:
821 return getpass.getpass('')
813 return getpass.getpass('')
822 except EOFError:
814 except EOFError:
823 raise error.ResponseExpected()
815 raise error.ResponseExpected()
824 def status(self, *msg, **opts):
816 def status(self, *msg, **opts):
825 '''write status message to output (if ui.quiet is False)
817 '''write status message to output (if ui.quiet is False)
826
818
827 This adds an output label of "ui.status".
819 This adds an output label of "ui.status".
828 '''
820 '''
829 if not self.quiet:
821 if not self.quiet:
830 opts['label'] = opts.get('label', '') + ' ui.status'
822 opts['label'] = opts.get('label', '') + ' ui.status'
831 self.write(*msg, **opts)
823 self.write(*msg, **opts)
832 def warn(self, *msg, **opts):
824 def warn(self, *msg, **opts):
833 '''write warning message to output (stderr)
825 '''write warning message to output (stderr)
834
826
835 This adds an output label of "ui.warning".
827 This adds an output label of "ui.warning".
836 '''
828 '''
837 opts['label'] = opts.get('label', '') + ' ui.warning'
829 opts['label'] = opts.get('label', '') + ' ui.warning'
838 self.write_err(*msg, **opts)
830 self.write_err(*msg, **opts)
839 def note(self, *msg, **opts):
831 def note(self, *msg, **opts):
840 '''write note to output (if ui.verbose is True)
832 '''write note to output (if ui.verbose is True)
841
833
842 This adds an output label of "ui.note".
834 This adds an output label of "ui.note".
843 '''
835 '''
844 if self.verbose:
836 if self.verbose:
845 opts['label'] = opts.get('label', '') + ' ui.note'
837 opts['label'] = opts.get('label', '') + ' ui.note'
846 self.write(*msg, **opts)
838 self.write(*msg, **opts)
847 def debug(self, *msg, **opts):
839 def debug(self, *msg, **opts):
848 '''write debug message to output (if ui.debugflag is True)
840 '''write debug message to output (if ui.debugflag is True)
849
841
850 This adds an output label of "ui.debug".
842 This adds an output label of "ui.debug".
851 '''
843 '''
852 if self.debugflag:
844 if self.debugflag:
853 opts['label'] = opts.get('label', '') + ' ui.debug'
845 opts['label'] = opts.get('label', '') + ' ui.debug'
854 self.write(*msg, **opts)
846 self.write(*msg, **opts)
855
847
856 def edit(self, text, user, extra=None, editform=None, pending=None):
848 def edit(self, text, user, extra=None, editform=None, pending=None):
857 if extra is None:
849 if extra is None:
858 extra = {}
850 extra = {}
859 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
851 (fd, name) = tempfile.mkstemp(prefix="hg-editor-", suffix=".txt",
860 text=True)
852 text=True)
861 try:
853 try:
862 f = os.fdopen(fd, "w")
854 f = os.fdopen(fd, "w")
863 f.write(text)
855 f.write(text)
864 f.close()
856 f.close()
865
857
866 environ = {'HGUSER': user}
858 environ = {'HGUSER': user}
867 if 'transplant_source' in extra:
859 if 'transplant_source' in extra:
868 environ.update({'HGREVISION': hex(extra['transplant_source'])})
860 environ.update({'HGREVISION': hex(extra['transplant_source'])})
869 for label in ('intermediate-source', 'source', 'rebase_source'):
861 for label in ('intermediate-source', 'source', 'rebase_source'):
870 if label in extra:
862 if label in extra:
871 environ.update({'HGREVISION': extra[label]})
863 environ.update({'HGREVISION': extra[label]})
872 break
864 break
873 if editform:
865 if editform:
874 environ.update({'HGEDITFORM': editform})
866 environ.update({'HGEDITFORM': editform})
875 if pending:
867 if pending:
876 environ.update({'HG_PENDING': pending})
868 environ.update({'HG_PENDING': pending})
877
869
878 editor = self.geteditor()
870 editor = self.geteditor()
879
871
880 self.system("%s \"%s\"" % (editor, name),
872 self.system("%s \"%s\"" % (editor, name),
881 environ=environ,
873 environ=environ,
882 onerr=error.Abort, errprefix=_("edit failed"))
874 onerr=error.Abort, errprefix=_("edit failed"))
883
875
884 f = open(name)
876 f = open(name)
885 t = f.read()
877 t = f.read()
886 f.close()
878 f.close()
887 finally:
879 finally:
888 os.unlink(name)
880 os.unlink(name)
889
881
890 return t
882 return t
891
883
892 def system(self, cmd, environ=None, cwd=None, onerr=None, errprefix=None):
884 def system(self, cmd, environ=None, cwd=None, onerr=None, errprefix=None):
893 '''execute shell command with appropriate output stream. command
885 '''execute shell command with appropriate output stream. command
894 output will be redirected if fout is not stdout.
886 output will be redirected if fout is not stdout.
895 '''
887 '''
896 out = self.fout
888 out = self.fout
897 if any(s[1] for s in self._bufferstates):
889 if any(s[1] for s in self._bufferstates):
898 out = self
890 out = self
899 return util.system(cmd, environ=environ, cwd=cwd, onerr=onerr,
891 return util.system(cmd, environ=environ, cwd=cwd, onerr=onerr,
900 errprefix=errprefix, out=out)
892 errprefix=errprefix, out=out)
901
893
902 def traceback(self, exc=None, force=False):
894 def traceback(self, exc=None, force=False):
903 '''print exception traceback if traceback printing enabled or forced.
895 '''print exception traceback if traceback printing enabled or forced.
904 only to call in exception handler. returns true if traceback
896 only to call in exception handler. returns true if traceback
905 printed.'''
897 printed.'''
906 if self.tracebackflag or force:
898 if self.tracebackflag or force:
907 if exc is None:
899 if exc is None:
908 exc = sys.exc_info()
900 exc = sys.exc_info()
909 cause = getattr(exc[1], 'cause', None)
901 cause = getattr(exc[1], 'cause', None)
910
902
911 if cause is not None:
903 if cause is not None:
912 causetb = traceback.format_tb(cause[2])
904 causetb = traceback.format_tb(cause[2])
913 exctb = traceback.format_tb(exc[2])
905 exctb = traceback.format_tb(exc[2])
914 exconly = traceback.format_exception_only(cause[0], cause[1])
906 exconly = traceback.format_exception_only(cause[0], cause[1])
915
907
916 # exclude frame where 'exc' was chained and rethrown from exctb
908 # exclude frame where 'exc' was chained and rethrown from exctb
917 self.write_err('Traceback (most recent call last):\n',
909 self.write_err('Traceback (most recent call last):\n',
918 ''.join(exctb[:-1]),
910 ''.join(exctb[:-1]),
919 ''.join(causetb),
911 ''.join(causetb),
920 ''.join(exconly))
912 ''.join(exconly))
921 else:
913 else:
922 output = traceback.format_exception(exc[0], exc[1], exc[2])
914 output = traceback.format_exception(exc[0], exc[1], exc[2])
923 self.write_err(''.join(output))
915 self.write_err(''.join(output))
924 return self.tracebackflag or force
916 return self.tracebackflag or force
925
917
926 def geteditor(self):
918 def geteditor(self):
927 '''return editor to use'''
919 '''return editor to use'''
928 if sys.platform == 'plan9':
920 if sys.platform == 'plan9':
929 # vi is the MIPS instruction simulator on Plan 9. We
921 # vi is the MIPS instruction simulator on Plan 9. We
930 # instead default to E to plumb commit messages to
922 # instead default to E to plumb commit messages to
931 # avoid confusion.
923 # avoid confusion.
932 editor = 'E'
924 editor = 'E'
933 else:
925 else:
934 editor = 'vi'
926 editor = 'vi'
935 return (os.environ.get("HGEDITOR") or
927 return (os.environ.get("HGEDITOR") or
936 self.config("ui", "editor") or
928 self.config("ui", "editor") or
937 os.environ.get("VISUAL") or
929 os.environ.get("VISUAL") or
938 os.environ.get("EDITOR", editor))
930 os.environ.get("EDITOR", editor))
939
931
940 @util.propertycache
932 @util.propertycache
941 def _progbar(self):
933 def _progbar(self):
942 """setup the progbar singleton to the ui object"""
934 """setup the progbar singleton to the ui object"""
943 if (self.quiet or self.debugflag
935 if (self.quiet or self.debugflag
944 or self.configbool('progress', 'disable', False)
936 or self.configbool('progress', 'disable', False)
945 or not progress.shouldprint(self)):
937 or not progress.shouldprint(self)):
946 return None
938 return None
947 return getprogbar(self)
939 return getprogbar(self)
948
940
949 def _progclear(self):
941 def _progclear(self):
950 """clear progress bar output if any. use it before any output"""
942 """clear progress bar output if any. use it before any output"""
951 if '_progbar' not in vars(self): # nothing loaded yet
943 if '_progbar' not in vars(self): # nothing loaded yet
952 return
944 return
953 if self._progbar is not None and self._progbar.printed:
945 if self._progbar is not None and self._progbar.printed:
954 self._progbar.clear()
946 self._progbar.clear()
955
947
956 def progress(self, topic, pos, item="", unit="", total=None):
948 def progress(self, topic, pos, item="", unit="", total=None):
957 '''show a progress message
949 '''show a progress message
958
950
959 With stock hg, this is simply a debug message that is hidden
951 With stock hg, this is simply a debug message that is hidden
960 by default, but with extensions or GUI tools it may be
952 by default, but with extensions or GUI tools it may be
961 visible. 'topic' is the current operation, 'item' is a
953 visible. 'topic' is the current operation, 'item' is a
962 non-numeric marker of the current position (i.e. the currently
954 non-numeric marker of the current position (i.e. the currently
963 in-process file), 'pos' is the current numeric position (i.e.
955 in-process file), 'pos' is the current numeric position (i.e.
964 revision, bytes, etc.), unit is a corresponding unit label,
956 revision, bytes, etc.), unit is a corresponding unit label,
965 and total is the highest expected pos.
957 and total is the highest expected pos.
966
958
967 Multiple nested topics may be active at a time.
959 Multiple nested topics may be active at a time.
968
960
969 All topics should be marked closed by setting pos to None at
961 All topics should be marked closed by setting pos to None at
970 termination.
962 termination.
971 '''
963 '''
972 if self._progbar is not None:
964 if self._progbar is not None:
973 self._progbar.progress(topic, pos, item=item, unit=unit,
965 self._progbar.progress(topic, pos, item=item, unit=unit,
974 total=total)
966 total=total)
975 if pos is None or not self.configbool('progress', 'debug'):
967 if pos is None or not self.configbool('progress', 'debug'):
976 return
968 return
977
969
978 if unit:
970 if unit:
979 unit = ' ' + unit
971 unit = ' ' + unit
980 if item:
972 if item:
981 item = ' ' + item
973 item = ' ' + item
982
974
983 if total:
975 if total:
984 pct = 100.0 * pos / total
976 pct = 100.0 * pos / total
985 self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
977 self.debug('%s:%s %s/%s%s (%4.2f%%)\n'
986 % (topic, item, pos, total, unit, pct))
978 % (topic, item, pos, total, unit, pct))
987 else:
979 else:
988 self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
980 self.debug('%s:%s %s%s\n' % (topic, item, pos, unit))
989
981
990 def log(self, service, *msg, **opts):
982 def log(self, service, *msg, **opts):
991 '''hook for logging facility extensions
983 '''hook for logging facility extensions
992
984
993 service should be a readily-identifiable subsystem, which will
985 service should be a readily-identifiable subsystem, which will
994 allow filtering.
986 allow filtering.
995
987
996 *msg should be a newline-terminated format string to log, and
988 *msg should be a newline-terminated format string to log, and
997 then any values to %-format into that format string.
989 then any values to %-format into that format string.
998
990
999 **opts currently has no defined meanings.
991 **opts currently has no defined meanings.
1000 '''
992 '''
1001
993
1002 def label(self, msg, label):
994 def label(self, msg, label):
1003 '''style msg based on supplied label
995 '''style msg based on supplied label
1004
996
1005 Like ui.write(), this just returns msg unchanged, but extensions
997 Like ui.write(), this just returns msg unchanged, but extensions
1006 and GUI tools can override it to allow styling output without
998 and GUI tools can override it to allow styling output without
1007 writing it.
999 writing it.
1008
1000
1009 ui.write(s, 'label') is equivalent to
1001 ui.write(s, 'label') is equivalent to
1010 ui.write(ui.label(s, 'label')).
1002 ui.write(ui.label(s, 'label')).
1011 '''
1003 '''
1012 return msg
1004 return msg
1013
1005
1014 def develwarn(self, msg):
1006 def develwarn(self, msg):
1015 """issue a developer warning message"""
1007 """issue a developer warning message"""
1016 msg = 'devel-warn: ' + msg
1008 msg = 'devel-warn: ' + msg
1017 if self.tracebackflag:
1009 if self.tracebackflag:
1018 util.debugstacktrace(msg, 2, self.ferr, self.fout)
1010 util.debugstacktrace(msg, 2, self.ferr, self.fout)
1019 else:
1011 else:
1020 curframe = inspect.currentframe()
1012 curframe = inspect.currentframe()
1021 calframe = inspect.getouterframes(curframe, 2)
1013 calframe = inspect.getouterframes(curframe, 2)
1022 self.write_err('%s at: %s:%s (%s)\n' % ((msg,) + calframe[2][1:4]))
1014 self.write_err('%s at: %s:%s (%s)\n' % ((msg,) + calframe[2][1:4]))
1023
1015
1024 class paths(dict):
1016 class paths(dict):
1025 """Represents a collection of paths and their configs.
1017 """Represents a collection of paths and their configs.
1026
1018
1027 Data is initially derived from ui instances and the config files they have
1019 Data is initially derived from ui instances and the config files they have
1028 loaded.
1020 loaded.
1029 """
1021 """
1030 def __init__(self, ui):
1022 def __init__(self, ui):
1031 dict.__init__(self)
1023 dict.__init__(self)
1032
1024
1033 for name, loc in ui.configitems('paths'):
1025 for name, loc in ui.configitems('paths'):
1034 # No location is the same as not existing.
1026 # No location is the same as not existing.
1035 if not loc:
1027 if not loc:
1036 continue
1028 continue
1037
1029
1038 # TODO ignore default-push once all consumers stop referencing it
1030 # TODO ignore default-push once all consumers stop referencing it
1039 # since it is handled specifically below.
1031 # since it is handled specifically below.
1040
1032
1041 self[name] = path(name, rawloc=loc)
1033 self[name] = path(name, rawloc=loc)
1042
1034
1043 # Handle default-push, which is a one-off that defines the push URL for
1035 # Handle default-push, which is a one-off that defines the push URL for
1044 # the "default" path.
1036 # the "default" path.
1045 defaultpush = ui.config('paths', 'default-push')
1037 defaultpush = ui.config('paths', 'default-push')
1046 if defaultpush:
1038 if defaultpush:
1047 # "default-push" can be defined without "default" entry. This is a
1039 # "default-push" can be defined without "default" entry. This is a
1048 # bit weird, but is allowed for backwards compatibility.
1040 # bit weird, but is allowed for backwards compatibility.
1049 if 'default' not in self:
1041 if 'default' not in self:
1050 self['default'] = path('default', rawloc=defaultpush)
1042 self['default'] = path('default', rawloc=defaultpush)
1051 self['default']._pushloc = defaultpush
1043 self['default']._pushloc = defaultpush
1052
1044
1053 def getpath(self, name, default=None):
1045 def getpath(self, name, default=None):
1054 """Return a ``path`` from a string, falling back to a default.
1046 """Return a ``path`` from a string, falling back to a default.
1055
1047
1056 ``name`` can be a named path or locations. Locations are filesystem
1048 ``name`` can be a named path or locations. Locations are filesystem
1057 paths or URIs.
1049 paths or URIs.
1058
1050
1059 Returns None if ``name`` is not a registered path, a URI, or a local
1051 Returns None if ``name`` is not a registered path, a URI, or a local
1060 path to a repo.
1052 path to a repo.
1061 """
1053 """
1062 # Only fall back to default if no path was requested.
1054 # Only fall back to default if no path was requested.
1063 if name is None:
1055 if name is None:
1064 if default:
1056 if default:
1065 try:
1057 try:
1066 return self[default]
1058 return self[default]
1067 except KeyError:
1059 except KeyError:
1068 return None
1060 return None
1069 else:
1061 else:
1070 return None
1062 return None
1071
1063
1072 # Most likely empty string.
1064 # Most likely empty string.
1073 # This may need to raise in the future.
1065 # This may need to raise in the future.
1074 if not name:
1066 if not name:
1075 return None
1067 return None
1076
1068
1077 try:
1069 try:
1078 return self[name]
1070 return self[name]
1079 except KeyError:
1071 except KeyError:
1080 # Try to resolve as a local path or URI.
1072 # Try to resolve as a local path or URI.
1081 try:
1073 try:
1082 return path(None, rawloc=name)
1074 return path(None, rawloc=name)
1083 except ValueError:
1075 except ValueError:
1084 raise error.RepoError(_('repository %s does not exist') %
1076 raise error.RepoError(_('repository %s does not exist') %
1085 name)
1077 name)
1086
1078
1087 assert False
1079 assert False
1088
1080
1089 class path(object):
1081 class path(object):
1090 """Represents an individual path and its configuration."""
1082 """Represents an individual path and its configuration."""
1091
1083
1092 def __init__(self, name, rawloc=None, pushloc=None):
1084 def __init__(self, name, rawloc=None, pushloc=None):
1093 """Construct a path from its config options.
1085 """Construct a path from its config options.
1094
1086
1095 ``name`` is the symbolic name of the path.
1087 ``name`` is the symbolic name of the path.
1096 ``rawloc`` is the raw location, as defined in the config.
1088 ``rawloc`` is the raw location, as defined in the config.
1097 ``pushloc`` is the raw locations pushes should be made to.
1089 ``pushloc`` is the raw locations pushes should be made to.
1098
1090
1099 If ``name`` is not defined, we require that the location be a) a local
1091 If ``name`` is not defined, we require that the location be a) a local
1100 filesystem path with a .hg directory or b) a URL. If not,
1092 filesystem path with a .hg directory or b) a URL. If not,
1101 ``ValueError`` is raised.
1093 ``ValueError`` is raised.
1102 """
1094 """
1103 if not rawloc:
1095 if not rawloc:
1104 raise ValueError('rawloc must be defined')
1096 raise ValueError('rawloc must be defined')
1105
1097
1106 # Locations may define branches via syntax <base>#<branch>.
1098 # Locations may define branches via syntax <base>#<branch>.
1107 u = util.url(rawloc)
1099 u = util.url(rawloc)
1108 branch = None
1100 branch = None
1109 if u.fragment:
1101 if u.fragment:
1110 branch = u.fragment
1102 branch = u.fragment
1111 u.fragment = None
1103 u.fragment = None
1112
1104
1113 self.url = u
1105 self.url = u
1114 self.branch = branch
1106 self.branch = branch
1115
1107
1116 self.name = name
1108 self.name = name
1117 self.rawloc = rawloc
1109 self.rawloc = rawloc
1118 self.loc = str(u)
1110 self.loc = str(u)
1119 self._pushloc = pushloc
1111 self._pushloc = pushloc
1120
1112
1121 # When given a raw location but not a symbolic name, validate the
1113 # When given a raw location but not a symbolic name, validate the
1122 # location is valid.
1114 # location is valid.
1123 if not name and not u.scheme and not self._isvalidlocalpath(self.loc):
1115 if not name and not u.scheme and not self._isvalidlocalpath(self.loc):
1124 raise ValueError('location is not a URL or path to a local '
1116 raise ValueError('location is not a URL or path to a local '
1125 'repo: %s' % rawloc)
1117 'repo: %s' % rawloc)
1126
1118
1127 def _isvalidlocalpath(self, path):
1119 def _isvalidlocalpath(self, path):
1128 """Returns True if the given path is a potentially valid repository.
1120 """Returns True if the given path is a potentially valid repository.
1129 This is its own function so that extensions can change the definition of
1121 This is its own function so that extensions can change the definition of
1130 'valid' in this case (like when pulling from a git repo into a hg
1122 'valid' in this case (like when pulling from a git repo into a hg
1131 one)."""
1123 one)."""
1132 return os.path.isdir(os.path.join(path, '.hg'))
1124 return os.path.isdir(os.path.join(path, '.hg'))
1133
1125
1134 @property
1126 @property
1135 def pushloc(self):
1127 def pushloc(self):
1136 return self._pushloc or self.loc
1128 return self._pushloc or self.loc
1137
1129
1138 # we instantiate one globally shared progress bar to avoid
1130 # we instantiate one globally shared progress bar to avoid
1139 # competing progress bars when multiple UI objects get created
1131 # competing progress bars when multiple UI objects get created
1140 _progresssingleton = None
1132 _progresssingleton = None
1141
1133
1142 def getprogbar(ui):
1134 def getprogbar(ui):
1143 global _progresssingleton
1135 global _progresssingleton
1144 if _progresssingleton is None:
1136 if _progresssingleton is None:
1145 # passing 'ui' object to the singleton is fishy,
1137 # passing 'ui' object to the singleton is fishy,
1146 # this is how the extension used to work but feel free to rework it.
1138 # this is how the extension used to work but feel free to rework it.
1147 _progresssingleton = progress.progbar(ui)
1139 _progresssingleton = progress.progbar(ui)
1148 return _progresssingleton
1140 return _progresssingleton
General Comments 0
You need to be logged in to leave comments. Login now