##// END OF EJS Templates
formatter: add general way to switch hex/short functions...
Yuya Nishihara -
r22701:cb28d2b3 default
parent child Browse files
Show More
@@ -1,6318 +1,6312 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing 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 node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _
10 from i18n import _
11 import os, re, difflib, time, tempfile, errno, shlex
11 import os, re, difflib, time, tempfile, errno, shlex
12 import sys, socket
12 import sys, socket
13 import hg, scmutil, util, revlog, copies, error, bookmarks
13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 import patch, help, encoding, templatekw, discovery
14 import patch, help, encoding, templatekw, discovery
15 import archival, changegroup, cmdutil, hbisect
15 import archival, changegroup, cmdutil, hbisect
16 import sshserver, hgweb, commandserver
16 import sshserver, hgweb, commandserver
17 import extensions
17 import extensions
18 from hgweb import server as hgweb_server
18 from hgweb import server as hgweb_server
19 import merge as mergemod
19 import merge as mergemod
20 import minirst, revset, fileset
20 import minirst, revset, fileset
21 import dagparser, context, simplemerge, graphmod
21 import dagparser, context, simplemerge, graphmod
22 import random
22 import random
23 import setdiscovery, treediscovery, dagutil, pvec, localrepo
23 import setdiscovery, treediscovery, dagutil, pvec, localrepo
24 import phases, obsolete, exchange
24 import phases, obsolete, exchange
25
25
26 table = {}
26 table = {}
27
27
28 command = cmdutil.command(table)
28 command = cmdutil.command(table)
29
29
30 # Space delimited list of commands that don't require local repositories.
30 # Space delimited list of commands that don't require local repositories.
31 # This should be populated by passing norepo=True into the @command decorator.
31 # This should be populated by passing norepo=True into the @command decorator.
32 norepo = ''
32 norepo = ''
33 # Space delimited list of commands that optionally require local repositories.
33 # Space delimited list of commands that optionally require local repositories.
34 # This should be populated by passing optionalrepo=True into the @command
34 # This should be populated by passing optionalrepo=True into the @command
35 # decorator.
35 # decorator.
36 optionalrepo = ''
36 optionalrepo = ''
37 # Space delimited list of commands that will examine arguments looking for
37 # Space delimited list of commands that will examine arguments looking for
38 # a repository. This should be populated by passing inferrepo=True into the
38 # a repository. This should be populated by passing inferrepo=True into the
39 # @command decorator.
39 # @command decorator.
40 inferrepo = ''
40 inferrepo = ''
41
41
42 # common command options
42 # common command options
43
43
44 globalopts = [
44 globalopts = [
45 ('R', 'repository', '',
45 ('R', 'repository', '',
46 _('repository root directory or name of overlay bundle file'),
46 _('repository root directory or name of overlay bundle file'),
47 _('REPO')),
47 _('REPO')),
48 ('', 'cwd', '',
48 ('', 'cwd', '',
49 _('change working directory'), _('DIR')),
49 _('change working directory'), _('DIR')),
50 ('y', 'noninteractive', None,
50 ('y', 'noninteractive', None,
51 _('do not prompt, automatically pick the first choice for all prompts')),
51 _('do not prompt, automatically pick the first choice for all prompts')),
52 ('q', 'quiet', None, _('suppress output')),
52 ('q', 'quiet', None, _('suppress output')),
53 ('v', 'verbose', None, _('enable additional output')),
53 ('v', 'verbose', None, _('enable additional output')),
54 ('', 'config', [],
54 ('', 'config', [],
55 _('set/override config option (use \'section.name=value\')'),
55 _('set/override config option (use \'section.name=value\')'),
56 _('CONFIG')),
56 _('CONFIG')),
57 ('', 'debug', None, _('enable debugging output')),
57 ('', 'debug', None, _('enable debugging output')),
58 ('', 'debugger', None, _('start debugger')),
58 ('', 'debugger', None, _('start debugger')),
59 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
59 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
60 _('ENCODE')),
60 _('ENCODE')),
61 ('', 'encodingmode', encoding.encodingmode,
61 ('', 'encodingmode', encoding.encodingmode,
62 _('set the charset encoding mode'), _('MODE')),
62 _('set the charset encoding mode'), _('MODE')),
63 ('', 'traceback', None, _('always print a traceback on exception')),
63 ('', 'traceback', None, _('always print a traceback on exception')),
64 ('', 'time', None, _('time how long the command takes')),
64 ('', 'time', None, _('time how long the command takes')),
65 ('', 'profile', None, _('print command execution profile')),
65 ('', 'profile', None, _('print command execution profile')),
66 ('', 'version', None, _('output version information and exit')),
66 ('', 'version', None, _('output version information and exit')),
67 ('h', 'help', None, _('display help and exit')),
67 ('h', 'help', None, _('display help and exit')),
68 ('', 'hidden', False, _('consider hidden changesets')),
68 ('', 'hidden', False, _('consider hidden changesets')),
69 ]
69 ]
70
70
71 dryrunopts = [('n', 'dry-run', None,
71 dryrunopts = [('n', 'dry-run', None,
72 _('do not perform actions, just print output'))]
72 _('do not perform actions, just print output'))]
73
73
74 remoteopts = [
74 remoteopts = [
75 ('e', 'ssh', '',
75 ('e', 'ssh', '',
76 _('specify ssh command to use'), _('CMD')),
76 _('specify ssh command to use'), _('CMD')),
77 ('', 'remotecmd', '',
77 ('', 'remotecmd', '',
78 _('specify hg command to run on the remote side'), _('CMD')),
78 _('specify hg command to run on the remote side'), _('CMD')),
79 ('', 'insecure', None,
79 ('', 'insecure', None,
80 _('do not verify server certificate (ignoring web.cacerts config)')),
80 _('do not verify server certificate (ignoring web.cacerts config)')),
81 ]
81 ]
82
82
83 walkopts = [
83 walkopts = [
84 ('I', 'include', [],
84 ('I', 'include', [],
85 _('include names matching the given patterns'), _('PATTERN')),
85 _('include names matching the given patterns'), _('PATTERN')),
86 ('X', 'exclude', [],
86 ('X', 'exclude', [],
87 _('exclude names matching the given patterns'), _('PATTERN')),
87 _('exclude names matching the given patterns'), _('PATTERN')),
88 ]
88 ]
89
89
90 commitopts = [
90 commitopts = [
91 ('m', 'message', '',
91 ('m', 'message', '',
92 _('use text as commit message'), _('TEXT')),
92 _('use text as commit message'), _('TEXT')),
93 ('l', 'logfile', '',
93 ('l', 'logfile', '',
94 _('read commit message from file'), _('FILE')),
94 _('read commit message from file'), _('FILE')),
95 ]
95 ]
96
96
97 commitopts2 = [
97 commitopts2 = [
98 ('d', 'date', '',
98 ('d', 'date', '',
99 _('record the specified date as commit date'), _('DATE')),
99 _('record the specified date as commit date'), _('DATE')),
100 ('u', 'user', '',
100 ('u', 'user', '',
101 _('record the specified user as committer'), _('USER')),
101 _('record the specified user as committer'), _('USER')),
102 ]
102 ]
103
103
104 # hidden for now
104 # hidden for now
105 formatteropts = [
105 formatteropts = [
106 ('T', 'template', '',
106 ('T', 'template', '',
107 _('display with template (DEPRECATED)'), _('TEMPLATE')),
107 _('display with template (DEPRECATED)'), _('TEMPLATE')),
108 ]
108 ]
109
109
110 templateopts = [
110 templateopts = [
111 ('', 'style', '',
111 ('', 'style', '',
112 _('display using template map file (DEPRECATED)'), _('STYLE')),
112 _('display using template map file (DEPRECATED)'), _('STYLE')),
113 ('T', 'template', '',
113 ('T', 'template', '',
114 _('display with template'), _('TEMPLATE')),
114 _('display with template'), _('TEMPLATE')),
115 ]
115 ]
116
116
117 logopts = [
117 logopts = [
118 ('p', 'patch', None, _('show patch')),
118 ('p', 'patch', None, _('show patch')),
119 ('g', 'git', None, _('use git extended diff format')),
119 ('g', 'git', None, _('use git extended diff format')),
120 ('l', 'limit', '',
120 ('l', 'limit', '',
121 _('limit number of changes displayed'), _('NUM')),
121 _('limit number of changes displayed'), _('NUM')),
122 ('M', 'no-merges', None, _('do not show merges')),
122 ('M', 'no-merges', None, _('do not show merges')),
123 ('', 'stat', None, _('output diffstat-style summary of changes')),
123 ('', 'stat', None, _('output diffstat-style summary of changes')),
124 ('G', 'graph', None, _("show the revision DAG")),
124 ('G', 'graph', None, _("show the revision DAG")),
125 ] + templateopts
125 ] + templateopts
126
126
127 diffopts = [
127 diffopts = [
128 ('a', 'text', None, _('treat all files as text')),
128 ('a', 'text', None, _('treat all files as text')),
129 ('g', 'git', None, _('use git extended diff format')),
129 ('g', 'git', None, _('use git extended diff format')),
130 ('', 'nodates', None, _('omit dates from diff headers'))
130 ('', 'nodates', None, _('omit dates from diff headers'))
131 ]
131 ]
132
132
133 diffwsopts = [
133 diffwsopts = [
134 ('w', 'ignore-all-space', None,
134 ('w', 'ignore-all-space', None,
135 _('ignore white space when comparing lines')),
135 _('ignore white space when comparing lines')),
136 ('b', 'ignore-space-change', None,
136 ('b', 'ignore-space-change', None,
137 _('ignore changes in the amount of white space')),
137 _('ignore changes in the amount of white space')),
138 ('B', 'ignore-blank-lines', None,
138 ('B', 'ignore-blank-lines', None,
139 _('ignore changes whose lines are all blank')),
139 _('ignore changes whose lines are all blank')),
140 ]
140 ]
141
141
142 diffopts2 = [
142 diffopts2 = [
143 ('p', 'show-function', None, _('show which function each change is in')),
143 ('p', 'show-function', None, _('show which function each change is in')),
144 ('', 'reverse', None, _('produce a diff that undoes the changes')),
144 ('', 'reverse', None, _('produce a diff that undoes the changes')),
145 ] + diffwsopts + [
145 ] + diffwsopts + [
146 ('U', 'unified', '',
146 ('U', 'unified', '',
147 _('number of lines of context to show'), _('NUM')),
147 _('number of lines of context to show'), _('NUM')),
148 ('', 'stat', None, _('output diffstat-style summary of changes')),
148 ('', 'stat', None, _('output diffstat-style summary of changes')),
149 ]
149 ]
150
150
151 mergetoolopts = [
151 mergetoolopts = [
152 ('t', 'tool', '', _('specify merge tool')),
152 ('t', 'tool', '', _('specify merge tool')),
153 ]
153 ]
154
154
155 similarityopts = [
155 similarityopts = [
156 ('s', 'similarity', '',
156 ('s', 'similarity', '',
157 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
157 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
158 ]
158 ]
159
159
160 subrepoopts = [
160 subrepoopts = [
161 ('S', 'subrepos', None,
161 ('S', 'subrepos', None,
162 _('recurse into subrepositories'))
162 _('recurse into subrepositories'))
163 ]
163 ]
164
164
165 # Commands start here, listed alphabetically
165 # Commands start here, listed alphabetically
166
166
167 @command('^add',
167 @command('^add',
168 walkopts + subrepoopts + dryrunopts,
168 walkopts + subrepoopts + dryrunopts,
169 _('[OPTION]... [FILE]...'),
169 _('[OPTION]... [FILE]...'),
170 inferrepo=True)
170 inferrepo=True)
171 def add(ui, repo, *pats, **opts):
171 def add(ui, repo, *pats, **opts):
172 """add the specified files on the next commit
172 """add the specified files on the next commit
173
173
174 Schedule files to be version controlled and added to the
174 Schedule files to be version controlled and added to the
175 repository.
175 repository.
176
176
177 The files will be added to the repository at the next commit. To
177 The files will be added to the repository at the next commit. To
178 undo an add before that, see :hg:`forget`.
178 undo an add before that, see :hg:`forget`.
179
179
180 If no names are given, add all files to the repository.
180 If no names are given, add all files to the repository.
181
181
182 .. container:: verbose
182 .. container:: verbose
183
183
184 An example showing how new (unknown) files are added
184 An example showing how new (unknown) files are added
185 automatically by :hg:`add`::
185 automatically by :hg:`add`::
186
186
187 $ ls
187 $ ls
188 foo.c
188 foo.c
189 $ hg status
189 $ hg status
190 ? foo.c
190 ? foo.c
191 $ hg add
191 $ hg add
192 adding foo.c
192 adding foo.c
193 $ hg status
193 $ hg status
194 A foo.c
194 A foo.c
195
195
196 Returns 0 if all files are successfully added.
196 Returns 0 if all files are successfully added.
197 """
197 """
198
198
199 m = scmutil.match(repo[None], pats, opts)
199 m = scmutil.match(repo[None], pats, opts)
200 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
200 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
201 opts.get('subrepos'), prefix="", explicitonly=False)
201 opts.get('subrepos'), prefix="", explicitonly=False)
202 return rejected and 1 or 0
202 return rejected and 1 or 0
203
203
204 @command('addremove',
204 @command('addremove',
205 similarityopts + walkopts + dryrunopts,
205 similarityopts + walkopts + dryrunopts,
206 _('[OPTION]... [FILE]...'),
206 _('[OPTION]... [FILE]...'),
207 inferrepo=True)
207 inferrepo=True)
208 def addremove(ui, repo, *pats, **opts):
208 def addremove(ui, repo, *pats, **opts):
209 """add all new files, delete all missing files
209 """add all new files, delete all missing files
210
210
211 Add all new files and remove all missing files from the
211 Add all new files and remove all missing files from the
212 repository.
212 repository.
213
213
214 New files are ignored if they match any of the patterns in
214 New files are ignored if they match any of the patterns in
215 ``.hgignore``. As with add, these changes take effect at the next
215 ``.hgignore``. As with add, these changes take effect at the next
216 commit.
216 commit.
217
217
218 Use the -s/--similarity option to detect renamed files. This
218 Use the -s/--similarity option to detect renamed files. This
219 option takes a percentage between 0 (disabled) and 100 (files must
219 option takes a percentage between 0 (disabled) and 100 (files must
220 be identical) as its parameter. With a parameter greater than 0,
220 be identical) as its parameter. With a parameter greater than 0,
221 this compares every removed file with every added file and records
221 this compares every removed file with every added file and records
222 those similar enough as renames. Detecting renamed files this way
222 those similar enough as renames. Detecting renamed files this way
223 can be expensive. After using this option, :hg:`status -C` can be
223 can be expensive. After using this option, :hg:`status -C` can be
224 used to check which files were identified as moved or renamed. If
224 used to check which files were identified as moved or renamed. If
225 not specified, -s/--similarity defaults to 100 and only renames of
225 not specified, -s/--similarity defaults to 100 and only renames of
226 identical files are detected.
226 identical files are detected.
227
227
228 Returns 0 if all files are successfully added.
228 Returns 0 if all files are successfully added.
229 """
229 """
230 try:
230 try:
231 sim = float(opts.get('similarity') or 100)
231 sim = float(opts.get('similarity') or 100)
232 except ValueError:
232 except ValueError:
233 raise util.Abort(_('similarity must be a number'))
233 raise util.Abort(_('similarity must be a number'))
234 if sim < 0 or sim > 100:
234 if sim < 0 or sim > 100:
235 raise util.Abort(_('similarity must be between 0 and 100'))
235 raise util.Abort(_('similarity must be between 0 and 100'))
236 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
236 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
237
237
238 @command('^annotate|blame',
238 @command('^annotate|blame',
239 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
239 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
240 ('', 'follow', None,
240 ('', 'follow', None,
241 _('follow copies/renames and list the filename (DEPRECATED)')),
241 _('follow copies/renames and list the filename (DEPRECATED)')),
242 ('', 'no-follow', None, _("don't follow copies and renames")),
242 ('', 'no-follow', None, _("don't follow copies and renames")),
243 ('a', 'text', None, _('treat all files as text')),
243 ('a', 'text', None, _('treat all files as text')),
244 ('u', 'user', None, _('list the author (long with -v)')),
244 ('u', 'user', None, _('list the author (long with -v)')),
245 ('f', 'file', None, _('list the filename')),
245 ('f', 'file', None, _('list the filename')),
246 ('d', 'date', None, _('list the date (short with -q)')),
246 ('d', 'date', None, _('list the date (short with -q)')),
247 ('n', 'number', None, _('list the revision number (default)')),
247 ('n', 'number', None, _('list the revision number (default)')),
248 ('c', 'changeset', None, _('list the changeset')),
248 ('c', 'changeset', None, _('list the changeset')),
249 ('l', 'line-number', None, _('show line number at the first appearance'))
249 ('l', 'line-number', None, _('show line number at the first appearance'))
250 ] + diffwsopts + walkopts + formatteropts,
250 ] + diffwsopts + walkopts + formatteropts,
251 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
251 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
252 inferrepo=True)
252 inferrepo=True)
253 def annotate(ui, repo, *pats, **opts):
253 def annotate(ui, repo, *pats, **opts):
254 """show changeset information by line for each file
254 """show changeset information by line for each file
255
255
256 List changes in files, showing the revision id responsible for
256 List changes in files, showing the revision id responsible for
257 each line
257 each line
258
258
259 This command is useful for discovering when a change was made and
259 This command is useful for discovering when a change was made and
260 by whom.
260 by whom.
261
261
262 Without the -a/--text option, annotate will avoid processing files
262 Without the -a/--text option, annotate will avoid processing files
263 it detects as binary. With -a, annotate will annotate the file
263 it detects as binary. With -a, annotate will annotate the file
264 anyway, although the results will probably be neither useful
264 anyway, although the results will probably be neither useful
265 nor desirable.
265 nor desirable.
266
266
267 Returns 0 on success.
267 Returns 0 on success.
268 """
268 """
269 if not pats:
269 if not pats:
270 raise util.Abort(_('at least one filename or pattern is required'))
270 raise util.Abort(_('at least one filename or pattern is required'))
271
271
272 if opts.get('follow'):
272 if opts.get('follow'):
273 # --follow is deprecated and now just an alias for -f/--file
273 # --follow is deprecated and now just an alias for -f/--file
274 # to mimic the behavior of Mercurial before version 1.5
274 # to mimic the behavior of Mercurial before version 1.5
275 opts['file'] = True
275 opts['file'] = True
276
276
277 fm = ui.formatter('annotate', opts)
277 fm = ui.formatter('annotate', opts)
278 datefunc = ui.quiet and util.shortdate or util.datestr
278 datefunc = ui.quiet and util.shortdate or util.datestr
279 if fm or ui.debugflag:
279 hexfn = fm.hexfunc
280 hexfn = hex
281 else:
282 hexfn = short
283
280
284 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
281 opmap = [('user', ' ', lambda x: x[0].user(), ui.shortuser),
285 ('number', ' ', lambda x: x[0].rev(), str),
282 ('number', ' ', lambda x: x[0].rev(), str),
286 ('changeset', ' ', lambda x: hexfn(x[0].node()), str),
283 ('changeset', ' ', lambda x: hexfn(x[0].node()), str),
287 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
284 ('date', ' ', lambda x: x[0].date(), util.cachefunc(datefunc)),
288 ('file', ' ', lambda x: x[0].path(), str),
285 ('file', ' ', lambda x: x[0].path(), str),
289 ('line_number', ':', lambda x: x[1], str),
286 ('line_number', ':', lambda x: x[1], str),
290 ]
287 ]
291 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
288 fieldnamemap = {'number': 'rev', 'changeset': 'node'}
292
289
293 if (not opts.get('user') and not opts.get('changeset')
290 if (not opts.get('user') and not opts.get('changeset')
294 and not opts.get('date') and not opts.get('file')):
291 and not opts.get('date') and not opts.get('file')):
295 opts['number'] = True
292 opts['number'] = True
296
293
297 linenumber = opts.get('line_number') is not None
294 linenumber = opts.get('line_number') is not None
298 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
295 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
299 raise util.Abort(_('at least one of -n/-c is required for -l'))
296 raise util.Abort(_('at least one of -n/-c is required for -l'))
300
297
301 if fm:
298 if fm:
302 def makefunc(get, fmt):
299 def makefunc(get, fmt):
303 return get
300 return get
304 else:
301 else:
305 def makefunc(get, fmt):
302 def makefunc(get, fmt):
306 return lambda x: fmt(get(x))
303 return lambda x: fmt(get(x))
307 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
304 funcmap = [(makefunc(get, fmt), sep) for op, sep, get, fmt in opmap
308 if opts.get(op)]
305 if opts.get(op)]
309 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
306 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
310 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
307 fields = ' '.join(fieldnamemap.get(op, op) for op, sep, get, fmt in opmap
311 if opts.get(op))
308 if opts.get(op))
312
309
313 def bad(x, y):
310 def bad(x, y):
314 raise util.Abort("%s: %s" % (x, y))
311 raise util.Abort("%s: %s" % (x, y))
315
312
316 ctx = scmutil.revsingle(repo, opts.get('rev'))
313 ctx = scmutil.revsingle(repo, opts.get('rev'))
317 m = scmutil.match(ctx, pats, opts)
314 m = scmutil.match(ctx, pats, opts)
318 m.bad = bad
315 m.bad = bad
319 follow = not opts.get('no_follow')
316 follow = not opts.get('no_follow')
320 diffopts = patch.diffopts(ui, opts, section='annotate')
317 diffopts = patch.diffopts(ui, opts, section='annotate')
321 for abs in ctx.walk(m):
318 for abs in ctx.walk(m):
322 fctx = ctx[abs]
319 fctx = ctx[abs]
323 if not opts.get('text') and util.binary(fctx.data()):
320 if not opts.get('text') and util.binary(fctx.data()):
324 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
321 fm.plain(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
325 continue
322 continue
326
323
327 lines = fctx.annotate(follow=follow, linenumber=linenumber,
324 lines = fctx.annotate(follow=follow, linenumber=linenumber,
328 diffopts=diffopts)
325 diffopts=diffopts)
329 formats = []
326 formats = []
330 pieces = []
327 pieces = []
331
328
332 for f, sep in funcmap:
329 for f, sep in funcmap:
333 l = [f(n) for n, dummy in lines]
330 l = [f(n) for n, dummy in lines]
334 if l:
331 if l:
335 if fm:
332 if fm:
336 formats.append(['%s' for x in l])
333 formats.append(['%s' for x in l])
337 else:
334 else:
338 sizes = [encoding.colwidth(x) for x in l]
335 sizes = [encoding.colwidth(x) for x in l]
339 ml = max(sizes)
336 ml = max(sizes)
340 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
337 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
341 pieces.append(l)
338 pieces.append(l)
342
339
343 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
340 for f, p, l in zip(zip(*formats), zip(*pieces), lines):
344 fm.startitem()
341 fm.startitem()
345 fm.write(fields, "".join(f), *p)
342 fm.write(fields, "".join(f), *p)
346 fm.write('line', ": %s", l[1])
343 fm.write('line', ": %s", l[1])
347
344
348 if lines and not lines[-1][1].endswith('\n'):
345 if lines and not lines[-1][1].endswith('\n'):
349 fm.plain('\n')
346 fm.plain('\n')
350
347
351 fm.end()
348 fm.end()
352
349
353 @command('archive',
350 @command('archive',
354 [('', 'no-decode', None, _('do not pass files through decoders')),
351 [('', 'no-decode', None, _('do not pass files through decoders')),
355 ('p', 'prefix', '', _('directory prefix for files in archive'),
352 ('p', 'prefix', '', _('directory prefix for files in archive'),
356 _('PREFIX')),
353 _('PREFIX')),
357 ('r', 'rev', '', _('revision to distribute'), _('REV')),
354 ('r', 'rev', '', _('revision to distribute'), _('REV')),
358 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
355 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
359 ] + subrepoopts + walkopts,
356 ] + subrepoopts + walkopts,
360 _('[OPTION]... DEST'))
357 _('[OPTION]... DEST'))
361 def archive(ui, repo, dest, **opts):
358 def archive(ui, repo, dest, **opts):
362 '''create an unversioned archive of a repository revision
359 '''create an unversioned archive of a repository revision
363
360
364 By default, the revision used is the parent of the working
361 By default, the revision used is the parent of the working
365 directory; use -r/--rev to specify a different revision.
362 directory; use -r/--rev to specify a different revision.
366
363
367 The archive type is automatically detected based on file
364 The archive type is automatically detected based on file
368 extension (or override using -t/--type).
365 extension (or override using -t/--type).
369
366
370 .. container:: verbose
367 .. container:: verbose
371
368
372 Examples:
369 Examples:
373
370
374 - create a zip file containing the 1.0 release::
371 - create a zip file containing the 1.0 release::
375
372
376 hg archive -r 1.0 project-1.0.zip
373 hg archive -r 1.0 project-1.0.zip
377
374
378 - create a tarball excluding .hg files::
375 - create a tarball excluding .hg files::
379
376
380 hg archive project.tar.gz -X ".hg*"
377 hg archive project.tar.gz -X ".hg*"
381
378
382 Valid types are:
379 Valid types are:
383
380
384 :``files``: a directory full of files (default)
381 :``files``: a directory full of files (default)
385 :``tar``: tar archive, uncompressed
382 :``tar``: tar archive, uncompressed
386 :``tbz2``: tar archive, compressed using bzip2
383 :``tbz2``: tar archive, compressed using bzip2
387 :``tgz``: tar archive, compressed using gzip
384 :``tgz``: tar archive, compressed using gzip
388 :``uzip``: zip archive, uncompressed
385 :``uzip``: zip archive, uncompressed
389 :``zip``: zip archive, compressed using deflate
386 :``zip``: zip archive, compressed using deflate
390
387
391 The exact name of the destination archive or directory is given
388 The exact name of the destination archive or directory is given
392 using a format string; see :hg:`help export` for details.
389 using a format string; see :hg:`help export` for details.
393
390
394 Each member added to an archive file has a directory prefix
391 Each member added to an archive file has a directory prefix
395 prepended. Use -p/--prefix to specify a format string for the
392 prepended. Use -p/--prefix to specify a format string for the
396 prefix. The default is the basename of the archive, with suffixes
393 prefix. The default is the basename of the archive, with suffixes
397 removed.
394 removed.
398
395
399 Returns 0 on success.
396 Returns 0 on success.
400 '''
397 '''
401
398
402 ctx = scmutil.revsingle(repo, opts.get('rev'))
399 ctx = scmutil.revsingle(repo, opts.get('rev'))
403 if not ctx:
400 if not ctx:
404 raise util.Abort(_('no working directory: please specify a revision'))
401 raise util.Abort(_('no working directory: please specify a revision'))
405 node = ctx.node()
402 node = ctx.node()
406 dest = cmdutil.makefilename(repo, dest, node)
403 dest = cmdutil.makefilename(repo, dest, node)
407 if os.path.realpath(dest) == repo.root:
404 if os.path.realpath(dest) == repo.root:
408 raise util.Abort(_('repository root cannot be destination'))
405 raise util.Abort(_('repository root cannot be destination'))
409
406
410 kind = opts.get('type') or archival.guesskind(dest) or 'files'
407 kind = opts.get('type') or archival.guesskind(dest) or 'files'
411 prefix = opts.get('prefix')
408 prefix = opts.get('prefix')
412
409
413 if dest == '-':
410 if dest == '-':
414 if kind == 'files':
411 if kind == 'files':
415 raise util.Abort(_('cannot archive plain files to stdout'))
412 raise util.Abort(_('cannot archive plain files to stdout'))
416 dest = cmdutil.makefileobj(repo, dest)
413 dest = cmdutil.makefileobj(repo, dest)
417 if not prefix:
414 if not prefix:
418 prefix = os.path.basename(repo.root) + '-%h'
415 prefix = os.path.basename(repo.root) + '-%h'
419
416
420 prefix = cmdutil.makefilename(repo, prefix, node)
417 prefix = cmdutil.makefilename(repo, prefix, node)
421 matchfn = scmutil.match(ctx, [], opts)
418 matchfn = scmutil.match(ctx, [], opts)
422 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
419 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
423 matchfn, prefix, subrepos=opts.get('subrepos'))
420 matchfn, prefix, subrepos=opts.get('subrepos'))
424
421
425 @command('backout',
422 @command('backout',
426 [('', 'merge', None, _('merge with old dirstate parent after backout')),
423 [('', 'merge', None, _('merge with old dirstate parent after backout')),
427 ('', 'parent', '',
424 ('', 'parent', '',
428 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
425 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
429 ('r', 'rev', '', _('revision to backout'), _('REV')),
426 ('r', 'rev', '', _('revision to backout'), _('REV')),
430 ('e', 'edit', False, _('invoke editor on commit messages')),
427 ('e', 'edit', False, _('invoke editor on commit messages')),
431 ] + mergetoolopts + walkopts + commitopts + commitopts2,
428 ] + mergetoolopts + walkopts + commitopts + commitopts2,
432 _('[OPTION]... [-r] REV'))
429 _('[OPTION]... [-r] REV'))
433 def backout(ui, repo, node=None, rev=None, **opts):
430 def backout(ui, repo, node=None, rev=None, **opts):
434 '''reverse effect of earlier changeset
431 '''reverse effect of earlier changeset
435
432
436 Prepare a new changeset with the effect of REV undone in the
433 Prepare a new changeset with the effect of REV undone in the
437 current working directory.
434 current working directory.
438
435
439 If REV is the parent of the working directory, then this new changeset
436 If REV is the parent of the working directory, then this new changeset
440 is committed automatically. Otherwise, hg needs to merge the
437 is committed automatically. Otherwise, hg needs to merge the
441 changes and the merged result is left uncommitted.
438 changes and the merged result is left uncommitted.
442
439
443 .. note::
440 .. note::
444
441
445 backout cannot be used to fix either an unwanted or
442 backout cannot be used to fix either an unwanted or
446 incorrect merge.
443 incorrect merge.
447
444
448 .. container:: verbose
445 .. container:: verbose
449
446
450 By default, the pending changeset will have one parent,
447 By default, the pending changeset will have one parent,
451 maintaining a linear history. With --merge, the pending
448 maintaining a linear history. With --merge, the pending
452 changeset will instead have two parents: the old parent of the
449 changeset will instead have two parents: the old parent of the
453 working directory and a new child of REV that simply undoes REV.
450 working directory and a new child of REV that simply undoes REV.
454
451
455 Before version 1.7, the behavior without --merge was equivalent
452 Before version 1.7, the behavior without --merge was equivalent
456 to specifying --merge followed by :hg:`update --clean .` to
453 to specifying --merge followed by :hg:`update --clean .` to
457 cancel the merge and leave the child of REV as a head to be
454 cancel the merge and leave the child of REV as a head to be
458 merged separately.
455 merged separately.
459
456
460 See :hg:`help dates` for a list of formats valid for -d/--date.
457 See :hg:`help dates` for a list of formats valid for -d/--date.
461
458
462 Returns 0 on success, 1 if nothing to backout or there are unresolved
459 Returns 0 on success, 1 if nothing to backout or there are unresolved
463 files.
460 files.
464 '''
461 '''
465 if rev and node:
462 if rev and node:
466 raise util.Abort(_("please specify just one revision"))
463 raise util.Abort(_("please specify just one revision"))
467
464
468 if not rev:
465 if not rev:
469 rev = node
466 rev = node
470
467
471 if not rev:
468 if not rev:
472 raise util.Abort(_("please specify a revision to backout"))
469 raise util.Abort(_("please specify a revision to backout"))
473
470
474 date = opts.get('date')
471 date = opts.get('date')
475 if date:
472 if date:
476 opts['date'] = util.parsedate(date)
473 opts['date'] = util.parsedate(date)
477
474
478 cmdutil.checkunfinished(repo)
475 cmdutil.checkunfinished(repo)
479 cmdutil.bailifchanged(repo)
476 cmdutil.bailifchanged(repo)
480 node = scmutil.revsingle(repo, rev).node()
477 node = scmutil.revsingle(repo, rev).node()
481
478
482 op1, op2 = repo.dirstate.parents()
479 op1, op2 = repo.dirstate.parents()
483 if not repo.changelog.isancestor(node, op1):
480 if not repo.changelog.isancestor(node, op1):
484 raise util.Abort(_('cannot backout change that is not an ancestor'))
481 raise util.Abort(_('cannot backout change that is not an ancestor'))
485
482
486 p1, p2 = repo.changelog.parents(node)
483 p1, p2 = repo.changelog.parents(node)
487 if p1 == nullid:
484 if p1 == nullid:
488 raise util.Abort(_('cannot backout a change with no parents'))
485 raise util.Abort(_('cannot backout a change with no parents'))
489 if p2 != nullid:
486 if p2 != nullid:
490 if not opts.get('parent'):
487 if not opts.get('parent'):
491 raise util.Abort(_('cannot backout a merge changeset'))
488 raise util.Abort(_('cannot backout a merge changeset'))
492 p = repo.lookup(opts['parent'])
489 p = repo.lookup(opts['parent'])
493 if p not in (p1, p2):
490 if p not in (p1, p2):
494 raise util.Abort(_('%s is not a parent of %s') %
491 raise util.Abort(_('%s is not a parent of %s') %
495 (short(p), short(node)))
492 (short(p), short(node)))
496 parent = p
493 parent = p
497 else:
494 else:
498 if opts.get('parent'):
495 if opts.get('parent'):
499 raise util.Abort(_('cannot use --parent on non-merge changeset'))
496 raise util.Abort(_('cannot use --parent on non-merge changeset'))
500 parent = p1
497 parent = p1
501
498
502 # the backout should appear on the same branch
499 # the backout should appear on the same branch
503 wlock = repo.wlock()
500 wlock = repo.wlock()
504 try:
501 try:
505 branch = repo.dirstate.branch()
502 branch = repo.dirstate.branch()
506 bheads = repo.branchheads(branch)
503 bheads = repo.branchheads(branch)
507 rctx = scmutil.revsingle(repo, hex(parent))
504 rctx = scmutil.revsingle(repo, hex(parent))
508 if not opts.get('merge') and op1 != node:
505 if not opts.get('merge') and op1 != node:
509 try:
506 try:
510 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
507 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
511 'backout')
508 'backout')
512 repo.dirstate.beginparentchange()
509 repo.dirstate.beginparentchange()
513 stats = mergemod.update(repo, parent, True, True, False,
510 stats = mergemod.update(repo, parent, True, True, False,
514 node, False)
511 node, False)
515 repo.setparents(op1, op2)
512 repo.setparents(op1, op2)
516 repo.dirstate.endparentchange()
513 repo.dirstate.endparentchange()
517 hg._showstats(repo, stats)
514 hg._showstats(repo, stats)
518 if stats[3]:
515 if stats[3]:
519 repo.ui.status(_("use 'hg resolve' to retry unresolved "
516 repo.ui.status(_("use 'hg resolve' to retry unresolved "
520 "file merges\n"))
517 "file merges\n"))
521 else:
518 else:
522 msg = _("changeset %s backed out, "
519 msg = _("changeset %s backed out, "
523 "don't forget to commit.\n")
520 "don't forget to commit.\n")
524 ui.status(msg % short(node))
521 ui.status(msg % short(node))
525 return stats[3] > 0
522 return stats[3] > 0
526 finally:
523 finally:
527 ui.setconfig('ui', 'forcemerge', '', '')
524 ui.setconfig('ui', 'forcemerge', '', '')
528 else:
525 else:
529 hg.clean(repo, node, show_stats=False)
526 hg.clean(repo, node, show_stats=False)
530 repo.dirstate.setbranch(branch)
527 repo.dirstate.setbranch(branch)
531 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
528 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
532
529
533
530
534 def commitfunc(ui, repo, message, match, opts):
531 def commitfunc(ui, repo, message, match, opts):
535 editform = 'backout'
532 editform = 'backout'
536 e = cmdutil.getcommiteditor(editform=editform, **opts)
533 e = cmdutil.getcommiteditor(editform=editform, **opts)
537 if not message:
534 if not message:
538 # we don't translate commit messages
535 # we don't translate commit messages
539 message = "Backed out changeset %s" % short(node)
536 message = "Backed out changeset %s" % short(node)
540 e = cmdutil.getcommiteditor(edit=True, editform=editform)
537 e = cmdutil.getcommiteditor(edit=True, editform=editform)
541 return repo.commit(message, opts.get('user'), opts.get('date'),
538 return repo.commit(message, opts.get('user'), opts.get('date'),
542 match, editor=e)
539 match, editor=e)
543 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
540 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
544 if not newnode:
541 if not newnode:
545 ui.status(_("nothing changed\n"))
542 ui.status(_("nothing changed\n"))
546 return 1
543 return 1
547 cmdutil.commitstatus(repo, newnode, branch, bheads)
544 cmdutil.commitstatus(repo, newnode, branch, bheads)
548
545
549 def nice(node):
546 def nice(node):
550 return '%d:%s' % (repo.changelog.rev(node), short(node))
547 return '%d:%s' % (repo.changelog.rev(node), short(node))
551 ui.status(_('changeset %s backs out changeset %s\n') %
548 ui.status(_('changeset %s backs out changeset %s\n') %
552 (nice(repo.changelog.tip()), nice(node)))
549 (nice(repo.changelog.tip()), nice(node)))
553 if opts.get('merge') and op1 != node:
550 if opts.get('merge') and op1 != node:
554 hg.clean(repo, op1, show_stats=False)
551 hg.clean(repo, op1, show_stats=False)
555 ui.status(_('merging with changeset %s\n')
552 ui.status(_('merging with changeset %s\n')
556 % nice(repo.changelog.tip()))
553 % nice(repo.changelog.tip()))
557 try:
554 try:
558 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
555 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
559 'backout')
556 'backout')
560 return hg.merge(repo, hex(repo.changelog.tip()))
557 return hg.merge(repo, hex(repo.changelog.tip()))
561 finally:
558 finally:
562 ui.setconfig('ui', 'forcemerge', '', '')
559 ui.setconfig('ui', 'forcemerge', '', '')
563 finally:
560 finally:
564 wlock.release()
561 wlock.release()
565 return 0
562 return 0
566
563
567 @command('bisect',
564 @command('bisect',
568 [('r', 'reset', False, _('reset bisect state')),
565 [('r', 'reset', False, _('reset bisect state')),
569 ('g', 'good', False, _('mark changeset good')),
566 ('g', 'good', False, _('mark changeset good')),
570 ('b', 'bad', False, _('mark changeset bad')),
567 ('b', 'bad', False, _('mark changeset bad')),
571 ('s', 'skip', False, _('skip testing changeset')),
568 ('s', 'skip', False, _('skip testing changeset')),
572 ('e', 'extend', False, _('extend the bisect range')),
569 ('e', 'extend', False, _('extend the bisect range')),
573 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
570 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
574 ('U', 'noupdate', False, _('do not update to target'))],
571 ('U', 'noupdate', False, _('do not update to target'))],
575 _("[-gbsr] [-U] [-c CMD] [REV]"))
572 _("[-gbsr] [-U] [-c CMD] [REV]"))
576 def bisect(ui, repo, rev=None, extra=None, command=None,
573 def bisect(ui, repo, rev=None, extra=None, command=None,
577 reset=None, good=None, bad=None, skip=None, extend=None,
574 reset=None, good=None, bad=None, skip=None, extend=None,
578 noupdate=None):
575 noupdate=None):
579 """subdivision search of changesets
576 """subdivision search of changesets
580
577
581 This command helps to find changesets which introduce problems. To
578 This command helps to find changesets which introduce problems. To
582 use, mark the earliest changeset you know exhibits the problem as
579 use, mark the earliest changeset you know exhibits the problem as
583 bad, then mark the latest changeset which is free from the problem
580 bad, then mark the latest changeset which is free from the problem
584 as good. Bisect will update your working directory to a revision
581 as good. Bisect will update your working directory to a revision
585 for testing (unless the -U/--noupdate option is specified). Once
582 for testing (unless the -U/--noupdate option is specified). Once
586 you have performed tests, mark the working directory as good or
583 you have performed tests, mark the working directory as good or
587 bad, and bisect will either update to another candidate changeset
584 bad, and bisect will either update to another candidate changeset
588 or announce that it has found the bad revision.
585 or announce that it has found the bad revision.
589
586
590 As a shortcut, you can also use the revision argument to mark a
587 As a shortcut, you can also use the revision argument to mark a
591 revision as good or bad without checking it out first.
588 revision as good or bad without checking it out first.
592
589
593 If you supply a command, it will be used for automatic bisection.
590 If you supply a command, it will be used for automatic bisection.
594 The environment variable HG_NODE will contain the ID of the
591 The environment variable HG_NODE will contain the ID of the
595 changeset being tested. The exit status of the command will be
592 changeset being tested. The exit status of the command will be
596 used to mark revisions as good or bad: status 0 means good, 125
593 used to mark revisions as good or bad: status 0 means good, 125
597 means to skip the revision, 127 (command not found) will abort the
594 means to skip the revision, 127 (command not found) will abort the
598 bisection, and any other non-zero exit status means the revision
595 bisection, and any other non-zero exit status means the revision
599 is bad.
596 is bad.
600
597
601 .. container:: verbose
598 .. container:: verbose
602
599
603 Some examples:
600 Some examples:
604
601
605 - start a bisection with known bad revision 34, and good revision 12::
602 - start a bisection with known bad revision 34, and good revision 12::
606
603
607 hg bisect --bad 34
604 hg bisect --bad 34
608 hg bisect --good 12
605 hg bisect --good 12
609
606
610 - advance the current bisection by marking current revision as good or
607 - advance the current bisection by marking current revision as good or
611 bad::
608 bad::
612
609
613 hg bisect --good
610 hg bisect --good
614 hg bisect --bad
611 hg bisect --bad
615
612
616 - mark the current revision, or a known revision, to be skipped (e.g. if
613 - mark the current revision, or a known revision, to be skipped (e.g. if
617 that revision is not usable because of another issue)::
614 that revision is not usable because of another issue)::
618
615
619 hg bisect --skip
616 hg bisect --skip
620 hg bisect --skip 23
617 hg bisect --skip 23
621
618
622 - skip all revisions that do not touch directories ``foo`` or ``bar``::
619 - skip all revisions that do not touch directories ``foo`` or ``bar``::
623
620
624 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
621 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
625
622
626 - forget the current bisection::
623 - forget the current bisection::
627
624
628 hg bisect --reset
625 hg bisect --reset
629
626
630 - use 'make && make tests' to automatically find the first broken
627 - use 'make && make tests' to automatically find the first broken
631 revision::
628 revision::
632
629
633 hg bisect --reset
630 hg bisect --reset
634 hg bisect --bad 34
631 hg bisect --bad 34
635 hg bisect --good 12
632 hg bisect --good 12
636 hg bisect --command "make && make tests"
633 hg bisect --command "make && make tests"
637
634
638 - see all changesets whose states are already known in the current
635 - see all changesets whose states are already known in the current
639 bisection::
636 bisection::
640
637
641 hg log -r "bisect(pruned)"
638 hg log -r "bisect(pruned)"
642
639
643 - see the changeset currently being bisected (especially useful
640 - see the changeset currently being bisected (especially useful
644 if running with -U/--noupdate)::
641 if running with -U/--noupdate)::
645
642
646 hg log -r "bisect(current)"
643 hg log -r "bisect(current)"
647
644
648 - see all changesets that took part in the current bisection::
645 - see all changesets that took part in the current bisection::
649
646
650 hg log -r "bisect(range)"
647 hg log -r "bisect(range)"
651
648
652 - you can even get a nice graph::
649 - you can even get a nice graph::
653
650
654 hg log --graph -r "bisect(range)"
651 hg log --graph -r "bisect(range)"
655
652
656 See :hg:`help revsets` for more about the `bisect()` keyword.
653 See :hg:`help revsets` for more about the `bisect()` keyword.
657
654
658 Returns 0 on success.
655 Returns 0 on success.
659 """
656 """
660 def extendbisectrange(nodes, good):
657 def extendbisectrange(nodes, good):
661 # bisect is incomplete when it ends on a merge node and
658 # bisect is incomplete when it ends on a merge node and
662 # one of the parent was not checked.
659 # one of the parent was not checked.
663 parents = repo[nodes[0]].parents()
660 parents = repo[nodes[0]].parents()
664 if len(parents) > 1:
661 if len(parents) > 1:
665 side = good and state['bad'] or state['good']
662 side = good and state['bad'] or state['good']
666 num = len(set(i.node() for i in parents) & set(side))
663 num = len(set(i.node() for i in parents) & set(side))
667 if num == 1:
664 if num == 1:
668 return parents[0].ancestor(parents[1])
665 return parents[0].ancestor(parents[1])
669 return None
666 return None
670
667
671 def print_result(nodes, good):
668 def print_result(nodes, good):
672 displayer = cmdutil.show_changeset(ui, repo, {})
669 displayer = cmdutil.show_changeset(ui, repo, {})
673 if len(nodes) == 1:
670 if len(nodes) == 1:
674 # narrowed it down to a single revision
671 # narrowed it down to a single revision
675 if good:
672 if good:
676 ui.write(_("The first good revision is:\n"))
673 ui.write(_("The first good revision is:\n"))
677 else:
674 else:
678 ui.write(_("The first bad revision is:\n"))
675 ui.write(_("The first bad revision is:\n"))
679 displayer.show(repo[nodes[0]])
676 displayer.show(repo[nodes[0]])
680 extendnode = extendbisectrange(nodes, good)
677 extendnode = extendbisectrange(nodes, good)
681 if extendnode is not None:
678 if extendnode is not None:
682 ui.write(_('Not all ancestors of this changeset have been'
679 ui.write(_('Not all ancestors of this changeset have been'
683 ' checked.\nUse bisect --extend to continue the '
680 ' checked.\nUse bisect --extend to continue the '
684 'bisection from\nthe common ancestor, %s.\n')
681 'bisection from\nthe common ancestor, %s.\n')
685 % extendnode)
682 % extendnode)
686 else:
683 else:
687 # multiple possible revisions
684 # multiple possible revisions
688 if good:
685 if good:
689 ui.write(_("Due to skipped revisions, the first "
686 ui.write(_("Due to skipped revisions, the first "
690 "good revision could be any of:\n"))
687 "good revision could be any of:\n"))
691 else:
688 else:
692 ui.write(_("Due to skipped revisions, the first "
689 ui.write(_("Due to skipped revisions, the first "
693 "bad revision could be any of:\n"))
690 "bad revision could be any of:\n"))
694 for n in nodes:
691 for n in nodes:
695 displayer.show(repo[n])
692 displayer.show(repo[n])
696 displayer.close()
693 displayer.close()
697
694
698 def check_state(state, interactive=True):
695 def check_state(state, interactive=True):
699 if not state['good'] or not state['bad']:
696 if not state['good'] or not state['bad']:
700 if (good or bad or skip or reset) and interactive:
697 if (good or bad or skip or reset) and interactive:
701 return
698 return
702 if not state['good']:
699 if not state['good']:
703 raise util.Abort(_('cannot bisect (no known good revisions)'))
700 raise util.Abort(_('cannot bisect (no known good revisions)'))
704 else:
701 else:
705 raise util.Abort(_('cannot bisect (no known bad revisions)'))
702 raise util.Abort(_('cannot bisect (no known bad revisions)'))
706 return True
703 return True
707
704
708 # backward compatibility
705 # backward compatibility
709 if rev in "good bad reset init".split():
706 if rev in "good bad reset init".split():
710 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
707 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
711 cmd, rev, extra = rev, extra, None
708 cmd, rev, extra = rev, extra, None
712 if cmd == "good":
709 if cmd == "good":
713 good = True
710 good = True
714 elif cmd == "bad":
711 elif cmd == "bad":
715 bad = True
712 bad = True
716 else:
713 else:
717 reset = True
714 reset = True
718 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
715 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
719 raise util.Abort(_('incompatible arguments'))
716 raise util.Abort(_('incompatible arguments'))
720
717
721 cmdutil.checkunfinished(repo)
718 cmdutil.checkunfinished(repo)
722
719
723 if reset:
720 if reset:
724 p = repo.join("bisect.state")
721 p = repo.join("bisect.state")
725 if os.path.exists(p):
722 if os.path.exists(p):
726 os.unlink(p)
723 os.unlink(p)
727 return
724 return
728
725
729 state = hbisect.load_state(repo)
726 state = hbisect.load_state(repo)
730
727
731 if command:
728 if command:
732 changesets = 1
729 changesets = 1
733 if noupdate:
730 if noupdate:
734 try:
731 try:
735 node = state['current'][0]
732 node = state['current'][0]
736 except LookupError:
733 except LookupError:
737 raise util.Abort(_('current bisect revision is unknown - '
734 raise util.Abort(_('current bisect revision is unknown - '
738 'start a new bisect to fix'))
735 'start a new bisect to fix'))
739 else:
736 else:
740 node, p2 = repo.dirstate.parents()
737 node, p2 = repo.dirstate.parents()
741 if p2 != nullid:
738 if p2 != nullid:
742 raise util.Abort(_('current bisect revision is a merge'))
739 raise util.Abort(_('current bisect revision is a merge'))
743 try:
740 try:
744 while changesets:
741 while changesets:
745 # update state
742 # update state
746 state['current'] = [node]
743 state['current'] = [node]
747 hbisect.save_state(repo, state)
744 hbisect.save_state(repo, state)
748 status = util.system(command,
745 status = util.system(command,
749 environ={'HG_NODE': hex(node)},
746 environ={'HG_NODE': hex(node)},
750 out=ui.fout)
747 out=ui.fout)
751 if status == 125:
748 if status == 125:
752 transition = "skip"
749 transition = "skip"
753 elif status == 0:
750 elif status == 0:
754 transition = "good"
751 transition = "good"
755 # status < 0 means process was killed
752 # status < 0 means process was killed
756 elif status == 127:
753 elif status == 127:
757 raise util.Abort(_("failed to execute %s") % command)
754 raise util.Abort(_("failed to execute %s") % command)
758 elif status < 0:
755 elif status < 0:
759 raise util.Abort(_("%s killed") % command)
756 raise util.Abort(_("%s killed") % command)
760 else:
757 else:
761 transition = "bad"
758 transition = "bad"
762 ctx = scmutil.revsingle(repo, rev, node)
759 ctx = scmutil.revsingle(repo, rev, node)
763 rev = None # clear for future iterations
760 rev = None # clear for future iterations
764 state[transition].append(ctx.node())
761 state[transition].append(ctx.node())
765 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
762 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
766 check_state(state, interactive=False)
763 check_state(state, interactive=False)
767 # bisect
764 # bisect
768 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
765 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
769 # update to next check
766 # update to next check
770 node = nodes[0]
767 node = nodes[0]
771 if not noupdate:
768 if not noupdate:
772 cmdutil.bailifchanged(repo)
769 cmdutil.bailifchanged(repo)
773 hg.clean(repo, node, show_stats=False)
770 hg.clean(repo, node, show_stats=False)
774 finally:
771 finally:
775 state['current'] = [node]
772 state['current'] = [node]
776 hbisect.save_state(repo, state)
773 hbisect.save_state(repo, state)
777 print_result(nodes, bgood)
774 print_result(nodes, bgood)
778 return
775 return
779
776
780 # update state
777 # update state
781
778
782 if rev:
779 if rev:
783 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
780 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
784 else:
781 else:
785 nodes = [repo.lookup('.')]
782 nodes = [repo.lookup('.')]
786
783
787 if good or bad or skip:
784 if good or bad or skip:
788 if good:
785 if good:
789 state['good'] += nodes
786 state['good'] += nodes
790 elif bad:
787 elif bad:
791 state['bad'] += nodes
788 state['bad'] += nodes
792 elif skip:
789 elif skip:
793 state['skip'] += nodes
790 state['skip'] += nodes
794 hbisect.save_state(repo, state)
791 hbisect.save_state(repo, state)
795
792
796 if not check_state(state):
793 if not check_state(state):
797 return
794 return
798
795
799 # actually bisect
796 # actually bisect
800 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
797 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
801 if extend:
798 if extend:
802 if not changesets:
799 if not changesets:
803 extendnode = extendbisectrange(nodes, good)
800 extendnode = extendbisectrange(nodes, good)
804 if extendnode is not None:
801 if extendnode is not None:
805 ui.write(_("Extending search to changeset %d:%s\n")
802 ui.write(_("Extending search to changeset %d:%s\n")
806 % (extendnode.rev(), extendnode))
803 % (extendnode.rev(), extendnode))
807 state['current'] = [extendnode.node()]
804 state['current'] = [extendnode.node()]
808 hbisect.save_state(repo, state)
805 hbisect.save_state(repo, state)
809 if noupdate:
806 if noupdate:
810 return
807 return
811 cmdutil.bailifchanged(repo)
808 cmdutil.bailifchanged(repo)
812 return hg.clean(repo, extendnode.node())
809 return hg.clean(repo, extendnode.node())
813 raise util.Abort(_("nothing to extend"))
810 raise util.Abort(_("nothing to extend"))
814
811
815 if changesets == 0:
812 if changesets == 0:
816 print_result(nodes, good)
813 print_result(nodes, good)
817 else:
814 else:
818 assert len(nodes) == 1 # only a single node can be tested next
815 assert len(nodes) == 1 # only a single node can be tested next
819 node = nodes[0]
816 node = nodes[0]
820 # compute the approximate number of remaining tests
817 # compute the approximate number of remaining tests
821 tests, size = 0, 2
818 tests, size = 0, 2
822 while size <= changesets:
819 while size <= changesets:
823 tests, size = tests + 1, size * 2
820 tests, size = tests + 1, size * 2
824 rev = repo.changelog.rev(node)
821 rev = repo.changelog.rev(node)
825 ui.write(_("Testing changeset %d:%s "
822 ui.write(_("Testing changeset %d:%s "
826 "(%d changesets remaining, ~%d tests)\n")
823 "(%d changesets remaining, ~%d tests)\n")
827 % (rev, short(node), changesets, tests))
824 % (rev, short(node), changesets, tests))
828 state['current'] = [node]
825 state['current'] = [node]
829 hbisect.save_state(repo, state)
826 hbisect.save_state(repo, state)
830 if not noupdate:
827 if not noupdate:
831 cmdutil.bailifchanged(repo)
828 cmdutil.bailifchanged(repo)
832 return hg.clean(repo, node)
829 return hg.clean(repo, node)
833
830
834 @command('bookmarks|bookmark',
831 @command('bookmarks|bookmark',
835 [('f', 'force', False, _('force')),
832 [('f', 'force', False, _('force')),
836 ('r', 'rev', '', _('revision'), _('REV')),
833 ('r', 'rev', '', _('revision'), _('REV')),
837 ('d', 'delete', False, _('delete a given bookmark')),
834 ('d', 'delete', False, _('delete a given bookmark')),
838 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
835 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
839 ('i', 'inactive', False, _('mark a bookmark inactive'))],
836 ('i', 'inactive', False, _('mark a bookmark inactive'))],
840 _('hg bookmarks [OPTIONS]... [NAME]...'))
837 _('hg bookmarks [OPTIONS]... [NAME]...'))
841 def bookmark(ui, repo, *names, **opts):
838 def bookmark(ui, repo, *names, **opts):
842 '''create a new bookmark or list existing bookmarks
839 '''create a new bookmark or list existing bookmarks
843
840
844 Bookmarks are labels on changesets to help track lines of development.
841 Bookmarks are labels on changesets to help track lines of development.
845 Bookmarks are unversioned and can be moved, renamed and deleted.
842 Bookmarks are unversioned and can be moved, renamed and deleted.
846 Deleting or moving a bookmark has no effect on the associated changesets.
843 Deleting or moving a bookmark has no effect on the associated changesets.
847
844
848 Creating or updating to a bookmark causes it to be marked as 'active'.
845 Creating or updating to a bookmark causes it to be marked as 'active'.
849 The active bookmark is indicated with a '*'.
846 The active bookmark is indicated with a '*'.
850 When a commit is made, the active bookmark will advance to the new commit.
847 When a commit is made, the active bookmark will advance to the new commit.
851 A plain :hg:`update` will also advance an active bookmark, if possible.
848 A plain :hg:`update` will also advance an active bookmark, if possible.
852 Updating away from a bookmark will cause it to be deactivated.
849 Updating away from a bookmark will cause it to be deactivated.
853
850
854 Bookmarks can be pushed and pulled between repositories (see
851 Bookmarks can be pushed and pulled between repositories (see
855 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
852 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
856 diverged, a new 'divergent bookmark' of the form 'name@path' will
853 diverged, a new 'divergent bookmark' of the form 'name@path' will
857 be created. Using :hg:'merge' will resolve the divergence.
854 be created. Using :hg:'merge' will resolve the divergence.
858
855
859 A bookmark named '@' has the special property that :hg:`clone` will
856 A bookmark named '@' has the special property that :hg:`clone` will
860 check it out by default if it exists.
857 check it out by default if it exists.
861
858
862 .. container:: verbose
859 .. container:: verbose
863
860
864 Examples:
861 Examples:
865
862
866 - create an active bookmark for a new line of development::
863 - create an active bookmark for a new line of development::
867
864
868 hg book new-feature
865 hg book new-feature
869
866
870 - create an inactive bookmark as a place marker::
867 - create an inactive bookmark as a place marker::
871
868
872 hg book -i reviewed
869 hg book -i reviewed
873
870
874 - create an inactive bookmark on another changeset::
871 - create an inactive bookmark on another changeset::
875
872
876 hg book -r .^ tested
873 hg book -r .^ tested
877
874
878 - move the '@' bookmark from another branch::
875 - move the '@' bookmark from another branch::
879
876
880 hg book -f @
877 hg book -f @
881 '''
878 '''
882 force = opts.get('force')
879 force = opts.get('force')
883 rev = opts.get('rev')
880 rev = opts.get('rev')
884 delete = opts.get('delete')
881 delete = opts.get('delete')
885 rename = opts.get('rename')
882 rename = opts.get('rename')
886 inactive = opts.get('inactive')
883 inactive = opts.get('inactive')
887
884
888 def checkformat(mark):
885 def checkformat(mark):
889 mark = mark.strip()
886 mark = mark.strip()
890 if not mark:
887 if not mark:
891 raise util.Abort(_("bookmark names cannot consist entirely of "
888 raise util.Abort(_("bookmark names cannot consist entirely of "
892 "whitespace"))
889 "whitespace"))
893 scmutil.checknewlabel(repo, mark, 'bookmark')
890 scmutil.checknewlabel(repo, mark, 'bookmark')
894 return mark
891 return mark
895
892
896 def checkconflict(repo, mark, cur, force=False, target=None):
893 def checkconflict(repo, mark, cur, force=False, target=None):
897 if mark in marks and not force:
894 if mark in marks and not force:
898 if target:
895 if target:
899 if marks[mark] == target and target == cur:
896 if marks[mark] == target and target == cur:
900 # re-activating a bookmark
897 # re-activating a bookmark
901 return
898 return
902 anc = repo.changelog.ancestors([repo[target].rev()])
899 anc = repo.changelog.ancestors([repo[target].rev()])
903 bmctx = repo[marks[mark]]
900 bmctx = repo[marks[mark]]
904 divs = [repo[b].node() for b in marks
901 divs = [repo[b].node() for b in marks
905 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
902 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
906
903
907 # allow resolving a single divergent bookmark even if moving
904 # allow resolving a single divergent bookmark even if moving
908 # the bookmark across branches when a revision is specified
905 # the bookmark across branches when a revision is specified
909 # that contains a divergent bookmark
906 # that contains a divergent bookmark
910 if bmctx.rev() not in anc and target in divs:
907 if bmctx.rev() not in anc and target in divs:
911 bookmarks.deletedivergent(repo, [target], mark)
908 bookmarks.deletedivergent(repo, [target], mark)
912 return
909 return
913
910
914 deletefrom = [b for b in divs
911 deletefrom = [b for b in divs
915 if repo[b].rev() in anc or b == target]
912 if repo[b].rev() in anc or b == target]
916 bookmarks.deletedivergent(repo, deletefrom, mark)
913 bookmarks.deletedivergent(repo, deletefrom, mark)
917 if bookmarks.validdest(repo, bmctx, repo[target]):
914 if bookmarks.validdest(repo, bmctx, repo[target]):
918 ui.status(_("moving bookmark '%s' forward from %s\n") %
915 ui.status(_("moving bookmark '%s' forward from %s\n") %
919 (mark, short(bmctx.node())))
916 (mark, short(bmctx.node())))
920 return
917 return
921 raise util.Abort(_("bookmark '%s' already exists "
918 raise util.Abort(_("bookmark '%s' already exists "
922 "(use -f to force)") % mark)
919 "(use -f to force)") % mark)
923 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
920 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
924 and not force):
921 and not force):
925 raise util.Abort(
922 raise util.Abort(
926 _("a bookmark cannot have the name of an existing branch"))
923 _("a bookmark cannot have the name of an existing branch"))
927
924
928 if delete and rename:
925 if delete and rename:
929 raise util.Abort(_("--delete and --rename are incompatible"))
926 raise util.Abort(_("--delete and --rename are incompatible"))
930 if delete and rev:
927 if delete and rev:
931 raise util.Abort(_("--rev is incompatible with --delete"))
928 raise util.Abort(_("--rev is incompatible with --delete"))
932 if rename and rev:
929 if rename and rev:
933 raise util.Abort(_("--rev is incompatible with --rename"))
930 raise util.Abort(_("--rev is incompatible with --rename"))
934 if not names and (delete or rev):
931 if not names and (delete or rev):
935 raise util.Abort(_("bookmark name required"))
932 raise util.Abort(_("bookmark name required"))
936
933
937 if delete or rename or names or inactive:
934 if delete or rename or names or inactive:
938 wlock = repo.wlock()
935 wlock = repo.wlock()
939 try:
936 try:
940 cur = repo.changectx('.').node()
937 cur = repo.changectx('.').node()
941 marks = repo._bookmarks
938 marks = repo._bookmarks
942 if delete:
939 if delete:
943 for mark in names:
940 for mark in names:
944 if mark not in marks:
941 if mark not in marks:
945 raise util.Abort(_("bookmark '%s' does not exist") %
942 raise util.Abort(_("bookmark '%s' does not exist") %
946 mark)
943 mark)
947 if mark == repo._bookmarkcurrent:
944 if mark == repo._bookmarkcurrent:
948 bookmarks.unsetcurrent(repo)
945 bookmarks.unsetcurrent(repo)
949 del marks[mark]
946 del marks[mark]
950 marks.write()
947 marks.write()
951
948
952 elif rename:
949 elif rename:
953 if not names:
950 if not names:
954 raise util.Abort(_("new bookmark name required"))
951 raise util.Abort(_("new bookmark name required"))
955 elif len(names) > 1:
952 elif len(names) > 1:
956 raise util.Abort(_("only one new bookmark name allowed"))
953 raise util.Abort(_("only one new bookmark name allowed"))
957 mark = checkformat(names[0])
954 mark = checkformat(names[0])
958 if rename not in marks:
955 if rename not in marks:
959 raise util.Abort(_("bookmark '%s' does not exist") % rename)
956 raise util.Abort(_("bookmark '%s' does not exist") % rename)
960 checkconflict(repo, mark, cur, force)
957 checkconflict(repo, mark, cur, force)
961 marks[mark] = marks[rename]
958 marks[mark] = marks[rename]
962 if repo._bookmarkcurrent == rename and not inactive:
959 if repo._bookmarkcurrent == rename and not inactive:
963 bookmarks.setcurrent(repo, mark)
960 bookmarks.setcurrent(repo, mark)
964 del marks[rename]
961 del marks[rename]
965 marks.write()
962 marks.write()
966
963
967 elif names:
964 elif names:
968 newact = None
965 newact = None
969 for mark in names:
966 for mark in names:
970 mark = checkformat(mark)
967 mark = checkformat(mark)
971 if newact is None:
968 if newact is None:
972 newact = mark
969 newact = mark
973 if inactive and mark == repo._bookmarkcurrent:
970 if inactive and mark == repo._bookmarkcurrent:
974 bookmarks.unsetcurrent(repo)
971 bookmarks.unsetcurrent(repo)
975 return
972 return
976 tgt = cur
973 tgt = cur
977 if rev:
974 if rev:
978 tgt = scmutil.revsingle(repo, rev).node()
975 tgt = scmutil.revsingle(repo, rev).node()
979 checkconflict(repo, mark, cur, force, tgt)
976 checkconflict(repo, mark, cur, force, tgt)
980 marks[mark] = tgt
977 marks[mark] = tgt
981 if not inactive and cur == marks[newact] and not rev:
978 if not inactive and cur == marks[newact] and not rev:
982 bookmarks.setcurrent(repo, newact)
979 bookmarks.setcurrent(repo, newact)
983 elif cur != tgt and newact == repo._bookmarkcurrent:
980 elif cur != tgt and newact == repo._bookmarkcurrent:
984 bookmarks.unsetcurrent(repo)
981 bookmarks.unsetcurrent(repo)
985 marks.write()
982 marks.write()
986
983
987 elif inactive:
984 elif inactive:
988 if len(marks) == 0:
985 if len(marks) == 0:
989 ui.status(_("no bookmarks set\n"))
986 ui.status(_("no bookmarks set\n"))
990 elif not repo._bookmarkcurrent:
987 elif not repo._bookmarkcurrent:
991 ui.status(_("no active bookmark\n"))
988 ui.status(_("no active bookmark\n"))
992 else:
989 else:
993 bookmarks.unsetcurrent(repo)
990 bookmarks.unsetcurrent(repo)
994 finally:
991 finally:
995 wlock.release()
992 wlock.release()
996 else: # show bookmarks
993 else: # show bookmarks
997 hexfn = ui.debugflag and hex or short
994 hexfn = ui.debugflag and hex or short
998 marks = repo._bookmarks
995 marks = repo._bookmarks
999 if len(marks) == 0:
996 if len(marks) == 0:
1000 ui.status(_("no bookmarks set\n"))
997 ui.status(_("no bookmarks set\n"))
1001 else:
998 else:
1002 for bmark, n in sorted(marks.iteritems()):
999 for bmark, n in sorted(marks.iteritems()):
1003 current = repo._bookmarkcurrent
1000 current = repo._bookmarkcurrent
1004 if bmark == current:
1001 if bmark == current:
1005 prefix, label = '*', 'bookmarks.current'
1002 prefix, label = '*', 'bookmarks.current'
1006 else:
1003 else:
1007 prefix, label = ' ', ''
1004 prefix, label = ' ', ''
1008
1005
1009 if ui.quiet:
1006 if ui.quiet:
1010 ui.write("%s\n" % bmark, label=label)
1007 ui.write("%s\n" % bmark, label=label)
1011 else:
1008 else:
1012 pad = " " * (25 - encoding.colwidth(bmark))
1009 pad = " " * (25 - encoding.colwidth(bmark))
1013 ui.write(" %s %s%s %d:%s\n" % (
1010 ui.write(" %s %s%s %d:%s\n" % (
1014 prefix, bmark, pad, repo.changelog.rev(n), hexfn(n)),
1011 prefix, bmark, pad, repo.changelog.rev(n), hexfn(n)),
1015 label=label)
1012 label=label)
1016
1013
1017 @command('branch',
1014 @command('branch',
1018 [('f', 'force', None,
1015 [('f', 'force', None,
1019 _('set branch name even if it shadows an existing branch')),
1016 _('set branch name even if it shadows an existing branch')),
1020 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1017 ('C', 'clean', None, _('reset branch name to parent branch name'))],
1021 _('[-fC] [NAME]'))
1018 _('[-fC] [NAME]'))
1022 def branch(ui, repo, label=None, **opts):
1019 def branch(ui, repo, label=None, **opts):
1023 """set or show the current branch name
1020 """set or show the current branch name
1024
1021
1025 .. note::
1022 .. note::
1026
1023
1027 Branch names are permanent and global. Use :hg:`bookmark` to create a
1024 Branch names are permanent and global. Use :hg:`bookmark` to create a
1028 light-weight bookmark instead. See :hg:`help glossary` for more
1025 light-weight bookmark instead. See :hg:`help glossary` for more
1029 information about named branches and bookmarks.
1026 information about named branches and bookmarks.
1030
1027
1031 With no argument, show the current branch name. With one argument,
1028 With no argument, show the current branch name. With one argument,
1032 set the working directory branch name (the branch will not exist
1029 set the working directory branch name (the branch will not exist
1033 in the repository until the next commit). Standard practice
1030 in the repository until the next commit). Standard practice
1034 recommends that primary development take place on the 'default'
1031 recommends that primary development take place on the 'default'
1035 branch.
1032 branch.
1036
1033
1037 Unless -f/--force is specified, branch will not let you set a
1034 Unless -f/--force is specified, branch will not let you set a
1038 branch name that already exists, even if it's inactive.
1035 branch name that already exists, even if it's inactive.
1039
1036
1040 Use -C/--clean to reset the working directory branch to that of
1037 Use -C/--clean to reset the working directory branch to that of
1041 the parent of the working directory, negating a previous branch
1038 the parent of the working directory, negating a previous branch
1042 change.
1039 change.
1043
1040
1044 Use the command :hg:`update` to switch to an existing branch. Use
1041 Use the command :hg:`update` to switch to an existing branch. Use
1045 :hg:`commit --close-branch` to mark this branch as closed.
1042 :hg:`commit --close-branch` to mark this branch as closed.
1046
1043
1047 Returns 0 on success.
1044 Returns 0 on success.
1048 """
1045 """
1049 if label:
1046 if label:
1050 label = label.strip()
1047 label = label.strip()
1051
1048
1052 if not opts.get('clean') and not label:
1049 if not opts.get('clean') and not label:
1053 ui.write("%s\n" % repo.dirstate.branch())
1050 ui.write("%s\n" % repo.dirstate.branch())
1054 return
1051 return
1055
1052
1056 wlock = repo.wlock()
1053 wlock = repo.wlock()
1057 try:
1054 try:
1058 if opts.get('clean'):
1055 if opts.get('clean'):
1059 label = repo[None].p1().branch()
1056 label = repo[None].p1().branch()
1060 repo.dirstate.setbranch(label)
1057 repo.dirstate.setbranch(label)
1061 ui.status(_('reset working directory to branch %s\n') % label)
1058 ui.status(_('reset working directory to branch %s\n') % label)
1062 elif label:
1059 elif label:
1063 if not opts.get('force') and label in repo.branchmap():
1060 if not opts.get('force') and label in repo.branchmap():
1064 if label not in [p.branch() for p in repo.parents()]:
1061 if label not in [p.branch() for p in repo.parents()]:
1065 raise util.Abort(_('a branch of the same name already'
1062 raise util.Abort(_('a branch of the same name already'
1066 ' exists'),
1063 ' exists'),
1067 # i18n: "it" refers to an existing branch
1064 # i18n: "it" refers to an existing branch
1068 hint=_("use 'hg update' to switch to it"))
1065 hint=_("use 'hg update' to switch to it"))
1069 scmutil.checknewlabel(repo, label, 'branch')
1066 scmutil.checknewlabel(repo, label, 'branch')
1070 repo.dirstate.setbranch(label)
1067 repo.dirstate.setbranch(label)
1071 ui.status(_('marked working directory as branch %s\n') % label)
1068 ui.status(_('marked working directory as branch %s\n') % label)
1072 ui.status(_('(branches are permanent and global, '
1069 ui.status(_('(branches are permanent and global, '
1073 'did you want a bookmark?)\n'))
1070 'did you want a bookmark?)\n'))
1074 finally:
1071 finally:
1075 wlock.release()
1072 wlock.release()
1076
1073
1077 @command('branches',
1074 @command('branches',
1078 [('a', 'active', False, _('show only branches that have unmerged heads')),
1075 [('a', 'active', False, _('show only branches that have unmerged heads')),
1079 ('c', 'closed', False, _('show normal and closed branches'))],
1076 ('c', 'closed', False, _('show normal and closed branches'))],
1080 _('[-ac]'))
1077 _('[-ac]'))
1081 def branches(ui, repo, active=False, closed=False):
1078 def branches(ui, repo, active=False, closed=False):
1082 """list repository named branches
1079 """list repository named branches
1083
1080
1084 List the repository's named branches, indicating which ones are
1081 List the repository's named branches, indicating which ones are
1085 inactive. If -c/--closed is specified, also list branches which have
1082 inactive. If -c/--closed is specified, also list branches which have
1086 been marked closed (see :hg:`commit --close-branch`).
1083 been marked closed (see :hg:`commit --close-branch`).
1087
1084
1088 If -a/--active is specified, only show active branches. A branch
1085 If -a/--active is specified, only show active branches. A branch
1089 is considered active if it contains repository heads.
1086 is considered active if it contains repository heads.
1090
1087
1091 Use the command :hg:`update` to switch to an existing branch.
1088 Use the command :hg:`update` to switch to an existing branch.
1092
1089
1093 Returns 0.
1090 Returns 0.
1094 """
1091 """
1095
1092
1096 hexfunc = ui.debugflag and hex or short
1093 hexfunc = ui.debugflag and hex or short
1097
1094
1098 allheads = set(repo.heads())
1095 allheads = set(repo.heads())
1099 branches = []
1096 branches = []
1100 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1097 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1101 isactive = not isclosed and bool(set(heads) & allheads)
1098 isactive = not isclosed and bool(set(heads) & allheads)
1102 branches.append((tag, repo[tip], isactive, not isclosed))
1099 branches.append((tag, repo[tip], isactive, not isclosed))
1103 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1100 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1104 reverse=True)
1101 reverse=True)
1105
1102
1106 for tag, ctx, isactive, isopen in branches:
1103 for tag, ctx, isactive, isopen in branches:
1107 if active and not isactive:
1104 if active and not isactive:
1108 continue
1105 continue
1109 if isactive:
1106 if isactive:
1110 label = 'branches.active'
1107 label = 'branches.active'
1111 notice = ''
1108 notice = ''
1112 elif not isopen:
1109 elif not isopen:
1113 if not closed:
1110 if not closed:
1114 continue
1111 continue
1115 label = 'branches.closed'
1112 label = 'branches.closed'
1116 notice = _(' (closed)')
1113 notice = _(' (closed)')
1117 else:
1114 else:
1118 label = 'branches.inactive'
1115 label = 'branches.inactive'
1119 notice = _(' (inactive)')
1116 notice = _(' (inactive)')
1120 if tag == repo.dirstate.branch():
1117 if tag == repo.dirstate.branch():
1121 label = 'branches.current'
1118 label = 'branches.current'
1122 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1119 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1123 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1120 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1124 'log.changeset changeset.%s' % ctx.phasestr())
1121 'log.changeset changeset.%s' % ctx.phasestr())
1125 labeledtag = ui.label(tag, label)
1122 labeledtag = ui.label(tag, label)
1126 if ui.quiet:
1123 if ui.quiet:
1127 ui.write("%s\n" % labeledtag)
1124 ui.write("%s\n" % labeledtag)
1128 else:
1125 else:
1129 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1126 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1130
1127
1131 @command('bundle',
1128 @command('bundle',
1132 [('f', 'force', None, _('run even when the destination is unrelated')),
1129 [('f', 'force', None, _('run even when the destination is unrelated')),
1133 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1130 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1134 _('REV')),
1131 _('REV')),
1135 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1132 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1136 _('BRANCH')),
1133 _('BRANCH')),
1137 ('', 'base', [],
1134 ('', 'base', [],
1138 _('a base changeset assumed to be available at the destination'),
1135 _('a base changeset assumed to be available at the destination'),
1139 _('REV')),
1136 _('REV')),
1140 ('a', 'all', None, _('bundle all changesets in the repository')),
1137 ('a', 'all', None, _('bundle all changesets in the repository')),
1141 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1138 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1142 ] + remoteopts,
1139 ] + remoteopts,
1143 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1140 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1144 def bundle(ui, repo, fname, dest=None, **opts):
1141 def bundle(ui, repo, fname, dest=None, **opts):
1145 """create a changegroup file
1142 """create a changegroup file
1146
1143
1147 Generate a compressed changegroup file collecting changesets not
1144 Generate a compressed changegroup file collecting changesets not
1148 known to be in another repository.
1145 known to be in another repository.
1149
1146
1150 If you omit the destination repository, then hg assumes the
1147 If you omit the destination repository, then hg assumes the
1151 destination will have all the nodes you specify with --base
1148 destination will have all the nodes you specify with --base
1152 parameters. To create a bundle containing all changesets, use
1149 parameters. To create a bundle containing all changesets, use
1153 -a/--all (or --base null).
1150 -a/--all (or --base null).
1154
1151
1155 You can change compression method with the -t/--type option.
1152 You can change compression method with the -t/--type option.
1156 The available compression methods are: none, bzip2, and
1153 The available compression methods are: none, bzip2, and
1157 gzip (by default, bundles are compressed using bzip2).
1154 gzip (by default, bundles are compressed using bzip2).
1158
1155
1159 The bundle file can then be transferred using conventional means
1156 The bundle file can then be transferred using conventional means
1160 and applied to another repository with the unbundle or pull
1157 and applied to another repository with the unbundle or pull
1161 command. This is useful when direct push and pull are not
1158 command. This is useful when direct push and pull are not
1162 available or when exporting an entire repository is undesirable.
1159 available or when exporting an entire repository is undesirable.
1163
1160
1164 Applying bundles preserves all changeset contents including
1161 Applying bundles preserves all changeset contents including
1165 permissions, copy/rename information, and revision history.
1162 permissions, copy/rename information, and revision history.
1166
1163
1167 Returns 0 on success, 1 if no changes found.
1164 Returns 0 on success, 1 if no changes found.
1168 """
1165 """
1169 revs = None
1166 revs = None
1170 if 'rev' in opts:
1167 if 'rev' in opts:
1171 revs = scmutil.revrange(repo, opts['rev'])
1168 revs = scmutil.revrange(repo, opts['rev'])
1172
1169
1173 bundletype = opts.get('type', 'bzip2').lower()
1170 bundletype = opts.get('type', 'bzip2').lower()
1174 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1171 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1175 bundletype = btypes.get(bundletype)
1172 bundletype = btypes.get(bundletype)
1176 if bundletype not in changegroup.bundletypes:
1173 if bundletype not in changegroup.bundletypes:
1177 raise util.Abort(_('unknown bundle type specified with --type'))
1174 raise util.Abort(_('unknown bundle type specified with --type'))
1178
1175
1179 if opts.get('all'):
1176 if opts.get('all'):
1180 base = ['null']
1177 base = ['null']
1181 else:
1178 else:
1182 base = scmutil.revrange(repo, opts.get('base'))
1179 base = scmutil.revrange(repo, opts.get('base'))
1183 # TODO: get desired bundlecaps from command line.
1180 # TODO: get desired bundlecaps from command line.
1184 bundlecaps = None
1181 bundlecaps = None
1185 if base:
1182 if base:
1186 if dest:
1183 if dest:
1187 raise util.Abort(_("--base is incompatible with specifying "
1184 raise util.Abort(_("--base is incompatible with specifying "
1188 "a destination"))
1185 "a destination"))
1189 common = [repo.lookup(rev) for rev in base]
1186 common = [repo.lookup(rev) for rev in base]
1190 heads = revs and map(repo.lookup, revs) or revs
1187 heads = revs and map(repo.lookup, revs) or revs
1191 cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
1188 cg = changegroup.getchangegroup(repo, 'bundle', heads=heads,
1192 common=common, bundlecaps=bundlecaps)
1189 common=common, bundlecaps=bundlecaps)
1193 outgoing = None
1190 outgoing = None
1194 else:
1191 else:
1195 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1192 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1196 dest, branches = hg.parseurl(dest, opts.get('branch'))
1193 dest, branches = hg.parseurl(dest, opts.get('branch'))
1197 other = hg.peer(repo, opts, dest)
1194 other = hg.peer(repo, opts, dest)
1198 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1195 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1199 heads = revs and map(repo.lookup, revs) or revs
1196 heads = revs and map(repo.lookup, revs) or revs
1200 outgoing = discovery.findcommonoutgoing(repo, other,
1197 outgoing = discovery.findcommonoutgoing(repo, other,
1201 onlyheads=heads,
1198 onlyheads=heads,
1202 force=opts.get('force'),
1199 force=opts.get('force'),
1203 portable=True)
1200 portable=True)
1204 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1201 cg = changegroup.getlocalchangegroup(repo, 'bundle', outgoing,
1205 bundlecaps)
1202 bundlecaps)
1206 if not cg:
1203 if not cg:
1207 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1204 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1208 return 1
1205 return 1
1209
1206
1210 changegroup.writebundle(cg, fname, bundletype)
1207 changegroup.writebundle(cg, fname, bundletype)
1211
1208
1212 @command('cat',
1209 @command('cat',
1213 [('o', 'output', '',
1210 [('o', 'output', '',
1214 _('print output to file with formatted name'), _('FORMAT')),
1211 _('print output to file with formatted name'), _('FORMAT')),
1215 ('r', 'rev', '', _('print the given revision'), _('REV')),
1212 ('r', 'rev', '', _('print the given revision'), _('REV')),
1216 ('', 'decode', None, _('apply any matching decode filter')),
1213 ('', 'decode', None, _('apply any matching decode filter')),
1217 ] + walkopts,
1214 ] + walkopts,
1218 _('[OPTION]... FILE...'),
1215 _('[OPTION]... FILE...'),
1219 inferrepo=True)
1216 inferrepo=True)
1220 def cat(ui, repo, file1, *pats, **opts):
1217 def cat(ui, repo, file1, *pats, **opts):
1221 """output the current or given revision of files
1218 """output the current or given revision of files
1222
1219
1223 Print the specified files as they were at the given revision. If
1220 Print the specified files as they were at the given revision. If
1224 no revision is given, the parent of the working directory is used.
1221 no revision is given, the parent of the working directory is used.
1225
1222
1226 Output may be to a file, in which case the name of the file is
1223 Output may be to a file, in which case the name of the file is
1227 given using a format string. The formatting rules as follows:
1224 given using a format string. The formatting rules as follows:
1228
1225
1229 :``%%``: literal "%" character
1226 :``%%``: literal "%" character
1230 :``%s``: basename of file being printed
1227 :``%s``: basename of file being printed
1231 :``%d``: dirname of file being printed, or '.' if in repository root
1228 :``%d``: dirname of file being printed, or '.' if in repository root
1232 :``%p``: root-relative path name of file being printed
1229 :``%p``: root-relative path name of file being printed
1233 :``%H``: changeset hash (40 hexadecimal digits)
1230 :``%H``: changeset hash (40 hexadecimal digits)
1234 :``%R``: changeset revision number
1231 :``%R``: changeset revision number
1235 :``%h``: short-form changeset hash (12 hexadecimal digits)
1232 :``%h``: short-form changeset hash (12 hexadecimal digits)
1236 :``%r``: zero-padded changeset revision number
1233 :``%r``: zero-padded changeset revision number
1237 :``%b``: basename of the exporting repository
1234 :``%b``: basename of the exporting repository
1238
1235
1239 Returns 0 on success.
1236 Returns 0 on success.
1240 """
1237 """
1241 ctx = scmutil.revsingle(repo, opts.get('rev'))
1238 ctx = scmutil.revsingle(repo, opts.get('rev'))
1242 m = scmutil.match(ctx, (file1,) + pats, opts)
1239 m = scmutil.match(ctx, (file1,) + pats, opts)
1243
1240
1244 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1241 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1245
1242
1246 @command('^clone',
1243 @command('^clone',
1247 [('U', 'noupdate', None,
1244 [('U', 'noupdate', None,
1248 _('the clone will include an empty working copy (only a repository)')),
1245 _('the clone will include an empty working copy (only a repository)')),
1249 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1246 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1250 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1247 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1251 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1248 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1252 ('', 'pull', None, _('use pull protocol to copy metadata')),
1249 ('', 'pull', None, _('use pull protocol to copy metadata')),
1253 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1250 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1254 ] + remoteopts,
1251 ] + remoteopts,
1255 _('[OPTION]... SOURCE [DEST]'),
1252 _('[OPTION]... SOURCE [DEST]'),
1256 norepo=True)
1253 norepo=True)
1257 def clone(ui, source, dest=None, **opts):
1254 def clone(ui, source, dest=None, **opts):
1258 """make a copy of an existing repository
1255 """make a copy of an existing repository
1259
1256
1260 Create a copy of an existing repository in a new directory.
1257 Create a copy of an existing repository in a new directory.
1261
1258
1262 If no destination directory name is specified, it defaults to the
1259 If no destination directory name is specified, it defaults to the
1263 basename of the source.
1260 basename of the source.
1264
1261
1265 The location of the source is added to the new repository's
1262 The location of the source is added to the new repository's
1266 ``.hg/hgrc`` file, as the default to be used for future pulls.
1263 ``.hg/hgrc`` file, as the default to be used for future pulls.
1267
1264
1268 Only local paths and ``ssh://`` URLs are supported as
1265 Only local paths and ``ssh://`` URLs are supported as
1269 destinations. For ``ssh://`` destinations, no working directory or
1266 destinations. For ``ssh://`` destinations, no working directory or
1270 ``.hg/hgrc`` will be created on the remote side.
1267 ``.hg/hgrc`` will be created on the remote side.
1271
1268
1272 To pull only a subset of changesets, specify one or more revisions
1269 To pull only a subset of changesets, specify one or more revisions
1273 identifiers with -r/--rev or branches with -b/--branch. The
1270 identifiers with -r/--rev or branches with -b/--branch. The
1274 resulting clone will contain only the specified changesets and
1271 resulting clone will contain only the specified changesets and
1275 their ancestors. These options (or 'clone src#rev dest') imply
1272 their ancestors. These options (or 'clone src#rev dest') imply
1276 --pull, even for local source repositories. Note that specifying a
1273 --pull, even for local source repositories. Note that specifying a
1277 tag will include the tagged changeset but not the changeset
1274 tag will include the tagged changeset but not the changeset
1278 containing the tag.
1275 containing the tag.
1279
1276
1280 If the source repository has a bookmark called '@' set, that
1277 If the source repository has a bookmark called '@' set, that
1281 revision will be checked out in the new repository by default.
1278 revision will be checked out in the new repository by default.
1282
1279
1283 To check out a particular version, use -u/--update, or
1280 To check out a particular version, use -u/--update, or
1284 -U/--noupdate to create a clone with no working directory.
1281 -U/--noupdate to create a clone with no working directory.
1285
1282
1286 .. container:: verbose
1283 .. container:: verbose
1287
1284
1288 For efficiency, hardlinks are used for cloning whenever the
1285 For efficiency, hardlinks are used for cloning whenever the
1289 source and destination are on the same filesystem (note this
1286 source and destination are on the same filesystem (note this
1290 applies only to the repository data, not to the working
1287 applies only to the repository data, not to the working
1291 directory). Some filesystems, such as AFS, implement hardlinking
1288 directory). Some filesystems, such as AFS, implement hardlinking
1292 incorrectly, but do not report errors. In these cases, use the
1289 incorrectly, but do not report errors. In these cases, use the
1293 --pull option to avoid hardlinking.
1290 --pull option to avoid hardlinking.
1294
1291
1295 In some cases, you can clone repositories and the working
1292 In some cases, you can clone repositories and the working
1296 directory using full hardlinks with ::
1293 directory using full hardlinks with ::
1297
1294
1298 $ cp -al REPO REPOCLONE
1295 $ cp -al REPO REPOCLONE
1299
1296
1300 This is the fastest way to clone, but it is not always safe. The
1297 This is the fastest way to clone, but it is not always safe. The
1301 operation is not atomic (making sure REPO is not modified during
1298 operation is not atomic (making sure REPO is not modified during
1302 the operation is up to you) and you have to make sure your
1299 the operation is up to you) and you have to make sure your
1303 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1300 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1304 so). Also, this is not compatible with certain extensions that
1301 so). Also, this is not compatible with certain extensions that
1305 place their metadata under the .hg directory, such as mq.
1302 place their metadata under the .hg directory, such as mq.
1306
1303
1307 Mercurial will update the working directory to the first applicable
1304 Mercurial will update the working directory to the first applicable
1308 revision from this list:
1305 revision from this list:
1309
1306
1310 a) null if -U or the source repository has no changesets
1307 a) null if -U or the source repository has no changesets
1311 b) if -u . and the source repository is local, the first parent of
1308 b) if -u . and the source repository is local, the first parent of
1312 the source repository's working directory
1309 the source repository's working directory
1313 c) the changeset specified with -u (if a branch name, this means the
1310 c) the changeset specified with -u (if a branch name, this means the
1314 latest head of that branch)
1311 latest head of that branch)
1315 d) the changeset specified with -r
1312 d) the changeset specified with -r
1316 e) the tipmost head specified with -b
1313 e) the tipmost head specified with -b
1317 f) the tipmost head specified with the url#branch source syntax
1314 f) the tipmost head specified with the url#branch source syntax
1318 g) the revision marked with the '@' bookmark, if present
1315 g) the revision marked with the '@' bookmark, if present
1319 h) the tipmost head of the default branch
1316 h) the tipmost head of the default branch
1320 i) tip
1317 i) tip
1321
1318
1322 Examples:
1319 Examples:
1323
1320
1324 - clone a remote repository to a new directory named hg/::
1321 - clone a remote repository to a new directory named hg/::
1325
1322
1326 hg clone http://selenic.com/hg
1323 hg clone http://selenic.com/hg
1327
1324
1328 - create a lightweight local clone::
1325 - create a lightweight local clone::
1329
1326
1330 hg clone project/ project-feature/
1327 hg clone project/ project-feature/
1331
1328
1332 - clone from an absolute path on an ssh server (note double-slash)::
1329 - clone from an absolute path on an ssh server (note double-slash)::
1333
1330
1334 hg clone ssh://user@server//home/projects/alpha/
1331 hg clone ssh://user@server//home/projects/alpha/
1335
1332
1336 - do a high-speed clone over a LAN while checking out a
1333 - do a high-speed clone over a LAN while checking out a
1337 specified version::
1334 specified version::
1338
1335
1339 hg clone --uncompressed http://server/repo -u 1.5
1336 hg clone --uncompressed http://server/repo -u 1.5
1340
1337
1341 - create a repository without changesets after a particular revision::
1338 - create a repository without changesets after a particular revision::
1342
1339
1343 hg clone -r 04e544 experimental/ good/
1340 hg clone -r 04e544 experimental/ good/
1344
1341
1345 - clone (and track) a particular named branch::
1342 - clone (and track) a particular named branch::
1346
1343
1347 hg clone http://selenic.com/hg#stable
1344 hg clone http://selenic.com/hg#stable
1348
1345
1349 See :hg:`help urls` for details on specifying URLs.
1346 See :hg:`help urls` for details on specifying URLs.
1350
1347
1351 Returns 0 on success.
1348 Returns 0 on success.
1352 """
1349 """
1353 if opts.get('noupdate') and opts.get('updaterev'):
1350 if opts.get('noupdate') and opts.get('updaterev'):
1354 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1351 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1355
1352
1356 r = hg.clone(ui, opts, source, dest,
1353 r = hg.clone(ui, opts, source, dest,
1357 pull=opts.get('pull'),
1354 pull=opts.get('pull'),
1358 stream=opts.get('uncompressed'),
1355 stream=opts.get('uncompressed'),
1359 rev=opts.get('rev'),
1356 rev=opts.get('rev'),
1360 update=opts.get('updaterev') or not opts.get('noupdate'),
1357 update=opts.get('updaterev') or not opts.get('noupdate'),
1361 branch=opts.get('branch'))
1358 branch=opts.get('branch'))
1362
1359
1363 return r is None
1360 return r is None
1364
1361
1365 @command('^commit|ci',
1362 @command('^commit|ci',
1366 [('A', 'addremove', None,
1363 [('A', 'addremove', None,
1367 _('mark new/missing files as added/removed before committing')),
1364 _('mark new/missing files as added/removed before committing')),
1368 ('', 'close-branch', None,
1365 ('', 'close-branch', None,
1369 _('mark a branch as closed, hiding it from the branch list')),
1366 _('mark a branch as closed, hiding it from the branch list')),
1370 ('', 'amend', None, _('amend the parent of the working dir')),
1367 ('', 'amend', None, _('amend the parent of the working dir')),
1371 ('s', 'secret', None, _('use the secret phase for committing')),
1368 ('s', 'secret', None, _('use the secret phase for committing')),
1372 ('e', 'edit', None, _('invoke editor on commit messages')),
1369 ('e', 'edit', None, _('invoke editor on commit messages')),
1373 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1370 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1374 _('[OPTION]... [FILE]...'),
1371 _('[OPTION]... [FILE]...'),
1375 inferrepo=True)
1372 inferrepo=True)
1376 def commit(ui, repo, *pats, **opts):
1373 def commit(ui, repo, *pats, **opts):
1377 """commit the specified files or all outstanding changes
1374 """commit the specified files or all outstanding changes
1378
1375
1379 Commit changes to the given files into the repository. Unlike a
1376 Commit changes to the given files into the repository. Unlike a
1380 centralized SCM, this operation is a local operation. See
1377 centralized SCM, this operation is a local operation. See
1381 :hg:`push` for a way to actively distribute your changes.
1378 :hg:`push` for a way to actively distribute your changes.
1382
1379
1383 If a list of files is omitted, all changes reported by :hg:`status`
1380 If a list of files is omitted, all changes reported by :hg:`status`
1384 will be committed.
1381 will be committed.
1385
1382
1386 If you are committing the result of a merge, do not provide any
1383 If you are committing the result of a merge, do not provide any
1387 filenames or -I/-X filters.
1384 filenames or -I/-X filters.
1388
1385
1389 If no commit message is specified, Mercurial starts your
1386 If no commit message is specified, Mercurial starts your
1390 configured editor where you can enter a message. In case your
1387 configured editor where you can enter a message. In case your
1391 commit fails, you will find a backup of your message in
1388 commit fails, you will find a backup of your message in
1392 ``.hg/last-message.txt``.
1389 ``.hg/last-message.txt``.
1393
1390
1394 The --amend flag can be used to amend the parent of the
1391 The --amend flag can be used to amend the parent of the
1395 working directory with a new commit that contains the changes
1392 working directory with a new commit that contains the changes
1396 in the parent in addition to those currently reported by :hg:`status`,
1393 in the parent in addition to those currently reported by :hg:`status`,
1397 if there are any. The old commit is stored in a backup bundle in
1394 if there are any. The old commit is stored in a backup bundle in
1398 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1395 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1399 on how to restore it).
1396 on how to restore it).
1400
1397
1401 Message, user and date are taken from the amended commit unless
1398 Message, user and date are taken from the amended commit unless
1402 specified. When a message isn't specified on the command line,
1399 specified. When a message isn't specified on the command line,
1403 the editor will open with the message of the amended commit.
1400 the editor will open with the message of the amended commit.
1404
1401
1405 It is not possible to amend public changesets (see :hg:`help phases`)
1402 It is not possible to amend public changesets (see :hg:`help phases`)
1406 or changesets that have children.
1403 or changesets that have children.
1407
1404
1408 See :hg:`help dates` for a list of formats valid for -d/--date.
1405 See :hg:`help dates` for a list of formats valid for -d/--date.
1409
1406
1410 Returns 0 on success, 1 if nothing changed.
1407 Returns 0 on success, 1 if nothing changed.
1411 """
1408 """
1412 if opts.get('subrepos'):
1409 if opts.get('subrepos'):
1413 if opts.get('amend'):
1410 if opts.get('amend'):
1414 raise util.Abort(_('cannot amend with --subrepos'))
1411 raise util.Abort(_('cannot amend with --subrepos'))
1415 # Let --subrepos on the command line override config setting.
1412 # Let --subrepos on the command line override config setting.
1416 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1413 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1417
1414
1418 cmdutil.checkunfinished(repo, commit=True)
1415 cmdutil.checkunfinished(repo, commit=True)
1419
1416
1420 branch = repo[None].branch()
1417 branch = repo[None].branch()
1421 bheads = repo.branchheads(branch)
1418 bheads = repo.branchheads(branch)
1422
1419
1423 extra = {}
1420 extra = {}
1424 if opts.get('close_branch'):
1421 if opts.get('close_branch'):
1425 extra['close'] = 1
1422 extra['close'] = 1
1426
1423
1427 if not bheads:
1424 if not bheads:
1428 raise util.Abort(_('can only close branch heads'))
1425 raise util.Abort(_('can only close branch heads'))
1429 elif opts.get('amend'):
1426 elif opts.get('amend'):
1430 if repo.parents()[0].p1().branch() != branch and \
1427 if repo.parents()[0].p1().branch() != branch and \
1431 repo.parents()[0].p2().branch() != branch:
1428 repo.parents()[0].p2().branch() != branch:
1432 raise util.Abort(_('can only close branch heads'))
1429 raise util.Abort(_('can only close branch heads'))
1433
1430
1434 if opts.get('amend'):
1431 if opts.get('amend'):
1435 if ui.configbool('ui', 'commitsubrepos'):
1432 if ui.configbool('ui', 'commitsubrepos'):
1436 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1433 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1437
1434
1438 old = repo['.']
1435 old = repo['.']
1439 if not old.mutable():
1436 if not old.mutable():
1440 raise util.Abort(_('cannot amend public changesets'))
1437 raise util.Abort(_('cannot amend public changesets'))
1441 if len(repo[None].parents()) > 1:
1438 if len(repo[None].parents()) > 1:
1442 raise util.Abort(_('cannot amend while merging'))
1439 raise util.Abort(_('cannot amend while merging'))
1443 if (not obsolete._enabled) and old.children():
1440 if (not obsolete._enabled) and old.children():
1444 raise util.Abort(_('cannot amend changeset with children'))
1441 raise util.Abort(_('cannot amend changeset with children'))
1445
1442
1446 # commitfunc is used only for temporary amend commit by cmdutil.amend
1443 # commitfunc is used only for temporary amend commit by cmdutil.amend
1447 def commitfunc(ui, repo, message, match, opts):
1444 def commitfunc(ui, repo, message, match, opts):
1448 return repo.commit(message,
1445 return repo.commit(message,
1449 opts.get('user') or old.user(),
1446 opts.get('user') or old.user(),
1450 opts.get('date') or old.date(),
1447 opts.get('date') or old.date(),
1451 match,
1448 match,
1452 extra=extra)
1449 extra=extra)
1453
1450
1454 current = repo._bookmarkcurrent
1451 current = repo._bookmarkcurrent
1455 marks = old.bookmarks()
1452 marks = old.bookmarks()
1456 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1453 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1457 if node == old.node():
1454 if node == old.node():
1458 ui.status(_("nothing changed\n"))
1455 ui.status(_("nothing changed\n"))
1459 return 1
1456 return 1
1460 elif marks:
1457 elif marks:
1461 ui.debug('moving bookmarks %r from %s to %s\n' %
1458 ui.debug('moving bookmarks %r from %s to %s\n' %
1462 (marks, old.hex(), hex(node)))
1459 (marks, old.hex(), hex(node)))
1463 newmarks = repo._bookmarks
1460 newmarks = repo._bookmarks
1464 for bm in marks:
1461 for bm in marks:
1465 newmarks[bm] = node
1462 newmarks[bm] = node
1466 if bm == current:
1463 if bm == current:
1467 bookmarks.setcurrent(repo, bm)
1464 bookmarks.setcurrent(repo, bm)
1468 newmarks.write()
1465 newmarks.write()
1469 else:
1466 else:
1470 def commitfunc(ui, repo, message, match, opts):
1467 def commitfunc(ui, repo, message, match, opts):
1471 backup = ui.backupconfig('phases', 'new-commit')
1468 backup = ui.backupconfig('phases', 'new-commit')
1472 baseui = repo.baseui
1469 baseui = repo.baseui
1473 basebackup = baseui.backupconfig('phases', 'new-commit')
1470 basebackup = baseui.backupconfig('phases', 'new-commit')
1474 try:
1471 try:
1475 if opts.get('secret'):
1472 if opts.get('secret'):
1476 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1473 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1477 # Propagate to subrepos
1474 # Propagate to subrepos
1478 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1475 baseui.setconfig('phases', 'new-commit', 'secret', 'commit')
1479
1476
1480 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1477 editform = cmdutil.mergeeditform(repo[None], 'commit.normal')
1481 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1478 editor = cmdutil.getcommiteditor(editform=editform, **opts)
1482 return repo.commit(message, opts.get('user'), opts.get('date'),
1479 return repo.commit(message, opts.get('user'), opts.get('date'),
1483 match,
1480 match,
1484 editor=editor,
1481 editor=editor,
1485 extra=extra)
1482 extra=extra)
1486 finally:
1483 finally:
1487 ui.restoreconfig(backup)
1484 ui.restoreconfig(backup)
1488 repo.baseui.restoreconfig(basebackup)
1485 repo.baseui.restoreconfig(basebackup)
1489
1486
1490
1487
1491 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1488 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1492
1489
1493 if not node:
1490 if not node:
1494 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1491 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1495 if stat[3]:
1492 if stat[3]:
1496 ui.status(_("nothing changed (%d missing files, see "
1493 ui.status(_("nothing changed (%d missing files, see "
1497 "'hg status')\n") % len(stat[3]))
1494 "'hg status')\n") % len(stat[3]))
1498 else:
1495 else:
1499 ui.status(_("nothing changed\n"))
1496 ui.status(_("nothing changed\n"))
1500 return 1
1497 return 1
1501
1498
1502 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1499 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1503
1500
1504 @command('config|showconfig|debugconfig',
1501 @command('config|showconfig|debugconfig',
1505 [('u', 'untrusted', None, _('show untrusted configuration options')),
1502 [('u', 'untrusted', None, _('show untrusted configuration options')),
1506 ('e', 'edit', None, _('edit user config')),
1503 ('e', 'edit', None, _('edit user config')),
1507 ('l', 'local', None, _('edit repository config')),
1504 ('l', 'local', None, _('edit repository config')),
1508 ('g', 'global', None, _('edit global config'))],
1505 ('g', 'global', None, _('edit global config'))],
1509 _('[-u] [NAME]...'),
1506 _('[-u] [NAME]...'),
1510 optionalrepo=True)
1507 optionalrepo=True)
1511 def config(ui, repo, *values, **opts):
1508 def config(ui, repo, *values, **opts):
1512 """show combined config settings from all hgrc files
1509 """show combined config settings from all hgrc files
1513
1510
1514 With no arguments, print names and values of all config items.
1511 With no arguments, print names and values of all config items.
1515
1512
1516 With one argument of the form section.name, print just the value
1513 With one argument of the form section.name, print just the value
1517 of that config item.
1514 of that config item.
1518
1515
1519 With multiple arguments, print names and values of all config
1516 With multiple arguments, print names and values of all config
1520 items with matching section names.
1517 items with matching section names.
1521
1518
1522 With --edit, start an editor on the user-level config file. With
1519 With --edit, start an editor on the user-level config file. With
1523 --global, edit the system-wide config file. With --local, edit the
1520 --global, edit the system-wide config file. With --local, edit the
1524 repository-level config file.
1521 repository-level config file.
1525
1522
1526 With --debug, the source (filename and line number) is printed
1523 With --debug, the source (filename and line number) is printed
1527 for each config item.
1524 for each config item.
1528
1525
1529 See :hg:`help config` for more information about config files.
1526 See :hg:`help config` for more information about config files.
1530
1527
1531 Returns 0 on success, 1 if NAME does not exist.
1528 Returns 0 on success, 1 if NAME does not exist.
1532
1529
1533 """
1530 """
1534
1531
1535 if opts.get('edit') or opts.get('local') or opts.get('global'):
1532 if opts.get('edit') or opts.get('local') or opts.get('global'):
1536 if opts.get('local') and opts.get('global'):
1533 if opts.get('local') and opts.get('global'):
1537 raise util.Abort(_("can't use --local and --global together"))
1534 raise util.Abort(_("can't use --local and --global together"))
1538
1535
1539 if opts.get('local'):
1536 if opts.get('local'):
1540 if not repo:
1537 if not repo:
1541 raise util.Abort(_("can't use --local outside a repository"))
1538 raise util.Abort(_("can't use --local outside a repository"))
1542 paths = [repo.join('hgrc')]
1539 paths = [repo.join('hgrc')]
1543 elif opts.get('global'):
1540 elif opts.get('global'):
1544 paths = scmutil.systemrcpath()
1541 paths = scmutil.systemrcpath()
1545 else:
1542 else:
1546 paths = scmutil.userrcpath()
1543 paths = scmutil.userrcpath()
1547
1544
1548 for f in paths:
1545 for f in paths:
1549 if os.path.exists(f):
1546 if os.path.exists(f):
1550 break
1547 break
1551 else:
1548 else:
1552 from ui import samplehgrcs
1549 from ui import samplehgrcs
1553
1550
1554 if opts.get('global'):
1551 if opts.get('global'):
1555 samplehgrc = samplehgrcs['global']
1552 samplehgrc = samplehgrcs['global']
1556 elif opts.get('local'):
1553 elif opts.get('local'):
1557 samplehgrc = samplehgrcs['local']
1554 samplehgrc = samplehgrcs['local']
1558 else:
1555 else:
1559 samplehgrc = samplehgrcs['user']
1556 samplehgrc = samplehgrcs['user']
1560
1557
1561 f = paths[0]
1558 f = paths[0]
1562 fp = open(f, "w")
1559 fp = open(f, "w")
1563 fp.write(samplehgrc)
1560 fp.write(samplehgrc)
1564 fp.close()
1561 fp.close()
1565
1562
1566 editor = ui.geteditor()
1563 editor = ui.geteditor()
1567 util.system("%s \"%s\"" % (editor, f),
1564 util.system("%s \"%s\"" % (editor, f),
1568 onerr=util.Abort, errprefix=_("edit failed"),
1565 onerr=util.Abort, errprefix=_("edit failed"),
1569 out=ui.fout)
1566 out=ui.fout)
1570 return
1567 return
1571
1568
1572 for f in scmutil.rcpath():
1569 for f in scmutil.rcpath():
1573 ui.debug('read config from: %s\n' % f)
1570 ui.debug('read config from: %s\n' % f)
1574 untrusted = bool(opts.get('untrusted'))
1571 untrusted = bool(opts.get('untrusted'))
1575 if values:
1572 if values:
1576 sections = [v for v in values if '.' not in v]
1573 sections = [v for v in values if '.' not in v]
1577 items = [v for v in values if '.' in v]
1574 items = [v for v in values if '.' in v]
1578 if len(items) > 1 or items and sections:
1575 if len(items) > 1 or items and sections:
1579 raise util.Abort(_('only one config item permitted'))
1576 raise util.Abort(_('only one config item permitted'))
1580 matched = False
1577 matched = False
1581 for section, name, value in ui.walkconfig(untrusted=untrusted):
1578 for section, name, value in ui.walkconfig(untrusted=untrusted):
1582 value = str(value).replace('\n', '\\n')
1579 value = str(value).replace('\n', '\\n')
1583 sectname = section + '.' + name
1580 sectname = section + '.' + name
1584 if values:
1581 if values:
1585 for v in values:
1582 for v in values:
1586 if v == section:
1583 if v == section:
1587 ui.debug('%s: ' %
1584 ui.debug('%s: ' %
1588 ui.configsource(section, name, untrusted))
1585 ui.configsource(section, name, untrusted))
1589 ui.write('%s=%s\n' % (sectname, value))
1586 ui.write('%s=%s\n' % (sectname, value))
1590 matched = True
1587 matched = True
1591 elif v == sectname:
1588 elif v == sectname:
1592 ui.debug('%s: ' %
1589 ui.debug('%s: ' %
1593 ui.configsource(section, name, untrusted))
1590 ui.configsource(section, name, untrusted))
1594 ui.write(value, '\n')
1591 ui.write(value, '\n')
1595 matched = True
1592 matched = True
1596 else:
1593 else:
1597 ui.debug('%s: ' %
1594 ui.debug('%s: ' %
1598 ui.configsource(section, name, untrusted))
1595 ui.configsource(section, name, untrusted))
1599 ui.write('%s=%s\n' % (sectname, value))
1596 ui.write('%s=%s\n' % (sectname, value))
1600 matched = True
1597 matched = True
1601 if matched:
1598 if matched:
1602 return 0
1599 return 0
1603 return 1
1600 return 1
1604
1601
1605 @command('copy|cp',
1602 @command('copy|cp',
1606 [('A', 'after', None, _('record a copy that has already occurred')),
1603 [('A', 'after', None, _('record a copy that has already occurred')),
1607 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1604 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1608 ] + walkopts + dryrunopts,
1605 ] + walkopts + dryrunopts,
1609 _('[OPTION]... [SOURCE]... DEST'))
1606 _('[OPTION]... [SOURCE]... DEST'))
1610 def copy(ui, repo, *pats, **opts):
1607 def copy(ui, repo, *pats, **opts):
1611 """mark files as copied for the next commit
1608 """mark files as copied for the next commit
1612
1609
1613 Mark dest as having copies of source files. If dest is a
1610 Mark dest as having copies of source files. If dest is a
1614 directory, copies are put in that directory. If dest is a file,
1611 directory, copies are put in that directory. If dest is a file,
1615 the source must be a single file.
1612 the source must be a single file.
1616
1613
1617 By default, this command copies the contents of files as they
1614 By default, this command copies the contents of files as they
1618 exist in the working directory. If invoked with -A/--after, the
1615 exist in the working directory. If invoked with -A/--after, the
1619 operation is recorded, but no copying is performed.
1616 operation is recorded, but no copying is performed.
1620
1617
1621 This command takes effect with the next commit. To undo a copy
1618 This command takes effect with the next commit. To undo a copy
1622 before that, see :hg:`revert`.
1619 before that, see :hg:`revert`.
1623
1620
1624 Returns 0 on success, 1 if errors are encountered.
1621 Returns 0 on success, 1 if errors are encountered.
1625 """
1622 """
1626 wlock = repo.wlock(False)
1623 wlock = repo.wlock(False)
1627 try:
1624 try:
1628 return cmdutil.copy(ui, repo, pats, opts)
1625 return cmdutil.copy(ui, repo, pats, opts)
1629 finally:
1626 finally:
1630 wlock.release()
1627 wlock.release()
1631
1628
1632 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1629 @command('debugancestor', [], _('[INDEX] REV1 REV2'), optionalrepo=True)
1633 def debugancestor(ui, repo, *args):
1630 def debugancestor(ui, repo, *args):
1634 """find the ancestor revision of two revisions in a given index"""
1631 """find the ancestor revision of two revisions in a given index"""
1635 if len(args) == 3:
1632 if len(args) == 3:
1636 index, rev1, rev2 = args
1633 index, rev1, rev2 = args
1637 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1634 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1638 lookup = r.lookup
1635 lookup = r.lookup
1639 elif len(args) == 2:
1636 elif len(args) == 2:
1640 if not repo:
1637 if not repo:
1641 raise util.Abort(_("there is no Mercurial repository here "
1638 raise util.Abort(_("there is no Mercurial repository here "
1642 "(.hg not found)"))
1639 "(.hg not found)"))
1643 rev1, rev2 = args
1640 rev1, rev2 = args
1644 r = repo.changelog
1641 r = repo.changelog
1645 lookup = repo.lookup
1642 lookup = repo.lookup
1646 else:
1643 else:
1647 raise util.Abort(_('either two or three arguments required'))
1644 raise util.Abort(_('either two or three arguments required'))
1648 a = r.ancestor(lookup(rev1), lookup(rev2))
1645 a = r.ancestor(lookup(rev1), lookup(rev2))
1649 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1646 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1650
1647
1651 @command('debugbuilddag',
1648 @command('debugbuilddag',
1652 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1649 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1653 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1650 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1654 ('n', 'new-file', None, _('add new file at each rev'))],
1651 ('n', 'new-file', None, _('add new file at each rev'))],
1655 _('[OPTION]... [TEXT]'))
1652 _('[OPTION]... [TEXT]'))
1656 def debugbuilddag(ui, repo, text=None,
1653 def debugbuilddag(ui, repo, text=None,
1657 mergeable_file=False,
1654 mergeable_file=False,
1658 overwritten_file=False,
1655 overwritten_file=False,
1659 new_file=False):
1656 new_file=False):
1660 """builds a repo with a given DAG from scratch in the current empty repo
1657 """builds a repo with a given DAG from scratch in the current empty repo
1661
1658
1662 The description of the DAG is read from stdin if not given on the
1659 The description of the DAG is read from stdin if not given on the
1663 command line.
1660 command line.
1664
1661
1665 Elements:
1662 Elements:
1666
1663
1667 - "+n" is a linear run of n nodes based on the current default parent
1664 - "+n" is a linear run of n nodes based on the current default parent
1668 - "." is a single node based on the current default parent
1665 - "." is a single node based on the current default parent
1669 - "$" resets the default parent to null (implied at the start);
1666 - "$" resets the default parent to null (implied at the start);
1670 otherwise the default parent is always the last node created
1667 otherwise the default parent is always the last node created
1671 - "<p" sets the default parent to the backref p
1668 - "<p" sets the default parent to the backref p
1672 - "*p" is a fork at parent p, which is a backref
1669 - "*p" is a fork at parent p, which is a backref
1673 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1670 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1674 - "/p2" is a merge of the preceding node and p2
1671 - "/p2" is a merge of the preceding node and p2
1675 - ":tag" defines a local tag for the preceding node
1672 - ":tag" defines a local tag for the preceding node
1676 - "@branch" sets the named branch for subsequent nodes
1673 - "@branch" sets the named branch for subsequent nodes
1677 - "#...\\n" is a comment up to the end of the line
1674 - "#...\\n" is a comment up to the end of the line
1678
1675
1679 Whitespace between the above elements is ignored.
1676 Whitespace between the above elements is ignored.
1680
1677
1681 A backref is either
1678 A backref is either
1682
1679
1683 - a number n, which references the node curr-n, where curr is the current
1680 - a number n, which references the node curr-n, where curr is the current
1684 node, or
1681 node, or
1685 - the name of a local tag you placed earlier using ":tag", or
1682 - the name of a local tag you placed earlier using ":tag", or
1686 - empty to denote the default parent.
1683 - empty to denote the default parent.
1687
1684
1688 All string valued-elements are either strictly alphanumeric, or must
1685 All string valued-elements are either strictly alphanumeric, or must
1689 be enclosed in double quotes ("..."), with "\\" as escape character.
1686 be enclosed in double quotes ("..."), with "\\" as escape character.
1690 """
1687 """
1691
1688
1692 if text is None:
1689 if text is None:
1693 ui.status(_("reading DAG from stdin\n"))
1690 ui.status(_("reading DAG from stdin\n"))
1694 text = ui.fin.read()
1691 text = ui.fin.read()
1695
1692
1696 cl = repo.changelog
1693 cl = repo.changelog
1697 if len(cl) > 0:
1694 if len(cl) > 0:
1698 raise util.Abort(_('repository is not empty'))
1695 raise util.Abort(_('repository is not empty'))
1699
1696
1700 # determine number of revs in DAG
1697 # determine number of revs in DAG
1701 total = 0
1698 total = 0
1702 for type, data in dagparser.parsedag(text):
1699 for type, data in dagparser.parsedag(text):
1703 if type == 'n':
1700 if type == 'n':
1704 total += 1
1701 total += 1
1705
1702
1706 if mergeable_file:
1703 if mergeable_file:
1707 linesperrev = 2
1704 linesperrev = 2
1708 # make a file with k lines per rev
1705 # make a file with k lines per rev
1709 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1706 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1710 initialmergedlines.append("")
1707 initialmergedlines.append("")
1711
1708
1712 tags = []
1709 tags = []
1713
1710
1714 lock = tr = None
1711 lock = tr = None
1715 try:
1712 try:
1716 lock = repo.lock()
1713 lock = repo.lock()
1717 tr = repo.transaction("builddag")
1714 tr = repo.transaction("builddag")
1718
1715
1719 at = -1
1716 at = -1
1720 atbranch = 'default'
1717 atbranch = 'default'
1721 nodeids = []
1718 nodeids = []
1722 id = 0
1719 id = 0
1723 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1720 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1724 for type, data in dagparser.parsedag(text):
1721 for type, data in dagparser.parsedag(text):
1725 if type == 'n':
1722 if type == 'n':
1726 ui.note(('node %s\n' % str(data)))
1723 ui.note(('node %s\n' % str(data)))
1727 id, ps = data
1724 id, ps = data
1728
1725
1729 files = []
1726 files = []
1730 fctxs = {}
1727 fctxs = {}
1731
1728
1732 p2 = None
1729 p2 = None
1733 if mergeable_file:
1730 if mergeable_file:
1734 fn = "mf"
1731 fn = "mf"
1735 p1 = repo[ps[0]]
1732 p1 = repo[ps[0]]
1736 if len(ps) > 1:
1733 if len(ps) > 1:
1737 p2 = repo[ps[1]]
1734 p2 = repo[ps[1]]
1738 pa = p1.ancestor(p2)
1735 pa = p1.ancestor(p2)
1739 base, local, other = [x[fn].data() for x in (pa, p1,
1736 base, local, other = [x[fn].data() for x in (pa, p1,
1740 p2)]
1737 p2)]
1741 m3 = simplemerge.Merge3Text(base, local, other)
1738 m3 = simplemerge.Merge3Text(base, local, other)
1742 ml = [l.strip() for l in m3.merge_lines()]
1739 ml = [l.strip() for l in m3.merge_lines()]
1743 ml.append("")
1740 ml.append("")
1744 elif at > 0:
1741 elif at > 0:
1745 ml = p1[fn].data().split("\n")
1742 ml = p1[fn].data().split("\n")
1746 else:
1743 else:
1747 ml = initialmergedlines
1744 ml = initialmergedlines
1748 ml[id * linesperrev] += " r%i" % id
1745 ml[id * linesperrev] += " r%i" % id
1749 mergedtext = "\n".join(ml)
1746 mergedtext = "\n".join(ml)
1750 files.append(fn)
1747 files.append(fn)
1751 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1748 fctxs[fn] = context.memfilectx(repo, fn, mergedtext)
1752
1749
1753 if overwritten_file:
1750 if overwritten_file:
1754 fn = "of"
1751 fn = "of"
1755 files.append(fn)
1752 files.append(fn)
1756 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1753 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1757
1754
1758 if new_file:
1755 if new_file:
1759 fn = "nf%i" % id
1756 fn = "nf%i" % id
1760 files.append(fn)
1757 files.append(fn)
1761 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1758 fctxs[fn] = context.memfilectx(repo, fn, "r%i\n" % id)
1762 if len(ps) > 1:
1759 if len(ps) > 1:
1763 if not p2:
1760 if not p2:
1764 p2 = repo[ps[1]]
1761 p2 = repo[ps[1]]
1765 for fn in p2:
1762 for fn in p2:
1766 if fn.startswith("nf"):
1763 if fn.startswith("nf"):
1767 files.append(fn)
1764 files.append(fn)
1768 fctxs[fn] = p2[fn]
1765 fctxs[fn] = p2[fn]
1769
1766
1770 def fctxfn(repo, cx, path):
1767 def fctxfn(repo, cx, path):
1771 return fctxs.get(path)
1768 return fctxs.get(path)
1772
1769
1773 if len(ps) == 0 or ps[0] < 0:
1770 if len(ps) == 0 or ps[0] < 0:
1774 pars = [None, None]
1771 pars = [None, None]
1775 elif len(ps) == 1:
1772 elif len(ps) == 1:
1776 pars = [nodeids[ps[0]], None]
1773 pars = [nodeids[ps[0]], None]
1777 else:
1774 else:
1778 pars = [nodeids[p] for p in ps]
1775 pars = [nodeids[p] for p in ps]
1779 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1776 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1780 date=(id, 0),
1777 date=(id, 0),
1781 user="debugbuilddag",
1778 user="debugbuilddag",
1782 extra={'branch': atbranch})
1779 extra={'branch': atbranch})
1783 nodeid = repo.commitctx(cx)
1780 nodeid = repo.commitctx(cx)
1784 nodeids.append(nodeid)
1781 nodeids.append(nodeid)
1785 at = id
1782 at = id
1786 elif type == 'l':
1783 elif type == 'l':
1787 id, name = data
1784 id, name = data
1788 ui.note(('tag %s\n' % name))
1785 ui.note(('tag %s\n' % name))
1789 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1786 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1790 elif type == 'a':
1787 elif type == 'a':
1791 ui.note(('branch %s\n' % data))
1788 ui.note(('branch %s\n' % data))
1792 atbranch = data
1789 atbranch = data
1793 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1790 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1794 tr.close()
1791 tr.close()
1795
1792
1796 if tags:
1793 if tags:
1797 repo.opener.write("localtags", "".join(tags))
1794 repo.opener.write("localtags", "".join(tags))
1798 finally:
1795 finally:
1799 ui.progress(_('building'), None)
1796 ui.progress(_('building'), None)
1800 release(tr, lock)
1797 release(tr, lock)
1801
1798
1802 @command('debugbundle',
1799 @command('debugbundle',
1803 [('a', 'all', None, _('show all details'))],
1800 [('a', 'all', None, _('show all details'))],
1804 _('FILE'),
1801 _('FILE'),
1805 norepo=True)
1802 norepo=True)
1806 def debugbundle(ui, bundlepath, all=None, **opts):
1803 def debugbundle(ui, bundlepath, all=None, **opts):
1807 """lists the contents of a bundle"""
1804 """lists the contents of a bundle"""
1808 f = hg.openpath(ui, bundlepath)
1805 f = hg.openpath(ui, bundlepath)
1809 try:
1806 try:
1810 gen = exchange.readbundle(ui, f, bundlepath)
1807 gen = exchange.readbundle(ui, f, bundlepath)
1811 if all:
1808 if all:
1812 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1809 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1813
1810
1814 def showchunks(named):
1811 def showchunks(named):
1815 ui.write("\n%s\n" % named)
1812 ui.write("\n%s\n" % named)
1816 chain = None
1813 chain = None
1817 while True:
1814 while True:
1818 chunkdata = gen.deltachunk(chain)
1815 chunkdata = gen.deltachunk(chain)
1819 if not chunkdata:
1816 if not chunkdata:
1820 break
1817 break
1821 node = chunkdata['node']
1818 node = chunkdata['node']
1822 p1 = chunkdata['p1']
1819 p1 = chunkdata['p1']
1823 p2 = chunkdata['p2']
1820 p2 = chunkdata['p2']
1824 cs = chunkdata['cs']
1821 cs = chunkdata['cs']
1825 deltabase = chunkdata['deltabase']
1822 deltabase = chunkdata['deltabase']
1826 delta = chunkdata['delta']
1823 delta = chunkdata['delta']
1827 ui.write("%s %s %s %s %s %s\n" %
1824 ui.write("%s %s %s %s %s %s\n" %
1828 (hex(node), hex(p1), hex(p2),
1825 (hex(node), hex(p1), hex(p2),
1829 hex(cs), hex(deltabase), len(delta)))
1826 hex(cs), hex(deltabase), len(delta)))
1830 chain = node
1827 chain = node
1831
1828
1832 chunkdata = gen.changelogheader()
1829 chunkdata = gen.changelogheader()
1833 showchunks("changelog")
1830 showchunks("changelog")
1834 chunkdata = gen.manifestheader()
1831 chunkdata = gen.manifestheader()
1835 showchunks("manifest")
1832 showchunks("manifest")
1836 while True:
1833 while True:
1837 chunkdata = gen.filelogheader()
1834 chunkdata = gen.filelogheader()
1838 if not chunkdata:
1835 if not chunkdata:
1839 break
1836 break
1840 fname = chunkdata['filename']
1837 fname = chunkdata['filename']
1841 showchunks(fname)
1838 showchunks(fname)
1842 else:
1839 else:
1843 chunkdata = gen.changelogheader()
1840 chunkdata = gen.changelogheader()
1844 chain = None
1841 chain = None
1845 while True:
1842 while True:
1846 chunkdata = gen.deltachunk(chain)
1843 chunkdata = gen.deltachunk(chain)
1847 if not chunkdata:
1844 if not chunkdata:
1848 break
1845 break
1849 node = chunkdata['node']
1846 node = chunkdata['node']
1850 ui.write("%s\n" % hex(node))
1847 ui.write("%s\n" % hex(node))
1851 chain = node
1848 chain = node
1852 finally:
1849 finally:
1853 f.close()
1850 f.close()
1854
1851
1855 @command('debugcheckstate', [], '')
1852 @command('debugcheckstate', [], '')
1856 def debugcheckstate(ui, repo):
1853 def debugcheckstate(ui, repo):
1857 """validate the correctness of the current dirstate"""
1854 """validate the correctness of the current dirstate"""
1858 parent1, parent2 = repo.dirstate.parents()
1855 parent1, parent2 = repo.dirstate.parents()
1859 m1 = repo[parent1].manifest()
1856 m1 = repo[parent1].manifest()
1860 m2 = repo[parent2].manifest()
1857 m2 = repo[parent2].manifest()
1861 errors = 0
1858 errors = 0
1862 for f in repo.dirstate:
1859 for f in repo.dirstate:
1863 state = repo.dirstate[f]
1860 state = repo.dirstate[f]
1864 if state in "nr" and f not in m1:
1861 if state in "nr" and f not in m1:
1865 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1862 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1866 errors += 1
1863 errors += 1
1867 if state in "a" and f in m1:
1864 if state in "a" and f in m1:
1868 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1865 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1869 errors += 1
1866 errors += 1
1870 if state in "m" and f not in m1 and f not in m2:
1867 if state in "m" and f not in m1 and f not in m2:
1871 ui.warn(_("%s in state %s, but not in either manifest\n") %
1868 ui.warn(_("%s in state %s, but not in either manifest\n") %
1872 (f, state))
1869 (f, state))
1873 errors += 1
1870 errors += 1
1874 for f in m1:
1871 for f in m1:
1875 state = repo.dirstate[f]
1872 state = repo.dirstate[f]
1876 if state not in "nrm":
1873 if state not in "nrm":
1877 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1874 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1878 errors += 1
1875 errors += 1
1879 if errors:
1876 if errors:
1880 error = _(".hg/dirstate inconsistent with current parent's manifest")
1877 error = _(".hg/dirstate inconsistent with current parent's manifest")
1881 raise util.Abort(error)
1878 raise util.Abort(error)
1882
1879
1883 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1880 @command('debugcommands', [], _('[COMMAND]'), norepo=True)
1884 def debugcommands(ui, cmd='', *args):
1881 def debugcommands(ui, cmd='', *args):
1885 """list all available commands and options"""
1882 """list all available commands and options"""
1886 for cmd, vals in sorted(table.iteritems()):
1883 for cmd, vals in sorted(table.iteritems()):
1887 cmd = cmd.split('|')[0].strip('^')
1884 cmd = cmd.split('|')[0].strip('^')
1888 opts = ', '.join([i[1] for i in vals[1]])
1885 opts = ', '.join([i[1] for i in vals[1]])
1889 ui.write('%s: %s\n' % (cmd, opts))
1886 ui.write('%s: %s\n' % (cmd, opts))
1890
1887
1891 @command('debugcomplete',
1888 @command('debugcomplete',
1892 [('o', 'options', None, _('show the command options'))],
1889 [('o', 'options', None, _('show the command options'))],
1893 _('[-o] CMD'),
1890 _('[-o] CMD'),
1894 norepo=True)
1891 norepo=True)
1895 def debugcomplete(ui, cmd='', **opts):
1892 def debugcomplete(ui, cmd='', **opts):
1896 """returns the completion list associated with the given command"""
1893 """returns the completion list associated with the given command"""
1897
1894
1898 if opts.get('options'):
1895 if opts.get('options'):
1899 options = []
1896 options = []
1900 otables = [globalopts]
1897 otables = [globalopts]
1901 if cmd:
1898 if cmd:
1902 aliases, entry = cmdutil.findcmd(cmd, table, False)
1899 aliases, entry = cmdutil.findcmd(cmd, table, False)
1903 otables.append(entry[1])
1900 otables.append(entry[1])
1904 for t in otables:
1901 for t in otables:
1905 for o in t:
1902 for o in t:
1906 if "(DEPRECATED)" in o[3]:
1903 if "(DEPRECATED)" in o[3]:
1907 continue
1904 continue
1908 if o[0]:
1905 if o[0]:
1909 options.append('-%s' % o[0])
1906 options.append('-%s' % o[0])
1910 options.append('--%s' % o[1])
1907 options.append('--%s' % o[1])
1911 ui.write("%s\n" % "\n".join(options))
1908 ui.write("%s\n" % "\n".join(options))
1912 return
1909 return
1913
1910
1914 cmdlist = cmdutil.findpossible(cmd, table)
1911 cmdlist = cmdutil.findpossible(cmd, table)
1915 if ui.verbose:
1912 if ui.verbose:
1916 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1913 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1917 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1914 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1918
1915
1919 @command('debugdag',
1916 @command('debugdag',
1920 [('t', 'tags', None, _('use tags as labels')),
1917 [('t', 'tags', None, _('use tags as labels')),
1921 ('b', 'branches', None, _('annotate with branch names')),
1918 ('b', 'branches', None, _('annotate with branch names')),
1922 ('', 'dots', None, _('use dots for runs')),
1919 ('', 'dots', None, _('use dots for runs')),
1923 ('s', 'spaces', None, _('separate elements by spaces'))],
1920 ('s', 'spaces', None, _('separate elements by spaces'))],
1924 _('[OPTION]... [FILE [REV]...]'),
1921 _('[OPTION]... [FILE [REV]...]'),
1925 optionalrepo=True)
1922 optionalrepo=True)
1926 def debugdag(ui, repo, file_=None, *revs, **opts):
1923 def debugdag(ui, repo, file_=None, *revs, **opts):
1927 """format the changelog or an index DAG as a concise textual description
1924 """format the changelog or an index DAG as a concise textual description
1928
1925
1929 If you pass a revlog index, the revlog's DAG is emitted. If you list
1926 If you pass a revlog index, the revlog's DAG is emitted. If you list
1930 revision numbers, they get labeled in the output as rN.
1927 revision numbers, they get labeled in the output as rN.
1931
1928
1932 Otherwise, the changelog DAG of the current repo is emitted.
1929 Otherwise, the changelog DAG of the current repo is emitted.
1933 """
1930 """
1934 spaces = opts.get('spaces')
1931 spaces = opts.get('spaces')
1935 dots = opts.get('dots')
1932 dots = opts.get('dots')
1936 if file_:
1933 if file_:
1937 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1934 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1938 revs = set((int(r) for r in revs))
1935 revs = set((int(r) for r in revs))
1939 def events():
1936 def events():
1940 for r in rlog:
1937 for r in rlog:
1941 yield 'n', (r, list(p for p in rlog.parentrevs(r)
1938 yield 'n', (r, list(p for p in rlog.parentrevs(r)
1942 if p != -1))
1939 if p != -1))
1943 if r in revs:
1940 if r in revs:
1944 yield 'l', (r, "r%i" % r)
1941 yield 'l', (r, "r%i" % r)
1945 elif repo:
1942 elif repo:
1946 cl = repo.changelog
1943 cl = repo.changelog
1947 tags = opts.get('tags')
1944 tags = opts.get('tags')
1948 branches = opts.get('branches')
1945 branches = opts.get('branches')
1949 if tags:
1946 if tags:
1950 labels = {}
1947 labels = {}
1951 for l, n in repo.tags().items():
1948 for l, n in repo.tags().items():
1952 labels.setdefault(cl.rev(n), []).append(l)
1949 labels.setdefault(cl.rev(n), []).append(l)
1953 def events():
1950 def events():
1954 b = "default"
1951 b = "default"
1955 for r in cl:
1952 for r in cl:
1956 if branches:
1953 if branches:
1957 newb = cl.read(cl.node(r))[5]['branch']
1954 newb = cl.read(cl.node(r))[5]['branch']
1958 if newb != b:
1955 if newb != b:
1959 yield 'a', newb
1956 yield 'a', newb
1960 b = newb
1957 b = newb
1961 yield 'n', (r, list(p for p in cl.parentrevs(r)
1958 yield 'n', (r, list(p for p in cl.parentrevs(r)
1962 if p != -1))
1959 if p != -1))
1963 if tags:
1960 if tags:
1964 ls = labels.get(r)
1961 ls = labels.get(r)
1965 if ls:
1962 if ls:
1966 for l in ls:
1963 for l in ls:
1967 yield 'l', (r, l)
1964 yield 'l', (r, l)
1968 else:
1965 else:
1969 raise util.Abort(_('need repo for changelog dag'))
1966 raise util.Abort(_('need repo for changelog dag'))
1970
1967
1971 for line in dagparser.dagtextlines(events(),
1968 for line in dagparser.dagtextlines(events(),
1972 addspaces=spaces,
1969 addspaces=spaces,
1973 wraplabels=True,
1970 wraplabels=True,
1974 wrapannotations=True,
1971 wrapannotations=True,
1975 wrapnonlinear=dots,
1972 wrapnonlinear=dots,
1976 usedots=dots,
1973 usedots=dots,
1977 maxlinewidth=70):
1974 maxlinewidth=70):
1978 ui.write(line)
1975 ui.write(line)
1979 ui.write("\n")
1976 ui.write("\n")
1980
1977
1981 @command('debugdata',
1978 @command('debugdata',
1982 [('c', 'changelog', False, _('open changelog')),
1979 [('c', 'changelog', False, _('open changelog')),
1983 ('m', 'manifest', False, _('open manifest'))],
1980 ('m', 'manifest', False, _('open manifest'))],
1984 _('-c|-m|FILE REV'))
1981 _('-c|-m|FILE REV'))
1985 def debugdata(ui, repo, file_, rev=None, **opts):
1982 def debugdata(ui, repo, file_, rev=None, **opts):
1986 """dump the contents of a data file revision"""
1983 """dump the contents of a data file revision"""
1987 if opts.get('changelog') or opts.get('manifest'):
1984 if opts.get('changelog') or opts.get('manifest'):
1988 file_, rev = None, file_
1985 file_, rev = None, file_
1989 elif rev is None:
1986 elif rev is None:
1990 raise error.CommandError('debugdata', _('invalid arguments'))
1987 raise error.CommandError('debugdata', _('invalid arguments'))
1991 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1988 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1992 try:
1989 try:
1993 ui.write(r.revision(r.lookup(rev)))
1990 ui.write(r.revision(r.lookup(rev)))
1994 except KeyError:
1991 except KeyError:
1995 raise util.Abort(_('invalid revision identifier %s') % rev)
1992 raise util.Abort(_('invalid revision identifier %s') % rev)
1996
1993
1997 @command('debugdate',
1994 @command('debugdate',
1998 [('e', 'extended', None, _('try extended date formats'))],
1995 [('e', 'extended', None, _('try extended date formats'))],
1999 _('[-e] DATE [RANGE]'),
1996 _('[-e] DATE [RANGE]'),
2000 norepo=True, optionalrepo=True)
1997 norepo=True, optionalrepo=True)
2001 def debugdate(ui, date, range=None, **opts):
1998 def debugdate(ui, date, range=None, **opts):
2002 """parse and display a date"""
1999 """parse and display a date"""
2003 if opts["extended"]:
2000 if opts["extended"]:
2004 d = util.parsedate(date, util.extendeddateformats)
2001 d = util.parsedate(date, util.extendeddateformats)
2005 else:
2002 else:
2006 d = util.parsedate(date)
2003 d = util.parsedate(date)
2007 ui.write(("internal: %s %s\n") % d)
2004 ui.write(("internal: %s %s\n") % d)
2008 ui.write(("standard: %s\n") % util.datestr(d))
2005 ui.write(("standard: %s\n") % util.datestr(d))
2009 if range:
2006 if range:
2010 m = util.matchdate(range)
2007 m = util.matchdate(range)
2011 ui.write(("match: %s\n") % m(d[0]))
2008 ui.write(("match: %s\n") % m(d[0]))
2012
2009
2013 @command('debugdiscovery',
2010 @command('debugdiscovery',
2014 [('', 'old', None, _('use old-style discovery')),
2011 [('', 'old', None, _('use old-style discovery')),
2015 ('', 'nonheads', None,
2012 ('', 'nonheads', None,
2016 _('use old-style discovery with non-heads included')),
2013 _('use old-style discovery with non-heads included')),
2017 ] + remoteopts,
2014 ] + remoteopts,
2018 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
2015 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
2019 def debugdiscovery(ui, repo, remoteurl="default", **opts):
2016 def debugdiscovery(ui, repo, remoteurl="default", **opts):
2020 """runs the changeset discovery protocol in isolation"""
2017 """runs the changeset discovery protocol in isolation"""
2021 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
2018 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
2022 opts.get('branch'))
2019 opts.get('branch'))
2023 remote = hg.peer(repo, opts, remoteurl)
2020 remote = hg.peer(repo, opts, remoteurl)
2024 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
2021 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
2025
2022
2026 # make sure tests are repeatable
2023 # make sure tests are repeatable
2027 random.seed(12323)
2024 random.seed(12323)
2028
2025
2029 def doit(localheads, remoteheads, remote=remote):
2026 def doit(localheads, remoteheads, remote=remote):
2030 if opts.get('old'):
2027 if opts.get('old'):
2031 if localheads:
2028 if localheads:
2032 raise util.Abort('cannot use localheads with old style '
2029 raise util.Abort('cannot use localheads with old style '
2033 'discovery')
2030 'discovery')
2034 if not util.safehasattr(remote, 'branches'):
2031 if not util.safehasattr(remote, 'branches'):
2035 # enable in-client legacy support
2032 # enable in-client legacy support
2036 remote = localrepo.locallegacypeer(remote.local())
2033 remote = localrepo.locallegacypeer(remote.local())
2037 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2034 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
2038 force=True)
2035 force=True)
2039 common = set(common)
2036 common = set(common)
2040 if not opts.get('nonheads'):
2037 if not opts.get('nonheads'):
2041 ui.write(("unpruned common: %s\n") %
2038 ui.write(("unpruned common: %s\n") %
2042 " ".join(sorted(short(n) for n in common)))
2039 " ".join(sorted(short(n) for n in common)))
2043 dag = dagutil.revlogdag(repo.changelog)
2040 dag = dagutil.revlogdag(repo.changelog)
2044 all = dag.ancestorset(dag.internalizeall(common))
2041 all = dag.ancestorset(dag.internalizeall(common))
2045 common = dag.externalizeall(dag.headsetofconnecteds(all))
2042 common = dag.externalizeall(dag.headsetofconnecteds(all))
2046 else:
2043 else:
2047 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2044 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2048 common = set(common)
2045 common = set(common)
2049 rheads = set(hds)
2046 rheads = set(hds)
2050 lheads = set(repo.heads())
2047 lheads = set(repo.heads())
2051 ui.write(("common heads: %s\n") %
2048 ui.write(("common heads: %s\n") %
2052 " ".join(sorted(short(n) for n in common)))
2049 " ".join(sorted(short(n) for n in common)))
2053 if lheads <= common:
2050 if lheads <= common:
2054 ui.write(("local is subset\n"))
2051 ui.write(("local is subset\n"))
2055 elif rheads <= common:
2052 elif rheads <= common:
2056 ui.write(("remote is subset\n"))
2053 ui.write(("remote is subset\n"))
2057
2054
2058 serverlogs = opts.get('serverlog')
2055 serverlogs = opts.get('serverlog')
2059 if serverlogs:
2056 if serverlogs:
2060 for filename in serverlogs:
2057 for filename in serverlogs:
2061 logfile = open(filename, 'r')
2058 logfile = open(filename, 'r')
2062 try:
2059 try:
2063 line = logfile.readline()
2060 line = logfile.readline()
2064 while line:
2061 while line:
2065 parts = line.strip().split(';')
2062 parts = line.strip().split(';')
2066 op = parts[1]
2063 op = parts[1]
2067 if op == 'cg':
2064 if op == 'cg':
2068 pass
2065 pass
2069 elif op == 'cgss':
2066 elif op == 'cgss':
2070 doit(parts[2].split(' '), parts[3].split(' '))
2067 doit(parts[2].split(' '), parts[3].split(' '))
2071 elif op == 'unb':
2068 elif op == 'unb':
2072 doit(parts[3].split(' '), parts[2].split(' '))
2069 doit(parts[3].split(' '), parts[2].split(' '))
2073 line = logfile.readline()
2070 line = logfile.readline()
2074 finally:
2071 finally:
2075 logfile.close()
2072 logfile.close()
2076
2073
2077 else:
2074 else:
2078 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2075 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2079 opts.get('remote_head'))
2076 opts.get('remote_head'))
2080 localrevs = opts.get('local_head')
2077 localrevs = opts.get('local_head')
2081 doit(localrevs, remoterevs)
2078 doit(localrevs, remoterevs)
2082
2079
2083 @command('debugfileset',
2080 @command('debugfileset',
2084 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2081 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2085 _('[-r REV] FILESPEC'))
2082 _('[-r REV] FILESPEC'))
2086 def debugfileset(ui, repo, expr, **opts):
2083 def debugfileset(ui, repo, expr, **opts):
2087 '''parse and apply a fileset specification'''
2084 '''parse and apply a fileset specification'''
2088 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2085 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2089 if ui.verbose:
2086 if ui.verbose:
2090 tree = fileset.parse(expr)[0]
2087 tree = fileset.parse(expr)[0]
2091 ui.note(tree, "\n")
2088 ui.note(tree, "\n")
2092
2089
2093 for f in ctx.getfileset(expr):
2090 for f in ctx.getfileset(expr):
2094 ui.write("%s\n" % f)
2091 ui.write("%s\n" % f)
2095
2092
2096 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2093 @command('debugfsinfo', [], _('[PATH]'), norepo=True)
2097 def debugfsinfo(ui, path="."):
2094 def debugfsinfo(ui, path="."):
2098 """show information detected about current filesystem"""
2095 """show information detected about current filesystem"""
2099 util.writefile('.debugfsinfo', '')
2096 util.writefile('.debugfsinfo', '')
2100 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2097 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2101 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2098 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2102 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2099 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2103 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2100 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2104 and 'yes' or 'no'))
2101 and 'yes' or 'no'))
2105 os.unlink('.debugfsinfo')
2102 os.unlink('.debugfsinfo')
2106
2103
2107 @command('debuggetbundle',
2104 @command('debuggetbundle',
2108 [('H', 'head', [], _('id of head node'), _('ID')),
2105 [('H', 'head', [], _('id of head node'), _('ID')),
2109 ('C', 'common', [], _('id of common node'), _('ID')),
2106 ('C', 'common', [], _('id of common node'), _('ID')),
2110 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2107 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2111 _('REPO FILE [-H|-C ID]...'),
2108 _('REPO FILE [-H|-C ID]...'),
2112 norepo=True)
2109 norepo=True)
2113 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2110 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2114 """retrieves a bundle from a repo
2111 """retrieves a bundle from a repo
2115
2112
2116 Every ID must be a full-length hex node id string. Saves the bundle to the
2113 Every ID must be a full-length hex node id string. Saves the bundle to the
2117 given file.
2114 given file.
2118 """
2115 """
2119 repo = hg.peer(ui, opts, repopath)
2116 repo = hg.peer(ui, opts, repopath)
2120 if not repo.capable('getbundle'):
2117 if not repo.capable('getbundle'):
2121 raise util.Abort("getbundle() not supported by target repository")
2118 raise util.Abort("getbundle() not supported by target repository")
2122 args = {}
2119 args = {}
2123 if common:
2120 if common:
2124 args['common'] = [bin(s) for s in common]
2121 args['common'] = [bin(s) for s in common]
2125 if head:
2122 if head:
2126 args['heads'] = [bin(s) for s in head]
2123 args['heads'] = [bin(s) for s in head]
2127 # TODO: get desired bundlecaps from command line.
2124 # TODO: get desired bundlecaps from command line.
2128 args['bundlecaps'] = None
2125 args['bundlecaps'] = None
2129 bundle = repo.getbundle('debug', **args)
2126 bundle = repo.getbundle('debug', **args)
2130
2127
2131 bundletype = opts.get('type', 'bzip2').lower()
2128 bundletype = opts.get('type', 'bzip2').lower()
2132 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2129 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2133 bundletype = btypes.get(bundletype)
2130 bundletype = btypes.get(bundletype)
2134 if bundletype not in changegroup.bundletypes:
2131 if bundletype not in changegroup.bundletypes:
2135 raise util.Abort(_('unknown bundle type specified with --type'))
2132 raise util.Abort(_('unknown bundle type specified with --type'))
2136 changegroup.writebundle(bundle, bundlepath, bundletype)
2133 changegroup.writebundle(bundle, bundlepath, bundletype)
2137
2134
2138 @command('debugignore', [], '')
2135 @command('debugignore', [], '')
2139 def debugignore(ui, repo, *values, **opts):
2136 def debugignore(ui, repo, *values, **opts):
2140 """display the combined ignore pattern"""
2137 """display the combined ignore pattern"""
2141 ignore = repo.dirstate._ignore
2138 ignore = repo.dirstate._ignore
2142 includepat = getattr(ignore, 'includepat', None)
2139 includepat = getattr(ignore, 'includepat', None)
2143 if includepat is not None:
2140 if includepat is not None:
2144 ui.write("%s\n" % includepat)
2141 ui.write("%s\n" % includepat)
2145 else:
2142 else:
2146 raise util.Abort(_("no ignore patterns found"))
2143 raise util.Abort(_("no ignore patterns found"))
2147
2144
2148 @command('debugindex',
2145 @command('debugindex',
2149 [('c', 'changelog', False, _('open changelog')),
2146 [('c', 'changelog', False, _('open changelog')),
2150 ('m', 'manifest', False, _('open manifest')),
2147 ('m', 'manifest', False, _('open manifest')),
2151 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2148 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2152 _('[-f FORMAT] -c|-m|FILE'),
2149 _('[-f FORMAT] -c|-m|FILE'),
2153 optionalrepo=True)
2150 optionalrepo=True)
2154 def debugindex(ui, repo, file_=None, **opts):
2151 def debugindex(ui, repo, file_=None, **opts):
2155 """dump the contents of an index file"""
2152 """dump the contents of an index file"""
2156 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2153 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2157 format = opts.get('format', 0)
2154 format = opts.get('format', 0)
2158 if format not in (0, 1):
2155 if format not in (0, 1):
2159 raise util.Abort(_("unknown format %d") % format)
2156 raise util.Abort(_("unknown format %d") % format)
2160
2157
2161 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2158 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2162 if generaldelta:
2159 if generaldelta:
2163 basehdr = ' delta'
2160 basehdr = ' delta'
2164 else:
2161 else:
2165 basehdr = ' base'
2162 basehdr = ' base'
2166
2163
2167 if format == 0:
2164 if format == 0:
2168 ui.write(" rev offset length " + basehdr + " linkrev"
2165 ui.write(" rev offset length " + basehdr + " linkrev"
2169 " nodeid p1 p2\n")
2166 " nodeid p1 p2\n")
2170 elif format == 1:
2167 elif format == 1:
2171 ui.write(" rev flag offset length"
2168 ui.write(" rev flag offset length"
2172 " size " + basehdr + " link p1 p2"
2169 " size " + basehdr + " link p1 p2"
2173 " nodeid\n")
2170 " nodeid\n")
2174
2171
2175 for i in r:
2172 for i in r:
2176 node = r.node(i)
2173 node = r.node(i)
2177 if generaldelta:
2174 if generaldelta:
2178 base = r.deltaparent(i)
2175 base = r.deltaparent(i)
2179 else:
2176 else:
2180 base = r.chainbase(i)
2177 base = r.chainbase(i)
2181 if format == 0:
2178 if format == 0:
2182 try:
2179 try:
2183 pp = r.parents(node)
2180 pp = r.parents(node)
2184 except Exception:
2181 except Exception:
2185 pp = [nullid, nullid]
2182 pp = [nullid, nullid]
2186 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2183 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2187 i, r.start(i), r.length(i), base, r.linkrev(i),
2184 i, r.start(i), r.length(i), base, r.linkrev(i),
2188 short(node), short(pp[0]), short(pp[1])))
2185 short(node), short(pp[0]), short(pp[1])))
2189 elif format == 1:
2186 elif format == 1:
2190 pr = r.parentrevs(i)
2187 pr = r.parentrevs(i)
2191 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2188 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2192 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2189 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2193 base, r.linkrev(i), pr[0], pr[1], short(node)))
2190 base, r.linkrev(i), pr[0], pr[1], short(node)))
2194
2191
2195 @command('debugindexdot', [], _('FILE'), optionalrepo=True)
2192 @command('debugindexdot', [], _('FILE'), optionalrepo=True)
2196 def debugindexdot(ui, repo, file_):
2193 def debugindexdot(ui, repo, file_):
2197 """dump an index DAG as a graphviz dot file"""
2194 """dump an index DAG as a graphviz dot file"""
2198 r = None
2195 r = None
2199 if repo:
2196 if repo:
2200 filelog = repo.file(file_)
2197 filelog = repo.file(file_)
2201 if len(filelog):
2198 if len(filelog):
2202 r = filelog
2199 r = filelog
2203 if not r:
2200 if not r:
2204 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2201 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2205 ui.write(("digraph G {\n"))
2202 ui.write(("digraph G {\n"))
2206 for i in r:
2203 for i in r:
2207 node = r.node(i)
2204 node = r.node(i)
2208 pp = r.parents(node)
2205 pp = r.parents(node)
2209 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2206 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2210 if pp[1] != nullid:
2207 if pp[1] != nullid:
2211 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2208 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2212 ui.write("}\n")
2209 ui.write("}\n")
2213
2210
2214 @command('debuginstall', [], '', norepo=True)
2211 @command('debuginstall', [], '', norepo=True)
2215 def debuginstall(ui):
2212 def debuginstall(ui):
2216 '''test Mercurial installation
2213 '''test Mercurial installation
2217
2214
2218 Returns 0 on success.
2215 Returns 0 on success.
2219 '''
2216 '''
2220
2217
2221 def writetemp(contents):
2218 def writetemp(contents):
2222 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2219 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2223 f = os.fdopen(fd, "wb")
2220 f = os.fdopen(fd, "wb")
2224 f.write(contents)
2221 f.write(contents)
2225 f.close()
2222 f.close()
2226 return name
2223 return name
2227
2224
2228 problems = 0
2225 problems = 0
2229
2226
2230 # encoding
2227 # encoding
2231 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2228 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2232 try:
2229 try:
2233 encoding.fromlocal("test")
2230 encoding.fromlocal("test")
2234 except util.Abort, inst:
2231 except util.Abort, inst:
2235 ui.write(" %s\n" % inst)
2232 ui.write(" %s\n" % inst)
2236 ui.write(_(" (check that your locale is properly set)\n"))
2233 ui.write(_(" (check that your locale is properly set)\n"))
2237 problems += 1
2234 problems += 1
2238
2235
2239 # Python
2236 # Python
2240 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2237 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2241 ui.status(_("checking Python version (%s)\n")
2238 ui.status(_("checking Python version (%s)\n")
2242 % ("%s.%s.%s" % sys.version_info[:3]))
2239 % ("%s.%s.%s" % sys.version_info[:3]))
2243 ui.status(_("checking Python lib (%s)...\n")
2240 ui.status(_("checking Python lib (%s)...\n")
2244 % os.path.dirname(os.__file__))
2241 % os.path.dirname(os.__file__))
2245
2242
2246 # compiled modules
2243 # compiled modules
2247 ui.status(_("checking installed modules (%s)...\n")
2244 ui.status(_("checking installed modules (%s)...\n")
2248 % os.path.dirname(__file__))
2245 % os.path.dirname(__file__))
2249 try:
2246 try:
2250 import bdiff, mpatch, base85, osutil
2247 import bdiff, mpatch, base85, osutil
2251 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2248 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2252 except Exception, inst:
2249 except Exception, inst:
2253 ui.write(" %s\n" % inst)
2250 ui.write(" %s\n" % inst)
2254 ui.write(_(" One or more extensions could not be found"))
2251 ui.write(_(" One or more extensions could not be found"))
2255 ui.write(_(" (check that you compiled the extensions)\n"))
2252 ui.write(_(" (check that you compiled the extensions)\n"))
2256 problems += 1
2253 problems += 1
2257
2254
2258 # templates
2255 # templates
2259 import templater
2256 import templater
2260 p = templater.templatepaths()
2257 p = templater.templatepaths()
2261 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2258 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2262 if p:
2259 if p:
2263 m = templater.templatepath("map-cmdline.default")
2260 m = templater.templatepath("map-cmdline.default")
2264 if m:
2261 if m:
2265 # template found, check if it is working
2262 # template found, check if it is working
2266 try:
2263 try:
2267 templater.templater(m)
2264 templater.templater(m)
2268 except Exception, inst:
2265 except Exception, inst:
2269 ui.write(" %s\n" % inst)
2266 ui.write(" %s\n" % inst)
2270 p = None
2267 p = None
2271 else:
2268 else:
2272 ui.write(_(" template 'default' not found\n"))
2269 ui.write(_(" template 'default' not found\n"))
2273 p = None
2270 p = None
2274 else:
2271 else:
2275 ui.write(_(" no template directories found\n"))
2272 ui.write(_(" no template directories found\n"))
2276 if not p:
2273 if not p:
2277 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2274 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2278 problems += 1
2275 problems += 1
2279
2276
2280 # editor
2277 # editor
2281 ui.status(_("checking commit editor...\n"))
2278 ui.status(_("checking commit editor...\n"))
2282 editor = ui.geteditor()
2279 editor = ui.geteditor()
2283 cmdpath = util.findexe(shlex.split(editor)[0])
2280 cmdpath = util.findexe(shlex.split(editor)[0])
2284 if not cmdpath:
2281 if not cmdpath:
2285 if editor == 'vi':
2282 if editor == 'vi':
2286 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2283 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2287 ui.write(_(" (specify a commit editor in your configuration"
2284 ui.write(_(" (specify a commit editor in your configuration"
2288 " file)\n"))
2285 " file)\n"))
2289 else:
2286 else:
2290 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2287 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2291 ui.write(_(" (specify a commit editor in your configuration"
2288 ui.write(_(" (specify a commit editor in your configuration"
2292 " file)\n"))
2289 " file)\n"))
2293 problems += 1
2290 problems += 1
2294
2291
2295 # check username
2292 # check username
2296 ui.status(_("checking username...\n"))
2293 ui.status(_("checking username...\n"))
2297 try:
2294 try:
2298 ui.username()
2295 ui.username()
2299 except util.Abort, e:
2296 except util.Abort, e:
2300 ui.write(" %s\n" % e)
2297 ui.write(" %s\n" % e)
2301 ui.write(_(" (specify a username in your configuration file)\n"))
2298 ui.write(_(" (specify a username in your configuration file)\n"))
2302 problems += 1
2299 problems += 1
2303
2300
2304 if not problems:
2301 if not problems:
2305 ui.status(_("no problems detected\n"))
2302 ui.status(_("no problems detected\n"))
2306 else:
2303 else:
2307 ui.write(_("%s problems detected,"
2304 ui.write(_("%s problems detected,"
2308 " please check your install!\n") % problems)
2305 " please check your install!\n") % problems)
2309
2306
2310 return problems
2307 return problems
2311
2308
2312 @command('debugknown', [], _('REPO ID...'), norepo=True)
2309 @command('debugknown', [], _('REPO ID...'), norepo=True)
2313 def debugknown(ui, repopath, *ids, **opts):
2310 def debugknown(ui, repopath, *ids, **opts):
2314 """test whether node ids are known to a repo
2311 """test whether node ids are known to a repo
2315
2312
2316 Every ID must be a full-length hex node id string. Returns a list of 0s
2313 Every ID must be a full-length hex node id string. Returns a list of 0s
2317 and 1s indicating unknown/known.
2314 and 1s indicating unknown/known.
2318 """
2315 """
2319 repo = hg.peer(ui, opts, repopath)
2316 repo = hg.peer(ui, opts, repopath)
2320 if not repo.capable('known'):
2317 if not repo.capable('known'):
2321 raise util.Abort("known() not supported by target repository")
2318 raise util.Abort("known() not supported by target repository")
2322 flags = repo.known([bin(s) for s in ids])
2319 flags = repo.known([bin(s) for s in ids])
2323 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2320 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2324
2321
2325 @command('debuglabelcomplete', [], _('LABEL...'))
2322 @command('debuglabelcomplete', [], _('LABEL...'))
2326 def debuglabelcomplete(ui, repo, *args):
2323 def debuglabelcomplete(ui, repo, *args):
2327 '''complete "labels" - tags, open branch names, bookmark names'''
2324 '''complete "labels" - tags, open branch names, bookmark names'''
2328
2325
2329 labels = set()
2326 labels = set()
2330 labels.update(t[0] for t in repo.tagslist())
2327 labels.update(t[0] for t in repo.tagslist())
2331 labels.update(repo._bookmarks.keys())
2328 labels.update(repo._bookmarks.keys())
2332 labels.update(tag for (tag, heads, tip, closed)
2329 labels.update(tag for (tag, heads, tip, closed)
2333 in repo.branchmap().iterbranches() if not closed)
2330 in repo.branchmap().iterbranches() if not closed)
2334 completions = set()
2331 completions = set()
2335 if not args:
2332 if not args:
2336 args = ['']
2333 args = ['']
2337 for a in args:
2334 for a in args:
2338 completions.update(l for l in labels if l.startswith(a))
2335 completions.update(l for l in labels if l.startswith(a))
2339 ui.write('\n'.join(sorted(completions)))
2336 ui.write('\n'.join(sorted(completions)))
2340 ui.write('\n')
2337 ui.write('\n')
2341
2338
2342 @command('debuglocks',
2339 @command('debuglocks',
2343 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2340 [('L', 'force-lock', None, _('free the store lock (DANGEROUS)')),
2344 ('W', 'force-wlock', None,
2341 ('W', 'force-wlock', None,
2345 _('free the working state lock (DANGEROUS)'))],
2342 _('free the working state lock (DANGEROUS)'))],
2346 _(''))
2343 _(''))
2347 def debuglocks(ui, repo, **opts):
2344 def debuglocks(ui, repo, **opts):
2348 """show or modify state of locks
2345 """show or modify state of locks
2349
2346
2350 By default, this command will show which locks are held. This
2347 By default, this command will show which locks are held. This
2351 includes the user and process holding the lock, the amount of time
2348 includes the user and process holding the lock, the amount of time
2352 the lock has been held, and the machine name where the process is
2349 the lock has been held, and the machine name where the process is
2353 running if it's not local.
2350 running if it's not local.
2354
2351
2355 Locks protect the integrity of Mercurial's data, so should be
2352 Locks protect the integrity of Mercurial's data, so should be
2356 treated with care. System crashes or other interruptions may cause
2353 treated with care. System crashes or other interruptions may cause
2357 locks to not be properly released, though Mercurial will usually
2354 locks to not be properly released, though Mercurial will usually
2358 detect and remove such stale locks automatically.
2355 detect and remove such stale locks automatically.
2359
2356
2360 However, detecting stale locks may not always be possible (for
2357 However, detecting stale locks may not always be possible (for
2361 instance, on a shared filesystem). Removing locks may also be
2358 instance, on a shared filesystem). Removing locks may also be
2362 blocked by filesystem permissions.
2359 blocked by filesystem permissions.
2363
2360
2364 Returns 0 if no locks are held.
2361 Returns 0 if no locks are held.
2365
2362
2366 """
2363 """
2367
2364
2368 if opts.get('force_lock'):
2365 if opts.get('force_lock'):
2369 repo.svfs.unlink('lock')
2366 repo.svfs.unlink('lock')
2370 if opts.get('force_wlock'):
2367 if opts.get('force_wlock'):
2371 repo.vfs.unlink('wlock')
2368 repo.vfs.unlink('wlock')
2372 if opts.get('force_lock') or opts.get('force_lock'):
2369 if opts.get('force_lock') or opts.get('force_lock'):
2373 return 0
2370 return 0
2374
2371
2375 now = time.time()
2372 now = time.time()
2376 held = 0
2373 held = 0
2377
2374
2378 def report(vfs, name, method):
2375 def report(vfs, name, method):
2379 # this causes stale locks to get reaped for more accurate reporting
2376 # this causes stale locks to get reaped for more accurate reporting
2380 try:
2377 try:
2381 l = method(False)
2378 l = method(False)
2382 except error.LockHeld:
2379 except error.LockHeld:
2383 l = None
2380 l = None
2384
2381
2385 if l:
2382 if l:
2386 l.release()
2383 l.release()
2387 else:
2384 else:
2388 try:
2385 try:
2389 stat = repo.svfs.lstat(name)
2386 stat = repo.svfs.lstat(name)
2390 age = now - stat.st_mtime
2387 age = now - stat.st_mtime
2391 user = util.username(stat.st_uid)
2388 user = util.username(stat.st_uid)
2392 locker = vfs.readlock(name)
2389 locker = vfs.readlock(name)
2393 if ":" in locker:
2390 if ":" in locker:
2394 host, pid = locker.split(':')
2391 host, pid = locker.split(':')
2395 if host == socket.gethostname():
2392 if host == socket.gethostname():
2396 locker = 'user %s, process %s' % (user, pid)
2393 locker = 'user %s, process %s' % (user, pid)
2397 else:
2394 else:
2398 locker = 'user %s, process %s, host %s' \
2395 locker = 'user %s, process %s, host %s' \
2399 % (user, pid, host)
2396 % (user, pid, host)
2400 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
2397 ui.write("%-6s %s (%ds)\n" % (name + ":", locker, age))
2401 return 1
2398 return 1
2402 except OSError, e:
2399 except OSError, e:
2403 if e.errno != errno.ENOENT:
2400 if e.errno != errno.ENOENT:
2404 raise
2401 raise
2405
2402
2406 ui.write("%-6s free\n" % (name + ":"))
2403 ui.write("%-6s free\n" % (name + ":"))
2407 return 0
2404 return 0
2408
2405
2409 held += report(repo.svfs, "lock", repo.lock)
2406 held += report(repo.svfs, "lock", repo.lock)
2410 held += report(repo.vfs, "wlock", repo.wlock)
2407 held += report(repo.vfs, "wlock", repo.wlock)
2411
2408
2412 return held
2409 return held
2413
2410
2414 @command('debugobsolete',
2411 @command('debugobsolete',
2415 [('', 'flags', 0, _('markers flag')),
2412 [('', 'flags', 0, _('markers flag')),
2416 ('', 'record-parents', False,
2413 ('', 'record-parents', False,
2417 _('record parent information for the precursor')),
2414 _('record parent information for the precursor')),
2418 ('r', 'rev', [], _('display markers relevant to REV')),
2415 ('r', 'rev', [], _('display markers relevant to REV')),
2419 ] + commitopts2,
2416 ] + commitopts2,
2420 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2417 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2421 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2418 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2422 """create arbitrary obsolete marker
2419 """create arbitrary obsolete marker
2423
2420
2424 With no arguments, displays the list of obsolescence markers."""
2421 With no arguments, displays the list of obsolescence markers."""
2425
2422
2426 def parsenodeid(s):
2423 def parsenodeid(s):
2427 try:
2424 try:
2428 # We do not use revsingle/revrange functions here to accept
2425 # We do not use revsingle/revrange functions here to accept
2429 # arbitrary node identifiers, possibly not present in the
2426 # arbitrary node identifiers, possibly not present in the
2430 # local repository.
2427 # local repository.
2431 n = bin(s)
2428 n = bin(s)
2432 if len(n) != len(nullid):
2429 if len(n) != len(nullid):
2433 raise TypeError()
2430 raise TypeError()
2434 return n
2431 return n
2435 except TypeError:
2432 except TypeError:
2436 raise util.Abort('changeset references must be full hexadecimal '
2433 raise util.Abort('changeset references must be full hexadecimal '
2437 'node identifiers')
2434 'node identifiers')
2438
2435
2439 if precursor is not None:
2436 if precursor is not None:
2440 if opts['rev']:
2437 if opts['rev']:
2441 raise util.Abort('cannot select revision when creating marker')
2438 raise util.Abort('cannot select revision when creating marker')
2442 metadata = {}
2439 metadata = {}
2443 metadata['user'] = opts['user'] or ui.username()
2440 metadata['user'] = opts['user'] or ui.username()
2444 succs = tuple(parsenodeid(succ) for succ in successors)
2441 succs = tuple(parsenodeid(succ) for succ in successors)
2445 l = repo.lock()
2442 l = repo.lock()
2446 try:
2443 try:
2447 tr = repo.transaction('debugobsolete')
2444 tr = repo.transaction('debugobsolete')
2448 try:
2445 try:
2449 try:
2446 try:
2450 date = opts.get('date')
2447 date = opts.get('date')
2451 if date:
2448 if date:
2452 date = util.parsedate(date)
2449 date = util.parsedate(date)
2453 else:
2450 else:
2454 date = None
2451 date = None
2455 prec = parsenodeid(precursor)
2452 prec = parsenodeid(precursor)
2456 parents = None
2453 parents = None
2457 if opts['record_parents']:
2454 if opts['record_parents']:
2458 if prec not in repo.unfiltered():
2455 if prec not in repo.unfiltered():
2459 raise util.Abort('cannot used --record-parents on '
2456 raise util.Abort('cannot used --record-parents on '
2460 'unknown changesets')
2457 'unknown changesets')
2461 parents = repo.unfiltered()[prec].parents()
2458 parents = repo.unfiltered()[prec].parents()
2462 parents = tuple(p.node() for p in parents)
2459 parents = tuple(p.node() for p in parents)
2463 repo.obsstore.create(tr, prec, succs, opts['flags'],
2460 repo.obsstore.create(tr, prec, succs, opts['flags'],
2464 parents=parents, date=date,
2461 parents=parents, date=date,
2465 metadata=metadata)
2462 metadata=metadata)
2466 tr.close()
2463 tr.close()
2467 except ValueError, exc:
2464 except ValueError, exc:
2468 raise util.Abort(_('bad obsmarker input: %s') % exc)
2465 raise util.Abort(_('bad obsmarker input: %s') % exc)
2469 finally:
2466 finally:
2470 tr.release()
2467 tr.release()
2471 finally:
2468 finally:
2472 l.release()
2469 l.release()
2473 else:
2470 else:
2474 if opts['rev']:
2471 if opts['rev']:
2475 revs = scmutil.revrange(repo, opts['rev'])
2472 revs = scmutil.revrange(repo, opts['rev'])
2476 nodes = [repo[r].node() for r in revs]
2473 nodes = [repo[r].node() for r in revs]
2477 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2474 markers = list(obsolete.getmarkers(repo, nodes=nodes))
2478 markers.sort(key=lambda x: x._data)
2475 markers.sort(key=lambda x: x._data)
2479 else:
2476 else:
2480 markers = obsolete.getmarkers(repo)
2477 markers = obsolete.getmarkers(repo)
2481
2478
2482 for m in markers:
2479 for m in markers:
2483 cmdutil.showmarker(ui, m)
2480 cmdutil.showmarker(ui, m)
2484
2481
2485 @command('debugpathcomplete',
2482 @command('debugpathcomplete',
2486 [('f', 'full', None, _('complete an entire path')),
2483 [('f', 'full', None, _('complete an entire path')),
2487 ('n', 'normal', None, _('show only normal files')),
2484 ('n', 'normal', None, _('show only normal files')),
2488 ('a', 'added', None, _('show only added files')),
2485 ('a', 'added', None, _('show only added files')),
2489 ('r', 'removed', None, _('show only removed files'))],
2486 ('r', 'removed', None, _('show only removed files'))],
2490 _('FILESPEC...'))
2487 _('FILESPEC...'))
2491 def debugpathcomplete(ui, repo, *specs, **opts):
2488 def debugpathcomplete(ui, repo, *specs, **opts):
2492 '''complete part or all of a tracked path
2489 '''complete part or all of a tracked path
2493
2490
2494 This command supports shells that offer path name completion. It
2491 This command supports shells that offer path name completion. It
2495 currently completes only files already known to the dirstate.
2492 currently completes only files already known to the dirstate.
2496
2493
2497 Completion extends only to the next path segment unless
2494 Completion extends only to the next path segment unless
2498 --full is specified, in which case entire paths are used.'''
2495 --full is specified, in which case entire paths are used.'''
2499
2496
2500 def complete(path, acceptable):
2497 def complete(path, acceptable):
2501 dirstate = repo.dirstate
2498 dirstate = repo.dirstate
2502 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2499 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2503 rootdir = repo.root + os.sep
2500 rootdir = repo.root + os.sep
2504 if spec != repo.root and not spec.startswith(rootdir):
2501 if spec != repo.root and not spec.startswith(rootdir):
2505 return [], []
2502 return [], []
2506 if os.path.isdir(spec):
2503 if os.path.isdir(spec):
2507 spec += '/'
2504 spec += '/'
2508 spec = spec[len(rootdir):]
2505 spec = spec[len(rootdir):]
2509 fixpaths = os.sep != '/'
2506 fixpaths = os.sep != '/'
2510 if fixpaths:
2507 if fixpaths:
2511 spec = spec.replace(os.sep, '/')
2508 spec = spec.replace(os.sep, '/')
2512 speclen = len(spec)
2509 speclen = len(spec)
2513 fullpaths = opts['full']
2510 fullpaths = opts['full']
2514 files, dirs = set(), set()
2511 files, dirs = set(), set()
2515 adddir, addfile = dirs.add, files.add
2512 adddir, addfile = dirs.add, files.add
2516 for f, st in dirstate.iteritems():
2513 for f, st in dirstate.iteritems():
2517 if f.startswith(spec) and st[0] in acceptable:
2514 if f.startswith(spec) and st[0] in acceptable:
2518 if fixpaths:
2515 if fixpaths:
2519 f = f.replace('/', os.sep)
2516 f = f.replace('/', os.sep)
2520 if fullpaths:
2517 if fullpaths:
2521 addfile(f)
2518 addfile(f)
2522 continue
2519 continue
2523 s = f.find(os.sep, speclen)
2520 s = f.find(os.sep, speclen)
2524 if s >= 0:
2521 if s >= 0:
2525 adddir(f[:s])
2522 adddir(f[:s])
2526 else:
2523 else:
2527 addfile(f)
2524 addfile(f)
2528 return files, dirs
2525 return files, dirs
2529
2526
2530 acceptable = ''
2527 acceptable = ''
2531 if opts['normal']:
2528 if opts['normal']:
2532 acceptable += 'nm'
2529 acceptable += 'nm'
2533 if opts['added']:
2530 if opts['added']:
2534 acceptable += 'a'
2531 acceptable += 'a'
2535 if opts['removed']:
2532 if opts['removed']:
2536 acceptable += 'r'
2533 acceptable += 'r'
2537 cwd = repo.getcwd()
2534 cwd = repo.getcwd()
2538 if not specs:
2535 if not specs:
2539 specs = ['.']
2536 specs = ['.']
2540
2537
2541 files, dirs = set(), set()
2538 files, dirs = set(), set()
2542 for spec in specs:
2539 for spec in specs:
2543 f, d = complete(spec, acceptable or 'nmar')
2540 f, d = complete(spec, acceptable or 'nmar')
2544 files.update(f)
2541 files.update(f)
2545 dirs.update(d)
2542 dirs.update(d)
2546 files.update(dirs)
2543 files.update(dirs)
2547 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2544 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2548 ui.write('\n')
2545 ui.write('\n')
2549
2546
2550 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2547 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'), norepo=True)
2551 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2548 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2552 '''access the pushkey key/value protocol
2549 '''access the pushkey key/value protocol
2553
2550
2554 With two args, list the keys in the given namespace.
2551 With two args, list the keys in the given namespace.
2555
2552
2556 With five args, set a key to new if it currently is set to old.
2553 With five args, set a key to new if it currently is set to old.
2557 Reports success or failure.
2554 Reports success or failure.
2558 '''
2555 '''
2559
2556
2560 target = hg.peer(ui, {}, repopath)
2557 target = hg.peer(ui, {}, repopath)
2561 if keyinfo:
2558 if keyinfo:
2562 key, old, new = keyinfo
2559 key, old, new = keyinfo
2563 r = target.pushkey(namespace, key, old, new)
2560 r = target.pushkey(namespace, key, old, new)
2564 ui.status(str(r) + '\n')
2561 ui.status(str(r) + '\n')
2565 return not r
2562 return not r
2566 else:
2563 else:
2567 for k, v in sorted(target.listkeys(namespace).iteritems()):
2564 for k, v in sorted(target.listkeys(namespace).iteritems()):
2568 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2565 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2569 v.encode('string-escape')))
2566 v.encode('string-escape')))
2570
2567
2571 @command('debugpvec', [], _('A B'))
2568 @command('debugpvec', [], _('A B'))
2572 def debugpvec(ui, repo, a, b=None):
2569 def debugpvec(ui, repo, a, b=None):
2573 ca = scmutil.revsingle(repo, a)
2570 ca = scmutil.revsingle(repo, a)
2574 cb = scmutil.revsingle(repo, b)
2571 cb = scmutil.revsingle(repo, b)
2575 pa = pvec.ctxpvec(ca)
2572 pa = pvec.ctxpvec(ca)
2576 pb = pvec.ctxpvec(cb)
2573 pb = pvec.ctxpvec(cb)
2577 if pa == pb:
2574 if pa == pb:
2578 rel = "="
2575 rel = "="
2579 elif pa > pb:
2576 elif pa > pb:
2580 rel = ">"
2577 rel = ">"
2581 elif pa < pb:
2578 elif pa < pb:
2582 rel = "<"
2579 rel = "<"
2583 elif pa | pb:
2580 elif pa | pb:
2584 rel = "|"
2581 rel = "|"
2585 ui.write(_("a: %s\n") % pa)
2582 ui.write(_("a: %s\n") % pa)
2586 ui.write(_("b: %s\n") % pb)
2583 ui.write(_("b: %s\n") % pb)
2587 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2584 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2588 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2585 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2589 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2586 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2590 pa.distance(pb), rel))
2587 pa.distance(pb), rel))
2591
2588
2592 @command('debugrebuilddirstate|debugrebuildstate',
2589 @command('debugrebuilddirstate|debugrebuildstate',
2593 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2590 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2594 _('[-r REV]'))
2591 _('[-r REV]'))
2595 def debugrebuilddirstate(ui, repo, rev):
2592 def debugrebuilddirstate(ui, repo, rev):
2596 """rebuild the dirstate as it would look like for the given revision
2593 """rebuild the dirstate as it would look like for the given revision
2597
2594
2598 If no revision is specified the first current parent will be used.
2595 If no revision is specified the first current parent will be used.
2599
2596
2600 The dirstate will be set to the files of the given revision.
2597 The dirstate will be set to the files of the given revision.
2601 The actual working directory content or existing dirstate
2598 The actual working directory content or existing dirstate
2602 information such as adds or removes is not considered.
2599 information such as adds or removes is not considered.
2603
2600
2604 One use of this command is to make the next :hg:`status` invocation
2601 One use of this command is to make the next :hg:`status` invocation
2605 check the actual file content.
2602 check the actual file content.
2606 """
2603 """
2607 ctx = scmutil.revsingle(repo, rev)
2604 ctx = scmutil.revsingle(repo, rev)
2608 wlock = repo.wlock()
2605 wlock = repo.wlock()
2609 try:
2606 try:
2610 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2607 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2611 finally:
2608 finally:
2612 wlock.release()
2609 wlock.release()
2613
2610
2614 @command('debugrename',
2611 @command('debugrename',
2615 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2612 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2616 _('[-r REV] FILE'))
2613 _('[-r REV] FILE'))
2617 def debugrename(ui, repo, file1, *pats, **opts):
2614 def debugrename(ui, repo, file1, *pats, **opts):
2618 """dump rename information"""
2615 """dump rename information"""
2619
2616
2620 ctx = scmutil.revsingle(repo, opts.get('rev'))
2617 ctx = scmutil.revsingle(repo, opts.get('rev'))
2621 m = scmutil.match(ctx, (file1,) + pats, opts)
2618 m = scmutil.match(ctx, (file1,) + pats, opts)
2622 for abs in ctx.walk(m):
2619 for abs in ctx.walk(m):
2623 fctx = ctx[abs]
2620 fctx = ctx[abs]
2624 o = fctx.filelog().renamed(fctx.filenode())
2621 o = fctx.filelog().renamed(fctx.filenode())
2625 rel = m.rel(abs)
2622 rel = m.rel(abs)
2626 if o:
2623 if o:
2627 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2624 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2628 else:
2625 else:
2629 ui.write(_("%s not renamed\n") % rel)
2626 ui.write(_("%s not renamed\n") % rel)
2630
2627
2631 @command('debugrevlog',
2628 @command('debugrevlog',
2632 [('c', 'changelog', False, _('open changelog')),
2629 [('c', 'changelog', False, _('open changelog')),
2633 ('m', 'manifest', False, _('open manifest')),
2630 ('m', 'manifest', False, _('open manifest')),
2634 ('d', 'dump', False, _('dump index data'))],
2631 ('d', 'dump', False, _('dump index data'))],
2635 _('-c|-m|FILE'),
2632 _('-c|-m|FILE'),
2636 optionalrepo=True)
2633 optionalrepo=True)
2637 def debugrevlog(ui, repo, file_=None, **opts):
2634 def debugrevlog(ui, repo, file_=None, **opts):
2638 """show data and statistics about a revlog"""
2635 """show data and statistics about a revlog"""
2639 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2636 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2640
2637
2641 if opts.get("dump"):
2638 if opts.get("dump"):
2642 numrevs = len(r)
2639 numrevs = len(r)
2643 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2640 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2644 " rawsize totalsize compression heads chainlen\n")
2641 " rawsize totalsize compression heads chainlen\n")
2645 ts = 0
2642 ts = 0
2646 heads = set()
2643 heads = set()
2647 rindex = r.index
2644 rindex = r.index
2648
2645
2649 def chainbaseandlen(rev):
2646 def chainbaseandlen(rev):
2650 clen = 0
2647 clen = 0
2651 base = rindex[rev][3]
2648 base = rindex[rev][3]
2652 while base != rev:
2649 while base != rev:
2653 clen += 1
2650 clen += 1
2654 rev = base
2651 rev = base
2655 base = rindex[rev][3]
2652 base = rindex[rev][3]
2656 return base, clen
2653 return base, clen
2657
2654
2658 for rev in xrange(numrevs):
2655 for rev in xrange(numrevs):
2659 dbase = r.deltaparent(rev)
2656 dbase = r.deltaparent(rev)
2660 if dbase == -1:
2657 if dbase == -1:
2661 dbase = rev
2658 dbase = rev
2662 cbase, clen = chainbaseandlen(rev)
2659 cbase, clen = chainbaseandlen(rev)
2663 p1, p2 = r.parentrevs(rev)
2660 p1, p2 = r.parentrevs(rev)
2664 rs = r.rawsize(rev)
2661 rs = r.rawsize(rev)
2665 ts = ts + rs
2662 ts = ts + rs
2666 heads -= set(r.parentrevs(rev))
2663 heads -= set(r.parentrevs(rev))
2667 heads.add(rev)
2664 heads.add(rev)
2668 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2665 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d "
2669 "%11d %5d %8d\n" %
2666 "%11d %5d %8d\n" %
2670 (rev, p1, p2, r.start(rev), r.end(rev),
2667 (rev, p1, p2, r.start(rev), r.end(rev),
2671 r.start(dbase), r.start(cbase),
2668 r.start(dbase), r.start(cbase),
2672 r.start(p1), r.start(p2),
2669 r.start(p1), r.start(p2),
2673 rs, ts, ts / r.end(rev), len(heads), clen))
2670 rs, ts, ts / r.end(rev), len(heads), clen))
2674 return 0
2671 return 0
2675
2672
2676 v = r.version
2673 v = r.version
2677 format = v & 0xFFFF
2674 format = v & 0xFFFF
2678 flags = []
2675 flags = []
2679 gdelta = False
2676 gdelta = False
2680 if v & revlog.REVLOGNGINLINEDATA:
2677 if v & revlog.REVLOGNGINLINEDATA:
2681 flags.append('inline')
2678 flags.append('inline')
2682 if v & revlog.REVLOGGENERALDELTA:
2679 if v & revlog.REVLOGGENERALDELTA:
2683 gdelta = True
2680 gdelta = True
2684 flags.append('generaldelta')
2681 flags.append('generaldelta')
2685 if not flags:
2682 if not flags:
2686 flags = ['(none)']
2683 flags = ['(none)']
2687
2684
2688 nummerges = 0
2685 nummerges = 0
2689 numfull = 0
2686 numfull = 0
2690 numprev = 0
2687 numprev = 0
2691 nump1 = 0
2688 nump1 = 0
2692 nump2 = 0
2689 nump2 = 0
2693 numother = 0
2690 numother = 0
2694 nump1prev = 0
2691 nump1prev = 0
2695 nump2prev = 0
2692 nump2prev = 0
2696 chainlengths = []
2693 chainlengths = []
2697
2694
2698 datasize = [None, 0, 0L]
2695 datasize = [None, 0, 0L]
2699 fullsize = [None, 0, 0L]
2696 fullsize = [None, 0, 0L]
2700 deltasize = [None, 0, 0L]
2697 deltasize = [None, 0, 0L]
2701
2698
2702 def addsize(size, l):
2699 def addsize(size, l):
2703 if l[0] is None or size < l[0]:
2700 if l[0] is None or size < l[0]:
2704 l[0] = size
2701 l[0] = size
2705 if size > l[1]:
2702 if size > l[1]:
2706 l[1] = size
2703 l[1] = size
2707 l[2] += size
2704 l[2] += size
2708
2705
2709 numrevs = len(r)
2706 numrevs = len(r)
2710 for rev in xrange(numrevs):
2707 for rev in xrange(numrevs):
2711 p1, p2 = r.parentrevs(rev)
2708 p1, p2 = r.parentrevs(rev)
2712 delta = r.deltaparent(rev)
2709 delta = r.deltaparent(rev)
2713 if format > 0:
2710 if format > 0:
2714 addsize(r.rawsize(rev), datasize)
2711 addsize(r.rawsize(rev), datasize)
2715 if p2 != nullrev:
2712 if p2 != nullrev:
2716 nummerges += 1
2713 nummerges += 1
2717 size = r.length(rev)
2714 size = r.length(rev)
2718 if delta == nullrev:
2715 if delta == nullrev:
2719 chainlengths.append(0)
2716 chainlengths.append(0)
2720 numfull += 1
2717 numfull += 1
2721 addsize(size, fullsize)
2718 addsize(size, fullsize)
2722 else:
2719 else:
2723 chainlengths.append(chainlengths[delta] + 1)
2720 chainlengths.append(chainlengths[delta] + 1)
2724 addsize(size, deltasize)
2721 addsize(size, deltasize)
2725 if delta == rev - 1:
2722 if delta == rev - 1:
2726 numprev += 1
2723 numprev += 1
2727 if delta == p1:
2724 if delta == p1:
2728 nump1prev += 1
2725 nump1prev += 1
2729 elif delta == p2:
2726 elif delta == p2:
2730 nump2prev += 1
2727 nump2prev += 1
2731 elif delta == p1:
2728 elif delta == p1:
2732 nump1 += 1
2729 nump1 += 1
2733 elif delta == p2:
2730 elif delta == p2:
2734 nump2 += 1
2731 nump2 += 1
2735 elif delta != nullrev:
2732 elif delta != nullrev:
2736 numother += 1
2733 numother += 1
2737
2734
2738 # Adjust size min value for empty cases
2735 # Adjust size min value for empty cases
2739 for size in (datasize, fullsize, deltasize):
2736 for size in (datasize, fullsize, deltasize):
2740 if size[0] is None:
2737 if size[0] is None:
2741 size[0] = 0
2738 size[0] = 0
2742
2739
2743 numdeltas = numrevs - numfull
2740 numdeltas = numrevs - numfull
2744 numoprev = numprev - nump1prev - nump2prev
2741 numoprev = numprev - nump1prev - nump2prev
2745 totalrawsize = datasize[2]
2742 totalrawsize = datasize[2]
2746 datasize[2] /= numrevs
2743 datasize[2] /= numrevs
2747 fulltotal = fullsize[2]
2744 fulltotal = fullsize[2]
2748 fullsize[2] /= numfull
2745 fullsize[2] /= numfull
2749 deltatotal = deltasize[2]
2746 deltatotal = deltasize[2]
2750 if numrevs - numfull > 0:
2747 if numrevs - numfull > 0:
2751 deltasize[2] /= numrevs - numfull
2748 deltasize[2] /= numrevs - numfull
2752 totalsize = fulltotal + deltatotal
2749 totalsize = fulltotal + deltatotal
2753 avgchainlen = sum(chainlengths) / numrevs
2750 avgchainlen = sum(chainlengths) / numrevs
2754 compratio = totalrawsize / totalsize
2751 compratio = totalrawsize / totalsize
2755
2752
2756 basedfmtstr = '%%%dd\n'
2753 basedfmtstr = '%%%dd\n'
2757 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2754 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2758
2755
2759 def dfmtstr(max):
2756 def dfmtstr(max):
2760 return basedfmtstr % len(str(max))
2757 return basedfmtstr % len(str(max))
2761 def pcfmtstr(max, padding=0):
2758 def pcfmtstr(max, padding=0):
2762 return basepcfmtstr % (len(str(max)), ' ' * padding)
2759 return basepcfmtstr % (len(str(max)), ' ' * padding)
2763
2760
2764 def pcfmt(value, total):
2761 def pcfmt(value, total):
2765 return (value, 100 * float(value) / total)
2762 return (value, 100 * float(value) / total)
2766
2763
2767 ui.write(('format : %d\n') % format)
2764 ui.write(('format : %d\n') % format)
2768 ui.write(('flags : %s\n') % ', '.join(flags))
2765 ui.write(('flags : %s\n') % ', '.join(flags))
2769
2766
2770 ui.write('\n')
2767 ui.write('\n')
2771 fmt = pcfmtstr(totalsize)
2768 fmt = pcfmtstr(totalsize)
2772 fmt2 = dfmtstr(totalsize)
2769 fmt2 = dfmtstr(totalsize)
2773 ui.write(('revisions : ') + fmt2 % numrevs)
2770 ui.write(('revisions : ') + fmt2 % numrevs)
2774 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2771 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2775 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2772 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2776 ui.write(('revisions : ') + fmt2 % numrevs)
2773 ui.write(('revisions : ') + fmt2 % numrevs)
2777 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2774 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2778 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2775 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2779 ui.write(('revision size : ') + fmt2 % totalsize)
2776 ui.write(('revision size : ') + fmt2 % totalsize)
2780 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2777 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2781 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2778 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2782
2779
2783 ui.write('\n')
2780 ui.write('\n')
2784 fmt = dfmtstr(max(avgchainlen, compratio))
2781 fmt = dfmtstr(max(avgchainlen, compratio))
2785 ui.write(('avg chain length : ') + fmt % avgchainlen)
2782 ui.write(('avg chain length : ') + fmt % avgchainlen)
2786 ui.write(('compression ratio : ') + fmt % compratio)
2783 ui.write(('compression ratio : ') + fmt % compratio)
2787
2784
2788 if format > 0:
2785 if format > 0:
2789 ui.write('\n')
2786 ui.write('\n')
2790 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2787 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2791 % tuple(datasize))
2788 % tuple(datasize))
2792 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2789 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2793 % tuple(fullsize))
2790 % tuple(fullsize))
2794 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2791 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2795 % tuple(deltasize))
2792 % tuple(deltasize))
2796
2793
2797 if numdeltas > 0:
2794 if numdeltas > 0:
2798 ui.write('\n')
2795 ui.write('\n')
2799 fmt = pcfmtstr(numdeltas)
2796 fmt = pcfmtstr(numdeltas)
2800 fmt2 = pcfmtstr(numdeltas, 4)
2797 fmt2 = pcfmtstr(numdeltas, 4)
2801 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2798 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2802 if numprev > 0:
2799 if numprev > 0:
2803 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2800 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2804 numprev))
2801 numprev))
2805 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2802 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2806 numprev))
2803 numprev))
2807 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2804 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2808 numprev))
2805 numprev))
2809 if gdelta:
2806 if gdelta:
2810 ui.write(('deltas against p1 : ')
2807 ui.write(('deltas against p1 : ')
2811 + fmt % pcfmt(nump1, numdeltas))
2808 + fmt % pcfmt(nump1, numdeltas))
2812 ui.write(('deltas against p2 : ')
2809 ui.write(('deltas against p2 : ')
2813 + fmt % pcfmt(nump2, numdeltas))
2810 + fmt % pcfmt(nump2, numdeltas))
2814 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2811 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2815 numdeltas))
2812 numdeltas))
2816
2813
2817 @command('debugrevspec',
2814 @command('debugrevspec',
2818 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2815 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2819 ('REVSPEC'))
2816 ('REVSPEC'))
2820 def debugrevspec(ui, repo, expr, **opts):
2817 def debugrevspec(ui, repo, expr, **opts):
2821 """parse and apply a revision specification
2818 """parse and apply a revision specification
2822
2819
2823 Use --verbose to print the parsed tree before and after aliases
2820 Use --verbose to print the parsed tree before and after aliases
2824 expansion.
2821 expansion.
2825 """
2822 """
2826 if ui.verbose:
2823 if ui.verbose:
2827 tree = revset.parse(expr)[0]
2824 tree = revset.parse(expr)[0]
2828 ui.note(revset.prettyformat(tree), "\n")
2825 ui.note(revset.prettyformat(tree), "\n")
2829 newtree = revset.findaliases(ui, tree)
2826 newtree = revset.findaliases(ui, tree)
2830 if newtree != tree:
2827 if newtree != tree:
2831 ui.note(revset.prettyformat(newtree), "\n")
2828 ui.note(revset.prettyformat(newtree), "\n")
2832 if opts["optimize"]:
2829 if opts["optimize"]:
2833 weight, optimizedtree = revset.optimize(newtree, True)
2830 weight, optimizedtree = revset.optimize(newtree, True)
2834 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2831 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2835 func = revset.match(ui, expr)
2832 func = revset.match(ui, expr)
2836 for c in func(repo, revset.spanset(repo)):
2833 for c in func(repo, revset.spanset(repo)):
2837 ui.write("%s\n" % c)
2834 ui.write("%s\n" % c)
2838
2835
2839 @command('debugsetparents', [], _('REV1 [REV2]'))
2836 @command('debugsetparents', [], _('REV1 [REV2]'))
2840 def debugsetparents(ui, repo, rev1, rev2=None):
2837 def debugsetparents(ui, repo, rev1, rev2=None):
2841 """manually set the parents of the current working directory
2838 """manually set the parents of the current working directory
2842
2839
2843 This is useful for writing repository conversion tools, but should
2840 This is useful for writing repository conversion tools, but should
2844 be used with care.
2841 be used with care.
2845
2842
2846 Returns 0 on success.
2843 Returns 0 on success.
2847 """
2844 """
2848
2845
2849 r1 = scmutil.revsingle(repo, rev1).node()
2846 r1 = scmutil.revsingle(repo, rev1).node()
2850 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2847 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2851
2848
2852 wlock = repo.wlock()
2849 wlock = repo.wlock()
2853 try:
2850 try:
2854 repo.dirstate.beginparentchange()
2851 repo.dirstate.beginparentchange()
2855 repo.setparents(r1, r2)
2852 repo.setparents(r1, r2)
2856 repo.dirstate.endparentchange()
2853 repo.dirstate.endparentchange()
2857 finally:
2854 finally:
2858 wlock.release()
2855 wlock.release()
2859
2856
2860 @command('debugdirstate|debugstate',
2857 @command('debugdirstate|debugstate',
2861 [('', 'nodates', None, _('do not display the saved mtime')),
2858 [('', 'nodates', None, _('do not display the saved mtime')),
2862 ('', 'datesort', None, _('sort by saved mtime'))],
2859 ('', 'datesort', None, _('sort by saved mtime'))],
2863 _('[OPTION]...'))
2860 _('[OPTION]...'))
2864 def debugstate(ui, repo, nodates=None, datesort=None):
2861 def debugstate(ui, repo, nodates=None, datesort=None):
2865 """show the contents of the current dirstate"""
2862 """show the contents of the current dirstate"""
2866 timestr = ""
2863 timestr = ""
2867 showdate = not nodates
2864 showdate = not nodates
2868 if datesort:
2865 if datesort:
2869 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2866 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2870 else:
2867 else:
2871 keyfunc = None # sort by filename
2868 keyfunc = None # sort by filename
2872 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2869 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2873 if showdate:
2870 if showdate:
2874 if ent[3] == -1:
2871 if ent[3] == -1:
2875 # Pad or slice to locale representation
2872 # Pad or slice to locale representation
2876 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2873 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2877 time.localtime(0)))
2874 time.localtime(0)))
2878 timestr = 'unset'
2875 timestr = 'unset'
2879 timestr = (timestr[:locale_len] +
2876 timestr = (timestr[:locale_len] +
2880 ' ' * (locale_len - len(timestr)))
2877 ' ' * (locale_len - len(timestr)))
2881 else:
2878 else:
2882 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2879 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2883 time.localtime(ent[3]))
2880 time.localtime(ent[3]))
2884 if ent[1] & 020000:
2881 if ent[1] & 020000:
2885 mode = 'lnk'
2882 mode = 'lnk'
2886 else:
2883 else:
2887 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2884 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2888 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2885 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2889 for f in repo.dirstate.copies():
2886 for f in repo.dirstate.copies():
2890 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2887 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2891
2888
2892 @command('debugsub',
2889 @command('debugsub',
2893 [('r', 'rev', '',
2890 [('r', 'rev', '',
2894 _('revision to check'), _('REV'))],
2891 _('revision to check'), _('REV'))],
2895 _('[-r REV] [REV]'))
2892 _('[-r REV] [REV]'))
2896 def debugsub(ui, repo, rev=None):
2893 def debugsub(ui, repo, rev=None):
2897 ctx = scmutil.revsingle(repo, rev, None)
2894 ctx = scmutil.revsingle(repo, rev, None)
2898 for k, v in sorted(ctx.substate.items()):
2895 for k, v in sorted(ctx.substate.items()):
2899 ui.write(('path %s\n') % k)
2896 ui.write(('path %s\n') % k)
2900 ui.write((' source %s\n') % v[0])
2897 ui.write((' source %s\n') % v[0])
2901 ui.write((' revision %s\n') % v[1])
2898 ui.write((' revision %s\n') % v[1])
2902
2899
2903 @command('debugsuccessorssets',
2900 @command('debugsuccessorssets',
2904 [],
2901 [],
2905 _('[REV]'))
2902 _('[REV]'))
2906 def debugsuccessorssets(ui, repo, *revs):
2903 def debugsuccessorssets(ui, repo, *revs):
2907 """show set of successors for revision
2904 """show set of successors for revision
2908
2905
2909 A successors set of changeset A is a consistent group of revisions that
2906 A successors set of changeset A is a consistent group of revisions that
2910 succeed A. It contains non-obsolete changesets only.
2907 succeed A. It contains non-obsolete changesets only.
2911
2908
2912 In most cases a changeset A has a single successors set containing a single
2909 In most cases a changeset A has a single successors set containing a single
2913 successor (changeset A replaced by A').
2910 successor (changeset A replaced by A').
2914
2911
2915 A changeset that is made obsolete with no successors are called "pruned".
2912 A changeset that is made obsolete with no successors are called "pruned".
2916 Such changesets have no successors sets at all.
2913 Such changesets have no successors sets at all.
2917
2914
2918 A changeset that has been "split" will have a successors set containing
2915 A changeset that has been "split" will have a successors set containing
2919 more than one successor.
2916 more than one successor.
2920
2917
2921 A changeset that has been rewritten in multiple different ways is called
2918 A changeset that has been rewritten in multiple different ways is called
2922 "divergent". Such changesets have multiple successor sets (each of which
2919 "divergent". Such changesets have multiple successor sets (each of which
2923 may also be split, i.e. have multiple successors).
2920 may also be split, i.e. have multiple successors).
2924
2921
2925 Results are displayed as follows::
2922 Results are displayed as follows::
2926
2923
2927 <rev1>
2924 <rev1>
2928 <successors-1A>
2925 <successors-1A>
2929 <rev2>
2926 <rev2>
2930 <successors-2A>
2927 <successors-2A>
2931 <successors-2B1> <successors-2B2> <successors-2B3>
2928 <successors-2B1> <successors-2B2> <successors-2B3>
2932
2929
2933 Here rev2 has two possible (i.e. divergent) successors sets. The first
2930 Here rev2 has two possible (i.e. divergent) successors sets. The first
2934 holds one element, whereas the second holds three (i.e. the changeset has
2931 holds one element, whereas the second holds three (i.e. the changeset has
2935 been split).
2932 been split).
2936 """
2933 """
2937 # passed to successorssets caching computation from one call to another
2934 # passed to successorssets caching computation from one call to another
2938 cache = {}
2935 cache = {}
2939 ctx2str = str
2936 ctx2str = str
2940 node2str = short
2937 node2str = short
2941 if ui.debug():
2938 if ui.debug():
2942 def ctx2str(ctx):
2939 def ctx2str(ctx):
2943 return ctx.hex()
2940 return ctx.hex()
2944 node2str = hex
2941 node2str = hex
2945 for rev in scmutil.revrange(repo, revs):
2942 for rev in scmutil.revrange(repo, revs):
2946 ctx = repo[rev]
2943 ctx = repo[rev]
2947 ui.write('%s\n'% ctx2str(ctx))
2944 ui.write('%s\n'% ctx2str(ctx))
2948 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2945 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2949 if succsset:
2946 if succsset:
2950 ui.write(' ')
2947 ui.write(' ')
2951 ui.write(node2str(succsset[0]))
2948 ui.write(node2str(succsset[0]))
2952 for node in succsset[1:]:
2949 for node in succsset[1:]:
2953 ui.write(' ')
2950 ui.write(' ')
2954 ui.write(node2str(node))
2951 ui.write(node2str(node))
2955 ui.write('\n')
2952 ui.write('\n')
2956
2953
2957 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
2954 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'), inferrepo=True)
2958 def debugwalk(ui, repo, *pats, **opts):
2955 def debugwalk(ui, repo, *pats, **opts):
2959 """show how files match on given patterns"""
2956 """show how files match on given patterns"""
2960 m = scmutil.match(repo[None], pats, opts)
2957 m = scmutil.match(repo[None], pats, opts)
2961 items = list(repo.walk(m))
2958 items = list(repo.walk(m))
2962 if not items:
2959 if not items:
2963 return
2960 return
2964 f = lambda fn: fn
2961 f = lambda fn: fn
2965 if ui.configbool('ui', 'slash') and os.sep != '/':
2962 if ui.configbool('ui', 'slash') and os.sep != '/':
2966 f = lambda fn: util.normpath(fn)
2963 f = lambda fn: util.normpath(fn)
2967 fmt = 'f %%-%ds %%-%ds %%s' % (
2964 fmt = 'f %%-%ds %%-%ds %%s' % (
2968 max([len(abs) for abs in items]),
2965 max([len(abs) for abs in items]),
2969 max([len(m.rel(abs)) for abs in items]))
2966 max([len(m.rel(abs)) for abs in items]))
2970 for abs in items:
2967 for abs in items:
2971 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2968 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2972 ui.write("%s\n" % line.rstrip())
2969 ui.write("%s\n" % line.rstrip())
2973
2970
2974 @command('debugwireargs',
2971 @command('debugwireargs',
2975 [('', 'three', '', 'three'),
2972 [('', 'three', '', 'three'),
2976 ('', 'four', '', 'four'),
2973 ('', 'four', '', 'four'),
2977 ('', 'five', '', 'five'),
2974 ('', 'five', '', 'five'),
2978 ] + remoteopts,
2975 ] + remoteopts,
2979 _('REPO [OPTIONS]... [ONE [TWO]]'),
2976 _('REPO [OPTIONS]... [ONE [TWO]]'),
2980 norepo=True)
2977 norepo=True)
2981 def debugwireargs(ui, repopath, *vals, **opts):
2978 def debugwireargs(ui, repopath, *vals, **opts):
2982 repo = hg.peer(ui, opts, repopath)
2979 repo = hg.peer(ui, opts, repopath)
2983 for opt in remoteopts:
2980 for opt in remoteopts:
2984 del opts[opt[1]]
2981 del opts[opt[1]]
2985 args = {}
2982 args = {}
2986 for k, v in opts.iteritems():
2983 for k, v in opts.iteritems():
2987 if v:
2984 if v:
2988 args[k] = v
2985 args[k] = v
2989 # run twice to check that we don't mess up the stream for the next command
2986 # run twice to check that we don't mess up the stream for the next command
2990 res1 = repo.debugwireargs(*vals, **args)
2987 res1 = repo.debugwireargs(*vals, **args)
2991 res2 = repo.debugwireargs(*vals, **args)
2988 res2 = repo.debugwireargs(*vals, **args)
2992 ui.write("%s\n" % res1)
2989 ui.write("%s\n" % res1)
2993 if res1 != res2:
2990 if res1 != res2:
2994 ui.warn("%s\n" % res2)
2991 ui.warn("%s\n" % res2)
2995
2992
2996 @command('^diff',
2993 @command('^diff',
2997 [('r', 'rev', [], _('revision'), _('REV')),
2994 [('r', 'rev', [], _('revision'), _('REV')),
2998 ('c', 'change', '', _('change made by revision'), _('REV'))
2995 ('c', 'change', '', _('change made by revision'), _('REV'))
2999 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2996 ] + diffopts + diffopts2 + walkopts + subrepoopts,
3000 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
2997 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
3001 inferrepo=True)
2998 inferrepo=True)
3002 def diff(ui, repo, *pats, **opts):
2999 def diff(ui, repo, *pats, **opts):
3003 """diff repository (or selected files)
3000 """diff repository (or selected files)
3004
3001
3005 Show differences between revisions for the specified files.
3002 Show differences between revisions for the specified files.
3006
3003
3007 Differences between files are shown using the unified diff format.
3004 Differences between files are shown using the unified diff format.
3008
3005
3009 .. note::
3006 .. note::
3010
3007
3011 diff may generate unexpected results for merges, as it will
3008 diff may generate unexpected results for merges, as it will
3012 default to comparing against the working directory's first
3009 default to comparing against the working directory's first
3013 parent changeset if no revisions are specified.
3010 parent changeset if no revisions are specified.
3014
3011
3015 When two revision arguments are given, then changes are shown
3012 When two revision arguments are given, then changes are shown
3016 between those revisions. If only one revision is specified then
3013 between those revisions. If only one revision is specified then
3017 that revision is compared to the working directory, and, when no
3014 that revision is compared to the working directory, and, when no
3018 revisions are specified, the working directory files are compared
3015 revisions are specified, the working directory files are compared
3019 to its parent.
3016 to its parent.
3020
3017
3021 Alternatively you can specify -c/--change with a revision to see
3018 Alternatively you can specify -c/--change with a revision to see
3022 the changes in that changeset relative to its first parent.
3019 the changes in that changeset relative to its first parent.
3023
3020
3024 Without the -a/--text option, diff will avoid generating diffs of
3021 Without the -a/--text option, diff will avoid generating diffs of
3025 files it detects as binary. With -a, diff will generate a diff
3022 files it detects as binary. With -a, diff will generate a diff
3026 anyway, probably with undesirable results.
3023 anyway, probably with undesirable results.
3027
3024
3028 Use the -g/--git option to generate diffs in the git extended diff
3025 Use the -g/--git option to generate diffs in the git extended diff
3029 format. For more information, read :hg:`help diffs`.
3026 format. For more information, read :hg:`help diffs`.
3030
3027
3031 .. container:: verbose
3028 .. container:: verbose
3032
3029
3033 Examples:
3030 Examples:
3034
3031
3035 - compare a file in the current working directory to its parent::
3032 - compare a file in the current working directory to its parent::
3036
3033
3037 hg diff foo.c
3034 hg diff foo.c
3038
3035
3039 - compare two historical versions of a directory, with rename info::
3036 - compare two historical versions of a directory, with rename info::
3040
3037
3041 hg diff --git -r 1.0:1.2 lib/
3038 hg diff --git -r 1.0:1.2 lib/
3042
3039
3043 - get change stats relative to the last change on some date::
3040 - get change stats relative to the last change on some date::
3044
3041
3045 hg diff --stat -r "date('may 2')"
3042 hg diff --stat -r "date('may 2')"
3046
3043
3047 - diff all newly-added files that contain a keyword::
3044 - diff all newly-added files that contain a keyword::
3048
3045
3049 hg diff "set:added() and grep(GNU)"
3046 hg diff "set:added() and grep(GNU)"
3050
3047
3051 - compare a revision and its parents::
3048 - compare a revision and its parents::
3052
3049
3053 hg diff -c 9353 # compare against first parent
3050 hg diff -c 9353 # compare against first parent
3054 hg diff -r 9353^:9353 # same using revset syntax
3051 hg diff -r 9353^:9353 # same using revset syntax
3055 hg diff -r 9353^2:9353 # compare against the second parent
3052 hg diff -r 9353^2:9353 # compare against the second parent
3056
3053
3057 Returns 0 on success.
3054 Returns 0 on success.
3058 """
3055 """
3059
3056
3060 revs = opts.get('rev')
3057 revs = opts.get('rev')
3061 change = opts.get('change')
3058 change = opts.get('change')
3062 stat = opts.get('stat')
3059 stat = opts.get('stat')
3063 reverse = opts.get('reverse')
3060 reverse = opts.get('reverse')
3064
3061
3065 if revs and change:
3062 if revs and change:
3066 msg = _('cannot specify --rev and --change at the same time')
3063 msg = _('cannot specify --rev and --change at the same time')
3067 raise util.Abort(msg)
3064 raise util.Abort(msg)
3068 elif change:
3065 elif change:
3069 node2 = scmutil.revsingle(repo, change, None).node()
3066 node2 = scmutil.revsingle(repo, change, None).node()
3070 node1 = repo[node2].p1().node()
3067 node1 = repo[node2].p1().node()
3071 else:
3068 else:
3072 node1, node2 = scmutil.revpair(repo, revs)
3069 node1, node2 = scmutil.revpair(repo, revs)
3073
3070
3074 if reverse:
3071 if reverse:
3075 node1, node2 = node2, node1
3072 node1, node2 = node2, node1
3076
3073
3077 diffopts = patch.diffopts(ui, opts)
3074 diffopts = patch.diffopts(ui, opts)
3078 m = scmutil.match(repo[node2], pats, opts)
3075 m = scmutil.match(repo[node2], pats, opts)
3079 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3076 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
3080 listsubrepos=opts.get('subrepos'))
3077 listsubrepos=opts.get('subrepos'))
3081
3078
3082 @command('^export',
3079 @command('^export',
3083 [('o', 'output', '',
3080 [('o', 'output', '',
3084 _('print output to file with formatted name'), _('FORMAT')),
3081 _('print output to file with formatted name'), _('FORMAT')),
3085 ('', 'switch-parent', None, _('diff against the second parent')),
3082 ('', 'switch-parent', None, _('diff against the second parent')),
3086 ('r', 'rev', [], _('revisions to export'), _('REV')),
3083 ('r', 'rev', [], _('revisions to export'), _('REV')),
3087 ] + diffopts,
3084 ] + diffopts,
3088 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3085 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
3089 def export(ui, repo, *changesets, **opts):
3086 def export(ui, repo, *changesets, **opts):
3090 """dump the header and diffs for one or more changesets
3087 """dump the header and diffs for one or more changesets
3091
3088
3092 Print the changeset header and diffs for one or more revisions.
3089 Print the changeset header and diffs for one or more revisions.
3093 If no revision is given, the parent of the working directory is used.
3090 If no revision is given, the parent of the working directory is used.
3094
3091
3095 The information shown in the changeset header is: author, date,
3092 The information shown in the changeset header is: author, date,
3096 branch name (if non-default), changeset hash, parent(s) and commit
3093 branch name (if non-default), changeset hash, parent(s) and commit
3097 comment.
3094 comment.
3098
3095
3099 .. note::
3096 .. note::
3100
3097
3101 export may generate unexpected diff output for merge
3098 export may generate unexpected diff output for merge
3102 changesets, as it will compare the merge changeset against its
3099 changesets, as it will compare the merge changeset against its
3103 first parent only.
3100 first parent only.
3104
3101
3105 Output may be to a file, in which case the name of the file is
3102 Output may be to a file, in which case the name of the file is
3106 given using a format string. The formatting rules are as follows:
3103 given using a format string. The formatting rules are as follows:
3107
3104
3108 :``%%``: literal "%" character
3105 :``%%``: literal "%" character
3109 :``%H``: changeset hash (40 hexadecimal digits)
3106 :``%H``: changeset hash (40 hexadecimal digits)
3110 :``%N``: number of patches being generated
3107 :``%N``: number of patches being generated
3111 :``%R``: changeset revision number
3108 :``%R``: changeset revision number
3112 :``%b``: basename of the exporting repository
3109 :``%b``: basename of the exporting repository
3113 :``%h``: short-form changeset hash (12 hexadecimal digits)
3110 :``%h``: short-form changeset hash (12 hexadecimal digits)
3114 :``%m``: first line of the commit message (only alphanumeric characters)
3111 :``%m``: first line of the commit message (only alphanumeric characters)
3115 :``%n``: zero-padded sequence number, starting at 1
3112 :``%n``: zero-padded sequence number, starting at 1
3116 :``%r``: zero-padded changeset revision number
3113 :``%r``: zero-padded changeset revision number
3117
3114
3118 Without the -a/--text option, export will avoid generating diffs
3115 Without the -a/--text option, export will avoid generating diffs
3119 of files it detects as binary. With -a, export will generate a
3116 of files it detects as binary. With -a, export will generate a
3120 diff anyway, probably with undesirable results.
3117 diff anyway, probably with undesirable results.
3121
3118
3122 Use the -g/--git option to generate diffs in the git extended diff
3119 Use the -g/--git option to generate diffs in the git extended diff
3123 format. See :hg:`help diffs` for more information.
3120 format. See :hg:`help diffs` for more information.
3124
3121
3125 With the --switch-parent option, the diff will be against the
3122 With the --switch-parent option, the diff will be against the
3126 second parent. It can be useful to review a merge.
3123 second parent. It can be useful to review a merge.
3127
3124
3128 .. container:: verbose
3125 .. container:: verbose
3129
3126
3130 Examples:
3127 Examples:
3131
3128
3132 - use export and import to transplant a bugfix to the current
3129 - use export and import to transplant a bugfix to the current
3133 branch::
3130 branch::
3134
3131
3135 hg export -r 9353 | hg import -
3132 hg export -r 9353 | hg import -
3136
3133
3137 - export all the changesets between two revisions to a file with
3134 - export all the changesets between two revisions to a file with
3138 rename information::
3135 rename information::
3139
3136
3140 hg export --git -r 123:150 > changes.txt
3137 hg export --git -r 123:150 > changes.txt
3141
3138
3142 - split outgoing changes into a series of patches with
3139 - split outgoing changes into a series of patches with
3143 descriptive names::
3140 descriptive names::
3144
3141
3145 hg export -r "outgoing()" -o "%n-%m.patch"
3142 hg export -r "outgoing()" -o "%n-%m.patch"
3146
3143
3147 Returns 0 on success.
3144 Returns 0 on success.
3148 """
3145 """
3149 changesets += tuple(opts.get('rev', []))
3146 changesets += tuple(opts.get('rev', []))
3150 if not changesets:
3147 if not changesets:
3151 changesets = ['.']
3148 changesets = ['.']
3152 revs = scmutil.revrange(repo, changesets)
3149 revs = scmutil.revrange(repo, changesets)
3153 if not revs:
3150 if not revs:
3154 raise util.Abort(_("export requires at least one changeset"))
3151 raise util.Abort(_("export requires at least one changeset"))
3155 if len(revs) > 1:
3152 if len(revs) > 1:
3156 ui.note(_('exporting patches:\n'))
3153 ui.note(_('exporting patches:\n'))
3157 else:
3154 else:
3158 ui.note(_('exporting patch:\n'))
3155 ui.note(_('exporting patch:\n'))
3159 cmdutil.export(repo, revs, template=opts.get('output'),
3156 cmdutil.export(repo, revs, template=opts.get('output'),
3160 switch_parent=opts.get('switch_parent'),
3157 switch_parent=opts.get('switch_parent'),
3161 opts=patch.diffopts(ui, opts))
3158 opts=patch.diffopts(ui, opts))
3162
3159
3163 @command('files',
3160 @command('files',
3164 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3161 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3165 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3162 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3166 ] + walkopts + formatteropts,
3163 ] + walkopts + formatteropts,
3167 _('[OPTION]... [PATTERN]...'))
3164 _('[OPTION]... [PATTERN]...'))
3168 def files(ui, repo, *pats, **opts):
3165 def files(ui, repo, *pats, **opts):
3169 """list tracked files
3166 """list tracked files
3170
3167
3171 Print files under Mercurial control in the working directory or
3168 Print files under Mercurial control in the working directory or
3172 specified revision whose names match the given patterns (excluding
3169 specified revision whose names match the given patterns (excluding
3173 removed files).
3170 removed files).
3174
3171
3175 If no patterns are given to match, this command prints the names
3172 If no patterns are given to match, this command prints the names
3176 of all files under Mercurial control in the working copy.
3173 of all files under Mercurial control in the working copy.
3177
3174
3178 .. container:: verbose
3175 .. container:: verbose
3179
3176
3180 Examples:
3177 Examples:
3181
3178
3182 - list all files under the current directory::
3179 - list all files under the current directory::
3183
3180
3184 hg files .
3181 hg files .
3185
3182
3186 - shows sizes and flags for current revision::
3183 - shows sizes and flags for current revision::
3187
3184
3188 hg files -vr .
3185 hg files -vr .
3189
3186
3190 - list all files named README::
3187 - list all files named README::
3191
3188
3192 hg files -I "**/README"
3189 hg files -I "**/README"
3193
3190
3194 - list all binary files::
3191 - list all binary files::
3195
3192
3196 hg files "set:binary()"
3193 hg files "set:binary()"
3197
3194
3198 - find files containing a regular expression:
3195 - find files containing a regular expression:
3199
3196
3200 hg files "set:grep('bob')"
3197 hg files "set:grep('bob')"
3201
3198
3202 - search tracked file contents with xargs and grep::
3199 - search tracked file contents with xargs and grep::
3203
3200
3204 hg files -0 | xargs -0 grep foo
3201 hg files -0 | xargs -0 grep foo
3205
3202
3206 See :hg:'help pattern' and :hg:'help revsets' for more information
3203 See :hg:'help pattern' and :hg:'help revsets' for more information
3207 on specifying file patterns.
3204 on specifying file patterns.
3208
3205
3209 Returns 0 if a match is found, 1 otherwise.
3206 Returns 0 if a match is found, 1 otherwise.
3210
3207
3211 """
3208 """
3212 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3209 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3213 rev = ctx.rev()
3210 rev = ctx.rev()
3214 ret = 1
3211 ret = 1
3215
3212
3216 end = '\n'
3213 end = '\n'
3217 if opts.get('print0'):
3214 if opts.get('print0'):
3218 end = '\0'
3215 end = '\0'
3219 fm = ui.formatter('files', opts)
3216 fm = ui.formatter('files', opts)
3220 fmt = '%s' + end
3217 fmt = '%s' + end
3221
3218
3222 m = scmutil.match(ctx, pats, opts)
3219 m = scmutil.match(ctx, pats, opts)
3223 ds = repo.dirstate
3220 ds = repo.dirstate
3224 for f in ctx.matches(m):
3221 for f in ctx.matches(m):
3225 if rev is None and ds[f] == 'r':
3222 if rev is None and ds[f] == 'r':
3226 continue
3223 continue
3227 fm.startitem()
3224 fm.startitem()
3228 if ui.verbose:
3225 if ui.verbose:
3229 fc = ctx[f]
3226 fc = ctx[f]
3230 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
3227 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
3231 fm.data(abspath=f)
3228 fm.data(abspath=f)
3232 fm.write('path', fmt, m.rel(f))
3229 fm.write('path', fmt, m.rel(f))
3233 ret = 0
3230 ret = 0
3234
3231
3235 fm.end()
3232 fm.end()
3236
3233
3237 return ret
3234 return ret
3238
3235
3239 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3236 @command('^forget', walkopts, _('[OPTION]... FILE...'), inferrepo=True)
3240 def forget(ui, repo, *pats, **opts):
3237 def forget(ui, repo, *pats, **opts):
3241 """forget the specified files on the next commit
3238 """forget the specified files on the next commit
3242
3239
3243 Mark the specified files so they will no longer be tracked
3240 Mark the specified files so they will no longer be tracked
3244 after the next commit.
3241 after the next commit.
3245
3242
3246 This only removes files from the current branch, not from the
3243 This only removes files from the current branch, not from the
3247 entire project history, and it does not delete them from the
3244 entire project history, and it does not delete them from the
3248 working directory.
3245 working directory.
3249
3246
3250 To undo a forget before the next commit, see :hg:`add`.
3247 To undo a forget before the next commit, see :hg:`add`.
3251
3248
3252 .. container:: verbose
3249 .. container:: verbose
3253
3250
3254 Examples:
3251 Examples:
3255
3252
3256 - forget newly-added binary files::
3253 - forget newly-added binary files::
3257
3254
3258 hg forget "set:added() and binary()"
3255 hg forget "set:added() and binary()"
3259
3256
3260 - forget files that would be excluded by .hgignore::
3257 - forget files that would be excluded by .hgignore::
3261
3258
3262 hg forget "set:hgignore()"
3259 hg forget "set:hgignore()"
3263
3260
3264 Returns 0 on success.
3261 Returns 0 on success.
3265 """
3262 """
3266
3263
3267 if not pats:
3264 if not pats:
3268 raise util.Abort(_('no files specified'))
3265 raise util.Abort(_('no files specified'))
3269
3266
3270 m = scmutil.match(repo[None], pats, opts)
3267 m = scmutil.match(repo[None], pats, opts)
3271 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3268 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3272 return rejected and 1 or 0
3269 return rejected and 1 or 0
3273
3270
3274 @command(
3271 @command(
3275 'graft',
3272 'graft',
3276 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3273 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3277 ('c', 'continue', False, _('resume interrupted graft')),
3274 ('c', 'continue', False, _('resume interrupted graft')),
3278 ('e', 'edit', False, _('invoke editor on commit messages')),
3275 ('e', 'edit', False, _('invoke editor on commit messages')),
3279 ('', 'log', None, _('append graft info to log message')),
3276 ('', 'log', None, _('append graft info to log message')),
3280 ('f', 'force', False, _('force graft')),
3277 ('f', 'force', False, _('force graft')),
3281 ('D', 'currentdate', False,
3278 ('D', 'currentdate', False,
3282 _('record the current date as commit date')),
3279 _('record the current date as commit date')),
3283 ('U', 'currentuser', False,
3280 ('U', 'currentuser', False,
3284 _('record the current user as committer'), _('DATE'))]
3281 _('record the current user as committer'), _('DATE'))]
3285 + commitopts2 + mergetoolopts + dryrunopts,
3282 + commitopts2 + mergetoolopts + dryrunopts,
3286 _('[OPTION]... [-r] REV...'))
3283 _('[OPTION]... [-r] REV...'))
3287 def graft(ui, repo, *revs, **opts):
3284 def graft(ui, repo, *revs, **opts):
3288 '''copy changes from other branches onto the current branch
3285 '''copy changes from other branches onto the current branch
3289
3286
3290 This command uses Mercurial's merge logic to copy individual
3287 This command uses Mercurial's merge logic to copy individual
3291 changes from other branches without merging branches in the
3288 changes from other branches without merging branches in the
3292 history graph. This is sometimes known as 'backporting' or
3289 history graph. This is sometimes known as 'backporting' or
3293 'cherry-picking'. By default, graft will copy user, date, and
3290 'cherry-picking'. By default, graft will copy user, date, and
3294 description from the source changesets.
3291 description from the source changesets.
3295
3292
3296 Changesets that are ancestors of the current revision, that have
3293 Changesets that are ancestors of the current revision, that have
3297 already been grafted, or that are merges will be skipped.
3294 already been grafted, or that are merges will be skipped.
3298
3295
3299 If --log is specified, log messages will have a comment appended
3296 If --log is specified, log messages will have a comment appended
3300 of the form::
3297 of the form::
3301
3298
3302 (grafted from CHANGESETHASH)
3299 (grafted from CHANGESETHASH)
3303
3300
3304 If --force is specified, revisions will be grafted even if they
3301 If --force is specified, revisions will be grafted even if they
3305 are already ancestors of or have been grafted to the destination.
3302 are already ancestors of or have been grafted to the destination.
3306 This is useful when the revisions have since been backed out.
3303 This is useful when the revisions have since been backed out.
3307
3304
3308 If a graft merge results in conflicts, the graft process is
3305 If a graft merge results in conflicts, the graft process is
3309 interrupted so that the current merge can be manually resolved.
3306 interrupted so that the current merge can be manually resolved.
3310 Once all conflicts are addressed, the graft process can be
3307 Once all conflicts are addressed, the graft process can be
3311 continued with the -c/--continue option.
3308 continued with the -c/--continue option.
3312
3309
3313 .. note::
3310 .. note::
3314
3311
3315 The -c/--continue option does not reapply earlier options, except
3312 The -c/--continue option does not reapply earlier options, except
3316 for --force.
3313 for --force.
3317
3314
3318 .. container:: verbose
3315 .. container:: verbose
3319
3316
3320 Examples:
3317 Examples:
3321
3318
3322 - copy a single change to the stable branch and edit its description::
3319 - copy a single change to the stable branch and edit its description::
3323
3320
3324 hg update stable
3321 hg update stable
3325 hg graft --edit 9393
3322 hg graft --edit 9393
3326
3323
3327 - graft a range of changesets with one exception, updating dates::
3324 - graft a range of changesets with one exception, updating dates::
3328
3325
3329 hg graft -D "2085::2093 and not 2091"
3326 hg graft -D "2085::2093 and not 2091"
3330
3327
3331 - continue a graft after resolving conflicts::
3328 - continue a graft after resolving conflicts::
3332
3329
3333 hg graft -c
3330 hg graft -c
3334
3331
3335 - show the source of a grafted changeset::
3332 - show the source of a grafted changeset::
3336
3333
3337 hg log --debug -r .
3334 hg log --debug -r .
3338
3335
3339 See :hg:`help revisions` and :hg:`help revsets` for more about
3336 See :hg:`help revisions` and :hg:`help revsets` for more about
3340 specifying revisions.
3337 specifying revisions.
3341
3338
3342 Returns 0 on successful completion.
3339 Returns 0 on successful completion.
3343 '''
3340 '''
3344
3341
3345 revs = list(revs)
3342 revs = list(revs)
3346 revs.extend(opts['rev'])
3343 revs.extend(opts['rev'])
3347
3344
3348 if not opts.get('user') and opts.get('currentuser'):
3345 if not opts.get('user') and opts.get('currentuser'):
3349 opts['user'] = ui.username()
3346 opts['user'] = ui.username()
3350 if not opts.get('date') and opts.get('currentdate'):
3347 if not opts.get('date') and opts.get('currentdate'):
3351 opts['date'] = "%d %d" % util.makedate()
3348 opts['date'] = "%d %d" % util.makedate()
3352
3349
3353 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3350 editor = cmdutil.getcommiteditor(editform='graft', **opts)
3354
3351
3355 cont = False
3352 cont = False
3356 if opts['continue']:
3353 if opts['continue']:
3357 cont = True
3354 cont = True
3358 if revs:
3355 if revs:
3359 raise util.Abort(_("can't specify --continue and revisions"))
3356 raise util.Abort(_("can't specify --continue and revisions"))
3360 # read in unfinished revisions
3357 # read in unfinished revisions
3361 try:
3358 try:
3362 nodes = repo.opener.read('graftstate').splitlines()
3359 nodes = repo.opener.read('graftstate').splitlines()
3363 revs = [repo[node].rev() for node in nodes]
3360 revs = [repo[node].rev() for node in nodes]
3364 except IOError, inst:
3361 except IOError, inst:
3365 if inst.errno != errno.ENOENT:
3362 if inst.errno != errno.ENOENT:
3366 raise
3363 raise
3367 raise util.Abort(_("no graft state found, can't continue"))
3364 raise util.Abort(_("no graft state found, can't continue"))
3368 else:
3365 else:
3369 cmdutil.checkunfinished(repo)
3366 cmdutil.checkunfinished(repo)
3370 cmdutil.bailifchanged(repo)
3367 cmdutil.bailifchanged(repo)
3371 if not revs:
3368 if not revs:
3372 raise util.Abort(_('no revisions specified'))
3369 raise util.Abort(_('no revisions specified'))
3373 revs = scmutil.revrange(repo, revs)
3370 revs = scmutil.revrange(repo, revs)
3374
3371
3375 # check for merges
3372 # check for merges
3376 for rev in repo.revs('%ld and merge()', revs):
3373 for rev in repo.revs('%ld and merge()', revs):
3377 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3374 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3378 revs.remove(rev)
3375 revs.remove(rev)
3379 if not revs:
3376 if not revs:
3380 return -1
3377 return -1
3381
3378
3382 # Don't check in the --continue case, in effect retaining --force across
3379 # Don't check in the --continue case, in effect retaining --force across
3383 # --continues. That's because without --force, any revisions we decided to
3380 # --continues. That's because without --force, any revisions we decided to
3384 # skip would have been filtered out here, so they wouldn't have made their
3381 # skip would have been filtered out here, so they wouldn't have made their
3385 # way to the graftstate. With --force, any revisions we would have otherwise
3382 # way to the graftstate. With --force, any revisions we would have otherwise
3386 # skipped would not have been filtered out, and if they hadn't been applied
3383 # skipped would not have been filtered out, and if they hadn't been applied
3387 # already, they'd have been in the graftstate.
3384 # already, they'd have been in the graftstate.
3388 if not (cont or opts.get('force')):
3385 if not (cont or opts.get('force')):
3389 # check for ancestors of dest branch
3386 # check for ancestors of dest branch
3390 crev = repo['.'].rev()
3387 crev = repo['.'].rev()
3391 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3388 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3392 # Cannot use x.remove(y) on smart set, this has to be a list.
3389 # Cannot use x.remove(y) on smart set, this has to be a list.
3393 # XXX make this lazy in the future
3390 # XXX make this lazy in the future
3394 revs = list(revs)
3391 revs = list(revs)
3395 # don't mutate while iterating, create a copy
3392 # don't mutate while iterating, create a copy
3396 for rev in list(revs):
3393 for rev in list(revs):
3397 if rev in ancestors:
3394 if rev in ancestors:
3398 ui.warn(_('skipping ancestor revision %s\n') % rev)
3395 ui.warn(_('skipping ancestor revision %s\n') % rev)
3399 # XXX remove on list is slow
3396 # XXX remove on list is slow
3400 revs.remove(rev)
3397 revs.remove(rev)
3401 if not revs:
3398 if not revs:
3402 return -1
3399 return -1
3403
3400
3404 # analyze revs for earlier grafts
3401 # analyze revs for earlier grafts
3405 ids = {}
3402 ids = {}
3406 for ctx in repo.set("%ld", revs):
3403 for ctx in repo.set("%ld", revs):
3407 ids[ctx.hex()] = ctx.rev()
3404 ids[ctx.hex()] = ctx.rev()
3408 n = ctx.extra().get('source')
3405 n = ctx.extra().get('source')
3409 if n:
3406 if n:
3410 ids[n] = ctx.rev()
3407 ids[n] = ctx.rev()
3411
3408
3412 # check ancestors for earlier grafts
3409 # check ancestors for earlier grafts
3413 ui.debug('scanning for duplicate grafts\n')
3410 ui.debug('scanning for duplicate grafts\n')
3414
3411
3415 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3412 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3416 ctx = repo[rev]
3413 ctx = repo[rev]
3417 n = ctx.extra().get('source')
3414 n = ctx.extra().get('source')
3418 if n in ids:
3415 if n in ids:
3419 try:
3416 try:
3420 r = repo[n].rev()
3417 r = repo[n].rev()
3421 except error.RepoLookupError:
3418 except error.RepoLookupError:
3422 r = None
3419 r = None
3423 if r in revs:
3420 if r in revs:
3424 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3421 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3425 % (r, rev))
3422 % (r, rev))
3426 revs.remove(r)
3423 revs.remove(r)
3427 elif ids[n] in revs:
3424 elif ids[n] in revs:
3428 if r is None:
3425 if r is None:
3429 ui.warn(_('skipping already grafted revision %s '
3426 ui.warn(_('skipping already grafted revision %s '
3430 '(%s also has unknown origin %s)\n')
3427 '(%s also has unknown origin %s)\n')
3431 % (ids[n], rev, n))
3428 % (ids[n], rev, n))
3432 else:
3429 else:
3433 ui.warn(_('skipping already grafted revision %s '
3430 ui.warn(_('skipping already grafted revision %s '
3434 '(%s also has origin %d)\n')
3431 '(%s also has origin %d)\n')
3435 % (ids[n], rev, r))
3432 % (ids[n], rev, r))
3436 revs.remove(ids[n])
3433 revs.remove(ids[n])
3437 elif ctx.hex() in ids:
3434 elif ctx.hex() in ids:
3438 r = ids[ctx.hex()]
3435 r = ids[ctx.hex()]
3439 ui.warn(_('skipping already grafted revision %s '
3436 ui.warn(_('skipping already grafted revision %s '
3440 '(was grafted from %d)\n') % (r, rev))
3437 '(was grafted from %d)\n') % (r, rev))
3441 revs.remove(r)
3438 revs.remove(r)
3442 if not revs:
3439 if not revs:
3443 return -1
3440 return -1
3444
3441
3445 wlock = repo.wlock()
3442 wlock = repo.wlock()
3446 try:
3443 try:
3447 current = repo['.']
3444 current = repo['.']
3448 for pos, ctx in enumerate(repo.set("%ld", revs)):
3445 for pos, ctx in enumerate(repo.set("%ld", revs)):
3449
3446
3450 ui.status(_('grafting revision %s\n') % ctx.rev())
3447 ui.status(_('grafting revision %s\n') % ctx.rev())
3451 if opts.get('dry_run'):
3448 if opts.get('dry_run'):
3452 continue
3449 continue
3453
3450
3454 source = ctx.extra().get('source')
3451 source = ctx.extra().get('source')
3455 if not source:
3452 if not source:
3456 source = ctx.hex()
3453 source = ctx.hex()
3457 extra = {'source': source}
3454 extra = {'source': source}
3458 user = ctx.user()
3455 user = ctx.user()
3459 if opts.get('user'):
3456 if opts.get('user'):
3460 user = opts['user']
3457 user = opts['user']
3461 date = ctx.date()
3458 date = ctx.date()
3462 if opts.get('date'):
3459 if opts.get('date'):
3463 date = opts['date']
3460 date = opts['date']
3464 message = ctx.description()
3461 message = ctx.description()
3465 if opts.get('log'):
3462 if opts.get('log'):
3466 message += '\n(grafted from %s)' % ctx.hex()
3463 message += '\n(grafted from %s)' % ctx.hex()
3467
3464
3468 # we don't merge the first commit when continuing
3465 # we don't merge the first commit when continuing
3469 if not cont:
3466 if not cont:
3470 # perform the graft merge with p1(rev) as 'ancestor'
3467 # perform the graft merge with p1(rev) as 'ancestor'
3471 try:
3468 try:
3472 # ui.forcemerge is an internal variable, do not document
3469 # ui.forcemerge is an internal variable, do not document
3473 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3470 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3474 'graft')
3471 'graft')
3475 stats = mergemod.update(repo, ctx.node(), True, True, False,
3472 stats = mergemod.update(repo, ctx.node(), True, True, False,
3476 ctx.p1().node(),
3473 ctx.p1().node(),
3477 labels=['local', 'graft'])
3474 labels=['local', 'graft'])
3478 finally:
3475 finally:
3479 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3476 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3480 # report any conflicts
3477 # report any conflicts
3481 if stats and stats[3] > 0:
3478 if stats and stats[3] > 0:
3482 # write out state for --continue
3479 # write out state for --continue
3483 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3480 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3484 repo.opener.write('graftstate', ''.join(nodelines))
3481 repo.opener.write('graftstate', ''.join(nodelines))
3485 raise util.Abort(
3482 raise util.Abort(
3486 _("unresolved conflicts, can't continue"),
3483 _("unresolved conflicts, can't continue"),
3487 hint=_('use hg resolve and hg graft --continue'))
3484 hint=_('use hg resolve and hg graft --continue'))
3488 else:
3485 else:
3489 cont = False
3486 cont = False
3490
3487
3491 # drop the second merge parent
3488 # drop the second merge parent
3492 repo.dirstate.beginparentchange()
3489 repo.dirstate.beginparentchange()
3493 repo.setparents(current.node(), nullid)
3490 repo.setparents(current.node(), nullid)
3494 repo.dirstate.write()
3491 repo.dirstate.write()
3495 # fix up dirstate for copies and renames
3492 # fix up dirstate for copies and renames
3496 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3493 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3497 repo.dirstate.endparentchange()
3494 repo.dirstate.endparentchange()
3498
3495
3499 # commit
3496 # commit
3500 node = repo.commit(text=message, user=user,
3497 node = repo.commit(text=message, user=user,
3501 date=date, extra=extra, editor=editor)
3498 date=date, extra=extra, editor=editor)
3502 if node is None:
3499 if node is None:
3503 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3500 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3504 else:
3501 else:
3505 current = repo[node]
3502 current = repo[node]
3506 finally:
3503 finally:
3507 wlock.release()
3504 wlock.release()
3508
3505
3509 # remove state when we complete successfully
3506 # remove state when we complete successfully
3510 if not opts.get('dry_run'):
3507 if not opts.get('dry_run'):
3511 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3508 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3512
3509
3513 return 0
3510 return 0
3514
3511
3515 @command('grep',
3512 @command('grep',
3516 [('0', 'print0', None, _('end fields with NUL')),
3513 [('0', 'print0', None, _('end fields with NUL')),
3517 ('', 'all', None, _('print all revisions that match')),
3514 ('', 'all', None, _('print all revisions that match')),
3518 ('a', 'text', None, _('treat all files as text')),
3515 ('a', 'text', None, _('treat all files as text')),
3519 ('f', 'follow', None,
3516 ('f', 'follow', None,
3520 _('follow changeset history,'
3517 _('follow changeset history,'
3521 ' or file history across copies and renames')),
3518 ' or file history across copies and renames')),
3522 ('i', 'ignore-case', None, _('ignore case when matching')),
3519 ('i', 'ignore-case', None, _('ignore case when matching')),
3523 ('l', 'files-with-matches', None,
3520 ('l', 'files-with-matches', None,
3524 _('print only filenames and revisions that match')),
3521 _('print only filenames and revisions that match')),
3525 ('n', 'line-number', None, _('print matching line numbers')),
3522 ('n', 'line-number', None, _('print matching line numbers')),
3526 ('r', 'rev', [],
3523 ('r', 'rev', [],
3527 _('only search files changed within revision range'), _('REV')),
3524 _('only search files changed within revision range'), _('REV')),
3528 ('u', 'user', None, _('list the author (long with -v)')),
3525 ('u', 'user', None, _('list the author (long with -v)')),
3529 ('d', 'date', None, _('list the date (short with -q)')),
3526 ('d', 'date', None, _('list the date (short with -q)')),
3530 ] + walkopts,
3527 ] + walkopts,
3531 _('[OPTION]... PATTERN [FILE]...'),
3528 _('[OPTION]... PATTERN [FILE]...'),
3532 inferrepo=True)
3529 inferrepo=True)
3533 def grep(ui, repo, pattern, *pats, **opts):
3530 def grep(ui, repo, pattern, *pats, **opts):
3534 """search for a pattern in specified files and revisions
3531 """search for a pattern in specified files and revisions
3535
3532
3536 Search revisions of files for a regular expression.
3533 Search revisions of files for a regular expression.
3537
3534
3538 This command behaves differently than Unix grep. It only accepts
3535 This command behaves differently than Unix grep. It only accepts
3539 Python/Perl regexps. It searches repository history, not the
3536 Python/Perl regexps. It searches repository history, not the
3540 working directory. It always prints the revision number in which a
3537 working directory. It always prints the revision number in which a
3541 match appears.
3538 match appears.
3542
3539
3543 By default, grep only prints output for the first revision of a
3540 By default, grep only prints output for the first revision of a
3544 file in which it finds a match. To get it to print every revision
3541 file in which it finds a match. To get it to print every revision
3545 that contains a change in match status ("-" for a match that
3542 that contains a change in match status ("-" for a match that
3546 becomes a non-match, or "+" for a non-match that becomes a match),
3543 becomes a non-match, or "+" for a non-match that becomes a match),
3547 use the --all flag.
3544 use the --all flag.
3548
3545
3549 Returns 0 if a match is found, 1 otherwise.
3546 Returns 0 if a match is found, 1 otherwise.
3550 """
3547 """
3551 reflags = re.M
3548 reflags = re.M
3552 if opts.get('ignore_case'):
3549 if opts.get('ignore_case'):
3553 reflags |= re.I
3550 reflags |= re.I
3554 try:
3551 try:
3555 regexp = util.re.compile(pattern, reflags)
3552 regexp = util.re.compile(pattern, reflags)
3556 except re.error, inst:
3553 except re.error, inst:
3557 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3554 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3558 return 1
3555 return 1
3559 sep, eol = ':', '\n'
3556 sep, eol = ':', '\n'
3560 if opts.get('print0'):
3557 if opts.get('print0'):
3561 sep = eol = '\0'
3558 sep = eol = '\0'
3562
3559
3563 getfile = util.lrucachefunc(repo.file)
3560 getfile = util.lrucachefunc(repo.file)
3564
3561
3565 def matchlines(body):
3562 def matchlines(body):
3566 begin = 0
3563 begin = 0
3567 linenum = 0
3564 linenum = 0
3568 while begin < len(body):
3565 while begin < len(body):
3569 match = regexp.search(body, begin)
3566 match = regexp.search(body, begin)
3570 if not match:
3567 if not match:
3571 break
3568 break
3572 mstart, mend = match.span()
3569 mstart, mend = match.span()
3573 linenum += body.count('\n', begin, mstart) + 1
3570 linenum += body.count('\n', begin, mstart) + 1
3574 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3571 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3575 begin = body.find('\n', mend) + 1 or len(body) + 1
3572 begin = body.find('\n', mend) + 1 or len(body) + 1
3576 lend = begin - 1
3573 lend = begin - 1
3577 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3574 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3578
3575
3579 class linestate(object):
3576 class linestate(object):
3580 def __init__(self, line, linenum, colstart, colend):
3577 def __init__(self, line, linenum, colstart, colend):
3581 self.line = line
3578 self.line = line
3582 self.linenum = linenum
3579 self.linenum = linenum
3583 self.colstart = colstart
3580 self.colstart = colstart
3584 self.colend = colend
3581 self.colend = colend
3585
3582
3586 def __hash__(self):
3583 def __hash__(self):
3587 return hash((self.linenum, self.line))
3584 return hash((self.linenum, self.line))
3588
3585
3589 def __eq__(self, other):
3586 def __eq__(self, other):
3590 return self.line == other.line
3587 return self.line == other.line
3591
3588
3592 def __iter__(self):
3589 def __iter__(self):
3593 yield (self.line[:self.colstart], '')
3590 yield (self.line[:self.colstart], '')
3594 yield (self.line[self.colstart:self.colend], 'grep.match')
3591 yield (self.line[self.colstart:self.colend], 'grep.match')
3595 rest = self.line[self.colend:]
3592 rest = self.line[self.colend:]
3596 while rest != '':
3593 while rest != '':
3597 match = regexp.search(rest)
3594 match = regexp.search(rest)
3598 if not match:
3595 if not match:
3599 yield (rest, '')
3596 yield (rest, '')
3600 break
3597 break
3601 mstart, mend = match.span()
3598 mstart, mend = match.span()
3602 yield (rest[:mstart], '')
3599 yield (rest[:mstart], '')
3603 yield (rest[mstart:mend], 'grep.match')
3600 yield (rest[mstart:mend], 'grep.match')
3604 rest = rest[mend:]
3601 rest = rest[mend:]
3605
3602
3606 matches = {}
3603 matches = {}
3607 copies = {}
3604 copies = {}
3608 def grepbody(fn, rev, body):
3605 def grepbody(fn, rev, body):
3609 matches[rev].setdefault(fn, [])
3606 matches[rev].setdefault(fn, [])
3610 m = matches[rev][fn]
3607 m = matches[rev][fn]
3611 for lnum, cstart, cend, line in matchlines(body):
3608 for lnum, cstart, cend, line in matchlines(body):
3612 s = linestate(line, lnum, cstart, cend)
3609 s = linestate(line, lnum, cstart, cend)
3613 m.append(s)
3610 m.append(s)
3614
3611
3615 def difflinestates(a, b):
3612 def difflinestates(a, b):
3616 sm = difflib.SequenceMatcher(None, a, b)
3613 sm = difflib.SequenceMatcher(None, a, b)
3617 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3614 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3618 if tag == 'insert':
3615 if tag == 'insert':
3619 for i in xrange(blo, bhi):
3616 for i in xrange(blo, bhi):
3620 yield ('+', b[i])
3617 yield ('+', b[i])
3621 elif tag == 'delete':
3618 elif tag == 'delete':
3622 for i in xrange(alo, ahi):
3619 for i in xrange(alo, ahi):
3623 yield ('-', a[i])
3620 yield ('-', a[i])
3624 elif tag == 'replace':
3621 elif tag == 'replace':
3625 for i in xrange(alo, ahi):
3622 for i in xrange(alo, ahi):
3626 yield ('-', a[i])
3623 yield ('-', a[i])
3627 for i in xrange(blo, bhi):
3624 for i in xrange(blo, bhi):
3628 yield ('+', b[i])
3625 yield ('+', b[i])
3629
3626
3630 def display(fn, ctx, pstates, states):
3627 def display(fn, ctx, pstates, states):
3631 rev = ctx.rev()
3628 rev = ctx.rev()
3632 datefunc = ui.quiet and util.shortdate or util.datestr
3629 datefunc = ui.quiet and util.shortdate or util.datestr
3633 found = False
3630 found = False
3634 @util.cachefunc
3631 @util.cachefunc
3635 def binary():
3632 def binary():
3636 flog = getfile(fn)
3633 flog = getfile(fn)
3637 return util.binary(flog.read(ctx.filenode(fn)))
3634 return util.binary(flog.read(ctx.filenode(fn)))
3638
3635
3639 if opts.get('all'):
3636 if opts.get('all'):
3640 iter = difflinestates(pstates, states)
3637 iter = difflinestates(pstates, states)
3641 else:
3638 else:
3642 iter = [('', l) for l in states]
3639 iter = [('', l) for l in states]
3643 for change, l in iter:
3640 for change, l in iter:
3644 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3641 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3645
3642
3646 if opts.get('line_number'):
3643 if opts.get('line_number'):
3647 cols.append((str(l.linenum), 'grep.linenumber'))
3644 cols.append((str(l.linenum), 'grep.linenumber'))
3648 if opts.get('all'):
3645 if opts.get('all'):
3649 cols.append((change, 'grep.change'))
3646 cols.append((change, 'grep.change'))
3650 if opts.get('user'):
3647 if opts.get('user'):
3651 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3648 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3652 if opts.get('date'):
3649 if opts.get('date'):
3653 cols.append((datefunc(ctx.date()), 'grep.date'))
3650 cols.append((datefunc(ctx.date()), 'grep.date'))
3654 for col, label in cols[:-1]:
3651 for col, label in cols[:-1]:
3655 ui.write(col, label=label)
3652 ui.write(col, label=label)
3656 ui.write(sep, label='grep.sep')
3653 ui.write(sep, label='grep.sep')
3657 ui.write(cols[-1][0], label=cols[-1][1])
3654 ui.write(cols[-1][0], label=cols[-1][1])
3658 if not opts.get('files_with_matches'):
3655 if not opts.get('files_with_matches'):
3659 ui.write(sep, label='grep.sep')
3656 ui.write(sep, label='grep.sep')
3660 if not opts.get('text') and binary():
3657 if not opts.get('text') and binary():
3661 ui.write(" Binary file matches")
3658 ui.write(" Binary file matches")
3662 else:
3659 else:
3663 for s, label in l:
3660 for s, label in l:
3664 ui.write(s, label=label)
3661 ui.write(s, label=label)
3665 ui.write(eol)
3662 ui.write(eol)
3666 found = True
3663 found = True
3667 if opts.get('files_with_matches'):
3664 if opts.get('files_with_matches'):
3668 break
3665 break
3669 return found
3666 return found
3670
3667
3671 skip = {}
3668 skip = {}
3672 revfiles = {}
3669 revfiles = {}
3673 matchfn = scmutil.match(repo[None], pats, opts)
3670 matchfn = scmutil.match(repo[None], pats, opts)
3674 found = False
3671 found = False
3675 follow = opts.get('follow')
3672 follow = opts.get('follow')
3676
3673
3677 def prep(ctx, fns):
3674 def prep(ctx, fns):
3678 rev = ctx.rev()
3675 rev = ctx.rev()
3679 pctx = ctx.p1()
3676 pctx = ctx.p1()
3680 parent = pctx.rev()
3677 parent = pctx.rev()
3681 matches.setdefault(rev, {})
3678 matches.setdefault(rev, {})
3682 matches.setdefault(parent, {})
3679 matches.setdefault(parent, {})
3683 files = revfiles.setdefault(rev, [])
3680 files = revfiles.setdefault(rev, [])
3684 for fn in fns:
3681 for fn in fns:
3685 flog = getfile(fn)
3682 flog = getfile(fn)
3686 try:
3683 try:
3687 fnode = ctx.filenode(fn)
3684 fnode = ctx.filenode(fn)
3688 except error.LookupError:
3685 except error.LookupError:
3689 continue
3686 continue
3690
3687
3691 copied = flog.renamed(fnode)
3688 copied = flog.renamed(fnode)
3692 copy = follow and copied and copied[0]
3689 copy = follow and copied and copied[0]
3693 if copy:
3690 if copy:
3694 copies.setdefault(rev, {})[fn] = copy
3691 copies.setdefault(rev, {})[fn] = copy
3695 if fn in skip:
3692 if fn in skip:
3696 if copy:
3693 if copy:
3697 skip[copy] = True
3694 skip[copy] = True
3698 continue
3695 continue
3699 files.append(fn)
3696 files.append(fn)
3700
3697
3701 if fn not in matches[rev]:
3698 if fn not in matches[rev]:
3702 grepbody(fn, rev, flog.read(fnode))
3699 grepbody(fn, rev, flog.read(fnode))
3703
3700
3704 pfn = copy or fn
3701 pfn = copy or fn
3705 if pfn not in matches[parent]:
3702 if pfn not in matches[parent]:
3706 try:
3703 try:
3707 fnode = pctx.filenode(pfn)
3704 fnode = pctx.filenode(pfn)
3708 grepbody(pfn, parent, flog.read(fnode))
3705 grepbody(pfn, parent, flog.read(fnode))
3709 except error.LookupError:
3706 except error.LookupError:
3710 pass
3707 pass
3711
3708
3712 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3709 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3713 rev = ctx.rev()
3710 rev = ctx.rev()
3714 parent = ctx.p1().rev()
3711 parent = ctx.p1().rev()
3715 for fn in sorted(revfiles.get(rev, [])):
3712 for fn in sorted(revfiles.get(rev, [])):
3716 states = matches[rev][fn]
3713 states = matches[rev][fn]
3717 copy = copies.get(rev, {}).get(fn)
3714 copy = copies.get(rev, {}).get(fn)
3718 if fn in skip:
3715 if fn in skip:
3719 if copy:
3716 if copy:
3720 skip[copy] = True
3717 skip[copy] = True
3721 continue
3718 continue
3722 pstates = matches.get(parent, {}).get(copy or fn, [])
3719 pstates = matches.get(parent, {}).get(copy or fn, [])
3723 if pstates or states:
3720 if pstates or states:
3724 r = display(fn, ctx, pstates, states)
3721 r = display(fn, ctx, pstates, states)
3725 found = found or r
3722 found = found or r
3726 if r and not opts.get('all'):
3723 if r and not opts.get('all'):
3727 skip[fn] = True
3724 skip[fn] = True
3728 if copy:
3725 if copy:
3729 skip[copy] = True
3726 skip[copy] = True
3730 del matches[rev]
3727 del matches[rev]
3731 del revfiles[rev]
3728 del revfiles[rev]
3732
3729
3733 return not found
3730 return not found
3734
3731
3735 @command('heads',
3732 @command('heads',
3736 [('r', 'rev', '',
3733 [('r', 'rev', '',
3737 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3734 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3738 ('t', 'topo', False, _('show topological heads only')),
3735 ('t', 'topo', False, _('show topological heads only')),
3739 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3736 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3740 ('c', 'closed', False, _('show normal and closed branch heads')),
3737 ('c', 'closed', False, _('show normal and closed branch heads')),
3741 ] + templateopts,
3738 ] + templateopts,
3742 _('[-ct] [-r STARTREV] [REV]...'))
3739 _('[-ct] [-r STARTREV] [REV]...'))
3743 def heads(ui, repo, *branchrevs, **opts):
3740 def heads(ui, repo, *branchrevs, **opts):
3744 """show branch heads
3741 """show branch heads
3745
3742
3746 With no arguments, show all open branch heads in the repository.
3743 With no arguments, show all open branch heads in the repository.
3747 Branch heads are changesets that have no descendants on the
3744 Branch heads are changesets that have no descendants on the
3748 same branch. They are where development generally takes place and
3745 same branch. They are where development generally takes place and
3749 are the usual targets for update and merge operations.
3746 are the usual targets for update and merge operations.
3750
3747
3751 If one or more REVs are given, only open branch heads on the
3748 If one or more REVs are given, only open branch heads on the
3752 branches associated with the specified changesets are shown. This
3749 branches associated with the specified changesets are shown. This
3753 means that you can use :hg:`heads .` to see the heads on the
3750 means that you can use :hg:`heads .` to see the heads on the
3754 currently checked-out branch.
3751 currently checked-out branch.
3755
3752
3756 If -c/--closed is specified, also show branch heads marked closed
3753 If -c/--closed is specified, also show branch heads marked closed
3757 (see :hg:`commit --close-branch`).
3754 (see :hg:`commit --close-branch`).
3758
3755
3759 If STARTREV is specified, only those heads that are descendants of
3756 If STARTREV is specified, only those heads that are descendants of
3760 STARTREV will be displayed.
3757 STARTREV will be displayed.
3761
3758
3762 If -t/--topo is specified, named branch mechanics will be ignored and only
3759 If -t/--topo is specified, named branch mechanics will be ignored and only
3763 topological heads (changesets with no children) will be shown.
3760 topological heads (changesets with no children) will be shown.
3764
3761
3765 Returns 0 if matching heads are found, 1 if not.
3762 Returns 0 if matching heads are found, 1 if not.
3766 """
3763 """
3767
3764
3768 start = None
3765 start = None
3769 if 'rev' in opts:
3766 if 'rev' in opts:
3770 start = scmutil.revsingle(repo, opts['rev'], None).node()
3767 start = scmutil.revsingle(repo, opts['rev'], None).node()
3771
3768
3772 if opts.get('topo'):
3769 if opts.get('topo'):
3773 heads = [repo[h] for h in repo.heads(start)]
3770 heads = [repo[h] for h in repo.heads(start)]
3774 else:
3771 else:
3775 heads = []
3772 heads = []
3776 for branch in repo.branchmap():
3773 for branch in repo.branchmap():
3777 heads += repo.branchheads(branch, start, opts.get('closed'))
3774 heads += repo.branchheads(branch, start, opts.get('closed'))
3778 heads = [repo[h] for h in heads]
3775 heads = [repo[h] for h in heads]
3779
3776
3780 if branchrevs:
3777 if branchrevs:
3781 branches = set(repo[br].branch() for br in branchrevs)
3778 branches = set(repo[br].branch() for br in branchrevs)
3782 heads = [h for h in heads if h.branch() in branches]
3779 heads = [h for h in heads if h.branch() in branches]
3783
3780
3784 if opts.get('active') and branchrevs:
3781 if opts.get('active') and branchrevs:
3785 dagheads = repo.heads(start)
3782 dagheads = repo.heads(start)
3786 heads = [h for h in heads if h.node() in dagheads]
3783 heads = [h for h in heads if h.node() in dagheads]
3787
3784
3788 if branchrevs:
3785 if branchrevs:
3789 haveheads = set(h.branch() for h in heads)
3786 haveheads = set(h.branch() for h in heads)
3790 if branches - haveheads:
3787 if branches - haveheads:
3791 headless = ', '.join(b for b in branches - haveheads)
3788 headless = ', '.join(b for b in branches - haveheads)
3792 msg = _('no open branch heads found on branches %s')
3789 msg = _('no open branch heads found on branches %s')
3793 if opts.get('rev'):
3790 if opts.get('rev'):
3794 msg += _(' (started at %s)') % opts['rev']
3791 msg += _(' (started at %s)') % opts['rev']
3795 ui.warn((msg + '\n') % headless)
3792 ui.warn((msg + '\n') % headless)
3796
3793
3797 if not heads:
3794 if not heads:
3798 return 1
3795 return 1
3799
3796
3800 heads = sorted(heads, key=lambda x: -x.rev())
3797 heads = sorted(heads, key=lambda x: -x.rev())
3801 displayer = cmdutil.show_changeset(ui, repo, opts)
3798 displayer = cmdutil.show_changeset(ui, repo, opts)
3802 for ctx in heads:
3799 for ctx in heads:
3803 displayer.show(ctx)
3800 displayer.show(ctx)
3804 displayer.close()
3801 displayer.close()
3805
3802
3806 @command('help',
3803 @command('help',
3807 [('e', 'extension', None, _('show only help for extensions')),
3804 [('e', 'extension', None, _('show only help for extensions')),
3808 ('c', 'command', None, _('show only help for commands')),
3805 ('c', 'command', None, _('show only help for commands')),
3809 ('k', 'keyword', '', _('show topics matching keyword')),
3806 ('k', 'keyword', '', _('show topics matching keyword')),
3810 ],
3807 ],
3811 _('[-ec] [TOPIC]'),
3808 _('[-ec] [TOPIC]'),
3812 norepo=True)
3809 norepo=True)
3813 def help_(ui, name=None, **opts):
3810 def help_(ui, name=None, **opts):
3814 """show help for a given topic or a help overview
3811 """show help for a given topic or a help overview
3815
3812
3816 With no arguments, print a list of commands with short help messages.
3813 With no arguments, print a list of commands with short help messages.
3817
3814
3818 Given a topic, extension, or command name, print help for that
3815 Given a topic, extension, or command name, print help for that
3819 topic.
3816 topic.
3820
3817
3821 Returns 0 if successful.
3818 Returns 0 if successful.
3822 """
3819 """
3823
3820
3824 textwidth = min(ui.termwidth(), 80) - 2
3821 textwidth = min(ui.termwidth(), 80) - 2
3825
3822
3826 keep = []
3823 keep = []
3827 if ui.verbose:
3824 if ui.verbose:
3828 keep.append('verbose')
3825 keep.append('verbose')
3829 if sys.platform.startswith('win'):
3826 if sys.platform.startswith('win'):
3830 keep.append('windows')
3827 keep.append('windows')
3831 elif sys.platform == 'OpenVMS':
3828 elif sys.platform == 'OpenVMS':
3832 keep.append('vms')
3829 keep.append('vms')
3833 elif sys.platform == 'plan9':
3830 elif sys.platform == 'plan9':
3834 keep.append('plan9')
3831 keep.append('plan9')
3835 else:
3832 else:
3836 keep.append('unix')
3833 keep.append('unix')
3837 keep.append(sys.platform.lower())
3834 keep.append(sys.platform.lower())
3838
3835
3839 section = None
3836 section = None
3840 if name and '.' in name:
3837 if name and '.' in name:
3841 name, section = name.split('.')
3838 name, section = name.split('.')
3842
3839
3843 text = help.help_(ui, name, **opts)
3840 text = help.help_(ui, name, **opts)
3844
3841
3845 formatted, pruned = minirst.format(text, textwidth, keep=keep,
3842 formatted, pruned = minirst.format(text, textwidth, keep=keep,
3846 section=section)
3843 section=section)
3847 if section and not formatted:
3844 if section and not formatted:
3848 raise util.Abort(_("help section not found"))
3845 raise util.Abort(_("help section not found"))
3849
3846
3850 if 'verbose' in pruned:
3847 if 'verbose' in pruned:
3851 keep.append('omitted')
3848 keep.append('omitted')
3852 else:
3849 else:
3853 keep.append('notomitted')
3850 keep.append('notomitted')
3854 formatted, pruned = minirst.format(text, textwidth, keep=keep,
3851 formatted, pruned = minirst.format(text, textwidth, keep=keep,
3855 section=section)
3852 section=section)
3856 ui.write(formatted)
3853 ui.write(formatted)
3857
3854
3858
3855
3859 @command('identify|id',
3856 @command('identify|id',
3860 [('r', 'rev', '',
3857 [('r', 'rev', '',
3861 _('identify the specified revision'), _('REV')),
3858 _('identify the specified revision'), _('REV')),
3862 ('n', 'num', None, _('show local revision number')),
3859 ('n', 'num', None, _('show local revision number')),
3863 ('i', 'id', None, _('show global revision id')),
3860 ('i', 'id', None, _('show global revision id')),
3864 ('b', 'branch', None, _('show branch')),
3861 ('b', 'branch', None, _('show branch')),
3865 ('t', 'tags', None, _('show tags')),
3862 ('t', 'tags', None, _('show tags')),
3866 ('B', 'bookmarks', None, _('show bookmarks')),
3863 ('B', 'bookmarks', None, _('show bookmarks')),
3867 ] + remoteopts,
3864 ] + remoteopts,
3868 _('[-nibtB] [-r REV] [SOURCE]'),
3865 _('[-nibtB] [-r REV] [SOURCE]'),
3869 optionalrepo=True)
3866 optionalrepo=True)
3870 def identify(ui, repo, source=None, rev=None,
3867 def identify(ui, repo, source=None, rev=None,
3871 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3868 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3872 """identify the working copy or specified revision
3869 """identify the working copy or specified revision
3873
3870
3874 Print a summary identifying the repository state at REV using one or
3871 Print a summary identifying the repository state at REV using one or
3875 two parent hash identifiers, followed by a "+" if the working
3872 two parent hash identifiers, followed by a "+" if the working
3876 directory has uncommitted changes, the branch name (if not default),
3873 directory has uncommitted changes, the branch name (if not default),
3877 a list of tags, and a list of bookmarks.
3874 a list of tags, and a list of bookmarks.
3878
3875
3879 When REV is not given, print a summary of the current state of the
3876 When REV is not given, print a summary of the current state of the
3880 repository.
3877 repository.
3881
3878
3882 Specifying a path to a repository root or Mercurial bundle will
3879 Specifying a path to a repository root or Mercurial bundle will
3883 cause lookup to operate on that repository/bundle.
3880 cause lookup to operate on that repository/bundle.
3884
3881
3885 .. container:: verbose
3882 .. container:: verbose
3886
3883
3887 Examples:
3884 Examples:
3888
3885
3889 - generate a build identifier for the working directory::
3886 - generate a build identifier for the working directory::
3890
3887
3891 hg id --id > build-id.dat
3888 hg id --id > build-id.dat
3892
3889
3893 - find the revision corresponding to a tag::
3890 - find the revision corresponding to a tag::
3894
3891
3895 hg id -n -r 1.3
3892 hg id -n -r 1.3
3896
3893
3897 - check the most recent revision of a remote repository::
3894 - check the most recent revision of a remote repository::
3898
3895
3899 hg id -r tip http://selenic.com/hg/
3896 hg id -r tip http://selenic.com/hg/
3900
3897
3901 Returns 0 if successful.
3898 Returns 0 if successful.
3902 """
3899 """
3903
3900
3904 if not repo and not source:
3901 if not repo and not source:
3905 raise util.Abort(_("there is no Mercurial repository here "
3902 raise util.Abort(_("there is no Mercurial repository here "
3906 "(.hg not found)"))
3903 "(.hg not found)"))
3907
3904
3908 hexfunc = ui.debugflag and hex or short
3905 hexfunc = ui.debugflag and hex or short
3909 default = not (num or id or branch or tags or bookmarks)
3906 default = not (num or id or branch or tags or bookmarks)
3910 output = []
3907 output = []
3911 revs = []
3908 revs = []
3912
3909
3913 if source:
3910 if source:
3914 source, branches = hg.parseurl(ui.expandpath(source))
3911 source, branches = hg.parseurl(ui.expandpath(source))
3915 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3912 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3916 repo = peer.local()
3913 repo = peer.local()
3917 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3914 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3918
3915
3919 if not repo:
3916 if not repo:
3920 if num or branch or tags:
3917 if num or branch or tags:
3921 raise util.Abort(
3918 raise util.Abort(
3922 _("can't query remote revision number, branch, or tags"))
3919 _("can't query remote revision number, branch, or tags"))
3923 if not rev and revs:
3920 if not rev and revs:
3924 rev = revs[0]
3921 rev = revs[0]
3925 if not rev:
3922 if not rev:
3926 rev = "tip"
3923 rev = "tip"
3927
3924
3928 remoterev = peer.lookup(rev)
3925 remoterev = peer.lookup(rev)
3929 if default or id:
3926 if default or id:
3930 output = [hexfunc(remoterev)]
3927 output = [hexfunc(remoterev)]
3931
3928
3932 def getbms():
3929 def getbms():
3933 bms = []
3930 bms = []
3934
3931
3935 if 'bookmarks' in peer.listkeys('namespaces'):
3932 if 'bookmarks' in peer.listkeys('namespaces'):
3936 hexremoterev = hex(remoterev)
3933 hexremoterev = hex(remoterev)
3937 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3934 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3938 if bmr == hexremoterev]
3935 if bmr == hexremoterev]
3939
3936
3940 return sorted(bms)
3937 return sorted(bms)
3941
3938
3942 if bookmarks:
3939 if bookmarks:
3943 output.extend(getbms())
3940 output.extend(getbms())
3944 elif default and not ui.quiet:
3941 elif default and not ui.quiet:
3945 # multiple bookmarks for a single parent separated by '/'
3942 # multiple bookmarks for a single parent separated by '/'
3946 bm = '/'.join(getbms())
3943 bm = '/'.join(getbms())
3947 if bm:
3944 if bm:
3948 output.append(bm)
3945 output.append(bm)
3949 else:
3946 else:
3950 if not rev:
3947 if not rev:
3951 ctx = repo[None]
3948 ctx = repo[None]
3952 parents = ctx.parents()
3949 parents = ctx.parents()
3953 changed = ""
3950 changed = ""
3954 if default or id or num:
3951 if default or id or num:
3955 if (util.any(repo.status())
3952 if (util.any(repo.status())
3956 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3953 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3957 changed = '+'
3954 changed = '+'
3958 if default or id:
3955 if default or id:
3959 output = ["%s%s" %
3956 output = ["%s%s" %
3960 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3957 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3961 if num:
3958 if num:
3962 output.append("%s%s" %
3959 output.append("%s%s" %
3963 ('+'.join([str(p.rev()) for p in parents]), changed))
3960 ('+'.join([str(p.rev()) for p in parents]), changed))
3964 else:
3961 else:
3965 ctx = scmutil.revsingle(repo, rev)
3962 ctx = scmutil.revsingle(repo, rev)
3966 if default or id:
3963 if default or id:
3967 output = [hexfunc(ctx.node())]
3964 output = [hexfunc(ctx.node())]
3968 if num:
3965 if num:
3969 output.append(str(ctx.rev()))
3966 output.append(str(ctx.rev()))
3970
3967
3971 if default and not ui.quiet:
3968 if default and not ui.quiet:
3972 b = ctx.branch()
3969 b = ctx.branch()
3973 if b != 'default':
3970 if b != 'default':
3974 output.append("(%s)" % b)
3971 output.append("(%s)" % b)
3975
3972
3976 # multiple tags for a single parent separated by '/'
3973 # multiple tags for a single parent separated by '/'
3977 t = '/'.join(ctx.tags())
3974 t = '/'.join(ctx.tags())
3978 if t:
3975 if t:
3979 output.append(t)
3976 output.append(t)
3980
3977
3981 # multiple bookmarks for a single parent separated by '/'
3978 # multiple bookmarks for a single parent separated by '/'
3982 bm = '/'.join(ctx.bookmarks())
3979 bm = '/'.join(ctx.bookmarks())
3983 if bm:
3980 if bm:
3984 output.append(bm)
3981 output.append(bm)
3985 else:
3982 else:
3986 if branch:
3983 if branch:
3987 output.append(ctx.branch())
3984 output.append(ctx.branch())
3988
3985
3989 if tags:
3986 if tags:
3990 output.extend(ctx.tags())
3987 output.extend(ctx.tags())
3991
3988
3992 if bookmarks:
3989 if bookmarks:
3993 output.extend(ctx.bookmarks())
3990 output.extend(ctx.bookmarks())
3994
3991
3995 ui.write("%s\n" % ' '.join(output))
3992 ui.write("%s\n" % ' '.join(output))
3996
3993
3997 @command('import|patch',
3994 @command('import|patch',
3998 [('p', 'strip', 1,
3995 [('p', 'strip', 1,
3999 _('directory strip option for patch. This has the same '
3996 _('directory strip option for patch. This has the same '
4000 'meaning as the corresponding patch option'), _('NUM')),
3997 'meaning as the corresponding patch option'), _('NUM')),
4001 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3998 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
4002 ('e', 'edit', False, _('invoke editor on commit messages')),
3999 ('e', 'edit', False, _('invoke editor on commit messages')),
4003 ('f', 'force', None,
4000 ('f', 'force', None,
4004 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4001 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
4005 ('', 'no-commit', None,
4002 ('', 'no-commit', None,
4006 _("don't commit, just update the working directory")),
4003 _("don't commit, just update the working directory")),
4007 ('', 'bypass', None,
4004 ('', 'bypass', None,
4008 _("apply patch without touching the working directory")),
4005 _("apply patch without touching the working directory")),
4009 ('', 'partial', None,
4006 ('', 'partial', None,
4010 _('commit even if some hunks fail')),
4007 _('commit even if some hunks fail')),
4011 ('', 'exact', None,
4008 ('', 'exact', None,
4012 _('apply patch to the nodes from which it was generated')),
4009 _('apply patch to the nodes from which it was generated')),
4013 ('', 'import-branch', None,
4010 ('', 'import-branch', None,
4014 _('use any branch information in patch (implied by --exact)'))] +
4011 _('use any branch information in patch (implied by --exact)'))] +
4015 commitopts + commitopts2 + similarityopts,
4012 commitopts + commitopts2 + similarityopts,
4016 _('[OPTION]... PATCH...'))
4013 _('[OPTION]... PATCH...'))
4017 def import_(ui, repo, patch1=None, *patches, **opts):
4014 def import_(ui, repo, patch1=None, *patches, **opts):
4018 """import an ordered set of patches
4015 """import an ordered set of patches
4019
4016
4020 Import a list of patches and commit them individually (unless
4017 Import a list of patches and commit them individually (unless
4021 --no-commit is specified).
4018 --no-commit is specified).
4022
4019
4023 Because import first applies changes to the working directory,
4020 Because import first applies changes to the working directory,
4024 import will abort if there are outstanding changes.
4021 import will abort if there are outstanding changes.
4025
4022
4026 You can import a patch straight from a mail message. Even patches
4023 You can import a patch straight from a mail message. Even patches
4027 as attachments work (to use the body part, it must have type
4024 as attachments work (to use the body part, it must have type
4028 text/plain or text/x-patch). From and Subject headers of email
4025 text/plain or text/x-patch). From and Subject headers of email
4029 message are used as default committer and commit message. All
4026 message are used as default committer and commit message. All
4030 text/plain body parts before first diff are added to commit
4027 text/plain body parts before first diff are added to commit
4031 message.
4028 message.
4032
4029
4033 If the imported patch was generated by :hg:`export`, user and
4030 If the imported patch was generated by :hg:`export`, user and
4034 description from patch override values from message headers and
4031 description from patch override values from message headers and
4035 body. Values given on command line with -m/--message and -u/--user
4032 body. Values given on command line with -m/--message and -u/--user
4036 override these.
4033 override these.
4037
4034
4038 If --exact is specified, import will set the working directory to
4035 If --exact is specified, import will set the working directory to
4039 the parent of each patch before applying it, and will abort if the
4036 the parent of each patch before applying it, and will abort if the
4040 resulting changeset has a different ID than the one recorded in
4037 resulting changeset has a different ID than the one recorded in
4041 the patch. This may happen due to character set problems or other
4038 the patch. This may happen due to character set problems or other
4042 deficiencies in the text patch format.
4039 deficiencies in the text patch format.
4043
4040
4044 Use --bypass to apply and commit patches directly to the
4041 Use --bypass to apply and commit patches directly to the
4045 repository, not touching the working directory. Without --exact,
4042 repository, not touching the working directory. Without --exact,
4046 patches will be applied on top of the working directory parent
4043 patches will be applied on top of the working directory parent
4047 revision.
4044 revision.
4048
4045
4049 With -s/--similarity, hg will attempt to discover renames and
4046 With -s/--similarity, hg will attempt to discover renames and
4050 copies in the patch in the same way as :hg:`addremove`.
4047 copies in the patch in the same way as :hg:`addremove`.
4051
4048
4052 Use --partial to ensure a changeset will be created from the patch
4049 Use --partial to ensure a changeset will be created from the patch
4053 even if some hunks fail to apply. Hunks that fail to apply will be
4050 even if some hunks fail to apply. Hunks that fail to apply will be
4054 written to a <target-file>.rej file. Conflicts can then be resolved
4051 written to a <target-file>.rej file. Conflicts can then be resolved
4055 by hand before :hg:`commit --amend` is run to update the created
4052 by hand before :hg:`commit --amend` is run to update the created
4056 changeset. This flag exists to let people import patches that
4053 changeset. This flag exists to let people import patches that
4057 partially apply without losing the associated metadata (author,
4054 partially apply without losing the associated metadata (author,
4058 date, description, ...). Note that when none of the hunk applies
4055 date, description, ...). Note that when none of the hunk applies
4059 cleanly, :hg:`import --partial` will create an empty changeset,
4056 cleanly, :hg:`import --partial` will create an empty changeset,
4060 importing only the patch metadata.
4057 importing only the patch metadata.
4061
4058
4062 To read a patch from standard input, use "-" as the patch name. If
4059 To read a patch from standard input, use "-" as the patch name. If
4063 a URL is specified, the patch will be downloaded from it.
4060 a URL is specified, the patch will be downloaded from it.
4064 See :hg:`help dates` for a list of formats valid for -d/--date.
4061 See :hg:`help dates` for a list of formats valid for -d/--date.
4065
4062
4066 .. container:: verbose
4063 .. container:: verbose
4067
4064
4068 Examples:
4065 Examples:
4069
4066
4070 - import a traditional patch from a website and detect renames::
4067 - import a traditional patch from a website and detect renames::
4071
4068
4072 hg import -s 80 http://example.com/bugfix.patch
4069 hg import -s 80 http://example.com/bugfix.patch
4073
4070
4074 - import a changeset from an hgweb server::
4071 - import a changeset from an hgweb server::
4075
4072
4076 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
4073 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
4077
4074
4078 - import all the patches in an Unix-style mbox::
4075 - import all the patches in an Unix-style mbox::
4079
4076
4080 hg import incoming-patches.mbox
4077 hg import incoming-patches.mbox
4081
4078
4082 - attempt to exactly restore an exported changeset (not always
4079 - attempt to exactly restore an exported changeset (not always
4083 possible)::
4080 possible)::
4084
4081
4085 hg import --exact proposed-fix.patch
4082 hg import --exact proposed-fix.patch
4086
4083
4087 Returns 0 on success, 1 on partial success (see --partial).
4084 Returns 0 on success, 1 on partial success (see --partial).
4088 """
4085 """
4089
4086
4090 if not patch1:
4087 if not patch1:
4091 raise util.Abort(_('need at least one patch to import'))
4088 raise util.Abort(_('need at least one patch to import'))
4092
4089
4093 patches = (patch1,) + patches
4090 patches = (patch1,) + patches
4094
4091
4095 date = opts.get('date')
4092 date = opts.get('date')
4096 if date:
4093 if date:
4097 opts['date'] = util.parsedate(date)
4094 opts['date'] = util.parsedate(date)
4098
4095
4099 update = not opts.get('bypass')
4096 update = not opts.get('bypass')
4100 if not update and opts.get('no_commit'):
4097 if not update and opts.get('no_commit'):
4101 raise util.Abort(_('cannot use --no-commit with --bypass'))
4098 raise util.Abort(_('cannot use --no-commit with --bypass'))
4102 try:
4099 try:
4103 sim = float(opts.get('similarity') or 0)
4100 sim = float(opts.get('similarity') or 0)
4104 except ValueError:
4101 except ValueError:
4105 raise util.Abort(_('similarity must be a number'))
4102 raise util.Abort(_('similarity must be a number'))
4106 if sim < 0 or sim > 100:
4103 if sim < 0 or sim > 100:
4107 raise util.Abort(_('similarity must be between 0 and 100'))
4104 raise util.Abort(_('similarity must be between 0 and 100'))
4108 if sim and not update:
4105 if sim and not update:
4109 raise util.Abort(_('cannot use --similarity with --bypass'))
4106 raise util.Abort(_('cannot use --similarity with --bypass'))
4110 if opts.get('exact') and opts.get('edit'):
4107 if opts.get('exact') and opts.get('edit'):
4111 raise util.Abort(_('cannot use --exact with --edit'))
4108 raise util.Abort(_('cannot use --exact with --edit'))
4112
4109
4113 if update:
4110 if update:
4114 cmdutil.checkunfinished(repo)
4111 cmdutil.checkunfinished(repo)
4115 if (opts.get('exact') or not opts.get('force')) and update:
4112 if (opts.get('exact') or not opts.get('force')) and update:
4116 cmdutil.bailifchanged(repo)
4113 cmdutil.bailifchanged(repo)
4117
4114
4118 base = opts["base"]
4115 base = opts["base"]
4119 wlock = lock = tr = None
4116 wlock = lock = tr = None
4120 msgs = []
4117 msgs = []
4121 ret = 0
4118 ret = 0
4122
4119
4123
4120
4124 try:
4121 try:
4125 try:
4122 try:
4126 wlock = repo.wlock()
4123 wlock = repo.wlock()
4127 repo.dirstate.beginparentchange()
4124 repo.dirstate.beginparentchange()
4128 if not opts.get('no_commit'):
4125 if not opts.get('no_commit'):
4129 lock = repo.lock()
4126 lock = repo.lock()
4130 tr = repo.transaction('import')
4127 tr = repo.transaction('import')
4131 parents = repo.parents()
4128 parents = repo.parents()
4132 for patchurl in patches:
4129 for patchurl in patches:
4133 if patchurl == '-':
4130 if patchurl == '-':
4134 ui.status(_('applying patch from stdin\n'))
4131 ui.status(_('applying patch from stdin\n'))
4135 patchfile = ui.fin
4132 patchfile = ui.fin
4136 patchurl = 'stdin' # for error message
4133 patchurl = 'stdin' # for error message
4137 else:
4134 else:
4138 patchurl = os.path.join(base, patchurl)
4135 patchurl = os.path.join(base, patchurl)
4139 ui.status(_('applying %s\n') % patchurl)
4136 ui.status(_('applying %s\n') % patchurl)
4140 patchfile = hg.openpath(ui, patchurl)
4137 patchfile = hg.openpath(ui, patchurl)
4141
4138
4142 haspatch = False
4139 haspatch = False
4143 for hunk in patch.split(patchfile):
4140 for hunk in patch.split(patchfile):
4144 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4141 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
4145 parents, opts,
4142 parents, opts,
4146 msgs, hg.clean)
4143 msgs, hg.clean)
4147 if msg:
4144 if msg:
4148 haspatch = True
4145 haspatch = True
4149 ui.note(msg + '\n')
4146 ui.note(msg + '\n')
4150 if update or opts.get('exact'):
4147 if update or opts.get('exact'):
4151 parents = repo.parents()
4148 parents = repo.parents()
4152 else:
4149 else:
4153 parents = [repo[node]]
4150 parents = [repo[node]]
4154 if rej:
4151 if rej:
4155 ui.write_err(_("patch applied partially\n"))
4152 ui.write_err(_("patch applied partially\n"))
4156 ui.write_err(_("(fix the .rej files and run "
4153 ui.write_err(_("(fix the .rej files and run "
4157 "`hg commit --amend`)\n"))
4154 "`hg commit --amend`)\n"))
4158 ret = 1
4155 ret = 1
4159 break
4156 break
4160
4157
4161 if not haspatch:
4158 if not haspatch:
4162 raise util.Abort(_('%s: no diffs found') % patchurl)
4159 raise util.Abort(_('%s: no diffs found') % patchurl)
4163
4160
4164 if tr:
4161 if tr:
4165 tr.close()
4162 tr.close()
4166 if msgs:
4163 if msgs:
4167 repo.savecommitmessage('\n* * *\n'.join(msgs))
4164 repo.savecommitmessage('\n* * *\n'.join(msgs))
4168 repo.dirstate.endparentchange()
4165 repo.dirstate.endparentchange()
4169 return ret
4166 return ret
4170 except: # re-raises
4167 except: # re-raises
4171 # wlock.release() indirectly calls dirstate.write(): since
4168 # wlock.release() indirectly calls dirstate.write(): since
4172 # we're crashing, we do not want to change the working dir
4169 # we're crashing, we do not want to change the working dir
4173 # parent after all, so make sure it writes nothing
4170 # parent after all, so make sure it writes nothing
4174 repo.dirstate.invalidate()
4171 repo.dirstate.invalidate()
4175 raise
4172 raise
4176 finally:
4173 finally:
4177 if tr:
4174 if tr:
4178 tr.release()
4175 tr.release()
4179 release(lock, wlock)
4176 release(lock, wlock)
4180
4177
4181 @command('incoming|in',
4178 @command('incoming|in',
4182 [('f', 'force', None,
4179 [('f', 'force', None,
4183 _('run even if remote repository is unrelated')),
4180 _('run even if remote repository is unrelated')),
4184 ('n', 'newest-first', None, _('show newest record first')),
4181 ('n', 'newest-first', None, _('show newest record first')),
4185 ('', 'bundle', '',
4182 ('', 'bundle', '',
4186 _('file to store the bundles into'), _('FILE')),
4183 _('file to store the bundles into'), _('FILE')),
4187 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4184 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4188 ('B', 'bookmarks', False, _("compare bookmarks")),
4185 ('B', 'bookmarks', False, _("compare bookmarks")),
4189 ('b', 'branch', [],
4186 ('b', 'branch', [],
4190 _('a specific branch you would like to pull'), _('BRANCH')),
4187 _('a specific branch you would like to pull'), _('BRANCH')),
4191 ] + logopts + remoteopts + subrepoopts,
4188 ] + logopts + remoteopts + subrepoopts,
4192 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4189 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
4193 def incoming(ui, repo, source="default", **opts):
4190 def incoming(ui, repo, source="default", **opts):
4194 """show new changesets found in source
4191 """show new changesets found in source
4195
4192
4196 Show new changesets found in the specified path/URL or the default
4193 Show new changesets found in the specified path/URL or the default
4197 pull location. These are the changesets that would have been pulled
4194 pull location. These are the changesets that would have been pulled
4198 if a pull at the time you issued this command.
4195 if a pull at the time you issued this command.
4199
4196
4200 For remote repository, using --bundle avoids downloading the
4197 For remote repository, using --bundle avoids downloading the
4201 changesets twice if the incoming is followed by a pull.
4198 changesets twice if the incoming is followed by a pull.
4202
4199
4203 See pull for valid source format details.
4200 See pull for valid source format details.
4204
4201
4205 .. container:: verbose
4202 .. container:: verbose
4206
4203
4207 Examples:
4204 Examples:
4208
4205
4209 - show incoming changes with patches and full description::
4206 - show incoming changes with patches and full description::
4210
4207
4211 hg incoming -vp
4208 hg incoming -vp
4212
4209
4213 - show incoming changes excluding merges, store a bundle::
4210 - show incoming changes excluding merges, store a bundle::
4214
4211
4215 hg in -vpM --bundle incoming.hg
4212 hg in -vpM --bundle incoming.hg
4216 hg pull incoming.hg
4213 hg pull incoming.hg
4217
4214
4218 - briefly list changes inside a bundle::
4215 - briefly list changes inside a bundle::
4219
4216
4220 hg in changes.hg -T "{desc|firstline}\\n"
4217 hg in changes.hg -T "{desc|firstline}\\n"
4221
4218
4222 Returns 0 if there are incoming changes, 1 otherwise.
4219 Returns 0 if there are incoming changes, 1 otherwise.
4223 """
4220 """
4224 if opts.get('graph'):
4221 if opts.get('graph'):
4225 cmdutil.checkunsupportedgraphflags([], opts)
4222 cmdutil.checkunsupportedgraphflags([], opts)
4226 def display(other, chlist, displayer):
4223 def display(other, chlist, displayer):
4227 revdag = cmdutil.graphrevs(other, chlist, opts)
4224 revdag = cmdutil.graphrevs(other, chlist, opts)
4228 showparents = [ctx.node() for ctx in repo[None].parents()]
4225 showparents = [ctx.node() for ctx in repo[None].parents()]
4229 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4226 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4230 graphmod.asciiedges)
4227 graphmod.asciiedges)
4231
4228
4232 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4229 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
4233 return 0
4230 return 0
4234
4231
4235 if opts.get('bundle') and opts.get('subrepos'):
4232 if opts.get('bundle') and opts.get('subrepos'):
4236 raise util.Abort(_('cannot combine --bundle and --subrepos'))
4233 raise util.Abort(_('cannot combine --bundle and --subrepos'))
4237
4234
4238 if opts.get('bookmarks'):
4235 if opts.get('bookmarks'):
4239 source, branches = hg.parseurl(ui.expandpath(source),
4236 source, branches = hg.parseurl(ui.expandpath(source),
4240 opts.get('branch'))
4237 opts.get('branch'))
4241 other = hg.peer(repo, opts, source)
4238 other = hg.peer(repo, opts, source)
4242 if 'bookmarks' not in other.listkeys('namespaces'):
4239 if 'bookmarks' not in other.listkeys('namespaces'):
4243 ui.warn(_("remote doesn't support bookmarks\n"))
4240 ui.warn(_("remote doesn't support bookmarks\n"))
4244 return 0
4241 return 0
4245 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4242 ui.status(_('comparing with %s\n') % util.hidepassword(source))
4246 return bookmarks.diff(ui, repo, other)
4243 return bookmarks.diff(ui, repo, other)
4247
4244
4248 repo._subtoppath = ui.expandpath(source)
4245 repo._subtoppath = ui.expandpath(source)
4249 try:
4246 try:
4250 return hg.incoming(ui, repo, source, opts)
4247 return hg.incoming(ui, repo, source, opts)
4251 finally:
4248 finally:
4252 del repo._subtoppath
4249 del repo._subtoppath
4253
4250
4254
4251
4255 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4252 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
4256 norepo=True)
4253 norepo=True)
4257 def init(ui, dest=".", **opts):
4254 def init(ui, dest=".", **opts):
4258 """create a new repository in the given directory
4255 """create a new repository in the given directory
4259
4256
4260 Initialize a new repository in the given directory. If the given
4257 Initialize a new repository in the given directory. If the given
4261 directory does not exist, it will be created.
4258 directory does not exist, it will be created.
4262
4259
4263 If no directory is given, the current directory is used.
4260 If no directory is given, the current directory is used.
4264
4261
4265 It is possible to specify an ``ssh://`` URL as the destination.
4262 It is possible to specify an ``ssh://`` URL as the destination.
4266 See :hg:`help urls` for more information.
4263 See :hg:`help urls` for more information.
4267
4264
4268 Returns 0 on success.
4265 Returns 0 on success.
4269 """
4266 """
4270 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4267 hg.peer(ui, opts, ui.expandpath(dest), create=True)
4271
4268
4272 @command('locate',
4269 @command('locate',
4273 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4270 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
4274 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4271 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4275 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4272 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
4276 ] + walkopts,
4273 ] + walkopts,
4277 _('[OPTION]... [PATTERN]...'))
4274 _('[OPTION]... [PATTERN]...'))
4278 def locate(ui, repo, *pats, **opts):
4275 def locate(ui, repo, *pats, **opts):
4279 """locate files matching specific patterns (DEPRECATED)
4276 """locate files matching specific patterns (DEPRECATED)
4280
4277
4281 Print files under Mercurial control in the working directory whose
4278 Print files under Mercurial control in the working directory whose
4282 names match the given patterns.
4279 names match the given patterns.
4283
4280
4284 By default, this command searches all directories in the working
4281 By default, this command searches all directories in the working
4285 directory. To search just the current directory and its
4282 directory. To search just the current directory and its
4286 subdirectories, use "--include .".
4283 subdirectories, use "--include .".
4287
4284
4288 If no patterns are given to match, this command prints the names
4285 If no patterns are given to match, this command prints the names
4289 of all files under Mercurial control in the working directory.
4286 of all files under Mercurial control in the working directory.
4290
4287
4291 If you want to feed the output of this command into the "xargs"
4288 If you want to feed the output of this command into the "xargs"
4292 command, use the -0 option to both this command and "xargs". This
4289 command, use the -0 option to both this command and "xargs". This
4293 will avoid the problem of "xargs" treating single filenames that
4290 will avoid the problem of "xargs" treating single filenames that
4294 contain whitespace as multiple filenames.
4291 contain whitespace as multiple filenames.
4295
4292
4296 See :hg:`help files` for a more versatile command.
4293 See :hg:`help files` for a more versatile command.
4297
4294
4298 Returns 0 if a match is found, 1 otherwise.
4295 Returns 0 if a match is found, 1 otherwise.
4299 """
4296 """
4300 end = opts.get('print0') and '\0' or '\n'
4297 end = opts.get('print0') and '\0' or '\n'
4301 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4298 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4302
4299
4303 ret = 1
4300 ret = 1
4304 ctx = repo[rev]
4301 ctx = repo[rev]
4305 m = scmutil.match(ctx, pats, opts, default='relglob')
4302 m = scmutil.match(ctx, pats, opts, default='relglob')
4306 m.bad = lambda x, y: False
4303 m.bad = lambda x, y: False
4307
4304
4308 for abs in ctx.matches(m):
4305 for abs in ctx.matches(m):
4309 if opts.get('fullpath'):
4306 if opts.get('fullpath'):
4310 ui.write(repo.wjoin(abs), end)
4307 ui.write(repo.wjoin(abs), end)
4311 else:
4308 else:
4312 ui.write(((pats and m.rel(abs)) or abs), end)
4309 ui.write(((pats and m.rel(abs)) or abs), end)
4313 ret = 0
4310 ret = 0
4314
4311
4315 return ret
4312 return ret
4316
4313
4317 @command('^log|history',
4314 @command('^log|history',
4318 [('f', 'follow', None,
4315 [('f', 'follow', None,
4319 _('follow changeset history, or file history across copies and renames')),
4316 _('follow changeset history, or file history across copies and renames')),
4320 ('', 'follow-first', None,
4317 ('', 'follow-first', None,
4321 _('only follow the first parent of merge changesets (DEPRECATED)')),
4318 _('only follow the first parent of merge changesets (DEPRECATED)')),
4322 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4319 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4323 ('C', 'copies', None, _('show copied files')),
4320 ('C', 'copies', None, _('show copied files')),
4324 ('k', 'keyword', [],
4321 ('k', 'keyword', [],
4325 _('do case-insensitive search for a given text'), _('TEXT')),
4322 _('do case-insensitive search for a given text'), _('TEXT')),
4326 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4323 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4327 ('', 'removed', None, _('include revisions where files were removed')),
4324 ('', 'removed', None, _('include revisions where files were removed')),
4328 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4325 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4329 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4326 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4330 ('', 'only-branch', [],
4327 ('', 'only-branch', [],
4331 _('show only changesets within the given named branch (DEPRECATED)'),
4328 _('show only changesets within the given named branch (DEPRECATED)'),
4332 _('BRANCH')),
4329 _('BRANCH')),
4333 ('b', 'branch', [],
4330 ('b', 'branch', [],
4334 _('show changesets within the given named branch'), _('BRANCH')),
4331 _('show changesets within the given named branch'), _('BRANCH')),
4335 ('P', 'prune', [],
4332 ('P', 'prune', [],
4336 _('do not display revision or any of its ancestors'), _('REV')),
4333 _('do not display revision or any of its ancestors'), _('REV')),
4337 ] + logopts + walkopts,
4334 ] + logopts + walkopts,
4338 _('[OPTION]... [FILE]'),
4335 _('[OPTION]... [FILE]'),
4339 inferrepo=True)
4336 inferrepo=True)
4340 def log(ui, repo, *pats, **opts):
4337 def log(ui, repo, *pats, **opts):
4341 """show revision history of entire repository or files
4338 """show revision history of entire repository or files
4342
4339
4343 Print the revision history of the specified files or the entire
4340 Print the revision history of the specified files or the entire
4344 project.
4341 project.
4345
4342
4346 If no revision range is specified, the default is ``tip:0`` unless
4343 If no revision range is specified, the default is ``tip:0`` unless
4347 --follow is set, in which case the working directory parent is
4344 --follow is set, in which case the working directory parent is
4348 used as the starting revision.
4345 used as the starting revision.
4349
4346
4350 File history is shown without following rename or copy history of
4347 File history is shown without following rename or copy history of
4351 files. Use -f/--follow with a filename to follow history across
4348 files. Use -f/--follow with a filename to follow history across
4352 renames and copies. --follow without a filename will only show
4349 renames and copies. --follow without a filename will only show
4353 ancestors or descendants of the starting revision.
4350 ancestors or descendants of the starting revision.
4354
4351
4355 By default this command prints revision number and changeset id,
4352 By default this command prints revision number and changeset id,
4356 tags, non-trivial parents, user, date and time, and a summary for
4353 tags, non-trivial parents, user, date and time, and a summary for
4357 each commit. When the -v/--verbose switch is used, the list of
4354 each commit. When the -v/--verbose switch is used, the list of
4358 changed files and full commit message are shown.
4355 changed files and full commit message are shown.
4359
4356
4360 With --graph the revisions are shown as an ASCII art DAG with the most
4357 With --graph the revisions are shown as an ASCII art DAG with the most
4361 recent changeset at the top.
4358 recent changeset at the top.
4362 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4359 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4363 and '+' represents a fork where the changeset from the lines below is a
4360 and '+' represents a fork where the changeset from the lines below is a
4364 parent of the 'o' merge on the same line.
4361 parent of the 'o' merge on the same line.
4365
4362
4366 .. note::
4363 .. note::
4367
4364
4368 log -p/--patch may generate unexpected diff output for merge
4365 log -p/--patch may generate unexpected diff output for merge
4369 changesets, as it will only compare the merge changeset against
4366 changesets, as it will only compare the merge changeset against
4370 its first parent. Also, only files different from BOTH parents
4367 its first parent. Also, only files different from BOTH parents
4371 will appear in files:.
4368 will appear in files:.
4372
4369
4373 .. note::
4370 .. note::
4374
4371
4375 for performance reasons, log FILE may omit duplicate changes
4372 for performance reasons, log FILE may omit duplicate changes
4376 made on branches and will not show removals or mode changes. To
4373 made on branches and will not show removals or mode changes. To
4377 see all such changes, use the --removed switch.
4374 see all such changes, use the --removed switch.
4378
4375
4379 .. container:: verbose
4376 .. container:: verbose
4380
4377
4381 Some examples:
4378 Some examples:
4382
4379
4383 - changesets with full descriptions and file lists::
4380 - changesets with full descriptions and file lists::
4384
4381
4385 hg log -v
4382 hg log -v
4386
4383
4387 - changesets ancestral to the working directory::
4384 - changesets ancestral to the working directory::
4388
4385
4389 hg log -f
4386 hg log -f
4390
4387
4391 - last 10 commits on the current branch::
4388 - last 10 commits on the current branch::
4392
4389
4393 hg log -l 10 -b .
4390 hg log -l 10 -b .
4394
4391
4395 - changesets showing all modifications of a file, including removals::
4392 - changesets showing all modifications of a file, including removals::
4396
4393
4397 hg log --removed file.c
4394 hg log --removed file.c
4398
4395
4399 - all changesets that touch a directory, with diffs, excluding merges::
4396 - all changesets that touch a directory, with diffs, excluding merges::
4400
4397
4401 hg log -Mp lib/
4398 hg log -Mp lib/
4402
4399
4403 - all revision numbers that match a keyword::
4400 - all revision numbers that match a keyword::
4404
4401
4405 hg log -k bug --template "{rev}\\n"
4402 hg log -k bug --template "{rev}\\n"
4406
4403
4407 - list available log templates::
4404 - list available log templates::
4408
4405
4409 hg log -T list
4406 hg log -T list
4410
4407
4411 - check if a given changeset is included in a tagged release::
4408 - check if a given changeset is included in a tagged release::
4412
4409
4413 hg log -r "a21ccf and ancestor(1.9)"
4410 hg log -r "a21ccf and ancestor(1.9)"
4414
4411
4415 - find all changesets by some user in a date range::
4412 - find all changesets by some user in a date range::
4416
4413
4417 hg log -k alice -d "may 2008 to jul 2008"
4414 hg log -k alice -d "may 2008 to jul 2008"
4418
4415
4419 - summary of all changesets after the last tag::
4416 - summary of all changesets after the last tag::
4420
4417
4421 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4418 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4422
4419
4423 See :hg:`help dates` for a list of formats valid for -d/--date.
4420 See :hg:`help dates` for a list of formats valid for -d/--date.
4424
4421
4425 See :hg:`help revisions` and :hg:`help revsets` for more about
4422 See :hg:`help revisions` and :hg:`help revsets` for more about
4426 specifying revisions.
4423 specifying revisions.
4427
4424
4428 See :hg:`help templates` for more about pre-packaged styles and
4425 See :hg:`help templates` for more about pre-packaged styles and
4429 specifying custom templates.
4426 specifying custom templates.
4430
4427
4431 Returns 0 on success.
4428 Returns 0 on success.
4432
4429
4433 """
4430 """
4434 if opts.get('graph'):
4431 if opts.get('graph'):
4435 return cmdutil.graphlog(ui, repo, *pats, **opts)
4432 return cmdutil.graphlog(ui, repo, *pats, **opts)
4436
4433
4437 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4434 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4438 limit = cmdutil.loglimit(opts)
4435 limit = cmdutil.loglimit(opts)
4439 count = 0
4436 count = 0
4440
4437
4441 getrenamed = None
4438 getrenamed = None
4442 if opts.get('copies'):
4439 if opts.get('copies'):
4443 endrev = None
4440 endrev = None
4444 if opts.get('rev'):
4441 if opts.get('rev'):
4445 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4442 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4446 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4443 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4447
4444
4448 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4445 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4449 for rev in revs:
4446 for rev in revs:
4450 if count == limit:
4447 if count == limit:
4451 break
4448 break
4452 ctx = repo[rev]
4449 ctx = repo[rev]
4453 copies = None
4450 copies = None
4454 if getrenamed is not None and rev:
4451 if getrenamed is not None and rev:
4455 copies = []
4452 copies = []
4456 for fn in ctx.files():
4453 for fn in ctx.files():
4457 rename = getrenamed(fn, rev)
4454 rename = getrenamed(fn, rev)
4458 if rename:
4455 if rename:
4459 copies.append((fn, rename[0]))
4456 copies.append((fn, rename[0]))
4460 revmatchfn = filematcher and filematcher(ctx.rev()) or None
4457 revmatchfn = filematcher and filematcher(ctx.rev()) or None
4461 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4458 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4462 if displayer.flush(rev):
4459 if displayer.flush(rev):
4463 count += 1
4460 count += 1
4464
4461
4465 displayer.close()
4462 displayer.close()
4466
4463
4467 @command('manifest',
4464 @command('manifest',
4468 [('r', 'rev', '', _('revision to display'), _('REV')),
4465 [('r', 'rev', '', _('revision to display'), _('REV')),
4469 ('', 'all', False, _("list files from all revisions"))]
4466 ('', 'all', False, _("list files from all revisions"))]
4470 + formatteropts,
4467 + formatteropts,
4471 _('[-r REV]'))
4468 _('[-r REV]'))
4472 def manifest(ui, repo, node=None, rev=None, **opts):
4469 def manifest(ui, repo, node=None, rev=None, **opts):
4473 """output the current or given revision of the project manifest
4470 """output the current or given revision of the project manifest
4474
4471
4475 Print a list of version controlled files for the given revision.
4472 Print a list of version controlled files for the given revision.
4476 If no revision is given, the first parent of the working directory
4473 If no revision is given, the first parent of the working directory
4477 is used, or the null revision if no revision is checked out.
4474 is used, or the null revision if no revision is checked out.
4478
4475
4479 With -v, print file permissions, symlink and executable bits.
4476 With -v, print file permissions, symlink and executable bits.
4480 With --debug, print file revision hashes.
4477 With --debug, print file revision hashes.
4481
4478
4482 If option --all is specified, the list of all files from all revisions
4479 If option --all is specified, the list of all files from all revisions
4483 is printed. This includes deleted and renamed files.
4480 is printed. This includes deleted and renamed files.
4484
4481
4485 Returns 0 on success.
4482 Returns 0 on success.
4486 """
4483 """
4487
4484
4488 fm = ui.formatter('manifest', opts)
4485 fm = ui.formatter('manifest', opts)
4489
4486
4490 if opts.get('all'):
4487 if opts.get('all'):
4491 if rev or node:
4488 if rev or node:
4492 raise util.Abort(_("can't specify a revision with --all"))
4489 raise util.Abort(_("can't specify a revision with --all"))
4493
4490
4494 res = []
4491 res = []
4495 prefix = "data/"
4492 prefix = "data/"
4496 suffix = ".i"
4493 suffix = ".i"
4497 plen = len(prefix)
4494 plen = len(prefix)
4498 slen = len(suffix)
4495 slen = len(suffix)
4499 lock = repo.lock()
4496 lock = repo.lock()
4500 try:
4497 try:
4501 for fn, b, size in repo.store.datafiles():
4498 for fn, b, size in repo.store.datafiles():
4502 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4499 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4503 res.append(fn[plen:-slen])
4500 res.append(fn[plen:-slen])
4504 finally:
4501 finally:
4505 lock.release()
4502 lock.release()
4506 for f in res:
4503 for f in res:
4507 fm.startitem()
4504 fm.startitem()
4508 fm.write("path", '%s\n', f)
4505 fm.write("path", '%s\n', f)
4509 fm.end()
4506 fm.end()
4510 return
4507 return
4511
4508
4512 if rev and node:
4509 if rev and node:
4513 raise util.Abort(_("please specify just one revision"))
4510 raise util.Abort(_("please specify just one revision"))
4514
4511
4515 if not node:
4512 if not node:
4516 node = rev
4513 node = rev
4517
4514
4518 char = {'l': '@', 'x': '*', '': ''}
4515 char = {'l': '@', 'x': '*', '': ''}
4519 mode = {'l': '644', 'x': '755', '': '644'}
4516 mode = {'l': '644', 'x': '755', '': '644'}
4520 ctx = scmutil.revsingle(repo, node)
4517 ctx = scmutil.revsingle(repo, node)
4521 mf = ctx.manifest()
4518 mf = ctx.manifest()
4522 for f in ctx:
4519 for f in ctx:
4523 fm.startitem()
4520 fm.startitem()
4524 fl = ctx[f].flags()
4521 fl = ctx[f].flags()
4525 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4522 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4526 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4523 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4527 fm.write('path', '%s\n', f)
4524 fm.write('path', '%s\n', f)
4528 fm.end()
4525 fm.end()
4529
4526
4530 @command('^merge',
4527 @command('^merge',
4531 [('f', 'force', None,
4528 [('f', 'force', None,
4532 _('force a merge including outstanding changes (DEPRECATED)')),
4529 _('force a merge including outstanding changes (DEPRECATED)')),
4533 ('r', 'rev', '', _('revision to merge'), _('REV')),
4530 ('r', 'rev', '', _('revision to merge'), _('REV')),
4534 ('P', 'preview', None,
4531 ('P', 'preview', None,
4535 _('review revisions to merge (no merge is performed)'))
4532 _('review revisions to merge (no merge is performed)'))
4536 ] + mergetoolopts,
4533 ] + mergetoolopts,
4537 _('[-P] [-f] [[-r] REV]'))
4534 _('[-P] [-f] [[-r] REV]'))
4538 def merge(ui, repo, node=None, **opts):
4535 def merge(ui, repo, node=None, **opts):
4539 """merge working directory with another revision
4536 """merge working directory with another revision
4540
4537
4541 The current working directory is updated with all changes made in
4538 The current working directory is updated with all changes made in
4542 the requested revision since the last common predecessor revision.
4539 the requested revision since the last common predecessor revision.
4543
4540
4544 Files that changed between either parent are marked as changed for
4541 Files that changed between either parent are marked as changed for
4545 the next commit and a commit must be performed before any further
4542 the next commit and a commit must be performed before any further
4546 updates to the repository are allowed. The next commit will have
4543 updates to the repository are allowed. The next commit will have
4547 two parents.
4544 two parents.
4548
4545
4549 ``--tool`` can be used to specify the merge tool used for file
4546 ``--tool`` can be used to specify the merge tool used for file
4550 merges. It overrides the HGMERGE environment variable and your
4547 merges. It overrides the HGMERGE environment variable and your
4551 configuration files. See :hg:`help merge-tools` for options.
4548 configuration files. See :hg:`help merge-tools` for options.
4552
4549
4553 If no revision is specified, the working directory's parent is a
4550 If no revision is specified, the working directory's parent is a
4554 head revision, and the current branch contains exactly one other
4551 head revision, and the current branch contains exactly one other
4555 head, the other head is merged with by default. Otherwise, an
4552 head, the other head is merged with by default. Otherwise, an
4556 explicit revision with which to merge with must be provided.
4553 explicit revision with which to merge with must be provided.
4557
4554
4558 :hg:`resolve` must be used to resolve unresolved files.
4555 :hg:`resolve` must be used to resolve unresolved files.
4559
4556
4560 To undo an uncommitted merge, use :hg:`update --clean .` which
4557 To undo an uncommitted merge, use :hg:`update --clean .` which
4561 will check out a clean copy of the original merge parent, losing
4558 will check out a clean copy of the original merge parent, losing
4562 all changes.
4559 all changes.
4563
4560
4564 Returns 0 on success, 1 if there are unresolved files.
4561 Returns 0 on success, 1 if there are unresolved files.
4565 """
4562 """
4566
4563
4567 if opts.get('rev') and node:
4564 if opts.get('rev') and node:
4568 raise util.Abort(_("please specify just one revision"))
4565 raise util.Abort(_("please specify just one revision"))
4569 if not node:
4566 if not node:
4570 node = opts.get('rev')
4567 node = opts.get('rev')
4571
4568
4572 if node:
4569 if node:
4573 node = scmutil.revsingle(repo, node).node()
4570 node = scmutil.revsingle(repo, node).node()
4574
4571
4575 if not node and repo._bookmarkcurrent:
4572 if not node and repo._bookmarkcurrent:
4576 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4573 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4577 curhead = repo[repo._bookmarkcurrent].node()
4574 curhead = repo[repo._bookmarkcurrent].node()
4578 if len(bmheads) == 2:
4575 if len(bmheads) == 2:
4579 if curhead == bmheads[0]:
4576 if curhead == bmheads[0]:
4580 node = bmheads[1]
4577 node = bmheads[1]
4581 else:
4578 else:
4582 node = bmheads[0]
4579 node = bmheads[0]
4583 elif len(bmheads) > 2:
4580 elif len(bmheads) > 2:
4584 raise util.Abort(_("multiple matching bookmarks to merge - "
4581 raise util.Abort(_("multiple matching bookmarks to merge - "
4585 "please merge with an explicit rev or bookmark"),
4582 "please merge with an explicit rev or bookmark"),
4586 hint=_("run 'hg heads' to see all heads"))
4583 hint=_("run 'hg heads' to see all heads"))
4587 elif len(bmheads) <= 1:
4584 elif len(bmheads) <= 1:
4588 raise util.Abort(_("no matching bookmark to merge - "
4585 raise util.Abort(_("no matching bookmark to merge - "
4589 "please merge with an explicit rev or bookmark"),
4586 "please merge with an explicit rev or bookmark"),
4590 hint=_("run 'hg heads' to see all heads"))
4587 hint=_("run 'hg heads' to see all heads"))
4591
4588
4592 if not node and not repo._bookmarkcurrent:
4589 if not node and not repo._bookmarkcurrent:
4593 branch = repo[None].branch()
4590 branch = repo[None].branch()
4594 bheads = repo.branchheads(branch)
4591 bheads = repo.branchheads(branch)
4595 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4592 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4596
4593
4597 if len(nbhs) > 2:
4594 if len(nbhs) > 2:
4598 raise util.Abort(_("branch '%s' has %d heads - "
4595 raise util.Abort(_("branch '%s' has %d heads - "
4599 "please merge with an explicit rev")
4596 "please merge with an explicit rev")
4600 % (branch, len(bheads)),
4597 % (branch, len(bheads)),
4601 hint=_("run 'hg heads .' to see heads"))
4598 hint=_("run 'hg heads .' to see heads"))
4602
4599
4603 parent = repo.dirstate.p1()
4600 parent = repo.dirstate.p1()
4604 if len(nbhs) <= 1:
4601 if len(nbhs) <= 1:
4605 if len(bheads) > 1:
4602 if len(bheads) > 1:
4606 raise util.Abort(_("heads are bookmarked - "
4603 raise util.Abort(_("heads are bookmarked - "
4607 "please merge with an explicit rev"),
4604 "please merge with an explicit rev"),
4608 hint=_("run 'hg heads' to see all heads"))
4605 hint=_("run 'hg heads' to see all heads"))
4609 if len(repo.heads()) > 1:
4606 if len(repo.heads()) > 1:
4610 raise util.Abort(_("branch '%s' has one head - "
4607 raise util.Abort(_("branch '%s' has one head - "
4611 "please merge with an explicit rev")
4608 "please merge with an explicit rev")
4612 % branch,
4609 % branch,
4613 hint=_("run 'hg heads' to see all heads"))
4610 hint=_("run 'hg heads' to see all heads"))
4614 msg, hint = _('nothing to merge'), None
4611 msg, hint = _('nothing to merge'), None
4615 if parent != repo.lookup(branch):
4612 if parent != repo.lookup(branch):
4616 hint = _("use 'hg update' instead")
4613 hint = _("use 'hg update' instead")
4617 raise util.Abort(msg, hint=hint)
4614 raise util.Abort(msg, hint=hint)
4618
4615
4619 if parent not in bheads:
4616 if parent not in bheads:
4620 raise util.Abort(_('working directory not at a head revision'),
4617 raise util.Abort(_('working directory not at a head revision'),
4621 hint=_("use 'hg update' or merge with an "
4618 hint=_("use 'hg update' or merge with an "
4622 "explicit revision"))
4619 "explicit revision"))
4623 if parent == nbhs[0]:
4620 if parent == nbhs[0]:
4624 node = nbhs[-1]
4621 node = nbhs[-1]
4625 else:
4622 else:
4626 node = nbhs[0]
4623 node = nbhs[0]
4627
4624
4628 if opts.get('preview'):
4625 if opts.get('preview'):
4629 # find nodes that are ancestors of p2 but not of p1
4626 # find nodes that are ancestors of p2 but not of p1
4630 p1 = repo.lookup('.')
4627 p1 = repo.lookup('.')
4631 p2 = repo.lookup(node)
4628 p2 = repo.lookup(node)
4632 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4629 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4633
4630
4634 displayer = cmdutil.show_changeset(ui, repo, opts)
4631 displayer = cmdutil.show_changeset(ui, repo, opts)
4635 for node in nodes:
4632 for node in nodes:
4636 displayer.show(repo[node])
4633 displayer.show(repo[node])
4637 displayer.close()
4634 displayer.close()
4638 return 0
4635 return 0
4639
4636
4640 try:
4637 try:
4641 # ui.forcemerge is an internal variable, do not document
4638 # ui.forcemerge is an internal variable, do not document
4642 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4639 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4643 return hg.merge(repo, node, force=opts.get('force'))
4640 return hg.merge(repo, node, force=opts.get('force'))
4644 finally:
4641 finally:
4645 ui.setconfig('ui', 'forcemerge', '', 'merge')
4642 ui.setconfig('ui', 'forcemerge', '', 'merge')
4646
4643
4647 @command('outgoing|out',
4644 @command('outgoing|out',
4648 [('f', 'force', None, _('run even when the destination is unrelated')),
4645 [('f', 'force', None, _('run even when the destination is unrelated')),
4649 ('r', 'rev', [],
4646 ('r', 'rev', [],
4650 _('a changeset intended to be included in the destination'), _('REV')),
4647 _('a changeset intended to be included in the destination'), _('REV')),
4651 ('n', 'newest-first', None, _('show newest record first')),
4648 ('n', 'newest-first', None, _('show newest record first')),
4652 ('B', 'bookmarks', False, _('compare bookmarks')),
4649 ('B', 'bookmarks', False, _('compare bookmarks')),
4653 ('b', 'branch', [], _('a specific branch you would like to push'),
4650 ('b', 'branch', [], _('a specific branch you would like to push'),
4654 _('BRANCH')),
4651 _('BRANCH')),
4655 ] + logopts + remoteopts + subrepoopts,
4652 ] + logopts + remoteopts + subrepoopts,
4656 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4653 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4657 def outgoing(ui, repo, dest=None, **opts):
4654 def outgoing(ui, repo, dest=None, **opts):
4658 """show changesets not found in the destination
4655 """show changesets not found in the destination
4659
4656
4660 Show changesets not found in the specified destination repository
4657 Show changesets not found in the specified destination repository
4661 or the default push location. These are the changesets that would
4658 or the default push location. These are the changesets that would
4662 be pushed if a push was requested.
4659 be pushed if a push was requested.
4663
4660
4664 See pull for details of valid destination formats.
4661 See pull for details of valid destination formats.
4665
4662
4666 Returns 0 if there are outgoing changes, 1 otherwise.
4663 Returns 0 if there are outgoing changes, 1 otherwise.
4667 """
4664 """
4668 if opts.get('graph'):
4665 if opts.get('graph'):
4669 cmdutil.checkunsupportedgraphflags([], opts)
4666 cmdutil.checkunsupportedgraphflags([], opts)
4670 o, other = hg._outgoing(ui, repo, dest, opts)
4667 o, other = hg._outgoing(ui, repo, dest, opts)
4671 if not o:
4668 if not o:
4672 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4669 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4673 return
4670 return
4674
4671
4675 revdag = cmdutil.graphrevs(repo, o, opts)
4672 revdag = cmdutil.graphrevs(repo, o, opts)
4676 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4673 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4677 showparents = [ctx.node() for ctx in repo[None].parents()]
4674 showparents = [ctx.node() for ctx in repo[None].parents()]
4678 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4675 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4679 graphmod.asciiedges)
4676 graphmod.asciiedges)
4680 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4677 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4681 return 0
4678 return 0
4682
4679
4683 if opts.get('bookmarks'):
4680 if opts.get('bookmarks'):
4684 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4681 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4685 dest, branches = hg.parseurl(dest, opts.get('branch'))
4682 dest, branches = hg.parseurl(dest, opts.get('branch'))
4686 other = hg.peer(repo, opts, dest)
4683 other = hg.peer(repo, opts, dest)
4687 if 'bookmarks' not in other.listkeys('namespaces'):
4684 if 'bookmarks' not in other.listkeys('namespaces'):
4688 ui.warn(_("remote doesn't support bookmarks\n"))
4685 ui.warn(_("remote doesn't support bookmarks\n"))
4689 return 0
4686 return 0
4690 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4687 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4691 return bookmarks.diff(ui, other, repo)
4688 return bookmarks.diff(ui, other, repo)
4692
4689
4693 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4690 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4694 try:
4691 try:
4695 return hg.outgoing(ui, repo, dest, opts)
4692 return hg.outgoing(ui, repo, dest, opts)
4696 finally:
4693 finally:
4697 del repo._subtoppath
4694 del repo._subtoppath
4698
4695
4699 @command('parents',
4696 @command('parents',
4700 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4697 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4701 ] + templateopts,
4698 ] + templateopts,
4702 _('[-r REV] [FILE]'),
4699 _('[-r REV] [FILE]'),
4703 inferrepo=True)
4700 inferrepo=True)
4704 def parents(ui, repo, file_=None, **opts):
4701 def parents(ui, repo, file_=None, **opts):
4705 """show the parents of the working directory or revision (DEPRECATED)
4702 """show the parents of the working directory or revision (DEPRECATED)
4706
4703
4707 Print the working directory's parent revisions. If a revision is
4704 Print the working directory's parent revisions. If a revision is
4708 given via -r/--rev, the parent of that revision will be printed.
4705 given via -r/--rev, the parent of that revision will be printed.
4709 If a file argument is given, the revision in which the file was
4706 If a file argument is given, the revision in which the file was
4710 last changed (before the working directory revision or the
4707 last changed (before the working directory revision or the
4711 argument to --rev if given) is printed.
4708 argument to --rev if given) is printed.
4712
4709
4713 See :hg:`summary` and :hg:`help revsets` for related information.
4710 See :hg:`summary` and :hg:`help revsets` for related information.
4714
4711
4715 Returns 0 on success.
4712 Returns 0 on success.
4716 """
4713 """
4717
4714
4718 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4715 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4719
4716
4720 if file_:
4717 if file_:
4721 m = scmutil.match(ctx, (file_,), opts)
4718 m = scmutil.match(ctx, (file_,), opts)
4722 if m.anypats() or len(m.files()) != 1:
4719 if m.anypats() or len(m.files()) != 1:
4723 raise util.Abort(_('can only specify an explicit filename'))
4720 raise util.Abort(_('can only specify an explicit filename'))
4724 file_ = m.files()[0]
4721 file_ = m.files()[0]
4725 filenodes = []
4722 filenodes = []
4726 for cp in ctx.parents():
4723 for cp in ctx.parents():
4727 if not cp:
4724 if not cp:
4728 continue
4725 continue
4729 try:
4726 try:
4730 filenodes.append(cp.filenode(file_))
4727 filenodes.append(cp.filenode(file_))
4731 except error.LookupError:
4728 except error.LookupError:
4732 pass
4729 pass
4733 if not filenodes:
4730 if not filenodes:
4734 raise util.Abort(_("'%s' not found in manifest!") % file_)
4731 raise util.Abort(_("'%s' not found in manifest!") % file_)
4735 p = []
4732 p = []
4736 for fn in filenodes:
4733 for fn in filenodes:
4737 fctx = repo.filectx(file_, fileid=fn)
4734 fctx = repo.filectx(file_, fileid=fn)
4738 p.append(fctx.node())
4735 p.append(fctx.node())
4739 else:
4736 else:
4740 p = [cp.node() for cp in ctx.parents()]
4737 p = [cp.node() for cp in ctx.parents()]
4741
4738
4742 displayer = cmdutil.show_changeset(ui, repo, opts)
4739 displayer = cmdutil.show_changeset(ui, repo, opts)
4743 for n in p:
4740 for n in p:
4744 if n != nullid:
4741 if n != nullid:
4745 displayer.show(repo[n])
4742 displayer.show(repo[n])
4746 displayer.close()
4743 displayer.close()
4747
4744
4748 @command('paths', [], _('[NAME]'), optionalrepo=True)
4745 @command('paths', [], _('[NAME]'), optionalrepo=True)
4749 def paths(ui, repo, search=None):
4746 def paths(ui, repo, search=None):
4750 """show aliases for remote repositories
4747 """show aliases for remote repositories
4751
4748
4752 Show definition of symbolic path name NAME. If no name is given,
4749 Show definition of symbolic path name NAME. If no name is given,
4753 show definition of all available names.
4750 show definition of all available names.
4754
4751
4755 Option -q/--quiet suppresses all output when searching for NAME
4752 Option -q/--quiet suppresses all output when searching for NAME
4756 and shows only the path names when listing all definitions.
4753 and shows only the path names when listing all definitions.
4757
4754
4758 Path names are defined in the [paths] section of your
4755 Path names are defined in the [paths] section of your
4759 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4756 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4760 repository, ``.hg/hgrc`` is used, too.
4757 repository, ``.hg/hgrc`` is used, too.
4761
4758
4762 The path names ``default`` and ``default-push`` have a special
4759 The path names ``default`` and ``default-push`` have a special
4763 meaning. When performing a push or pull operation, they are used
4760 meaning. When performing a push or pull operation, they are used
4764 as fallbacks if no location is specified on the command-line.
4761 as fallbacks if no location is specified on the command-line.
4765 When ``default-push`` is set, it will be used for push and
4762 When ``default-push`` is set, it will be used for push and
4766 ``default`` will be used for pull; otherwise ``default`` is used
4763 ``default`` will be used for pull; otherwise ``default`` is used
4767 as the fallback for both. When cloning a repository, the clone
4764 as the fallback for both. When cloning a repository, the clone
4768 source is written as ``default`` in ``.hg/hgrc``. Note that
4765 source is written as ``default`` in ``.hg/hgrc``. Note that
4769 ``default`` and ``default-push`` apply to all inbound (e.g.
4766 ``default`` and ``default-push`` apply to all inbound (e.g.
4770 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4767 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4771 :hg:`bundle`) operations.
4768 :hg:`bundle`) operations.
4772
4769
4773 See :hg:`help urls` for more information.
4770 See :hg:`help urls` for more information.
4774
4771
4775 Returns 0 on success.
4772 Returns 0 on success.
4776 """
4773 """
4777 if search:
4774 if search:
4778 for name, path in ui.configitems("paths"):
4775 for name, path in ui.configitems("paths"):
4779 if name == search:
4776 if name == search:
4780 ui.status("%s\n" % util.hidepassword(path))
4777 ui.status("%s\n" % util.hidepassword(path))
4781 return
4778 return
4782 if not ui.quiet:
4779 if not ui.quiet:
4783 ui.warn(_("not found!\n"))
4780 ui.warn(_("not found!\n"))
4784 return 1
4781 return 1
4785 else:
4782 else:
4786 for name, path in ui.configitems("paths"):
4783 for name, path in ui.configitems("paths"):
4787 if ui.quiet:
4784 if ui.quiet:
4788 ui.write("%s\n" % name)
4785 ui.write("%s\n" % name)
4789 else:
4786 else:
4790 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4787 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4791
4788
4792 @command('phase',
4789 @command('phase',
4793 [('p', 'public', False, _('set changeset phase to public')),
4790 [('p', 'public', False, _('set changeset phase to public')),
4794 ('d', 'draft', False, _('set changeset phase to draft')),
4791 ('d', 'draft', False, _('set changeset phase to draft')),
4795 ('s', 'secret', False, _('set changeset phase to secret')),
4792 ('s', 'secret', False, _('set changeset phase to secret')),
4796 ('f', 'force', False, _('allow to move boundary backward')),
4793 ('f', 'force', False, _('allow to move boundary backward')),
4797 ('r', 'rev', [], _('target revision'), _('REV')),
4794 ('r', 'rev', [], _('target revision'), _('REV')),
4798 ],
4795 ],
4799 _('[-p|-d|-s] [-f] [-r] REV...'))
4796 _('[-p|-d|-s] [-f] [-r] REV...'))
4800 def phase(ui, repo, *revs, **opts):
4797 def phase(ui, repo, *revs, **opts):
4801 """set or show the current phase name
4798 """set or show the current phase name
4802
4799
4803 With no argument, show the phase name of specified revisions.
4800 With no argument, show the phase name of specified revisions.
4804
4801
4805 With one of -p/--public, -d/--draft or -s/--secret, change the
4802 With one of -p/--public, -d/--draft or -s/--secret, change the
4806 phase value of the specified revisions.
4803 phase value of the specified revisions.
4807
4804
4808 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4805 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4809 lower phase to an higher phase. Phases are ordered as follows::
4806 lower phase to an higher phase. Phases are ordered as follows::
4810
4807
4811 public < draft < secret
4808 public < draft < secret
4812
4809
4813 Returns 0 on success, 1 if no phases were changed or some could not
4810 Returns 0 on success, 1 if no phases were changed or some could not
4814 be changed.
4811 be changed.
4815 """
4812 """
4816 # search for a unique phase argument
4813 # search for a unique phase argument
4817 targetphase = None
4814 targetphase = None
4818 for idx, name in enumerate(phases.phasenames):
4815 for idx, name in enumerate(phases.phasenames):
4819 if opts[name]:
4816 if opts[name]:
4820 if targetphase is not None:
4817 if targetphase is not None:
4821 raise util.Abort(_('only one phase can be specified'))
4818 raise util.Abort(_('only one phase can be specified'))
4822 targetphase = idx
4819 targetphase = idx
4823
4820
4824 # look for specified revision
4821 # look for specified revision
4825 revs = list(revs)
4822 revs = list(revs)
4826 revs.extend(opts['rev'])
4823 revs.extend(opts['rev'])
4827 if not revs:
4824 if not revs:
4828 raise util.Abort(_('no revisions specified'))
4825 raise util.Abort(_('no revisions specified'))
4829
4826
4830 revs = scmutil.revrange(repo, revs)
4827 revs = scmutil.revrange(repo, revs)
4831
4828
4832 lock = None
4829 lock = None
4833 ret = 0
4830 ret = 0
4834 if targetphase is None:
4831 if targetphase is None:
4835 # display
4832 # display
4836 for r in revs:
4833 for r in revs:
4837 ctx = repo[r]
4834 ctx = repo[r]
4838 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4835 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4839 else:
4836 else:
4840 tr = None
4837 tr = None
4841 lock = repo.lock()
4838 lock = repo.lock()
4842 try:
4839 try:
4843 tr = repo.transaction("phase")
4840 tr = repo.transaction("phase")
4844 # set phase
4841 # set phase
4845 if not revs:
4842 if not revs:
4846 raise util.Abort(_('empty revision set'))
4843 raise util.Abort(_('empty revision set'))
4847 nodes = [repo[r].node() for r in revs]
4844 nodes = [repo[r].node() for r in revs]
4848 olddata = repo._phasecache.getphaserevs(repo)[:]
4845 olddata = repo._phasecache.getphaserevs(repo)[:]
4849 phases.advanceboundary(repo, tr, targetphase, nodes)
4846 phases.advanceboundary(repo, tr, targetphase, nodes)
4850 if opts['force']:
4847 if opts['force']:
4851 phases.retractboundary(repo, tr, targetphase, nodes)
4848 phases.retractboundary(repo, tr, targetphase, nodes)
4852 tr.close()
4849 tr.close()
4853 finally:
4850 finally:
4854 if tr is not None:
4851 if tr is not None:
4855 tr.release()
4852 tr.release()
4856 lock.release()
4853 lock.release()
4857 # moving revision from public to draft may hide them
4854 # moving revision from public to draft may hide them
4858 # We have to check result on an unfiltered repository
4855 # We have to check result on an unfiltered repository
4859 unfi = repo.unfiltered()
4856 unfi = repo.unfiltered()
4860 newdata = repo._phasecache.getphaserevs(unfi)
4857 newdata = repo._phasecache.getphaserevs(unfi)
4861 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4858 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4862 cl = unfi.changelog
4859 cl = unfi.changelog
4863 rejected = [n for n in nodes
4860 rejected = [n for n in nodes
4864 if newdata[cl.rev(n)] < targetphase]
4861 if newdata[cl.rev(n)] < targetphase]
4865 if rejected:
4862 if rejected:
4866 ui.warn(_('cannot move %i changesets to a higher '
4863 ui.warn(_('cannot move %i changesets to a higher '
4867 'phase, use --force\n') % len(rejected))
4864 'phase, use --force\n') % len(rejected))
4868 ret = 1
4865 ret = 1
4869 if changes:
4866 if changes:
4870 msg = _('phase changed for %i changesets\n') % changes
4867 msg = _('phase changed for %i changesets\n') % changes
4871 if ret:
4868 if ret:
4872 ui.status(msg)
4869 ui.status(msg)
4873 else:
4870 else:
4874 ui.note(msg)
4871 ui.note(msg)
4875 else:
4872 else:
4876 ui.warn(_('no phases changed\n'))
4873 ui.warn(_('no phases changed\n'))
4877 ret = 1
4874 ret = 1
4878 return ret
4875 return ret
4879
4876
4880 def postincoming(ui, repo, modheads, optupdate, checkout):
4877 def postincoming(ui, repo, modheads, optupdate, checkout):
4881 if modheads == 0:
4878 if modheads == 0:
4882 return
4879 return
4883 if optupdate:
4880 if optupdate:
4884 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4881 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4885 try:
4882 try:
4886 ret = hg.update(repo, checkout)
4883 ret = hg.update(repo, checkout)
4887 except util.Abort, inst:
4884 except util.Abort, inst:
4888 ui.warn(_("not updating: %s\n") % str(inst))
4885 ui.warn(_("not updating: %s\n") % str(inst))
4889 if inst.hint:
4886 if inst.hint:
4890 ui.warn(_("(%s)\n") % inst.hint)
4887 ui.warn(_("(%s)\n") % inst.hint)
4891 return 0
4888 return 0
4892 if not ret and not checkout:
4889 if not ret and not checkout:
4893 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4890 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4894 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4891 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4895 return ret
4892 return ret
4896 if modheads > 1:
4893 if modheads > 1:
4897 currentbranchheads = len(repo.branchheads())
4894 currentbranchheads = len(repo.branchheads())
4898 if currentbranchheads == modheads:
4895 if currentbranchheads == modheads:
4899 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4896 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4900 elif currentbranchheads > 1:
4897 elif currentbranchheads > 1:
4901 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4898 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4902 "merge)\n"))
4899 "merge)\n"))
4903 else:
4900 else:
4904 ui.status(_("(run 'hg heads' to see heads)\n"))
4901 ui.status(_("(run 'hg heads' to see heads)\n"))
4905 else:
4902 else:
4906 ui.status(_("(run 'hg update' to get a working copy)\n"))
4903 ui.status(_("(run 'hg update' to get a working copy)\n"))
4907
4904
4908 @command('^pull',
4905 @command('^pull',
4909 [('u', 'update', None,
4906 [('u', 'update', None,
4910 _('update to new branch head if changesets were pulled')),
4907 _('update to new branch head if changesets were pulled')),
4911 ('f', 'force', None, _('run even when remote repository is unrelated')),
4908 ('f', 'force', None, _('run even when remote repository is unrelated')),
4912 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4909 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4913 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4910 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4914 ('b', 'branch', [], _('a specific branch you would like to pull'),
4911 ('b', 'branch', [], _('a specific branch you would like to pull'),
4915 _('BRANCH')),
4912 _('BRANCH')),
4916 ] + remoteopts,
4913 ] + remoteopts,
4917 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4914 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4918 def pull(ui, repo, source="default", **opts):
4915 def pull(ui, repo, source="default", **opts):
4919 """pull changes from the specified source
4916 """pull changes from the specified source
4920
4917
4921 Pull changes from a remote repository to a local one.
4918 Pull changes from a remote repository to a local one.
4922
4919
4923 This finds all changes from the repository at the specified path
4920 This finds all changes from the repository at the specified path
4924 or URL and adds them to a local repository (the current one unless
4921 or URL and adds them to a local repository (the current one unless
4925 -R is specified). By default, this does not update the copy of the
4922 -R is specified). By default, this does not update the copy of the
4926 project in the working directory.
4923 project in the working directory.
4927
4924
4928 Use :hg:`incoming` if you want to see what would have been added
4925 Use :hg:`incoming` if you want to see what would have been added
4929 by a pull at the time you issued this command. If you then decide
4926 by a pull at the time you issued this command. If you then decide
4930 to add those changes to the repository, you should use :hg:`pull
4927 to add those changes to the repository, you should use :hg:`pull
4931 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4928 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4932
4929
4933 If SOURCE is omitted, the 'default' path will be used.
4930 If SOURCE is omitted, the 'default' path will be used.
4934 See :hg:`help urls` for more information.
4931 See :hg:`help urls` for more information.
4935
4932
4936 Returns 0 on success, 1 if an update had unresolved files.
4933 Returns 0 on success, 1 if an update had unresolved files.
4937 """
4934 """
4938 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4935 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4939 other = hg.peer(repo, opts, source)
4936 other = hg.peer(repo, opts, source)
4940 try:
4937 try:
4941 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4938 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4942 revs, checkout = hg.addbranchrevs(repo, other, branches,
4939 revs, checkout = hg.addbranchrevs(repo, other, branches,
4943 opts.get('rev'))
4940 opts.get('rev'))
4944
4941
4945 remotebookmarks = other.listkeys('bookmarks')
4942 remotebookmarks = other.listkeys('bookmarks')
4946
4943
4947 if opts.get('bookmark'):
4944 if opts.get('bookmark'):
4948 if not revs:
4945 if not revs:
4949 revs = []
4946 revs = []
4950 for b in opts['bookmark']:
4947 for b in opts['bookmark']:
4951 if b not in remotebookmarks:
4948 if b not in remotebookmarks:
4952 raise util.Abort(_('remote bookmark %s not found!') % b)
4949 raise util.Abort(_('remote bookmark %s not found!') % b)
4953 revs.append(remotebookmarks[b])
4950 revs.append(remotebookmarks[b])
4954
4951
4955 if revs:
4952 if revs:
4956 try:
4953 try:
4957 revs = [other.lookup(rev) for rev in revs]
4954 revs = [other.lookup(rev) for rev in revs]
4958 except error.CapabilityError:
4955 except error.CapabilityError:
4959 err = _("other repository doesn't support revision lookup, "
4956 err = _("other repository doesn't support revision lookup, "
4960 "so a rev cannot be specified.")
4957 "so a rev cannot be specified.")
4961 raise util.Abort(err)
4958 raise util.Abort(err)
4962
4959
4963 modheads = exchange.pull(repo, other, heads=revs,
4960 modheads = exchange.pull(repo, other, heads=revs,
4964 force=opts.get('force'),
4961 force=opts.get('force'),
4965 bookmarks=opts.get('bookmark', ())).cgresult
4962 bookmarks=opts.get('bookmark', ())).cgresult
4966 if checkout:
4963 if checkout:
4967 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4964 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4968 repo._subtoppath = source
4965 repo._subtoppath = source
4969 try:
4966 try:
4970 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4967 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4971
4968
4972 finally:
4969 finally:
4973 del repo._subtoppath
4970 del repo._subtoppath
4974
4971
4975 finally:
4972 finally:
4976 other.close()
4973 other.close()
4977 return ret
4974 return ret
4978
4975
4979 @command('^push',
4976 @command('^push',
4980 [('f', 'force', None, _('force push')),
4977 [('f', 'force', None, _('force push')),
4981 ('r', 'rev', [],
4978 ('r', 'rev', [],
4982 _('a changeset intended to be included in the destination'),
4979 _('a changeset intended to be included in the destination'),
4983 _('REV')),
4980 _('REV')),
4984 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4981 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4985 ('b', 'branch', [],
4982 ('b', 'branch', [],
4986 _('a specific branch you would like to push'), _('BRANCH')),
4983 _('a specific branch you would like to push'), _('BRANCH')),
4987 ('', 'new-branch', False, _('allow pushing a new branch')),
4984 ('', 'new-branch', False, _('allow pushing a new branch')),
4988 ] + remoteopts,
4985 ] + remoteopts,
4989 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4986 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4990 def push(ui, repo, dest=None, **opts):
4987 def push(ui, repo, dest=None, **opts):
4991 """push changes to the specified destination
4988 """push changes to the specified destination
4992
4989
4993 Push changesets from the local repository to the specified
4990 Push changesets from the local repository to the specified
4994 destination.
4991 destination.
4995
4992
4996 This operation is symmetrical to pull: it is identical to a pull
4993 This operation is symmetrical to pull: it is identical to a pull
4997 in the destination repository from the current one.
4994 in the destination repository from the current one.
4998
4995
4999 By default, push will not allow creation of new heads at the
4996 By default, push will not allow creation of new heads at the
5000 destination, since multiple heads would make it unclear which head
4997 destination, since multiple heads would make it unclear which head
5001 to use. In this situation, it is recommended to pull and merge
4998 to use. In this situation, it is recommended to pull and merge
5002 before pushing.
4999 before pushing.
5003
5000
5004 Use --new-branch if you want to allow push to create a new named
5001 Use --new-branch if you want to allow push to create a new named
5005 branch that is not present at the destination. This allows you to
5002 branch that is not present at the destination. This allows you to
5006 only create a new branch without forcing other changes.
5003 only create a new branch without forcing other changes.
5007
5004
5008 .. note::
5005 .. note::
5009
5006
5010 Extra care should be taken with the -f/--force option,
5007 Extra care should be taken with the -f/--force option,
5011 which will push all new heads on all branches, an action which will
5008 which will push all new heads on all branches, an action which will
5012 almost always cause confusion for collaborators.
5009 almost always cause confusion for collaborators.
5013
5010
5014 If -r/--rev is used, the specified revision and all its ancestors
5011 If -r/--rev is used, the specified revision and all its ancestors
5015 will be pushed to the remote repository.
5012 will be pushed to the remote repository.
5016
5013
5017 If -B/--bookmark is used, the specified bookmarked revision, its
5014 If -B/--bookmark is used, the specified bookmarked revision, its
5018 ancestors, and the bookmark will be pushed to the remote
5015 ancestors, and the bookmark will be pushed to the remote
5019 repository.
5016 repository.
5020
5017
5021 Please see :hg:`help urls` for important details about ``ssh://``
5018 Please see :hg:`help urls` for important details about ``ssh://``
5022 URLs. If DESTINATION is omitted, a default path will be used.
5019 URLs. If DESTINATION is omitted, a default path will be used.
5023
5020
5024 Returns 0 if push was successful, 1 if nothing to push.
5021 Returns 0 if push was successful, 1 if nothing to push.
5025 """
5022 """
5026
5023
5027 if opts.get('bookmark'):
5024 if opts.get('bookmark'):
5028 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5025 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
5029 for b in opts['bookmark']:
5026 for b in opts['bookmark']:
5030 # translate -B options to -r so changesets get pushed
5027 # translate -B options to -r so changesets get pushed
5031 if b in repo._bookmarks:
5028 if b in repo._bookmarks:
5032 opts.setdefault('rev', []).append(b)
5029 opts.setdefault('rev', []).append(b)
5033 else:
5030 else:
5034 # if we try to push a deleted bookmark, translate it to null
5031 # if we try to push a deleted bookmark, translate it to null
5035 # this lets simultaneous -r, -b options continue working
5032 # this lets simultaneous -r, -b options continue working
5036 opts.setdefault('rev', []).append("null")
5033 opts.setdefault('rev', []).append("null")
5037
5034
5038 dest = ui.expandpath(dest or 'default-push', dest or 'default')
5035 dest = ui.expandpath(dest or 'default-push', dest or 'default')
5039 dest, branches = hg.parseurl(dest, opts.get('branch'))
5036 dest, branches = hg.parseurl(dest, opts.get('branch'))
5040 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5037 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
5041 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5038 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
5042 try:
5039 try:
5043 other = hg.peer(repo, opts, dest)
5040 other = hg.peer(repo, opts, dest)
5044 except error.RepoError:
5041 except error.RepoError:
5045 if dest == "default-push":
5042 if dest == "default-push":
5046 raise util.Abort(_("default repository not configured!"),
5043 raise util.Abort(_("default repository not configured!"),
5047 hint=_('see the "path" section in "hg help config"'))
5044 hint=_('see the "path" section in "hg help config"'))
5048 else:
5045 else:
5049 raise
5046 raise
5050
5047
5051 if revs:
5048 if revs:
5052 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5049 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
5053
5050
5054 repo._subtoppath = dest
5051 repo._subtoppath = dest
5055 try:
5052 try:
5056 # push subrepos depth-first for coherent ordering
5053 # push subrepos depth-first for coherent ordering
5057 c = repo['']
5054 c = repo['']
5058 subs = c.substate # only repos that are committed
5055 subs = c.substate # only repos that are committed
5059 for s in sorted(subs):
5056 for s in sorted(subs):
5060 result = c.sub(s).push(opts)
5057 result = c.sub(s).push(opts)
5061 if result == 0:
5058 if result == 0:
5062 return not result
5059 return not result
5063 finally:
5060 finally:
5064 del repo._subtoppath
5061 del repo._subtoppath
5065 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5062 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
5066 newbranch=opts.get('new_branch'),
5063 newbranch=opts.get('new_branch'),
5067 bookmarks=opts.get('bookmark', ()))
5064 bookmarks=opts.get('bookmark', ()))
5068
5065
5069 result = not pushop.cgresult
5066 result = not pushop.cgresult
5070
5067
5071 if pushop.bkresult is not None:
5068 if pushop.bkresult is not None:
5072 if pushop.bkresult == 2:
5069 if pushop.bkresult == 2:
5073 result = 2
5070 result = 2
5074 elif not result and pushop.bkresult:
5071 elif not result and pushop.bkresult:
5075 result = 2
5072 result = 2
5076
5073
5077 return result
5074 return result
5078
5075
5079 @command('recover', [])
5076 @command('recover', [])
5080 def recover(ui, repo):
5077 def recover(ui, repo):
5081 """roll back an interrupted transaction
5078 """roll back an interrupted transaction
5082
5079
5083 Recover from an interrupted commit or pull.
5080 Recover from an interrupted commit or pull.
5084
5081
5085 This command tries to fix the repository status after an
5082 This command tries to fix the repository status after an
5086 interrupted operation. It should only be necessary when Mercurial
5083 interrupted operation. It should only be necessary when Mercurial
5087 suggests it.
5084 suggests it.
5088
5085
5089 Returns 0 if successful, 1 if nothing to recover or verify fails.
5086 Returns 0 if successful, 1 if nothing to recover or verify fails.
5090 """
5087 """
5091 if repo.recover():
5088 if repo.recover():
5092 return hg.verify(repo)
5089 return hg.verify(repo)
5093 return 1
5090 return 1
5094
5091
5095 @command('^remove|rm',
5092 @command('^remove|rm',
5096 [('A', 'after', None, _('record delete for missing files')),
5093 [('A', 'after', None, _('record delete for missing files')),
5097 ('f', 'force', None,
5094 ('f', 'force', None,
5098 _('remove (and delete) file even if added or modified')),
5095 _('remove (and delete) file even if added or modified')),
5099 ] + walkopts,
5096 ] + walkopts,
5100 _('[OPTION]... FILE...'),
5097 _('[OPTION]... FILE...'),
5101 inferrepo=True)
5098 inferrepo=True)
5102 def remove(ui, repo, *pats, **opts):
5099 def remove(ui, repo, *pats, **opts):
5103 """remove the specified files on the next commit
5100 """remove the specified files on the next commit
5104
5101
5105 Schedule the indicated files for removal from the current branch.
5102 Schedule the indicated files for removal from the current branch.
5106
5103
5107 This command schedules the files to be removed at the next commit.
5104 This command schedules the files to be removed at the next commit.
5108 To undo a remove before that, see :hg:`revert`. To undo added
5105 To undo a remove before that, see :hg:`revert`. To undo added
5109 files, see :hg:`forget`.
5106 files, see :hg:`forget`.
5110
5107
5111 .. container:: verbose
5108 .. container:: verbose
5112
5109
5113 -A/--after can be used to remove only files that have already
5110 -A/--after can be used to remove only files that have already
5114 been deleted, -f/--force can be used to force deletion, and -Af
5111 been deleted, -f/--force can be used to force deletion, and -Af
5115 can be used to remove files from the next revision without
5112 can be used to remove files from the next revision without
5116 deleting them from the working directory.
5113 deleting them from the working directory.
5117
5114
5118 The following table details the behavior of remove for different
5115 The following table details the behavior of remove for different
5119 file states (columns) and option combinations (rows). The file
5116 file states (columns) and option combinations (rows). The file
5120 states are Added [A], Clean [C], Modified [M] and Missing [!]
5117 states are Added [A], Clean [C], Modified [M] and Missing [!]
5121 (as reported by :hg:`status`). The actions are Warn, Remove
5118 (as reported by :hg:`status`). The actions are Warn, Remove
5122 (from branch) and Delete (from disk):
5119 (from branch) and Delete (from disk):
5123
5120
5124 ========= == == == ==
5121 ========= == == == ==
5125 opt/state A C M !
5122 opt/state A C M !
5126 ========= == == == ==
5123 ========= == == == ==
5127 none W RD W R
5124 none W RD W R
5128 -f R RD RD R
5125 -f R RD RD R
5129 -A W W W R
5126 -A W W W R
5130 -Af R R R R
5127 -Af R R R R
5131 ========= == == == ==
5128 ========= == == == ==
5132
5129
5133 Note that remove never deletes files in Added [A] state from the
5130 Note that remove never deletes files in Added [A] state from the
5134 working directory, not even if option --force is specified.
5131 working directory, not even if option --force is specified.
5135
5132
5136 Returns 0 on success, 1 if any warnings encountered.
5133 Returns 0 on success, 1 if any warnings encountered.
5137 """
5134 """
5138
5135
5139 ret = 0
5136 ret = 0
5140 after, force = opts.get('after'), opts.get('force')
5137 after, force = opts.get('after'), opts.get('force')
5141 if not pats and not after:
5138 if not pats and not after:
5142 raise util.Abort(_('no files specified'))
5139 raise util.Abort(_('no files specified'))
5143
5140
5144 m = scmutil.match(repo[None], pats, opts)
5141 m = scmutil.match(repo[None], pats, opts)
5145 s = repo.status(match=m, clean=True)
5142 s = repo.status(match=m, clean=True)
5146 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
5143 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
5147
5144
5148 # warn about failure to delete explicit files/dirs
5145 # warn about failure to delete explicit files/dirs
5149 wctx = repo[None]
5146 wctx = repo[None]
5150 for f in m.files():
5147 for f in m.files():
5151 if f in repo.dirstate or f in wctx.dirs():
5148 if f in repo.dirstate or f in wctx.dirs():
5152 continue
5149 continue
5153 if os.path.exists(m.rel(f)):
5150 if os.path.exists(m.rel(f)):
5154 if os.path.isdir(m.rel(f)):
5151 if os.path.isdir(m.rel(f)):
5155 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
5152 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
5156 else:
5153 else:
5157 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
5154 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
5158 # missing files will generate a warning elsewhere
5155 # missing files will generate a warning elsewhere
5159 ret = 1
5156 ret = 1
5160
5157
5161 if force:
5158 if force:
5162 list = modified + deleted + clean + added
5159 list = modified + deleted + clean + added
5163 elif after:
5160 elif after:
5164 list = deleted
5161 list = deleted
5165 for f in modified + added + clean:
5162 for f in modified + added + clean:
5166 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
5163 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
5167 ret = 1
5164 ret = 1
5168 else:
5165 else:
5169 list = deleted + clean
5166 list = deleted + clean
5170 for f in modified:
5167 for f in modified:
5171 ui.warn(_('not removing %s: file is modified (use -f'
5168 ui.warn(_('not removing %s: file is modified (use -f'
5172 ' to force removal)\n') % m.rel(f))
5169 ' to force removal)\n') % m.rel(f))
5173 ret = 1
5170 ret = 1
5174 for f in added:
5171 for f in added:
5175 ui.warn(_('not removing %s: file has been marked for add'
5172 ui.warn(_('not removing %s: file has been marked for add'
5176 ' (use forget to undo)\n') % m.rel(f))
5173 ' (use forget to undo)\n') % m.rel(f))
5177 ret = 1
5174 ret = 1
5178
5175
5179 for f in sorted(list):
5176 for f in sorted(list):
5180 if ui.verbose or not m.exact(f):
5177 if ui.verbose or not m.exact(f):
5181 ui.status(_('removing %s\n') % m.rel(f))
5178 ui.status(_('removing %s\n') % m.rel(f))
5182
5179
5183 wlock = repo.wlock()
5180 wlock = repo.wlock()
5184 try:
5181 try:
5185 if not after:
5182 if not after:
5186 for f in list:
5183 for f in list:
5187 if f in added:
5184 if f in added:
5188 continue # we never unlink added files on remove
5185 continue # we never unlink added files on remove
5189 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
5186 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
5190 repo[None].forget(list)
5187 repo[None].forget(list)
5191 finally:
5188 finally:
5192 wlock.release()
5189 wlock.release()
5193
5190
5194 return ret
5191 return ret
5195
5192
5196 @command('rename|move|mv',
5193 @command('rename|move|mv',
5197 [('A', 'after', None, _('record a rename that has already occurred')),
5194 [('A', 'after', None, _('record a rename that has already occurred')),
5198 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5195 ('f', 'force', None, _('forcibly copy over an existing managed file')),
5199 ] + walkopts + dryrunopts,
5196 ] + walkopts + dryrunopts,
5200 _('[OPTION]... SOURCE... DEST'))
5197 _('[OPTION]... SOURCE... DEST'))
5201 def rename(ui, repo, *pats, **opts):
5198 def rename(ui, repo, *pats, **opts):
5202 """rename files; equivalent of copy + remove
5199 """rename files; equivalent of copy + remove
5203
5200
5204 Mark dest as copies of sources; mark sources for deletion. If dest
5201 Mark dest as copies of sources; mark sources for deletion. If dest
5205 is a directory, copies are put in that directory. If dest is a
5202 is a directory, copies are put in that directory. If dest is a
5206 file, there can only be one source.
5203 file, there can only be one source.
5207
5204
5208 By default, this command copies the contents of files as they
5205 By default, this command copies the contents of files as they
5209 exist in the working directory. If invoked with -A/--after, the
5206 exist in the working directory. If invoked with -A/--after, the
5210 operation is recorded, but no copying is performed.
5207 operation is recorded, but no copying is performed.
5211
5208
5212 This command takes effect at the next commit. To undo a rename
5209 This command takes effect at the next commit. To undo a rename
5213 before that, see :hg:`revert`.
5210 before that, see :hg:`revert`.
5214
5211
5215 Returns 0 on success, 1 if errors are encountered.
5212 Returns 0 on success, 1 if errors are encountered.
5216 """
5213 """
5217 wlock = repo.wlock(False)
5214 wlock = repo.wlock(False)
5218 try:
5215 try:
5219 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5216 return cmdutil.copy(ui, repo, pats, opts, rename=True)
5220 finally:
5217 finally:
5221 wlock.release()
5218 wlock.release()
5222
5219
5223 @command('resolve',
5220 @command('resolve',
5224 [('a', 'all', None, _('select all unresolved files')),
5221 [('a', 'all', None, _('select all unresolved files')),
5225 ('l', 'list', None, _('list state of files needing merge')),
5222 ('l', 'list', None, _('list state of files needing merge')),
5226 ('m', 'mark', None, _('mark files as resolved')),
5223 ('m', 'mark', None, _('mark files as resolved')),
5227 ('u', 'unmark', None, _('mark files as unresolved')),
5224 ('u', 'unmark', None, _('mark files as unresolved')),
5228 ('n', 'no-status', None, _('hide status prefix'))]
5225 ('n', 'no-status', None, _('hide status prefix'))]
5229 + mergetoolopts + walkopts,
5226 + mergetoolopts + walkopts,
5230 _('[OPTION]... [FILE]...'),
5227 _('[OPTION]... [FILE]...'),
5231 inferrepo=True)
5228 inferrepo=True)
5232 def resolve(ui, repo, *pats, **opts):
5229 def resolve(ui, repo, *pats, **opts):
5233 """redo merges or set/view the merge status of files
5230 """redo merges or set/view the merge status of files
5234
5231
5235 Merges with unresolved conflicts are often the result of
5232 Merges with unresolved conflicts are often the result of
5236 non-interactive merging using the ``internal:merge`` configuration
5233 non-interactive merging using the ``internal:merge`` configuration
5237 setting, or a command-line merge tool like ``diff3``. The resolve
5234 setting, or a command-line merge tool like ``diff3``. The resolve
5238 command is used to manage the files involved in a merge, after
5235 command is used to manage the files involved in a merge, after
5239 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5236 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
5240 working directory must have two parents). See :hg:`help
5237 working directory must have two parents). See :hg:`help
5241 merge-tools` for information on configuring merge tools.
5238 merge-tools` for information on configuring merge tools.
5242
5239
5243 The resolve command can be used in the following ways:
5240 The resolve command can be used in the following ways:
5244
5241
5245 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5242 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
5246 files, discarding any previous merge attempts. Re-merging is not
5243 files, discarding any previous merge attempts. Re-merging is not
5247 performed for files already marked as resolved. Use ``--all/-a``
5244 performed for files already marked as resolved. Use ``--all/-a``
5248 to select all unresolved files. ``--tool`` can be used to specify
5245 to select all unresolved files. ``--tool`` can be used to specify
5249 the merge tool used for the given files. It overrides the HGMERGE
5246 the merge tool used for the given files. It overrides the HGMERGE
5250 environment variable and your configuration files. Previous file
5247 environment variable and your configuration files. Previous file
5251 contents are saved with a ``.orig`` suffix.
5248 contents are saved with a ``.orig`` suffix.
5252
5249
5253 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5250 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
5254 (e.g. after having manually fixed-up the files). The default is
5251 (e.g. after having manually fixed-up the files). The default is
5255 to mark all unresolved files.
5252 to mark all unresolved files.
5256
5253
5257 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5254 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
5258 default is to mark all resolved files.
5255 default is to mark all resolved files.
5259
5256
5260 - :hg:`resolve -l`: list files which had or still have conflicts.
5257 - :hg:`resolve -l`: list files which had or still have conflicts.
5261 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5258 In the printed list, ``U`` = unresolved and ``R`` = resolved.
5262
5259
5263 Note that Mercurial will not let you commit files with unresolved
5260 Note that Mercurial will not let you commit files with unresolved
5264 merge conflicts. You must use :hg:`resolve -m ...` before you can
5261 merge conflicts. You must use :hg:`resolve -m ...` before you can
5265 commit after a conflicting merge.
5262 commit after a conflicting merge.
5266
5263
5267 Returns 0 on success, 1 if any files fail a resolve attempt.
5264 Returns 0 on success, 1 if any files fail a resolve attempt.
5268 """
5265 """
5269
5266
5270 all, mark, unmark, show, nostatus = \
5267 all, mark, unmark, show, nostatus = \
5271 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5268 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
5272
5269
5273 if (show and (mark or unmark)) or (mark and unmark):
5270 if (show and (mark or unmark)) or (mark and unmark):
5274 raise util.Abort(_("too many options specified"))
5271 raise util.Abort(_("too many options specified"))
5275 if pats and all:
5272 if pats and all:
5276 raise util.Abort(_("can't specify --all and patterns"))
5273 raise util.Abort(_("can't specify --all and patterns"))
5277 if not (all or pats or show or mark or unmark):
5274 if not (all or pats or show or mark or unmark):
5278 raise util.Abort(_('no files or directories specified'),
5275 raise util.Abort(_('no files or directories specified'),
5279 hint=('use --all to remerge all files'))
5276 hint=('use --all to remerge all files'))
5280
5277
5281 wlock = repo.wlock()
5278 wlock = repo.wlock()
5282 try:
5279 try:
5283 ms = mergemod.mergestate(repo)
5280 ms = mergemod.mergestate(repo)
5284
5281
5285 if not ms.active() and not show:
5282 if not ms.active() and not show:
5286 raise util.Abort(
5283 raise util.Abort(
5287 _('resolve command not applicable when not merging'))
5284 _('resolve command not applicable when not merging'))
5288
5285
5289 m = scmutil.match(repo[None], pats, opts)
5286 m = scmutil.match(repo[None], pats, opts)
5290 ret = 0
5287 ret = 0
5291 didwork = False
5288 didwork = False
5292
5289
5293 for f in ms:
5290 for f in ms:
5294 if not m(f):
5291 if not m(f):
5295 continue
5292 continue
5296
5293
5297 didwork = True
5294 didwork = True
5298
5295
5299 if show:
5296 if show:
5300 if nostatus:
5297 if nostatus:
5301 ui.write("%s\n" % f)
5298 ui.write("%s\n" % f)
5302 else:
5299 else:
5303 ui.write("%s %s\n" % (ms[f].upper(), f),
5300 ui.write("%s %s\n" % (ms[f].upper(), f),
5304 label='resolve.' +
5301 label='resolve.' +
5305 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5302 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5306 elif mark:
5303 elif mark:
5307 ms.mark(f, "r")
5304 ms.mark(f, "r")
5308 elif unmark:
5305 elif unmark:
5309 ms.mark(f, "u")
5306 ms.mark(f, "u")
5310 else:
5307 else:
5311 wctx = repo[None]
5308 wctx = repo[None]
5312
5309
5313 # backup pre-resolve (merge uses .orig for its own purposes)
5310 # backup pre-resolve (merge uses .orig for its own purposes)
5314 a = repo.wjoin(f)
5311 a = repo.wjoin(f)
5315 util.copyfile(a, a + ".resolve")
5312 util.copyfile(a, a + ".resolve")
5316
5313
5317 try:
5314 try:
5318 # resolve file
5315 # resolve file
5319 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5316 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5320 'resolve')
5317 'resolve')
5321 if ms.resolve(f, wctx):
5318 if ms.resolve(f, wctx):
5322 ret = 1
5319 ret = 1
5323 finally:
5320 finally:
5324 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5321 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5325 ms.commit()
5322 ms.commit()
5326
5323
5327 # replace filemerge's .orig file with our resolve file
5324 # replace filemerge's .orig file with our resolve file
5328 util.rename(a + ".resolve", a + ".orig")
5325 util.rename(a + ".resolve", a + ".orig")
5329
5326
5330 ms.commit()
5327 ms.commit()
5331
5328
5332 if not didwork and pats:
5329 if not didwork and pats:
5333 ui.warn(_("arguments do not match paths that need resolving\n"))
5330 ui.warn(_("arguments do not match paths that need resolving\n"))
5334
5331
5335 finally:
5332 finally:
5336 wlock.release()
5333 wlock.release()
5337
5334
5338 # Nudge users into finishing an unfinished operation. We don't print
5335 # Nudge users into finishing an unfinished operation. We don't print
5339 # this with the list/show operation because we want list/show to remain
5336 # this with the list/show operation because we want list/show to remain
5340 # machine readable.
5337 # machine readable.
5341 if not list(ms.unresolved()) and not show:
5338 if not list(ms.unresolved()) and not show:
5342 ui.status(_('(no more unresolved files)\n'))
5339 ui.status(_('(no more unresolved files)\n'))
5343
5340
5344 return ret
5341 return ret
5345
5342
5346 @command('revert',
5343 @command('revert',
5347 [('a', 'all', None, _('revert all changes when no arguments given')),
5344 [('a', 'all', None, _('revert all changes when no arguments given')),
5348 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5345 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5349 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5346 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5350 ('C', 'no-backup', None, _('do not save backup copies of files')),
5347 ('C', 'no-backup', None, _('do not save backup copies of files')),
5351 ] + walkopts + dryrunopts,
5348 ] + walkopts + dryrunopts,
5352 _('[OPTION]... [-r REV] [NAME]...'))
5349 _('[OPTION]... [-r REV] [NAME]...'))
5353 def revert(ui, repo, *pats, **opts):
5350 def revert(ui, repo, *pats, **opts):
5354 """restore files to their checkout state
5351 """restore files to their checkout state
5355
5352
5356 .. note::
5353 .. note::
5357
5354
5358 To check out earlier revisions, you should use :hg:`update REV`.
5355 To check out earlier revisions, you should use :hg:`update REV`.
5359 To cancel an uncommitted merge (and lose your changes),
5356 To cancel an uncommitted merge (and lose your changes),
5360 use :hg:`update --clean .`.
5357 use :hg:`update --clean .`.
5361
5358
5362 With no revision specified, revert the specified files or directories
5359 With no revision specified, revert the specified files or directories
5363 to the contents they had in the parent of the working directory.
5360 to the contents they had in the parent of the working directory.
5364 This restores the contents of files to an unmodified
5361 This restores the contents of files to an unmodified
5365 state and unschedules adds, removes, copies, and renames. If the
5362 state and unschedules adds, removes, copies, and renames. If the
5366 working directory has two parents, you must explicitly specify a
5363 working directory has two parents, you must explicitly specify a
5367 revision.
5364 revision.
5368
5365
5369 Using the -r/--rev or -d/--date options, revert the given files or
5366 Using the -r/--rev or -d/--date options, revert the given files or
5370 directories to their states as of a specific revision. Because
5367 directories to their states as of a specific revision. Because
5371 revert does not change the working directory parents, this will
5368 revert does not change the working directory parents, this will
5372 cause these files to appear modified. This can be helpful to "back
5369 cause these files to appear modified. This can be helpful to "back
5373 out" some or all of an earlier change. See :hg:`backout` for a
5370 out" some or all of an earlier change. See :hg:`backout` for a
5374 related method.
5371 related method.
5375
5372
5376 Modified files are saved with a .orig suffix before reverting.
5373 Modified files are saved with a .orig suffix before reverting.
5377 To disable these backups, use --no-backup.
5374 To disable these backups, use --no-backup.
5378
5375
5379 See :hg:`help dates` for a list of formats valid for -d/--date.
5376 See :hg:`help dates` for a list of formats valid for -d/--date.
5380
5377
5381 Returns 0 on success.
5378 Returns 0 on success.
5382 """
5379 """
5383
5380
5384 if opts.get("date"):
5381 if opts.get("date"):
5385 if opts.get("rev"):
5382 if opts.get("rev"):
5386 raise util.Abort(_("you can't specify a revision and a date"))
5383 raise util.Abort(_("you can't specify a revision and a date"))
5387 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5384 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5388
5385
5389 parent, p2 = repo.dirstate.parents()
5386 parent, p2 = repo.dirstate.parents()
5390 if not opts.get('rev') and p2 != nullid:
5387 if not opts.get('rev') and p2 != nullid:
5391 # revert after merge is a trap for new users (issue2915)
5388 # revert after merge is a trap for new users (issue2915)
5392 raise util.Abort(_('uncommitted merge with no revision specified'),
5389 raise util.Abort(_('uncommitted merge with no revision specified'),
5393 hint=_('use "hg update" or see "hg help revert"'))
5390 hint=_('use "hg update" or see "hg help revert"'))
5394
5391
5395 ctx = scmutil.revsingle(repo, opts.get('rev'))
5392 ctx = scmutil.revsingle(repo, opts.get('rev'))
5396
5393
5397 if not pats and not opts.get('all'):
5394 if not pats and not opts.get('all'):
5398 msg = _("no files or directories specified")
5395 msg = _("no files or directories specified")
5399 if p2 != nullid:
5396 if p2 != nullid:
5400 hint = _("uncommitted merge, use --all to discard all changes,"
5397 hint = _("uncommitted merge, use --all to discard all changes,"
5401 " or 'hg update -C .' to abort the merge")
5398 " or 'hg update -C .' to abort the merge")
5402 raise util.Abort(msg, hint=hint)
5399 raise util.Abort(msg, hint=hint)
5403 dirty = util.any(repo.status())
5400 dirty = util.any(repo.status())
5404 node = ctx.node()
5401 node = ctx.node()
5405 if node != parent:
5402 if node != parent:
5406 if dirty:
5403 if dirty:
5407 hint = _("uncommitted changes, use --all to discard all"
5404 hint = _("uncommitted changes, use --all to discard all"
5408 " changes, or 'hg update %s' to update") % ctx.rev()
5405 " changes, or 'hg update %s' to update") % ctx.rev()
5409 else:
5406 else:
5410 hint = _("use --all to revert all files,"
5407 hint = _("use --all to revert all files,"
5411 " or 'hg update %s' to update") % ctx.rev()
5408 " or 'hg update %s' to update") % ctx.rev()
5412 elif dirty:
5409 elif dirty:
5413 hint = _("uncommitted changes, use --all to discard all changes")
5410 hint = _("uncommitted changes, use --all to discard all changes")
5414 else:
5411 else:
5415 hint = _("use --all to revert all files")
5412 hint = _("use --all to revert all files")
5416 raise util.Abort(msg, hint=hint)
5413 raise util.Abort(msg, hint=hint)
5417
5414
5418 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5415 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5419
5416
5420 @command('rollback', dryrunopts +
5417 @command('rollback', dryrunopts +
5421 [('f', 'force', False, _('ignore safety measures'))])
5418 [('f', 'force', False, _('ignore safety measures'))])
5422 def rollback(ui, repo, **opts):
5419 def rollback(ui, repo, **opts):
5423 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5420 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5424
5421
5425 Please use :hg:`commit --amend` instead of rollback to correct
5422 Please use :hg:`commit --amend` instead of rollback to correct
5426 mistakes in the last commit.
5423 mistakes in the last commit.
5427
5424
5428 This command should be used with care. There is only one level of
5425 This command should be used with care. There is only one level of
5429 rollback, and there is no way to undo a rollback. It will also
5426 rollback, and there is no way to undo a rollback. It will also
5430 restore the dirstate at the time of the last transaction, losing
5427 restore the dirstate at the time of the last transaction, losing
5431 any dirstate changes since that time. This command does not alter
5428 any dirstate changes since that time. This command does not alter
5432 the working directory.
5429 the working directory.
5433
5430
5434 Transactions are used to encapsulate the effects of all commands
5431 Transactions are used to encapsulate the effects of all commands
5435 that create new changesets or propagate existing changesets into a
5432 that create new changesets or propagate existing changesets into a
5436 repository.
5433 repository.
5437
5434
5438 .. container:: verbose
5435 .. container:: verbose
5439
5436
5440 For example, the following commands are transactional, and their
5437 For example, the following commands are transactional, and their
5441 effects can be rolled back:
5438 effects can be rolled back:
5442
5439
5443 - commit
5440 - commit
5444 - import
5441 - import
5445 - pull
5442 - pull
5446 - push (with this repository as the destination)
5443 - push (with this repository as the destination)
5447 - unbundle
5444 - unbundle
5448
5445
5449 To avoid permanent data loss, rollback will refuse to rollback a
5446 To avoid permanent data loss, rollback will refuse to rollback a
5450 commit transaction if it isn't checked out. Use --force to
5447 commit transaction if it isn't checked out. Use --force to
5451 override this protection.
5448 override this protection.
5452
5449
5453 This command is not intended for use on public repositories. Once
5450 This command is not intended for use on public repositories. Once
5454 changes are visible for pull by other users, rolling a transaction
5451 changes are visible for pull by other users, rolling a transaction
5455 back locally is ineffective (someone else may already have pulled
5452 back locally is ineffective (someone else may already have pulled
5456 the changes). Furthermore, a race is possible with readers of the
5453 the changes). Furthermore, a race is possible with readers of the
5457 repository; for example an in-progress pull from the repository
5454 repository; for example an in-progress pull from the repository
5458 may fail if a rollback is performed.
5455 may fail if a rollback is performed.
5459
5456
5460 Returns 0 on success, 1 if no rollback data is available.
5457 Returns 0 on success, 1 if no rollback data is available.
5461 """
5458 """
5462 return repo.rollback(dryrun=opts.get('dry_run'),
5459 return repo.rollback(dryrun=opts.get('dry_run'),
5463 force=opts.get('force'))
5460 force=opts.get('force'))
5464
5461
5465 @command('root', [])
5462 @command('root', [])
5466 def root(ui, repo):
5463 def root(ui, repo):
5467 """print the root (top) of the current working directory
5464 """print the root (top) of the current working directory
5468
5465
5469 Print the root directory of the current repository.
5466 Print the root directory of the current repository.
5470
5467
5471 Returns 0 on success.
5468 Returns 0 on success.
5472 """
5469 """
5473 ui.write(repo.root + "\n")
5470 ui.write(repo.root + "\n")
5474
5471
5475 @command('^serve',
5472 @command('^serve',
5476 [('A', 'accesslog', '', _('name of access log file to write to'),
5473 [('A', 'accesslog', '', _('name of access log file to write to'),
5477 _('FILE')),
5474 _('FILE')),
5478 ('d', 'daemon', None, _('run server in background')),
5475 ('d', 'daemon', None, _('run server in background')),
5479 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5476 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5480 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5477 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5481 # use string type, then we can check if something was passed
5478 # use string type, then we can check if something was passed
5482 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5479 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5483 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5480 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5484 _('ADDR')),
5481 _('ADDR')),
5485 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5482 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5486 _('PREFIX')),
5483 _('PREFIX')),
5487 ('n', 'name', '',
5484 ('n', 'name', '',
5488 _('name to show in web pages (default: working directory)'), _('NAME')),
5485 _('name to show in web pages (default: working directory)'), _('NAME')),
5489 ('', 'web-conf', '',
5486 ('', 'web-conf', '',
5490 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5487 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5491 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5488 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5492 _('FILE')),
5489 _('FILE')),
5493 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5490 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5494 ('', 'stdio', None, _('for remote clients')),
5491 ('', 'stdio', None, _('for remote clients')),
5495 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5492 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5496 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5493 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5497 ('', 'style', '', _('template style to use'), _('STYLE')),
5494 ('', 'style', '', _('template style to use'), _('STYLE')),
5498 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5495 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5499 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5496 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5500 _('[OPTION]...'),
5497 _('[OPTION]...'),
5501 optionalrepo=True)
5498 optionalrepo=True)
5502 def serve(ui, repo, **opts):
5499 def serve(ui, repo, **opts):
5503 """start stand-alone webserver
5500 """start stand-alone webserver
5504
5501
5505 Start a local HTTP repository browser and pull server. You can use
5502 Start a local HTTP repository browser and pull server. You can use
5506 this for ad-hoc sharing and browsing of repositories. It is
5503 this for ad-hoc sharing and browsing of repositories. It is
5507 recommended to use a real web server to serve a repository for
5504 recommended to use a real web server to serve a repository for
5508 longer periods of time.
5505 longer periods of time.
5509
5506
5510 Please note that the server does not implement access control.
5507 Please note that the server does not implement access control.
5511 This means that, by default, anybody can read from the server and
5508 This means that, by default, anybody can read from the server and
5512 nobody can write to it by default. Set the ``web.allow_push``
5509 nobody can write to it by default. Set the ``web.allow_push``
5513 option to ``*`` to allow everybody to push to the server. You
5510 option to ``*`` to allow everybody to push to the server. You
5514 should use a real web server if you need to authenticate users.
5511 should use a real web server if you need to authenticate users.
5515
5512
5516 By default, the server logs accesses to stdout and errors to
5513 By default, the server logs accesses to stdout and errors to
5517 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5514 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5518 files.
5515 files.
5519
5516
5520 To have the server choose a free port number to listen on, specify
5517 To have the server choose a free port number to listen on, specify
5521 a port number of 0; in this case, the server will print the port
5518 a port number of 0; in this case, the server will print the port
5522 number it uses.
5519 number it uses.
5523
5520
5524 Returns 0 on success.
5521 Returns 0 on success.
5525 """
5522 """
5526
5523
5527 if opts["stdio"] and opts["cmdserver"]:
5524 if opts["stdio"] and opts["cmdserver"]:
5528 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5525 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5529
5526
5530 if opts["stdio"]:
5527 if opts["stdio"]:
5531 if repo is None:
5528 if repo is None:
5532 raise error.RepoError(_("there is no Mercurial repository here"
5529 raise error.RepoError(_("there is no Mercurial repository here"
5533 " (.hg not found)"))
5530 " (.hg not found)"))
5534 s = sshserver.sshserver(ui, repo)
5531 s = sshserver.sshserver(ui, repo)
5535 s.serve_forever()
5532 s.serve_forever()
5536
5533
5537 if opts["cmdserver"]:
5534 if opts["cmdserver"]:
5538 s = commandserver.server(ui, repo, opts["cmdserver"])
5535 s = commandserver.server(ui, repo, opts["cmdserver"])
5539 return s.serve()
5536 return s.serve()
5540
5537
5541 # this way we can check if something was given in the command-line
5538 # this way we can check if something was given in the command-line
5542 if opts.get('port'):
5539 if opts.get('port'):
5543 opts['port'] = util.getport(opts.get('port'))
5540 opts['port'] = util.getport(opts.get('port'))
5544
5541
5545 baseui = repo and repo.baseui or ui
5542 baseui = repo and repo.baseui or ui
5546 optlist = ("name templates style address port prefix ipv6"
5543 optlist = ("name templates style address port prefix ipv6"
5547 " accesslog errorlog certificate encoding")
5544 " accesslog errorlog certificate encoding")
5548 for o in optlist.split():
5545 for o in optlist.split():
5549 val = opts.get(o, '')
5546 val = opts.get(o, '')
5550 if val in (None, ''): # should check against default options instead
5547 if val in (None, ''): # should check against default options instead
5551 continue
5548 continue
5552 baseui.setconfig("web", o, val, 'serve')
5549 baseui.setconfig("web", o, val, 'serve')
5553 if repo and repo.ui != baseui:
5550 if repo and repo.ui != baseui:
5554 repo.ui.setconfig("web", o, val, 'serve')
5551 repo.ui.setconfig("web", o, val, 'serve')
5555
5552
5556 o = opts.get('web_conf') or opts.get('webdir_conf')
5553 o = opts.get('web_conf') or opts.get('webdir_conf')
5557 if not o:
5554 if not o:
5558 if not repo:
5555 if not repo:
5559 raise error.RepoError(_("there is no Mercurial repository"
5556 raise error.RepoError(_("there is no Mercurial repository"
5560 " here (.hg not found)"))
5557 " here (.hg not found)"))
5561 o = repo
5558 o = repo
5562
5559
5563 app = hgweb.hgweb(o, baseui=baseui)
5560 app = hgweb.hgweb(o, baseui=baseui)
5564 service = httpservice(ui, app, opts)
5561 service = httpservice(ui, app, opts)
5565 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5562 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5566
5563
5567 class httpservice(object):
5564 class httpservice(object):
5568 def __init__(self, ui, app, opts):
5565 def __init__(self, ui, app, opts):
5569 self.ui = ui
5566 self.ui = ui
5570 self.app = app
5567 self.app = app
5571 self.opts = opts
5568 self.opts = opts
5572
5569
5573 def init(self):
5570 def init(self):
5574 util.setsignalhandler()
5571 util.setsignalhandler()
5575 self.httpd = hgweb_server.create_server(self.ui, self.app)
5572 self.httpd = hgweb_server.create_server(self.ui, self.app)
5576
5573
5577 if self.opts['port'] and not self.ui.verbose:
5574 if self.opts['port'] and not self.ui.verbose:
5578 return
5575 return
5579
5576
5580 if self.httpd.prefix:
5577 if self.httpd.prefix:
5581 prefix = self.httpd.prefix.strip('/') + '/'
5578 prefix = self.httpd.prefix.strip('/') + '/'
5582 else:
5579 else:
5583 prefix = ''
5580 prefix = ''
5584
5581
5585 port = ':%d' % self.httpd.port
5582 port = ':%d' % self.httpd.port
5586 if port == ':80':
5583 if port == ':80':
5587 port = ''
5584 port = ''
5588
5585
5589 bindaddr = self.httpd.addr
5586 bindaddr = self.httpd.addr
5590 if bindaddr == '0.0.0.0':
5587 if bindaddr == '0.0.0.0':
5591 bindaddr = '*'
5588 bindaddr = '*'
5592 elif ':' in bindaddr: # IPv6
5589 elif ':' in bindaddr: # IPv6
5593 bindaddr = '[%s]' % bindaddr
5590 bindaddr = '[%s]' % bindaddr
5594
5591
5595 fqaddr = self.httpd.fqaddr
5592 fqaddr = self.httpd.fqaddr
5596 if ':' in fqaddr:
5593 if ':' in fqaddr:
5597 fqaddr = '[%s]' % fqaddr
5594 fqaddr = '[%s]' % fqaddr
5598 if self.opts['port']:
5595 if self.opts['port']:
5599 write = self.ui.status
5596 write = self.ui.status
5600 else:
5597 else:
5601 write = self.ui.write
5598 write = self.ui.write
5602 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5599 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5603 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5600 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5604 self.ui.flush() # avoid buffering of status message
5601 self.ui.flush() # avoid buffering of status message
5605
5602
5606 def run(self):
5603 def run(self):
5607 self.httpd.serve_forever()
5604 self.httpd.serve_forever()
5608
5605
5609
5606
5610 @command('^status|st',
5607 @command('^status|st',
5611 [('A', 'all', None, _('show status of all files')),
5608 [('A', 'all', None, _('show status of all files')),
5612 ('m', 'modified', None, _('show only modified files')),
5609 ('m', 'modified', None, _('show only modified files')),
5613 ('a', 'added', None, _('show only added files')),
5610 ('a', 'added', None, _('show only added files')),
5614 ('r', 'removed', None, _('show only removed files')),
5611 ('r', 'removed', None, _('show only removed files')),
5615 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5612 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5616 ('c', 'clean', None, _('show only files without changes')),
5613 ('c', 'clean', None, _('show only files without changes')),
5617 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5614 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5618 ('i', 'ignored', None, _('show only ignored files')),
5615 ('i', 'ignored', None, _('show only ignored files')),
5619 ('n', 'no-status', None, _('hide status prefix')),
5616 ('n', 'no-status', None, _('hide status prefix')),
5620 ('C', 'copies', None, _('show source of copied files')),
5617 ('C', 'copies', None, _('show source of copied files')),
5621 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5618 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5622 ('', 'rev', [], _('show difference from revision'), _('REV')),
5619 ('', 'rev', [], _('show difference from revision'), _('REV')),
5623 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5620 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5624 ] + walkopts + subrepoopts + formatteropts,
5621 ] + walkopts + subrepoopts + formatteropts,
5625 _('[OPTION]... [FILE]...'),
5622 _('[OPTION]... [FILE]...'),
5626 inferrepo=True)
5623 inferrepo=True)
5627 def status(ui, repo, *pats, **opts):
5624 def status(ui, repo, *pats, **opts):
5628 """show changed files in the working directory
5625 """show changed files in the working directory
5629
5626
5630 Show status of files in the repository. If names are given, only
5627 Show status of files in the repository. If names are given, only
5631 files that match are shown. Files that are clean or ignored or
5628 files that match are shown. Files that are clean or ignored or
5632 the source of a copy/move operation, are not listed unless
5629 the source of a copy/move operation, are not listed unless
5633 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5630 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5634 Unless options described with "show only ..." are given, the
5631 Unless options described with "show only ..." are given, the
5635 options -mardu are used.
5632 options -mardu are used.
5636
5633
5637 Option -q/--quiet hides untracked (unknown and ignored) files
5634 Option -q/--quiet hides untracked (unknown and ignored) files
5638 unless explicitly requested with -u/--unknown or -i/--ignored.
5635 unless explicitly requested with -u/--unknown or -i/--ignored.
5639
5636
5640 .. note::
5637 .. note::
5641
5638
5642 status may appear to disagree with diff if permissions have
5639 status may appear to disagree with diff if permissions have
5643 changed or a merge has occurred. The standard diff format does
5640 changed or a merge has occurred. The standard diff format does
5644 not report permission changes and diff only reports changes
5641 not report permission changes and diff only reports changes
5645 relative to one merge parent.
5642 relative to one merge parent.
5646
5643
5647 If one revision is given, it is used as the base revision.
5644 If one revision is given, it is used as the base revision.
5648 If two revisions are given, the differences between them are
5645 If two revisions are given, the differences between them are
5649 shown. The --change option can also be used as a shortcut to list
5646 shown. The --change option can also be used as a shortcut to list
5650 the changed files of a revision from its first parent.
5647 the changed files of a revision from its first parent.
5651
5648
5652 The codes used to show the status of files are::
5649 The codes used to show the status of files are::
5653
5650
5654 M = modified
5651 M = modified
5655 A = added
5652 A = added
5656 R = removed
5653 R = removed
5657 C = clean
5654 C = clean
5658 ! = missing (deleted by non-hg command, but still tracked)
5655 ! = missing (deleted by non-hg command, but still tracked)
5659 ? = not tracked
5656 ? = not tracked
5660 I = ignored
5657 I = ignored
5661 = origin of the previous file (with --copies)
5658 = origin of the previous file (with --copies)
5662
5659
5663 .. container:: verbose
5660 .. container:: verbose
5664
5661
5665 Examples:
5662 Examples:
5666
5663
5667 - show changes in the working directory relative to a
5664 - show changes in the working directory relative to a
5668 changeset::
5665 changeset::
5669
5666
5670 hg status --rev 9353
5667 hg status --rev 9353
5671
5668
5672 - show all changes including copies in an existing changeset::
5669 - show all changes including copies in an existing changeset::
5673
5670
5674 hg status --copies --change 9353
5671 hg status --copies --change 9353
5675
5672
5676 - get a NUL separated list of added files, suitable for xargs::
5673 - get a NUL separated list of added files, suitable for xargs::
5677
5674
5678 hg status -an0
5675 hg status -an0
5679
5676
5680 Returns 0 on success.
5677 Returns 0 on success.
5681 """
5678 """
5682
5679
5683 revs = opts.get('rev')
5680 revs = opts.get('rev')
5684 change = opts.get('change')
5681 change = opts.get('change')
5685
5682
5686 if revs and change:
5683 if revs and change:
5687 msg = _('cannot specify --rev and --change at the same time')
5684 msg = _('cannot specify --rev and --change at the same time')
5688 raise util.Abort(msg)
5685 raise util.Abort(msg)
5689 elif change:
5686 elif change:
5690 node2 = scmutil.revsingle(repo, change, None).node()
5687 node2 = scmutil.revsingle(repo, change, None).node()
5691 node1 = repo[node2].p1().node()
5688 node1 = repo[node2].p1().node()
5692 else:
5689 else:
5693 node1, node2 = scmutil.revpair(repo, revs)
5690 node1, node2 = scmutil.revpair(repo, revs)
5694
5691
5695 cwd = (pats and repo.getcwd()) or ''
5692 cwd = (pats and repo.getcwd()) or ''
5696 end = opts.get('print0') and '\0' or '\n'
5693 end = opts.get('print0') and '\0' or '\n'
5697 copy = {}
5694 copy = {}
5698 states = 'modified added removed deleted unknown ignored clean'.split()
5695 states = 'modified added removed deleted unknown ignored clean'.split()
5699 show = [k for k in states if opts.get(k)]
5696 show = [k for k in states if opts.get(k)]
5700 if opts.get('all'):
5697 if opts.get('all'):
5701 show += ui.quiet and (states[:4] + ['clean']) or states
5698 show += ui.quiet and (states[:4] + ['clean']) or states
5702 if not show:
5699 if not show:
5703 show = ui.quiet and states[:4] or states[:5]
5700 show = ui.quiet and states[:4] or states[:5]
5704
5701
5705 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5702 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5706 'ignored' in show, 'clean' in show, 'unknown' in show,
5703 'ignored' in show, 'clean' in show, 'unknown' in show,
5707 opts.get('subrepos'))
5704 opts.get('subrepos'))
5708 changestates = zip(states, 'MAR!?IC', stat)
5705 changestates = zip(states, 'MAR!?IC', stat)
5709
5706
5710 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5707 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5711 copy = copies.pathcopies(repo[node1], repo[node2])
5708 copy = copies.pathcopies(repo[node1], repo[node2])
5712
5709
5713 fm = ui.formatter('status', opts)
5710 fm = ui.formatter('status', opts)
5714 fmt = '%s' + end
5711 fmt = '%s' + end
5715 showchar = not opts.get('no_status')
5712 showchar = not opts.get('no_status')
5716
5713
5717 for state, char, files in changestates:
5714 for state, char, files in changestates:
5718 if state in show:
5715 if state in show:
5719 label = 'status.' + state
5716 label = 'status.' + state
5720 for f in files:
5717 for f in files:
5721 fm.startitem()
5718 fm.startitem()
5722 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5719 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5723 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5720 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5724 if f in copy:
5721 if f in copy:
5725 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5722 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5726 label='status.copied')
5723 label='status.copied')
5727 fm.end()
5724 fm.end()
5728
5725
5729 @command('^summary|sum',
5726 @command('^summary|sum',
5730 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5727 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5731 def summary(ui, repo, **opts):
5728 def summary(ui, repo, **opts):
5732 """summarize working directory state
5729 """summarize working directory state
5733
5730
5734 This generates a brief summary of the working directory state,
5731 This generates a brief summary of the working directory state,
5735 including parents, branch, commit status, and available updates.
5732 including parents, branch, commit status, and available updates.
5736
5733
5737 With the --remote option, this will check the default paths for
5734 With the --remote option, this will check the default paths for
5738 incoming and outgoing changes. This can be time-consuming.
5735 incoming and outgoing changes. This can be time-consuming.
5739
5736
5740 Returns 0 on success.
5737 Returns 0 on success.
5741 """
5738 """
5742
5739
5743 ctx = repo[None]
5740 ctx = repo[None]
5744 parents = ctx.parents()
5741 parents = ctx.parents()
5745 pnode = parents[0].node()
5742 pnode = parents[0].node()
5746 marks = []
5743 marks = []
5747
5744
5748 for p in parents:
5745 for p in parents:
5749 # label with log.changeset (instead of log.parent) since this
5746 # label with log.changeset (instead of log.parent) since this
5750 # shows a working directory parent *changeset*:
5747 # shows a working directory parent *changeset*:
5751 # i18n: column positioning for "hg summary"
5748 # i18n: column positioning for "hg summary"
5752 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5749 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5753 label='log.changeset changeset.%s' % p.phasestr())
5750 label='log.changeset changeset.%s' % p.phasestr())
5754 ui.write(' '.join(p.tags()), label='log.tag')
5751 ui.write(' '.join(p.tags()), label='log.tag')
5755 if p.bookmarks():
5752 if p.bookmarks():
5756 marks.extend(p.bookmarks())
5753 marks.extend(p.bookmarks())
5757 if p.rev() == -1:
5754 if p.rev() == -1:
5758 if not len(repo):
5755 if not len(repo):
5759 ui.write(_(' (empty repository)'))
5756 ui.write(_(' (empty repository)'))
5760 else:
5757 else:
5761 ui.write(_(' (no revision checked out)'))
5758 ui.write(_(' (no revision checked out)'))
5762 ui.write('\n')
5759 ui.write('\n')
5763 if p.description():
5760 if p.description():
5764 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5761 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5765 label='log.summary')
5762 label='log.summary')
5766
5763
5767 branch = ctx.branch()
5764 branch = ctx.branch()
5768 bheads = repo.branchheads(branch)
5765 bheads = repo.branchheads(branch)
5769 # i18n: column positioning for "hg summary"
5766 # i18n: column positioning for "hg summary"
5770 m = _('branch: %s\n') % branch
5767 m = _('branch: %s\n') % branch
5771 if branch != 'default':
5768 if branch != 'default':
5772 ui.write(m, label='log.branch')
5769 ui.write(m, label='log.branch')
5773 else:
5770 else:
5774 ui.status(m, label='log.branch')
5771 ui.status(m, label='log.branch')
5775
5772
5776 if marks:
5773 if marks:
5777 current = repo._bookmarkcurrent
5774 current = repo._bookmarkcurrent
5778 # i18n: column positioning for "hg summary"
5775 # i18n: column positioning for "hg summary"
5779 ui.write(_('bookmarks:'), label='log.bookmark')
5776 ui.write(_('bookmarks:'), label='log.bookmark')
5780 if current is not None:
5777 if current is not None:
5781 if current in marks:
5778 if current in marks:
5782 ui.write(' *' + current, label='bookmarks.current')
5779 ui.write(' *' + current, label='bookmarks.current')
5783 marks.remove(current)
5780 marks.remove(current)
5784 else:
5781 else:
5785 ui.write(' [%s]' % current, label='bookmarks.current')
5782 ui.write(' [%s]' % current, label='bookmarks.current')
5786 for m in marks:
5783 for m in marks:
5787 ui.write(' ' + m, label='log.bookmark')
5784 ui.write(' ' + m, label='log.bookmark')
5788 ui.write('\n', label='log.bookmark')
5785 ui.write('\n', label='log.bookmark')
5789
5786
5790 st = list(repo.status(unknown=True))[:5]
5787 st = list(repo.status(unknown=True))[:5]
5791
5788
5792 c = repo.dirstate.copies()
5789 c = repo.dirstate.copies()
5793 copied, renamed = [], []
5790 copied, renamed = [], []
5794 for d, s in c.iteritems():
5791 for d, s in c.iteritems():
5795 if s in st[2]:
5792 if s in st[2]:
5796 st[2].remove(s)
5793 st[2].remove(s)
5797 renamed.append(d)
5794 renamed.append(d)
5798 else:
5795 else:
5799 copied.append(d)
5796 copied.append(d)
5800 if d in st[1]:
5797 if d in st[1]:
5801 st[1].remove(d)
5798 st[1].remove(d)
5802 st.insert(3, renamed)
5799 st.insert(3, renamed)
5803 st.insert(4, copied)
5800 st.insert(4, copied)
5804
5801
5805 ms = mergemod.mergestate(repo)
5802 ms = mergemod.mergestate(repo)
5806 st.append([f for f in ms if ms[f] == 'u'])
5803 st.append([f for f in ms if ms[f] == 'u'])
5807
5804
5808 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5805 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5809 st.append(subs)
5806 st.append(subs)
5810
5807
5811 labels = [ui.label(_('%d modified'), 'status.modified'),
5808 labels = [ui.label(_('%d modified'), 'status.modified'),
5812 ui.label(_('%d added'), 'status.added'),
5809 ui.label(_('%d added'), 'status.added'),
5813 ui.label(_('%d removed'), 'status.removed'),
5810 ui.label(_('%d removed'), 'status.removed'),
5814 ui.label(_('%d renamed'), 'status.copied'),
5811 ui.label(_('%d renamed'), 'status.copied'),
5815 ui.label(_('%d copied'), 'status.copied'),
5812 ui.label(_('%d copied'), 'status.copied'),
5816 ui.label(_('%d deleted'), 'status.deleted'),
5813 ui.label(_('%d deleted'), 'status.deleted'),
5817 ui.label(_('%d unknown'), 'status.unknown'),
5814 ui.label(_('%d unknown'), 'status.unknown'),
5818 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5815 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5819 ui.label(_('%d subrepos'), 'status.modified')]
5816 ui.label(_('%d subrepos'), 'status.modified')]
5820 t = []
5817 t = []
5821 for s, l in zip(st, labels):
5818 for s, l in zip(st, labels):
5822 if s:
5819 if s:
5823 t.append(l % len(s))
5820 t.append(l % len(s))
5824
5821
5825 t = ', '.join(t)
5822 t = ', '.join(t)
5826 cleanworkdir = False
5823 cleanworkdir = False
5827
5824
5828 if repo.vfs.exists('updatestate'):
5825 if repo.vfs.exists('updatestate'):
5829 t += _(' (interrupted update)')
5826 t += _(' (interrupted update)')
5830 elif len(parents) > 1:
5827 elif len(parents) > 1:
5831 t += _(' (merge)')
5828 t += _(' (merge)')
5832 elif branch != parents[0].branch():
5829 elif branch != parents[0].branch():
5833 t += _(' (new branch)')
5830 t += _(' (new branch)')
5834 elif (parents[0].closesbranch() and
5831 elif (parents[0].closesbranch() and
5835 pnode in repo.branchheads(branch, closed=True)):
5832 pnode in repo.branchheads(branch, closed=True)):
5836 t += _(' (head closed)')
5833 t += _(' (head closed)')
5837 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[8]):
5834 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[8]):
5838 t += _(' (clean)')
5835 t += _(' (clean)')
5839 cleanworkdir = True
5836 cleanworkdir = True
5840 elif pnode not in bheads:
5837 elif pnode not in bheads:
5841 t += _(' (new branch head)')
5838 t += _(' (new branch head)')
5842
5839
5843 if cleanworkdir:
5840 if cleanworkdir:
5844 # i18n: column positioning for "hg summary"
5841 # i18n: column positioning for "hg summary"
5845 ui.status(_('commit: %s\n') % t.strip())
5842 ui.status(_('commit: %s\n') % t.strip())
5846 else:
5843 else:
5847 # i18n: column positioning for "hg summary"
5844 # i18n: column positioning for "hg summary"
5848 ui.write(_('commit: %s\n') % t.strip())
5845 ui.write(_('commit: %s\n') % t.strip())
5849
5846
5850 # all ancestors of branch heads - all ancestors of parent = new csets
5847 # all ancestors of branch heads - all ancestors of parent = new csets
5851 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5848 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5852 bheads))
5849 bheads))
5853
5850
5854 if new == 0:
5851 if new == 0:
5855 # i18n: column positioning for "hg summary"
5852 # i18n: column positioning for "hg summary"
5856 ui.status(_('update: (current)\n'))
5853 ui.status(_('update: (current)\n'))
5857 elif pnode not in bheads:
5854 elif pnode not in bheads:
5858 # i18n: column positioning for "hg summary"
5855 # i18n: column positioning for "hg summary"
5859 ui.write(_('update: %d new changesets (update)\n') % new)
5856 ui.write(_('update: %d new changesets (update)\n') % new)
5860 else:
5857 else:
5861 # i18n: column positioning for "hg summary"
5858 # i18n: column positioning for "hg summary"
5862 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5859 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5863 (new, len(bheads)))
5860 (new, len(bheads)))
5864
5861
5865 cmdutil.summaryhooks(ui, repo)
5862 cmdutil.summaryhooks(ui, repo)
5866
5863
5867 if opts.get('remote'):
5864 if opts.get('remote'):
5868 needsincoming, needsoutgoing = True, True
5865 needsincoming, needsoutgoing = True, True
5869 else:
5866 else:
5870 needsincoming, needsoutgoing = False, False
5867 needsincoming, needsoutgoing = False, False
5871 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5868 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5872 if i:
5869 if i:
5873 needsincoming = True
5870 needsincoming = True
5874 if o:
5871 if o:
5875 needsoutgoing = True
5872 needsoutgoing = True
5876 if not needsincoming and not needsoutgoing:
5873 if not needsincoming and not needsoutgoing:
5877 return
5874 return
5878
5875
5879 def getincoming():
5876 def getincoming():
5880 source, branches = hg.parseurl(ui.expandpath('default'))
5877 source, branches = hg.parseurl(ui.expandpath('default'))
5881 sbranch = branches[0]
5878 sbranch = branches[0]
5882 try:
5879 try:
5883 other = hg.peer(repo, {}, source)
5880 other = hg.peer(repo, {}, source)
5884 except error.RepoError:
5881 except error.RepoError:
5885 if opts.get('remote'):
5882 if opts.get('remote'):
5886 raise
5883 raise
5887 return source, sbranch, None, None, None
5884 return source, sbranch, None, None, None
5888 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5885 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5889 if revs:
5886 if revs:
5890 revs = [other.lookup(rev) for rev in revs]
5887 revs = [other.lookup(rev) for rev in revs]
5891 ui.debug('comparing with %s\n' % util.hidepassword(source))
5888 ui.debug('comparing with %s\n' % util.hidepassword(source))
5892 repo.ui.pushbuffer()
5889 repo.ui.pushbuffer()
5893 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5890 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5894 repo.ui.popbuffer()
5891 repo.ui.popbuffer()
5895 return source, sbranch, other, commoninc, commoninc[1]
5892 return source, sbranch, other, commoninc, commoninc[1]
5896
5893
5897 if needsincoming:
5894 if needsincoming:
5898 source, sbranch, sother, commoninc, incoming = getincoming()
5895 source, sbranch, sother, commoninc, incoming = getincoming()
5899 else:
5896 else:
5900 source = sbranch = sother = commoninc = incoming = None
5897 source = sbranch = sother = commoninc = incoming = None
5901
5898
5902 def getoutgoing():
5899 def getoutgoing():
5903 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5900 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5904 dbranch = branches[0]
5901 dbranch = branches[0]
5905 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5902 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5906 if source != dest:
5903 if source != dest:
5907 try:
5904 try:
5908 dother = hg.peer(repo, {}, dest)
5905 dother = hg.peer(repo, {}, dest)
5909 except error.RepoError:
5906 except error.RepoError:
5910 if opts.get('remote'):
5907 if opts.get('remote'):
5911 raise
5908 raise
5912 return dest, dbranch, None, None
5909 return dest, dbranch, None, None
5913 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5910 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5914 elif sother is None:
5911 elif sother is None:
5915 # there is no explicit destination peer, but source one is invalid
5912 # there is no explicit destination peer, but source one is invalid
5916 return dest, dbranch, None, None
5913 return dest, dbranch, None, None
5917 else:
5914 else:
5918 dother = sother
5915 dother = sother
5919 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5916 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5920 common = None
5917 common = None
5921 else:
5918 else:
5922 common = commoninc
5919 common = commoninc
5923 if revs:
5920 if revs:
5924 revs = [repo.lookup(rev) for rev in revs]
5921 revs = [repo.lookup(rev) for rev in revs]
5925 repo.ui.pushbuffer()
5922 repo.ui.pushbuffer()
5926 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5923 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5927 commoninc=common)
5924 commoninc=common)
5928 repo.ui.popbuffer()
5925 repo.ui.popbuffer()
5929 return dest, dbranch, dother, outgoing
5926 return dest, dbranch, dother, outgoing
5930
5927
5931 if needsoutgoing:
5928 if needsoutgoing:
5932 dest, dbranch, dother, outgoing = getoutgoing()
5929 dest, dbranch, dother, outgoing = getoutgoing()
5933 else:
5930 else:
5934 dest = dbranch = dother = outgoing = None
5931 dest = dbranch = dother = outgoing = None
5935
5932
5936 if opts.get('remote'):
5933 if opts.get('remote'):
5937 t = []
5934 t = []
5938 if incoming:
5935 if incoming:
5939 t.append(_('1 or more incoming'))
5936 t.append(_('1 or more incoming'))
5940 o = outgoing.missing
5937 o = outgoing.missing
5941 if o:
5938 if o:
5942 t.append(_('%d outgoing') % len(o))
5939 t.append(_('%d outgoing') % len(o))
5943 other = dother or sother
5940 other = dother or sother
5944 if 'bookmarks' in other.listkeys('namespaces'):
5941 if 'bookmarks' in other.listkeys('namespaces'):
5945 lmarks = repo.listkeys('bookmarks')
5942 lmarks = repo.listkeys('bookmarks')
5946 rmarks = other.listkeys('bookmarks')
5943 rmarks = other.listkeys('bookmarks')
5947 diff = set(rmarks) - set(lmarks)
5944 diff = set(rmarks) - set(lmarks)
5948 if len(diff) > 0:
5945 if len(diff) > 0:
5949 t.append(_('%d incoming bookmarks') % len(diff))
5946 t.append(_('%d incoming bookmarks') % len(diff))
5950 diff = set(lmarks) - set(rmarks)
5947 diff = set(lmarks) - set(rmarks)
5951 if len(diff) > 0:
5948 if len(diff) > 0:
5952 t.append(_('%d outgoing bookmarks') % len(diff))
5949 t.append(_('%d outgoing bookmarks') % len(diff))
5953
5950
5954 if t:
5951 if t:
5955 # i18n: column positioning for "hg summary"
5952 # i18n: column positioning for "hg summary"
5956 ui.write(_('remote: %s\n') % (', '.join(t)))
5953 ui.write(_('remote: %s\n') % (', '.join(t)))
5957 else:
5954 else:
5958 # i18n: column positioning for "hg summary"
5955 # i18n: column positioning for "hg summary"
5959 ui.status(_('remote: (synced)\n'))
5956 ui.status(_('remote: (synced)\n'))
5960
5957
5961 cmdutil.summaryremotehooks(ui, repo, opts,
5958 cmdutil.summaryremotehooks(ui, repo, opts,
5962 ((source, sbranch, sother, commoninc),
5959 ((source, sbranch, sother, commoninc),
5963 (dest, dbranch, dother, outgoing)))
5960 (dest, dbranch, dother, outgoing)))
5964
5961
5965 @command('tag',
5962 @command('tag',
5966 [('f', 'force', None, _('force tag')),
5963 [('f', 'force', None, _('force tag')),
5967 ('l', 'local', None, _('make the tag local')),
5964 ('l', 'local', None, _('make the tag local')),
5968 ('r', 'rev', '', _('revision to tag'), _('REV')),
5965 ('r', 'rev', '', _('revision to tag'), _('REV')),
5969 ('', 'remove', None, _('remove a tag')),
5966 ('', 'remove', None, _('remove a tag')),
5970 # -l/--local is already there, commitopts cannot be used
5967 # -l/--local is already there, commitopts cannot be used
5971 ('e', 'edit', None, _('invoke editor on commit messages')),
5968 ('e', 'edit', None, _('invoke editor on commit messages')),
5972 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5969 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5973 ] + commitopts2,
5970 ] + commitopts2,
5974 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5971 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5975 def tag(ui, repo, name1, *names, **opts):
5972 def tag(ui, repo, name1, *names, **opts):
5976 """add one or more tags for the current or given revision
5973 """add one or more tags for the current or given revision
5977
5974
5978 Name a particular revision using <name>.
5975 Name a particular revision using <name>.
5979
5976
5980 Tags are used to name particular revisions of the repository and are
5977 Tags are used to name particular revisions of the repository and are
5981 very useful to compare different revisions, to go back to significant
5978 very useful to compare different revisions, to go back to significant
5982 earlier versions or to mark branch points as releases, etc. Changing
5979 earlier versions or to mark branch points as releases, etc. Changing
5983 an existing tag is normally disallowed; use -f/--force to override.
5980 an existing tag is normally disallowed; use -f/--force to override.
5984
5981
5985 If no revision is given, the parent of the working directory is
5982 If no revision is given, the parent of the working directory is
5986 used.
5983 used.
5987
5984
5988 To facilitate version control, distribution, and merging of tags,
5985 To facilitate version control, distribution, and merging of tags,
5989 they are stored as a file named ".hgtags" which is managed similarly
5986 they are stored as a file named ".hgtags" which is managed similarly
5990 to other project files and can be hand-edited if necessary. This
5987 to other project files and can be hand-edited if necessary. This
5991 also means that tagging creates a new commit. The file
5988 also means that tagging creates a new commit. The file
5992 ".hg/localtags" is used for local tags (not shared among
5989 ".hg/localtags" is used for local tags (not shared among
5993 repositories).
5990 repositories).
5994
5991
5995 Tag commits are usually made at the head of a branch. If the parent
5992 Tag commits are usually made at the head of a branch. If the parent
5996 of the working directory is not a branch head, :hg:`tag` aborts; use
5993 of the working directory is not a branch head, :hg:`tag` aborts; use
5997 -f/--force to force the tag commit to be based on a non-head
5994 -f/--force to force the tag commit to be based on a non-head
5998 changeset.
5995 changeset.
5999
5996
6000 See :hg:`help dates` for a list of formats valid for -d/--date.
5997 See :hg:`help dates` for a list of formats valid for -d/--date.
6001
5998
6002 Since tag names have priority over branch names during revision
5999 Since tag names have priority over branch names during revision
6003 lookup, using an existing branch name as a tag name is discouraged.
6000 lookup, using an existing branch name as a tag name is discouraged.
6004
6001
6005 Returns 0 on success.
6002 Returns 0 on success.
6006 """
6003 """
6007 wlock = lock = None
6004 wlock = lock = None
6008 try:
6005 try:
6009 wlock = repo.wlock()
6006 wlock = repo.wlock()
6010 lock = repo.lock()
6007 lock = repo.lock()
6011 rev_ = "."
6008 rev_ = "."
6012 names = [t.strip() for t in (name1,) + names]
6009 names = [t.strip() for t in (name1,) + names]
6013 if len(names) != len(set(names)):
6010 if len(names) != len(set(names)):
6014 raise util.Abort(_('tag names must be unique'))
6011 raise util.Abort(_('tag names must be unique'))
6015 for n in names:
6012 for n in names:
6016 scmutil.checknewlabel(repo, n, 'tag')
6013 scmutil.checknewlabel(repo, n, 'tag')
6017 if not n:
6014 if not n:
6018 raise util.Abort(_('tag names cannot consist entirely of '
6015 raise util.Abort(_('tag names cannot consist entirely of '
6019 'whitespace'))
6016 'whitespace'))
6020 if opts.get('rev') and opts.get('remove'):
6017 if opts.get('rev') and opts.get('remove'):
6021 raise util.Abort(_("--rev and --remove are incompatible"))
6018 raise util.Abort(_("--rev and --remove are incompatible"))
6022 if opts.get('rev'):
6019 if opts.get('rev'):
6023 rev_ = opts['rev']
6020 rev_ = opts['rev']
6024 message = opts.get('message')
6021 message = opts.get('message')
6025 if opts.get('remove'):
6022 if opts.get('remove'):
6026 expectedtype = opts.get('local') and 'local' or 'global'
6023 expectedtype = opts.get('local') and 'local' or 'global'
6027 for n in names:
6024 for n in names:
6028 if not repo.tagtype(n):
6025 if not repo.tagtype(n):
6029 raise util.Abort(_("tag '%s' does not exist") % n)
6026 raise util.Abort(_("tag '%s' does not exist") % n)
6030 if repo.tagtype(n) != expectedtype:
6027 if repo.tagtype(n) != expectedtype:
6031 if expectedtype == 'global':
6028 if expectedtype == 'global':
6032 raise util.Abort(_("tag '%s' is not a global tag") % n)
6029 raise util.Abort(_("tag '%s' is not a global tag") % n)
6033 else:
6030 else:
6034 raise util.Abort(_("tag '%s' is not a local tag") % n)
6031 raise util.Abort(_("tag '%s' is not a local tag") % n)
6035 rev_ = nullid
6032 rev_ = nullid
6036 if not message:
6033 if not message:
6037 # we don't translate commit messages
6034 # we don't translate commit messages
6038 message = 'Removed tag %s' % ', '.join(names)
6035 message = 'Removed tag %s' % ', '.join(names)
6039 elif not opts.get('force'):
6036 elif not opts.get('force'):
6040 for n in names:
6037 for n in names:
6041 if n in repo.tags():
6038 if n in repo.tags():
6042 raise util.Abort(_("tag '%s' already exists "
6039 raise util.Abort(_("tag '%s' already exists "
6043 "(use -f to force)") % n)
6040 "(use -f to force)") % n)
6044 if not opts.get('local'):
6041 if not opts.get('local'):
6045 p1, p2 = repo.dirstate.parents()
6042 p1, p2 = repo.dirstate.parents()
6046 if p2 != nullid:
6043 if p2 != nullid:
6047 raise util.Abort(_('uncommitted merge'))
6044 raise util.Abort(_('uncommitted merge'))
6048 bheads = repo.branchheads()
6045 bheads = repo.branchheads()
6049 if not opts.get('force') and bheads and p1 not in bheads:
6046 if not opts.get('force') and bheads and p1 not in bheads:
6050 raise util.Abort(_('not at a branch head (use -f to force)'))
6047 raise util.Abort(_('not at a branch head (use -f to force)'))
6051 r = scmutil.revsingle(repo, rev_).node()
6048 r = scmutil.revsingle(repo, rev_).node()
6052
6049
6053 if not message:
6050 if not message:
6054 # we don't translate commit messages
6051 # we don't translate commit messages
6055 message = ('Added tag %s for changeset %s' %
6052 message = ('Added tag %s for changeset %s' %
6056 (', '.join(names), short(r)))
6053 (', '.join(names), short(r)))
6057
6054
6058 date = opts.get('date')
6055 date = opts.get('date')
6059 if date:
6056 if date:
6060 date = util.parsedate(date)
6057 date = util.parsedate(date)
6061
6058
6062 if opts.get('remove'):
6059 if opts.get('remove'):
6063 editform = 'tag.remove'
6060 editform = 'tag.remove'
6064 else:
6061 else:
6065 editform = 'tag.add'
6062 editform = 'tag.add'
6066 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6063 editor = cmdutil.getcommiteditor(editform=editform, **opts)
6067
6064
6068 # don't allow tagging the null rev
6065 # don't allow tagging the null rev
6069 if (not opts.get('remove') and
6066 if (not opts.get('remove') and
6070 scmutil.revsingle(repo, rev_).rev() == nullrev):
6067 scmutil.revsingle(repo, rev_).rev() == nullrev):
6071 raise util.Abort(_("cannot tag null revision"))
6068 raise util.Abort(_("cannot tag null revision"))
6072
6069
6073 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6070 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
6074 editor=editor)
6071 editor=editor)
6075 finally:
6072 finally:
6076 release(lock, wlock)
6073 release(lock, wlock)
6077
6074
6078 @command('tags', formatteropts, '')
6075 @command('tags', formatteropts, '')
6079 def tags(ui, repo, **opts):
6076 def tags(ui, repo, **opts):
6080 """list repository tags
6077 """list repository tags
6081
6078
6082 This lists both regular and local tags. When the -v/--verbose
6079 This lists both regular and local tags. When the -v/--verbose
6083 switch is used, a third column "local" is printed for local tags.
6080 switch is used, a third column "local" is printed for local tags.
6084
6081
6085 Returns 0 on success.
6082 Returns 0 on success.
6086 """
6083 """
6087
6084
6088 fm = ui.formatter('tags', opts)
6085 fm = ui.formatter('tags', opts)
6089 if fm or ui.debugflag:
6086 hexfunc = fm.hexfunc
6090 hexfunc = hex
6091 else:
6092 hexfunc = short
6093 tagtype = ""
6087 tagtype = ""
6094
6088
6095 for t, n in reversed(repo.tagslist()):
6089 for t, n in reversed(repo.tagslist()):
6096 hn = hexfunc(n)
6090 hn = hexfunc(n)
6097 label = 'tags.normal'
6091 label = 'tags.normal'
6098 tagtype = ''
6092 tagtype = ''
6099 if repo.tagtype(t) == 'local':
6093 if repo.tagtype(t) == 'local':
6100 label = 'tags.local'
6094 label = 'tags.local'
6101 tagtype = 'local'
6095 tagtype = 'local'
6102
6096
6103 fm.startitem()
6097 fm.startitem()
6104 fm.write('tag', '%s', t, label=label)
6098 fm.write('tag', '%s', t, label=label)
6105 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6099 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
6106 fm.condwrite(not ui.quiet, 'rev node', fmt,
6100 fm.condwrite(not ui.quiet, 'rev node', fmt,
6107 repo.changelog.rev(n), hn, label=label)
6101 repo.changelog.rev(n), hn, label=label)
6108 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6102 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
6109 tagtype, label=label)
6103 tagtype, label=label)
6110 fm.plain('\n')
6104 fm.plain('\n')
6111 fm.end()
6105 fm.end()
6112
6106
6113 @command('tip',
6107 @command('tip',
6114 [('p', 'patch', None, _('show patch')),
6108 [('p', 'patch', None, _('show patch')),
6115 ('g', 'git', None, _('use git extended diff format')),
6109 ('g', 'git', None, _('use git extended diff format')),
6116 ] + templateopts,
6110 ] + templateopts,
6117 _('[-p] [-g]'))
6111 _('[-p] [-g]'))
6118 def tip(ui, repo, **opts):
6112 def tip(ui, repo, **opts):
6119 """show the tip revision (DEPRECATED)
6113 """show the tip revision (DEPRECATED)
6120
6114
6121 The tip revision (usually just called the tip) is the changeset
6115 The tip revision (usually just called the tip) is the changeset
6122 most recently added to the repository (and therefore the most
6116 most recently added to the repository (and therefore the most
6123 recently changed head).
6117 recently changed head).
6124
6118
6125 If you have just made a commit, that commit will be the tip. If
6119 If you have just made a commit, that commit will be the tip. If
6126 you have just pulled changes from another repository, the tip of
6120 you have just pulled changes from another repository, the tip of
6127 that repository becomes the current tip. The "tip" tag is special
6121 that repository becomes the current tip. The "tip" tag is special
6128 and cannot be renamed or assigned to a different changeset.
6122 and cannot be renamed or assigned to a different changeset.
6129
6123
6130 This command is deprecated, please use :hg:`heads` instead.
6124 This command is deprecated, please use :hg:`heads` instead.
6131
6125
6132 Returns 0 on success.
6126 Returns 0 on success.
6133 """
6127 """
6134 displayer = cmdutil.show_changeset(ui, repo, opts)
6128 displayer = cmdutil.show_changeset(ui, repo, opts)
6135 displayer.show(repo['tip'])
6129 displayer.show(repo['tip'])
6136 displayer.close()
6130 displayer.close()
6137
6131
6138 @command('unbundle',
6132 @command('unbundle',
6139 [('u', 'update', None,
6133 [('u', 'update', None,
6140 _('update to new branch head if changesets were unbundled'))],
6134 _('update to new branch head if changesets were unbundled'))],
6141 _('[-u] FILE...'))
6135 _('[-u] FILE...'))
6142 def unbundle(ui, repo, fname1, *fnames, **opts):
6136 def unbundle(ui, repo, fname1, *fnames, **opts):
6143 """apply one or more changegroup files
6137 """apply one or more changegroup files
6144
6138
6145 Apply one or more compressed changegroup files generated by the
6139 Apply one or more compressed changegroup files generated by the
6146 bundle command.
6140 bundle command.
6147
6141
6148 Returns 0 on success, 1 if an update has unresolved files.
6142 Returns 0 on success, 1 if an update has unresolved files.
6149 """
6143 """
6150 fnames = (fname1,) + fnames
6144 fnames = (fname1,) + fnames
6151
6145
6152 lock = repo.lock()
6146 lock = repo.lock()
6153 try:
6147 try:
6154 for fname in fnames:
6148 for fname in fnames:
6155 f = hg.openpath(ui, fname)
6149 f = hg.openpath(ui, fname)
6156 gen = exchange.readbundle(ui, f, fname)
6150 gen = exchange.readbundle(ui, f, fname)
6157 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
6151 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
6158 'bundle:' + fname)
6152 'bundle:' + fname)
6159 finally:
6153 finally:
6160 lock.release()
6154 lock.release()
6161
6155
6162 return postincoming(ui, repo, modheads, opts.get('update'), None)
6156 return postincoming(ui, repo, modheads, opts.get('update'), None)
6163
6157
6164 @command('^update|up|checkout|co',
6158 @command('^update|up|checkout|co',
6165 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6159 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6166 ('c', 'check', None,
6160 ('c', 'check', None,
6167 _('update across branches if no uncommitted changes')),
6161 _('update across branches if no uncommitted changes')),
6168 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6162 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6169 ('r', 'rev', '', _('revision'), _('REV'))
6163 ('r', 'rev', '', _('revision'), _('REV'))
6170 ] + mergetoolopts,
6164 ] + mergetoolopts,
6171 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6165 _('[-c] [-C] [-d DATE] [[-r] REV]'))
6172 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6166 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
6173 tool=None):
6167 tool=None):
6174 """update working directory (or switch revisions)
6168 """update working directory (or switch revisions)
6175
6169
6176 Update the repository's working directory to the specified
6170 Update the repository's working directory to the specified
6177 changeset. If no changeset is specified, update to the tip of the
6171 changeset. If no changeset is specified, update to the tip of the
6178 current named branch and move the current bookmark (see :hg:`help
6172 current named branch and move the current bookmark (see :hg:`help
6179 bookmarks`).
6173 bookmarks`).
6180
6174
6181 Update sets the working directory's parent revision to the specified
6175 Update sets the working directory's parent revision to the specified
6182 changeset (see :hg:`help parents`).
6176 changeset (see :hg:`help parents`).
6183
6177
6184 If the changeset is not a descendant or ancestor of the working
6178 If the changeset is not a descendant or ancestor of the working
6185 directory's parent, the update is aborted. With the -c/--check
6179 directory's parent, the update is aborted. With the -c/--check
6186 option, the working directory is checked for uncommitted changes; if
6180 option, the working directory is checked for uncommitted changes; if
6187 none are found, the working directory is updated to the specified
6181 none are found, the working directory is updated to the specified
6188 changeset.
6182 changeset.
6189
6183
6190 .. container:: verbose
6184 .. container:: verbose
6191
6185
6192 The following rules apply when the working directory contains
6186 The following rules apply when the working directory contains
6193 uncommitted changes:
6187 uncommitted changes:
6194
6188
6195 1. If neither -c/--check nor -C/--clean is specified, and if
6189 1. If neither -c/--check nor -C/--clean is specified, and if
6196 the requested changeset is an ancestor or descendant of
6190 the requested changeset is an ancestor or descendant of
6197 the working directory's parent, the uncommitted changes
6191 the working directory's parent, the uncommitted changes
6198 are merged into the requested changeset and the merged
6192 are merged into the requested changeset and the merged
6199 result is left uncommitted. If the requested changeset is
6193 result is left uncommitted. If the requested changeset is
6200 not an ancestor or descendant (that is, it is on another
6194 not an ancestor or descendant (that is, it is on another
6201 branch), the update is aborted and the uncommitted changes
6195 branch), the update is aborted and the uncommitted changes
6202 are preserved.
6196 are preserved.
6203
6197
6204 2. With the -c/--check option, the update is aborted and the
6198 2. With the -c/--check option, the update is aborted and the
6205 uncommitted changes are preserved.
6199 uncommitted changes are preserved.
6206
6200
6207 3. With the -C/--clean option, uncommitted changes are discarded and
6201 3. With the -C/--clean option, uncommitted changes are discarded and
6208 the working directory is updated to the requested changeset.
6202 the working directory is updated to the requested changeset.
6209
6203
6210 To cancel an uncommitted merge (and lose your changes), use
6204 To cancel an uncommitted merge (and lose your changes), use
6211 :hg:`update --clean .`.
6205 :hg:`update --clean .`.
6212
6206
6213 Use null as the changeset to remove the working directory (like
6207 Use null as the changeset to remove the working directory (like
6214 :hg:`clone -U`).
6208 :hg:`clone -U`).
6215
6209
6216 If you want to revert just one file to an older revision, use
6210 If you want to revert just one file to an older revision, use
6217 :hg:`revert [-r REV] NAME`.
6211 :hg:`revert [-r REV] NAME`.
6218
6212
6219 See :hg:`help dates` for a list of formats valid for -d/--date.
6213 See :hg:`help dates` for a list of formats valid for -d/--date.
6220
6214
6221 Returns 0 on success, 1 if there are unresolved files.
6215 Returns 0 on success, 1 if there are unresolved files.
6222 """
6216 """
6223 if rev and node:
6217 if rev and node:
6224 raise util.Abort(_("please specify just one revision"))
6218 raise util.Abort(_("please specify just one revision"))
6225
6219
6226 if rev is None or rev == '':
6220 if rev is None or rev == '':
6227 rev = node
6221 rev = node
6228
6222
6229 cmdutil.clearunfinished(repo)
6223 cmdutil.clearunfinished(repo)
6230
6224
6231 # with no argument, we also move the current bookmark, if any
6225 # with no argument, we also move the current bookmark, if any
6232 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
6226 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
6233
6227
6234 # if we defined a bookmark, we have to remember the original bookmark name
6228 # if we defined a bookmark, we have to remember the original bookmark name
6235 brev = rev
6229 brev = rev
6236 rev = scmutil.revsingle(repo, rev, rev).rev()
6230 rev = scmutil.revsingle(repo, rev, rev).rev()
6237
6231
6238 if check and clean:
6232 if check and clean:
6239 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
6233 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
6240
6234
6241 if date:
6235 if date:
6242 if rev is not None:
6236 if rev is not None:
6243 raise util.Abort(_("you can't specify a revision and a date"))
6237 raise util.Abort(_("you can't specify a revision and a date"))
6244 rev = cmdutil.finddate(ui, repo, date)
6238 rev = cmdutil.finddate(ui, repo, date)
6245
6239
6246 if check:
6240 if check:
6247 c = repo[None]
6241 c = repo[None]
6248 if c.dirty(merge=False, branch=False, missing=True):
6242 if c.dirty(merge=False, branch=False, missing=True):
6249 raise util.Abort(_("uncommitted changes"))
6243 raise util.Abort(_("uncommitted changes"))
6250 if rev is None:
6244 if rev is None:
6251 rev = repo[repo[None].branch()].rev()
6245 rev = repo[repo[None].branch()].rev()
6252 mergemod._checkunknown(repo, repo[None], repo[rev])
6246 mergemod._checkunknown(repo, repo[None], repo[rev])
6253
6247
6254 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6248 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
6255
6249
6256 if clean:
6250 if clean:
6257 ret = hg.clean(repo, rev)
6251 ret = hg.clean(repo, rev)
6258 else:
6252 else:
6259 ret = hg.update(repo, rev)
6253 ret = hg.update(repo, rev)
6260
6254
6261 if not ret and movemarkfrom:
6255 if not ret and movemarkfrom:
6262 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6256 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
6263 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
6257 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
6264 elif brev in repo._bookmarks:
6258 elif brev in repo._bookmarks:
6265 bookmarks.setcurrent(repo, brev)
6259 bookmarks.setcurrent(repo, brev)
6266 ui.status(_("(activating bookmark %s)\n") % brev)
6260 ui.status(_("(activating bookmark %s)\n") % brev)
6267 elif brev:
6261 elif brev:
6268 if repo._bookmarkcurrent:
6262 if repo._bookmarkcurrent:
6269 ui.status(_("(leaving bookmark %s)\n") %
6263 ui.status(_("(leaving bookmark %s)\n") %
6270 repo._bookmarkcurrent)
6264 repo._bookmarkcurrent)
6271 bookmarks.unsetcurrent(repo)
6265 bookmarks.unsetcurrent(repo)
6272
6266
6273 return ret
6267 return ret
6274
6268
6275 @command('verify', [])
6269 @command('verify', [])
6276 def verify(ui, repo):
6270 def verify(ui, repo):
6277 """verify the integrity of the repository
6271 """verify the integrity of the repository
6278
6272
6279 Verify the integrity of the current repository.
6273 Verify the integrity of the current repository.
6280
6274
6281 This will perform an extensive check of the repository's
6275 This will perform an extensive check of the repository's
6282 integrity, validating the hashes and checksums of each entry in
6276 integrity, validating the hashes and checksums of each entry in
6283 the changelog, manifest, and tracked files, as well as the
6277 the changelog, manifest, and tracked files, as well as the
6284 integrity of their crosslinks and indices.
6278 integrity of their crosslinks and indices.
6285
6279
6286 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
6280 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
6287 for more information about recovery from corruption of the
6281 for more information about recovery from corruption of the
6288 repository.
6282 repository.
6289
6283
6290 Returns 0 on success, 1 if errors are encountered.
6284 Returns 0 on success, 1 if errors are encountered.
6291 """
6285 """
6292 return hg.verify(repo)
6286 return hg.verify(repo)
6293
6287
6294 @command('version', [], norepo=True)
6288 @command('version', [], norepo=True)
6295 def version_(ui):
6289 def version_(ui):
6296 """output version and copyright information"""
6290 """output version and copyright information"""
6297 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6291 ui.write(_("Mercurial Distributed SCM (version %s)\n")
6298 % util.version())
6292 % util.version())
6299 ui.status(_(
6293 ui.status(_(
6300 "(see http://mercurial.selenic.com for more information)\n"
6294 "(see http://mercurial.selenic.com for more information)\n"
6301 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
6295 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
6302 "This is free software; see the source for copying conditions. "
6296 "This is free software; see the source for copying conditions. "
6303 "There is NO\nwarranty; "
6297 "There is NO\nwarranty; "
6304 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6298 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6305 ))
6299 ))
6306
6300
6307 ui.note(_("\nEnabled extensions:\n\n"))
6301 ui.note(_("\nEnabled extensions:\n\n"))
6308 if ui.verbose:
6302 if ui.verbose:
6309 # format names and versions into columns
6303 # format names and versions into columns
6310 names = []
6304 names = []
6311 vers = []
6305 vers = []
6312 for name, module in extensions.extensions():
6306 for name, module in extensions.extensions():
6313 names.append(name)
6307 names.append(name)
6314 vers.append(extensions.moduleversion(module))
6308 vers.append(extensions.moduleversion(module))
6315 if names:
6309 if names:
6316 maxnamelen = max(len(n) for n in names)
6310 maxnamelen = max(len(n) for n in names)
6317 for i, name in enumerate(names):
6311 for i, name in enumerate(names):
6318 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
6312 ui.write(" %-*s %s\n" % (maxnamelen, name, vers[i]))
@@ -1,141 +1,148 b''
1 # formatter.py - generic output formatting for mercurial
1 # formatter.py - generic output formatting for mercurial
2 #
2 #
3 # Copyright 2012 Matt Mackall <mpm@selenic.com>
3 # Copyright 2012 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 import cPickle
8 import cPickle
9 from node import hex, short
9 from i18n import _
10 from i18n import _
10 import encoding, util
11 import encoding, util
11
12
12 class baseformatter(object):
13 class baseformatter(object):
13 def __init__(self, ui, topic, opts):
14 def __init__(self, ui, topic, opts):
14 self._ui = ui
15 self._ui = ui
15 self._topic = topic
16 self._topic = topic
16 self._style = opts.get("style")
17 self._style = opts.get("style")
17 self._template = opts.get("template")
18 self._template = opts.get("template")
18 self._item = None
19 self._item = None
20 # function to convert node to string suitable for this output
21 self.hexfunc = hex
19 def __nonzero__(self):
22 def __nonzero__(self):
20 '''return False if we're not doing real templating so we can
23 '''return False if we're not doing real templating so we can
21 skip extra work'''
24 skip extra work'''
22 return True
25 return True
23 def _showitem(self):
26 def _showitem(self):
24 '''show a formatted item once all data is collected'''
27 '''show a formatted item once all data is collected'''
25 pass
28 pass
26 def startitem(self):
29 def startitem(self):
27 '''begin an item in the format list'''
30 '''begin an item in the format list'''
28 if self._item is not None:
31 if self._item is not None:
29 self._showitem()
32 self._showitem()
30 self._item = {}
33 self._item = {}
31 def data(self, **data):
34 def data(self, **data):
32 '''insert data into item that's not shown in default output'''
35 '''insert data into item that's not shown in default output'''
33 self._item.update(data)
36 self._item.update(data)
34 def write(self, fields, deftext, *fielddata, **opts):
37 def write(self, fields, deftext, *fielddata, **opts):
35 '''do default text output while assigning data to item'''
38 '''do default text output while assigning data to item'''
36 for k, v in zip(fields.split(), fielddata):
39 for k, v in zip(fields.split(), fielddata):
37 self._item[k] = v
40 self._item[k] = v
38 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
41 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
39 '''do conditional write (primarily for plain formatter)'''
42 '''do conditional write (primarily for plain formatter)'''
40 for k, v in zip(fields.split(), fielddata):
43 for k, v in zip(fields.split(), fielddata):
41 self._item[k] = v
44 self._item[k] = v
42 def plain(self, text, **opts):
45 def plain(self, text, **opts):
43 '''show raw text for non-templated mode'''
46 '''show raw text for non-templated mode'''
44 pass
47 pass
45 def end(self):
48 def end(self):
46 '''end output for the formatter'''
49 '''end output for the formatter'''
47 if self._item is not None:
50 if self._item is not None:
48 self._showitem()
51 self._showitem()
49
52
50 class plainformatter(baseformatter):
53 class plainformatter(baseformatter):
51 '''the default text output scheme'''
54 '''the default text output scheme'''
52 def __init__(self, ui, topic, opts):
55 def __init__(self, ui, topic, opts):
53 baseformatter.__init__(self, ui, topic, opts)
56 baseformatter.__init__(self, ui, topic, opts)
57 if ui.debugflag:
58 self.hexfunc = hex
59 else:
60 self.hexfunc = short
54 def __nonzero__(self):
61 def __nonzero__(self):
55 return False
62 return False
56 def startitem(self):
63 def startitem(self):
57 pass
64 pass
58 def data(self, **data):
65 def data(self, **data):
59 pass
66 pass
60 def write(self, fields, deftext, *fielddata, **opts):
67 def write(self, fields, deftext, *fielddata, **opts):
61 self._ui.write(deftext % fielddata, **opts)
68 self._ui.write(deftext % fielddata, **opts)
62 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
69 def condwrite(self, cond, fields, deftext, *fielddata, **opts):
63 '''do conditional write'''
70 '''do conditional write'''
64 if cond:
71 if cond:
65 self._ui.write(deftext % fielddata, **opts)
72 self._ui.write(deftext % fielddata, **opts)
66 def plain(self, text, **opts):
73 def plain(self, text, **opts):
67 self._ui.write(text, **opts)
74 self._ui.write(text, **opts)
68 def end(self):
75 def end(self):
69 pass
76 pass
70
77
71 class debugformatter(baseformatter):
78 class debugformatter(baseformatter):
72 def __init__(self, ui, topic, opts):
79 def __init__(self, ui, topic, opts):
73 baseformatter.__init__(self, ui, topic, opts)
80 baseformatter.__init__(self, ui, topic, opts)
74 self._ui.write("%s = [\n" % self._topic)
81 self._ui.write("%s = [\n" % self._topic)
75 def _showitem(self):
82 def _showitem(self):
76 self._ui.write(" " + repr(self._item) + ",\n")
83 self._ui.write(" " + repr(self._item) + ",\n")
77 def end(self):
84 def end(self):
78 baseformatter.end(self)
85 baseformatter.end(self)
79 self._ui.write("]\n")
86 self._ui.write("]\n")
80
87
81 class pickleformatter(baseformatter):
88 class pickleformatter(baseformatter):
82 def __init__(self, ui, topic, opts):
89 def __init__(self, ui, topic, opts):
83 baseformatter.__init__(self, ui, topic, opts)
90 baseformatter.__init__(self, ui, topic, opts)
84 self._data = []
91 self._data = []
85 def _showitem(self):
92 def _showitem(self):
86 self._data.append(self._item)
93 self._data.append(self._item)
87 def end(self):
94 def end(self):
88 baseformatter.end(self)
95 baseformatter.end(self)
89 self._ui.write(cPickle.dumps(self._data))
96 self._ui.write(cPickle.dumps(self._data))
90
97
91 def _jsonifyobj(v):
98 def _jsonifyobj(v):
92 if isinstance(v, tuple):
99 if isinstance(v, tuple):
93 return '[' + ', '.join(_jsonifyobj(e) for e in v) + ']'
100 return '[' + ', '.join(_jsonifyobj(e) for e in v) + ']'
94 elif v is True:
101 elif v is True:
95 return 'true'
102 return 'true'
96 elif v is False:
103 elif v is False:
97 return 'false'
104 return 'false'
98 elif isinstance(v, (int, float)):
105 elif isinstance(v, (int, float)):
99 return str(v)
106 return str(v)
100 else:
107 else:
101 return '"%s"' % encoding.jsonescape(v)
108 return '"%s"' % encoding.jsonescape(v)
102
109
103 class jsonformatter(baseformatter):
110 class jsonformatter(baseformatter):
104 def __init__(self, ui, topic, opts):
111 def __init__(self, ui, topic, opts):
105 baseformatter.__init__(self, ui, topic, opts)
112 baseformatter.__init__(self, ui, topic, opts)
106 self._ui.write("[")
113 self._ui.write("[")
107 self._ui._first = True
114 self._ui._first = True
108 def _showitem(self):
115 def _showitem(self):
109 if self._ui._first:
116 if self._ui._first:
110 self._ui._first = False
117 self._ui._first = False
111 else:
118 else:
112 self._ui.write(",")
119 self._ui.write(",")
113
120
114 self._ui.write("\n {\n")
121 self._ui.write("\n {\n")
115 first = True
122 first = True
116 for k, v in sorted(self._item.items()):
123 for k, v in sorted(self._item.items()):
117 if first:
124 if first:
118 first = False
125 first = False
119 else:
126 else:
120 self._ui.write(",\n")
127 self._ui.write(",\n")
121 self._ui.write(' "%s": %s' % (k, _jsonifyobj(v)))
128 self._ui.write(' "%s": %s' % (k, _jsonifyobj(v)))
122 self._ui.write("\n }")
129 self._ui.write("\n }")
123 def end(self):
130 def end(self):
124 baseformatter.end(self)
131 baseformatter.end(self)
125 self._ui.write("\n]\n")
132 self._ui.write("\n]\n")
126
133
127 def formatter(ui, topic, opts):
134 def formatter(ui, topic, opts):
128 template = opts.get("template", "")
135 template = opts.get("template", "")
129 if template == "json":
136 if template == "json":
130 return jsonformatter(ui, topic, opts)
137 return jsonformatter(ui, topic, opts)
131 elif template == "pickle":
138 elif template == "pickle":
132 return pickleformatter(ui, topic, opts)
139 return pickleformatter(ui, topic, opts)
133 elif template == "debug":
140 elif template == "debug":
134 return debugformatter(ui, topic, opts)
141 return debugformatter(ui, topic, opts)
135 elif template != "":
142 elif template != "":
136 raise util.Abort(_("custom templates not yet supported"))
143 raise util.Abort(_("custom templates not yet supported"))
137 elif ui.configbool('ui', 'formatdebug'):
144 elif ui.configbool('ui', 'formatdebug'):
138 return debugformatter(ui, topic, opts)
145 return debugformatter(ui, topic, opts)
139 elif ui.configbool('ui', 'formatjson'):
146 elif ui.configbool('ui', 'formatjson'):
140 return jsonformatter(ui, topic, opts)
147 return jsonformatter(ui, topic, opts)
141 return plainformatter(ui, topic, opts)
148 return plainformatter(ui, topic, opts)
General Comments 0
You need to be logged in to leave comments. Login now