##// END OF EJS Templates
graft: explicit current node tracking...
David Schleimer -
r18039:2c256428 default
parent child Browse files
Show More
@@ -1,5983 +1,5985 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 _, gettext
10 from i18n import _, gettext
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, encoding, templatekw, discovery
13 import patch, help, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, hbisect
14 import archival, changegroup, cmdutil, hbisect
15 import sshserver, hgweb, hgweb.server, commandserver
15 import sshserver, hgweb, hgweb.server, commandserver
16 import merge as mergemod
16 import merge as mergemod
17 import minirst, revset, fileset
17 import minirst, revset, fileset
18 import dagparser, context, simplemerge, graphmod
18 import dagparser, context, simplemerge, graphmod
19 import random, setdiscovery, treediscovery, dagutil, pvec, localrepo
19 import random, setdiscovery, treediscovery, dagutil, pvec, localrepo
20 import phases, obsolete
20 import phases, obsolete
21
21
22 table = {}
22 table = {}
23
23
24 command = cmdutil.command(table)
24 command = cmdutil.command(table)
25
25
26 # common command options
26 # common command options
27
27
28 globalopts = [
28 globalopts = [
29 ('R', 'repository', '',
29 ('R', 'repository', '',
30 _('repository root directory or name of overlay bundle file'),
30 _('repository root directory or name of overlay bundle file'),
31 _('REPO')),
31 _('REPO')),
32 ('', 'cwd', '',
32 ('', 'cwd', '',
33 _('change working directory'), _('DIR')),
33 _('change working directory'), _('DIR')),
34 ('y', 'noninteractive', None,
34 ('y', 'noninteractive', None,
35 _('do not prompt, automatically pick the first choice for all prompts')),
35 _('do not prompt, automatically pick the first choice for all prompts')),
36 ('q', 'quiet', None, _('suppress output')),
36 ('q', 'quiet', None, _('suppress output')),
37 ('v', 'verbose', None, _('enable additional output')),
37 ('v', 'verbose', None, _('enable additional output')),
38 ('', 'config', [],
38 ('', 'config', [],
39 _('set/override config option (use \'section.name=value\')'),
39 _('set/override config option (use \'section.name=value\')'),
40 _('CONFIG')),
40 _('CONFIG')),
41 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debug', None, _('enable debugging output')),
42 ('', 'debugger', None, _('start debugger')),
42 ('', 'debugger', None, _('start debugger')),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
44 _('ENCODE')),
44 _('ENCODE')),
45 ('', 'encodingmode', encoding.encodingmode,
45 ('', 'encodingmode', encoding.encodingmode,
46 _('set the charset encoding mode'), _('MODE')),
46 _('set the charset encoding mode'), _('MODE')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
48 ('', 'time', None, _('time how long the command takes')),
48 ('', 'time', None, _('time how long the command takes')),
49 ('', 'profile', None, _('print command execution profile')),
49 ('', 'profile', None, _('print command execution profile')),
50 ('', 'version', None, _('output version information and exit')),
50 ('', 'version', None, _('output version information and exit')),
51 ('h', 'help', None, _('display help and exit')),
51 ('h', 'help', None, _('display help and exit')),
52 ]
52 ]
53
53
54 dryrunopts = [('n', 'dry-run', None,
54 dryrunopts = [('n', 'dry-run', None,
55 _('do not perform actions, just print output'))]
55 _('do not perform actions, just print output'))]
56
56
57 remoteopts = [
57 remoteopts = [
58 ('e', 'ssh', '',
58 ('e', 'ssh', '',
59 _('specify ssh command to use'), _('CMD')),
59 _('specify ssh command to use'), _('CMD')),
60 ('', 'remotecmd', '',
60 ('', 'remotecmd', '',
61 _('specify hg command to run on the remote side'), _('CMD')),
61 _('specify hg command to run on the remote side'), _('CMD')),
62 ('', 'insecure', None,
62 ('', 'insecure', None,
63 _('do not verify server certificate (ignoring web.cacerts config)')),
63 _('do not verify server certificate (ignoring web.cacerts config)')),
64 ]
64 ]
65
65
66 walkopts = [
66 walkopts = [
67 ('I', 'include', [],
67 ('I', 'include', [],
68 _('include names matching the given patterns'), _('PATTERN')),
68 _('include names matching the given patterns'), _('PATTERN')),
69 ('X', 'exclude', [],
69 ('X', 'exclude', [],
70 _('exclude names matching the given patterns'), _('PATTERN')),
70 _('exclude names matching the given patterns'), _('PATTERN')),
71 ]
71 ]
72
72
73 commitopts = [
73 commitopts = [
74 ('m', 'message', '',
74 ('m', 'message', '',
75 _('use text as commit message'), _('TEXT')),
75 _('use text as commit message'), _('TEXT')),
76 ('l', 'logfile', '',
76 ('l', 'logfile', '',
77 _('read commit message from file'), _('FILE')),
77 _('read commit message from file'), _('FILE')),
78 ]
78 ]
79
79
80 commitopts2 = [
80 commitopts2 = [
81 ('d', 'date', '',
81 ('d', 'date', '',
82 _('record the specified date as commit date'), _('DATE')),
82 _('record the specified date as commit date'), _('DATE')),
83 ('u', 'user', '',
83 ('u', 'user', '',
84 _('record the specified user as committer'), _('USER')),
84 _('record the specified user as committer'), _('USER')),
85 ]
85 ]
86
86
87 templateopts = [
87 templateopts = [
88 ('', 'style', '',
88 ('', 'style', '',
89 _('display using template map file'), _('STYLE')),
89 _('display using template map file'), _('STYLE')),
90 ('', 'template', '',
90 ('', 'template', '',
91 _('display with template'), _('TEMPLATE')),
91 _('display with template'), _('TEMPLATE')),
92 ]
92 ]
93
93
94 logopts = [
94 logopts = [
95 ('p', 'patch', None, _('show patch')),
95 ('p', 'patch', None, _('show patch')),
96 ('g', 'git', None, _('use git extended diff format')),
96 ('g', 'git', None, _('use git extended diff format')),
97 ('l', 'limit', '',
97 ('l', 'limit', '',
98 _('limit number of changes displayed'), _('NUM')),
98 _('limit number of changes displayed'), _('NUM')),
99 ('M', 'no-merges', None, _('do not show merges')),
99 ('M', 'no-merges', None, _('do not show merges')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
101 ('G', 'graph', None, _("show the revision DAG")),
101 ('G', 'graph', None, _("show the revision DAG")),
102 ] + templateopts
102 ] + templateopts
103
103
104 diffopts = [
104 diffopts = [
105 ('a', 'text', None, _('treat all files as text')),
105 ('a', 'text', None, _('treat all files as text')),
106 ('g', 'git', None, _('use git extended diff format')),
106 ('g', 'git', None, _('use git extended diff format')),
107 ('', 'nodates', None, _('omit dates from diff headers'))
107 ('', 'nodates', None, _('omit dates from diff headers'))
108 ]
108 ]
109
109
110 diffwsopts = [
110 diffwsopts = [
111 ('w', 'ignore-all-space', None,
111 ('w', 'ignore-all-space', None,
112 _('ignore white space when comparing lines')),
112 _('ignore white space when comparing lines')),
113 ('b', 'ignore-space-change', None,
113 ('b', 'ignore-space-change', None,
114 _('ignore changes in the amount of white space')),
114 _('ignore changes in the amount of white space')),
115 ('B', 'ignore-blank-lines', None,
115 ('B', 'ignore-blank-lines', None,
116 _('ignore changes whose lines are all blank')),
116 _('ignore changes whose lines are all blank')),
117 ]
117 ]
118
118
119 diffopts2 = [
119 diffopts2 = [
120 ('p', 'show-function', None, _('show which function each change is in')),
120 ('p', 'show-function', None, _('show which function each change is in')),
121 ('', 'reverse', None, _('produce a diff that undoes the changes')),
121 ('', 'reverse', None, _('produce a diff that undoes the changes')),
122 ] + diffwsopts + [
122 ] + diffwsopts + [
123 ('U', 'unified', '',
123 ('U', 'unified', '',
124 _('number of lines of context to show'), _('NUM')),
124 _('number of lines of context to show'), _('NUM')),
125 ('', 'stat', None, _('output diffstat-style summary of changes')),
125 ('', 'stat', None, _('output diffstat-style summary of changes')),
126 ]
126 ]
127
127
128 mergetoolopts = [
128 mergetoolopts = [
129 ('t', 'tool', '', _('specify merge tool')),
129 ('t', 'tool', '', _('specify merge tool')),
130 ]
130 ]
131
131
132 similarityopts = [
132 similarityopts = [
133 ('s', 'similarity', '',
133 ('s', 'similarity', '',
134 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
134 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
135 ]
135 ]
136
136
137 subrepoopts = [
137 subrepoopts = [
138 ('S', 'subrepos', None,
138 ('S', 'subrepos', None,
139 _('recurse into subrepositories'))
139 _('recurse into subrepositories'))
140 ]
140 ]
141
141
142 # Commands start here, listed alphabetically
142 # Commands start here, listed alphabetically
143
143
144 @command('^add',
144 @command('^add',
145 walkopts + subrepoopts + dryrunopts,
145 walkopts + subrepoopts + dryrunopts,
146 _('[OPTION]... [FILE]...'))
146 _('[OPTION]... [FILE]...'))
147 def add(ui, repo, *pats, **opts):
147 def add(ui, repo, *pats, **opts):
148 """add the specified files on the next commit
148 """add the specified files on the next commit
149
149
150 Schedule files to be version controlled and added to the
150 Schedule files to be version controlled and added to the
151 repository.
151 repository.
152
152
153 The files will be added to the repository at the next commit. To
153 The files will be added to the repository at the next commit. To
154 undo an add before that, see :hg:`forget`.
154 undo an add before that, see :hg:`forget`.
155
155
156 If no names are given, add all files to the repository.
156 If no names are given, add all files to the repository.
157
157
158 .. container:: verbose
158 .. container:: verbose
159
159
160 An example showing how new (unknown) files are added
160 An example showing how new (unknown) files are added
161 automatically by :hg:`add`::
161 automatically by :hg:`add`::
162
162
163 $ ls
163 $ ls
164 foo.c
164 foo.c
165 $ hg status
165 $ hg status
166 ? foo.c
166 ? foo.c
167 $ hg add
167 $ hg add
168 adding foo.c
168 adding foo.c
169 $ hg status
169 $ hg status
170 A foo.c
170 A foo.c
171
171
172 Returns 0 if all files are successfully added.
172 Returns 0 if all files are successfully added.
173 """
173 """
174
174
175 m = scmutil.match(repo[None], pats, opts)
175 m = scmutil.match(repo[None], pats, opts)
176 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
176 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
177 opts.get('subrepos'), prefix="", explicitonly=False)
177 opts.get('subrepos'), prefix="", explicitonly=False)
178 return rejected and 1 or 0
178 return rejected and 1 or 0
179
179
180 @command('addremove',
180 @command('addremove',
181 similarityopts + walkopts + dryrunopts,
181 similarityopts + walkopts + dryrunopts,
182 _('[OPTION]... [FILE]...'))
182 _('[OPTION]... [FILE]...'))
183 def addremove(ui, repo, *pats, **opts):
183 def addremove(ui, repo, *pats, **opts):
184 """add all new files, delete all missing files
184 """add all new files, delete all missing files
185
185
186 Add all new files and remove all missing files from the
186 Add all new files and remove all missing files from the
187 repository.
187 repository.
188
188
189 New files are ignored if they match any of the patterns in
189 New files are ignored if they match any of the patterns in
190 ``.hgignore``. As with add, these changes take effect at the next
190 ``.hgignore``. As with add, these changes take effect at the next
191 commit.
191 commit.
192
192
193 Use the -s/--similarity option to detect renamed files. This
193 Use the -s/--similarity option to detect renamed files. This
194 option takes a percentage between 0 (disabled) and 100 (files must
194 option takes a percentage between 0 (disabled) and 100 (files must
195 be identical) as its parameter. With a parameter greater than 0,
195 be identical) as its parameter. With a parameter greater than 0,
196 this compares every removed file with every added file and records
196 this compares every removed file with every added file and records
197 those similar enough as renames. Detecting renamed files this way
197 those similar enough as renames. Detecting renamed files this way
198 can be expensive. After using this option, :hg:`status -C` can be
198 can be expensive. After using this option, :hg:`status -C` can be
199 used to check which files were identified as moved or renamed. If
199 used to check which files were identified as moved or renamed. If
200 not specified, -s/--similarity defaults to 100 and only renames of
200 not specified, -s/--similarity defaults to 100 and only renames of
201 identical files are detected.
201 identical files are detected.
202
202
203 Returns 0 if all files are successfully added.
203 Returns 0 if all files are successfully added.
204 """
204 """
205 try:
205 try:
206 sim = float(opts.get('similarity') or 100)
206 sim = float(opts.get('similarity') or 100)
207 except ValueError:
207 except ValueError:
208 raise util.Abort(_('similarity must be a number'))
208 raise util.Abort(_('similarity must be a number'))
209 if sim < 0 or sim > 100:
209 if sim < 0 or sim > 100:
210 raise util.Abort(_('similarity must be between 0 and 100'))
210 raise util.Abort(_('similarity must be between 0 and 100'))
211 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
211 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
212
212
213 @command('^annotate|blame',
213 @command('^annotate|blame',
214 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
214 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
215 ('', 'follow', None,
215 ('', 'follow', None,
216 _('follow copies/renames and list the filename (DEPRECATED)')),
216 _('follow copies/renames and list the filename (DEPRECATED)')),
217 ('', 'no-follow', None, _("don't follow copies and renames")),
217 ('', 'no-follow', None, _("don't follow copies and renames")),
218 ('a', 'text', None, _('treat all files as text')),
218 ('a', 'text', None, _('treat all files as text')),
219 ('u', 'user', None, _('list the author (long with -v)')),
219 ('u', 'user', None, _('list the author (long with -v)')),
220 ('f', 'file', None, _('list the filename')),
220 ('f', 'file', None, _('list the filename')),
221 ('d', 'date', None, _('list the date (short with -q)')),
221 ('d', 'date', None, _('list the date (short with -q)')),
222 ('n', 'number', None, _('list the revision number (default)')),
222 ('n', 'number', None, _('list the revision number (default)')),
223 ('c', 'changeset', None, _('list the changeset')),
223 ('c', 'changeset', None, _('list the changeset')),
224 ('l', 'line-number', None, _('show line number at the first appearance'))
224 ('l', 'line-number', None, _('show line number at the first appearance'))
225 ] + diffwsopts + walkopts,
225 ] + diffwsopts + walkopts,
226 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
226 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
227 def annotate(ui, repo, *pats, **opts):
227 def annotate(ui, repo, *pats, **opts):
228 """show changeset information by line for each file
228 """show changeset information by line for each file
229
229
230 List changes in files, showing the revision id responsible for
230 List changes in files, showing the revision id responsible for
231 each line
231 each line
232
232
233 This command is useful for discovering when a change was made and
233 This command is useful for discovering when a change was made and
234 by whom.
234 by whom.
235
235
236 Without the -a/--text option, annotate will avoid processing files
236 Without the -a/--text option, annotate will avoid processing files
237 it detects as binary. With -a, annotate will annotate the file
237 it detects as binary. With -a, annotate will annotate the file
238 anyway, although the results will probably be neither useful
238 anyway, although the results will probably be neither useful
239 nor desirable.
239 nor desirable.
240
240
241 Returns 0 on success.
241 Returns 0 on success.
242 """
242 """
243 if opts.get('follow'):
243 if opts.get('follow'):
244 # --follow is deprecated and now just an alias for -f/--file
244 # --follow is deprecated and now just an alias for -f/--file
245 # to mimic the behavior of Mercurial before version 1.5
245 # to mimic the behavior of Mercurial before version 1.5
246 opts['file'] = True
246 opts['file'] = True
247
247
248 datefunc = ui.quiet and util.shortdate or util.datestr
248 datefunc = ui.quiet and util.shortdate or util.datestr
249 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
249 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
250
250
251 if not pats:
251 if not pats:
252 raise util.Abort(_('at least one filename or pattern is required'))
252 raise util.Abort(_('at least one filename or pattern is required'))
253
253
254 hexfn = ui.debugflag and hex or short
254 hexfn = ui.debugflag and hex or short
255
255
256 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
256 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
257 ('number', ' ', lambda x: str(x[0].rev())),
257 ('number', ' ', lambda x: str(x[0].rev())),
258 ('changeset', ' ', lambda x: hexfn(x[0].node())),
258 ('changeset', ' ', lambda x: hexfn(x[0].node())),
259 ('date', ' ', getdate),
259 ('date', ' ', getdate),
260 ('file', ' ', lambda x: x[0].path()),
260 ('file', ' ', lambda x: x[0].path()),
261 ('line_number', ':', lambda x: str(x[1])),
261 ('line_number', ':', lambda x: str(x[1])),
262 ]
262 ]
263
263
264 if (not opts.get('user') and not opts.get('changeset')
264 if (not opts.get('user') and not opts.get('changeset')
265 and not opts.get('date') and not opts.get('file')):
265 and not opts.get('date') and not opts.get('file')):
266 opts['number'] = True
266 opts['number'] = True
267
267
268 linenumber = opts.get('line_number') is not None
268 linenumber = opts.get('line_number') is not None
269 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
269 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
270 raise util.Abort(_('at least one of -n/-c is required for -l'))
270 raise util.Abort(_('at least one of -n/-c is required for -l'))
271
271
272 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
272 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
273 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
273 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
274
274
275 def bad(x, y):
275 def bad(x, y):
276 raise util.Abort("%s: %s" % (x, y))
276 raise util.Abort("%s: %s" % (x, y))
277
277
278 ctx = scmutil.revsingle(repo, opts.get('rev'))
278 ctx = scmutil.revsingle(repo, opts.get('rev'))
279 m = scmutil.match(ctx, pats, opts)
279 m = scmutil.match(ctx, pats, opts)
280 m.bad = bad
280 m.bad = bad
281 follow = not opts.get('no_follow')
281 follow = not opts.get('no_follow')
282 diffopts = patch.diffopts(ui, opts, section='annotate')
282 diffopts = patch.diffopts(ui, opts, section='annotate')
283 for abs in ctx.walk(m):
283 for abs in ctx.walk(m):
284 fctx = ctx[abs]
284 fctx = ctx[abs]
285 if not opts.get('text') and util.binary(fctx.data()):
285 if not opts.get('text') and util.binary(fctx.data()):
286 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
286 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
287 continue
287 continue
288
288
289 lines = fctx.annotate(follow=follow, linenumber=linenumber,
289 lines = fctx.annotate(follow=follow, linenumber=linenumber,
290 diffopts=diffopts)
290 diffopts=diffopts)
291 pieces = []
291 pieces = []
292
292
293 for f, sep in funcmap:
293 for f, sep in funcmap:
294 l = [f(n) for n, dummy in lines]
294 l = [f(n) for n, dummy in lines]
295 if l:
295 if l:
296 sized = [(x, encoding.colwidth(x)) for x in l]
296 sized = [(x, encoding.colwidth(x)) for x in l]
297 ml = max([w for x, w in sized])
297 ml = max([w for x, w in sized])
298 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
298 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
299 for x, w in sized])
299 for x, w in sized])
300
300
301 if pieces:
301 if pieces:
302 for p, l in zip(zip(*pieces), lines):
302 for p, l in zip(zip(*pieces), lines):
303 ui.write("%s: %s" % ("".join(p), l[1]))
303 ui.write("%s: %s" % ("".join(p), l[1]))
304
304
305 if lines and not lines[-1][1].endswith('\n'):
305 if lines and not lines[-1][1].endswith('\n'):
306 ui.write('\n')
306 ui.write('\n')
307
307
308 @command('archive',
308 @command('archive',
309 [('', 'no-decode', None, _('do not pass files through decoders')),
309 [('', 'no-decode', None, _('do not pass files through decoders')),
310 ('p', 'prefix', '', _('directory prefix for files in archive'),
310 ('p', 'prefix', '', _('directory prefix for files in archive'),
311 _('PREFIX')),
311 _('PREFIX')),
312 ('r', 'rev', '', _('revision to distribute'), _('REV')),
312 ('r', 'rev', '', _('revision to distribute'), _('REV')),
313 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
313 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
314 ] + subrepoopts + walkopts,
314 ] + subrepoopts + walkopts,
315 _('[OPTION]... DEST'))
315 _('[OPTION]... DEST'))
316 def archive(ui, repo, dest, **opts):
316 def archive(ui, repo, dest, **opts):
317 '''create an unversioned archive of a repository revision
317 '''create an unversioned archive of a repository revision
318
318
319 By default, the revision used is the parent of the working
319 By default, the revision used is the parent of the working
320 directory; use -r/--rev to specify a different revision.
320 directory; use -r/--rev to specify a different revision.
321
321
322 The archive type is automatically detected based on file
322 The archive type is automatically detected based on file
323 extension (or override using -t/--type).
323 extension (or override using -t/--type).
324
324
325 .. container:: verbose
325 .. container:: verbose
326
326
327 Examples:
327 Examples:
328
328
329 - create a zip file containing the 1.0 release::
329 - create a zip file containing the 1.0 release::
330
330
331 hg archive -r 1.0 project-1.0.zip
331 hg archive -r 1.0 project-1.0.zip
332
332
333 - create a tarball excluding .hg files::
333 - create a tarball excluding .hg files::
334
334
335 hg archive project.tar.gz -X ".hg*"
335 hg archive project.tar.gz -X ".hg*"
336
336
337 Valid types are:
337 Valid types are:
338
338
339 :``files``: a directory full of files (default)
339 :``files``: a directory full of files (default)
340 :``tar``: tar archive, uncompressed
340 :``tar``: tar archive, uncompressed
341 :``tbz2``: tar archive, compressed using bzip2
341 :``tbz2``: tar archive, compressed using bzip2
342 :``tgz``: tar archive, compressed using gzip
342 :``tgz``: tar archive, compressed using gzip
343 :``uzip``: zip archive, uncompressed
343 :``uzip``: zip archive, uncompressed
344 :``zip``: zip archive, compressed using deflate
344 :``zip``: zip archive, compressed using deflate
345
345
346 The exact name of the destination archive or directory is given
346 The exact name of the destination archive or directory is given
347 using a format string; see :hg:`help export` for details.
347 using a format string; see :hg:`help export` for details.
348
348
349 Each member added to an archive file has a directory prefix
349 Each member added to an archive file has a directory prefix
350 prepended. Use -p/--prefix to specify a format string for the
350 prepended. Use -p/--prefix to specify a format string for the
351 prefix. The default is the basename of the archive, with suffixes
351 prefix. The default is the basename of the archive, with suffixes
352 removed.
352 removed.
353
353
354 Returns 0 on success.
354 Returns 0 on success.
355 '''
355 '''
356
356
357 ctx = scmutil.revsingle(repo, opts.get('rev'))
357 ctx = scmutil.revsingle(repo, opts.get('rev'))
358 if not ctx:
358 if not ctx:
359 raise util.Abort(_('no working directory: please specify a revision'))
359 raise util.Abort(_('no working directory: please specify a revision'))
360 node = ctx.node()
360 node = ctx.node()
361 dest = cmdutil.makefilename(repo, dest, node)
361 dest = cmdutil.makefilename(repo, dest, node)
362 if os.path.realpath(dest) == repo.root:
362 if os.path.realpath(dest) == repo.root:
363 raise util.Abort(_('repository root cannot be destination'))
363 raise util.Abort(_('repository root cannot be destination'))
364
364
365 kind = opts.get('type') or archival.guesskind(dest) or 'files'
365 kind = opts.get('type') or archival.guesskind(dest) or 'files'
366 prefix = opts.get('prefix')
366 prefix = opts.get('prefix')
367
367
368 if dest == '-':
368 if dest == '-':
369 if kind == 'files':
369 if kind == 'files':
370 raise util.Abort(_('cannot archive plain files to stdout'))
370 raise util.Abort(_('cannot archive plain files to stdout'))
371 dest = cmdutil.makefileobj(repo, dest)
371 dest = cmdutil.makefileobj(repo, dest)
372 if not prefix:
372 if not prefix:
373 prefix = os.path.basename(repo.root) + '-%h'
373 prefix = os.path.basename(repo.root) + '-%h'
374
374
375 prefix = cmdutil.makefilename(repo, prefix, node)
375 prefix = cmdutil.makefilename(repo, prefix, node)
376 matchfn = scmutil.match(ctx, [], opts)
376 matchfn = scmutil.match(ctx, [], opts)
377 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
377 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
378 matchfn, prefix, subrepos=opts.get('subrepos'))
378 matchfn, prefix, subrepos=opts.get('subrepos'))
379
379
380 @command('backout',
380 @command('backout',
381 [('', 'merge', None, _('merge with old dirstate parent after backout')),
381 [('', 'merge', None, _('merge with old dirstate parent after backout')),
382 ('', 'parent', '',
382 ('', 'parent', '',
383 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
383 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
384 ('r', 'rev', '', _('revision to backout'), _('REV')),
384 ('r', 'rev', '', _('revision to backout'), _('REV')),
385 ] + mergetoolopts + walkopts + commitopts + commitopts2,
385 ] + mergetoolopts + walkopts + commitopts + commitopts2,
386 _('[OPTION]... [-r] REV'))
386 _('[OPTION]... [-r] REV'))
387 def backout(ui, repo, node=None, rev=None, **opts):
387 def backout(ui, repo, node=None, rev=None, **opts):
388 '''reverse effect of earlier changeset
388 '''reverse effect of earlier changeset
389
389
390 Prepare a new changeset with the effect of REV undone in the
390 Prepare a new changeset with the effect of REV undone in the
391 current working directory.
391 current working directory.
392
392
393 If REV is the parent of the working directory, then this new changeset
393 If REV is the parent of the working directory, then this new changeset
394 is committed automatically. Otherwise, hg needs to merge the
394 is committed automatically. Otherwise, hg needs to merge the
395 changes and the merged result is left uncommitted.
395 changes and the merged result is left uncommitted.
396
396
397 .. note::
397 .. note::
398 backout cannot be used to fix either an unwanted or
398 backout cannot be used to fix either an unwanted or
399 incorrect merge.
399 incorrect merge.
400
400
401 .. container:: verbose
401 .. container:: verbose
402
402
403 By default, the pending changeset will have one parent,
403 By default, the pending changeset will have one parent,
404 maintaining a linear history. With --merge, the pending
404 maintaining a linear history. With --merge, the pending
405 changeset will instead have two parents: the old parent of the
405 changeset will instead have two parents: the old parent of the
406 working directory and a new child of REV that simply undoes REV.
406 working directory and a new child of REV that simply undoes REV.
407
407
408 Before version 1.7, the behavior without --merge was equivalent
408 Before version 1.7, the behavior without --merge was equivalent
409 to specifying --merge followed by :hg:`update --clean .` to
409 to specifying --merge followed by :hg:`update --clean .` to
410 cancel the merge and leave the child of REV as a head to be
410 cancel the merge and leave the child of REV as a head to be
411 merged separately.
411 merged separately.
412
412
413 See :hg:`help dates` for a list of formats valid for -d/--date.
413 See :hg:`help dates` for a list of formats valid for -d/--date.
414
414
415 Returns 0 on success.
415 Returns 0 on success.
416 '''
416 '''
417 if rev and node:
417 if rev and node:
418 raise util.Abort(_("please specify just one revision"))
418 raise util.Abort(_("please specify just one revision"))
419
419
420 if not rev:
420 if not rev:
421 rev = node
421 rev = node
422
422
423 if not rev:
423 if not rev:
424 raise util.Abort(_("please specify a revision to backout"))
424 raise util.Abort(_("please specify a revision to backout"))
425
425
426 date = opts.get('date')
426 date = opts.get('date')
427 if date:
427 if date:
428 opts['date'] = util.parsedate(date)
428 opts['date'] = util.parsedate(date)
429
429
430 cmdutil.bailifchanged(repo)
430 cmdutil.bailifchanged(repo)
431 node = scmutil.revsingle(repo, rev).node()
431 node = scmutil.revsingle(repo, rev).node()
432
432
433 op1, op2 = repo.dirstate.parents()
433 op1, op2 = repo.dirstate.parents()
434 a = repo.changelog.ancestor(op1, node)
434 a = repo.changelog.ancestor(op1, node)
435 if a != node:
435 if a != node:
436 raise util.Abort(_('cannot backout change on a different branch'))
436 raise util.Abort(_('cannot backout change on a different branch'))
437
437
438 p1, p2 = repo.changelog.parents(node)
438 p1, p2 = repo.changelog.parents(node)
439 if p1 == nullid:
439 if p1 == nullid:
440 raise util.Abort(_('cannot backout a change with no parents'))
440 raise util.Abort(_('cannot backout a change with no parents'))
441 if p2 != nullid:
441 if p2 != nullid:
442 if not opts.get('parent'):
442 if not opts.get('parent'):
443 raise util.Abort(_('cannot backout a merge changeset'))
443 raise util.Abort(_('cannot backout a merge changeset'))
444 p = repo.lookup(opts['parent'])
444 p = repo.lookup(opts['parent'])
445 if p not in (p1, p2):
445 if p not in (p1, p2):
446 raise util.Abort(_('%s is not a parent of %s') %
446 raise util.Abort(_('%s is not a parent of %s') %
447 (short(p), short(node)))
447 (short(p), short(node)))
448 parent = p
448 parent = p
449 else:
449 else:
450 if opts.get('parent'):
450 if opts.get('parent'):
451 raise util.Abort(_('cannot use --parent on non-merge changeset'))
451 raise util.Abort(_('cannot use --parent on non-merge changeset'))
452 parent = p1
452 parent = p1
453
453
454 # the backout should appear on the same branch
454 # the backout should appear on the same branch
455 wlock = repo.wlock()
455 wlock = repo.wlock()
456 try:
456 try:
457 branch = repo.dirstate.branch()
457 branch = repo.dirstate.branch()
458 hg.clean(repo, node, show_stats=False)
458 hg.clean(repo, node, show_stats=False)
459 repo.dirstate.setbranch(branch)
459 repo.dirstate.setbranch(branch)
460 revert_opts = opts.copy()
460 revert_opts = opts.copy()
461 revert_opts['date'] = None
461 revert_opts['date'] = None
462 revert_opts['all'] = True
462 revert_opts['all'] = True
463 revert_opts['rev'] = hex(parent)
463 revert_opts['rev'] = hex(parent)
464 revert_opts['no_backup'] = None
464 revert_opts['no_backup'] = None
465 revert(ui, repo, **revert_opts)
465 revert(ui, repo, **revert_opts)
466 if not opts.get('merge') and op1 != node:
466 if not opts.get('merge') and op1 != node:
467 try:
467 try:
468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
469 return hg.update(repo, op1)
469 return hg.update(repo, op1)
470 finally:
470 finally:
471 ui.setconfig('ui', 'forcemerge', '')
471 ui.setconfig('ui', 'forcemerge', '')
472
472
473 commit_opts = opts.copy()
473 commit_opts = opts.copy()
474 commit_opts['addremove'] = False
474 commit_opts['addremove'] = False
475 if not commit_opts['message'] and not commit_opts['logfile']:
475 if not commit_opts['message'] and not commit_opts['logfile']:
476 # we don't translate commit messages
476 # we don't translate commit messages
477 commit_opts['message'] = "Backed out changeset %s" % short(node)
477 commit_opts['message'] = "Backed out changeset %s" % short(node)
478 commit_opts['force_editor'] = True
478 commit_opts['force_editor'] = True
479 commit(ui, repo, **commit_opts)
479 commit(ui, repo, **commit_opts)
480 def nice(node):
480 def nice(node):
481 return '%d:%s' % (repo.changelog.rev(node), short(node))
481 return '%d:%s' % (repo.changelog.rev(node), short(node))
482 ui.status(_('changeset %s backs out changeset %s\n') %
482 ui.status(_('changeset %s backs out changeset %s\n') %
483 (nice(repo.changelog.tip()), nice(node)))
483 (nice(repo.changelog.tip()), nice(node)))
484 if opts.get('merge') and op1 != node:
484 if opts.get('merge') and op1 != node:
485 hg.clean(repo, op1, show_stats=False)
485 hg.clean(repo, op1, show_stats=False)
486 ui.status(_('merging with changeset %s\n')
486 ui.status(_('merging with changeset %s\n')
487 % nice(repo.changelog.tip()))
487 % nice(repo.changelog.tip()))
488 try:
488 try:
489 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
489 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
490 return hg.merge(repo, hex(repo.changelog.tip()))
490 return hg.merge(repo, hex(repo.changelog.tip()))
491 finally:
491 finally:
492 ui.setconfig('ui', 'forcemerge', '')
492 ui.setconfig('ui', 'forcemerge', '')
493 finally:
493 finally:
494 wlock.release()
494 wlock.release()
495 return 0
495 return 0
496
496
497 @command('bisect',
497 @command('bisect',
498 [('r', 'reset', False, _('reset bisect state')),
498 [('r', 'reset', False, _('reset bisect state')),
499 ('g', 'good', False, _('mark changeset good')),
499 ('g', 'good', False, _('mark changeset good')),
500 ('b', 'bad', False, _('mark changeset bad')),
500 ('b', 'bad', False, _('mark changeset bad')),
501 ('s', 'skip', False, _('skip testing changeset')),
501 ('s', 'skip', False, _('skip testing changeset')),
502 ('e', 'extend', False, _('extend the bisect range')),
502 ('e', 'extend', False, _('extend the bisect range')),
503 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
503 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
504 ('U', 'noupdate', False, _('do not update to target'))],
504 ('U', 'noupdate', False, _('do not update to target'))],
505 _("[-gbsr] [-U] [-c CMD] [REV]"))
505 _("[-gbsr] [-U] [-c CMD] [REV]"))
506 def bisect(ui, repo, rev=None, extra=None, command=None,
506 def bisect(ui, repo, rev=None, extra=None, command=None,
507 reset=None, good=None, bad=None, skip=None, extend=None,
507 reset=None, good=None, bad=None, skip=None, extend=None,
508 noupdate=None):
508 noupdate=None):
509 """subdivision search of changesets
509 """subdivision search of changesets
510
510
511 This command helps to find changesets which introduce problems. To
511 This command helps to find changesets which introduce problems. To
512 use, mark the earliest changeset you know exhibits the problem as
512 use, mark the earliest changeset you know exhibits the problem as
513 bad, then mark the latest changeset which is free from the problem
513 bad, then mark the latest changeset which is free from the problem
514 as good. Bisect will update your working directory to a revision
514 as good. Bisect will update your working directory to a revision
515 for testing (unless the -U/--noupdate option is specified). Once
515 for testing (unless the -U/--noupdate option is specified). Once
516 you have performed tests, mark the working directory as good or
516 you have performed tests, mark the working directory as good or
517 bad, and bisect will either update to another candidate changeset
517 bad, and bisect will either update to another candidate changeset
518 or announce that it has found the bad revision.
518 or announce that it has found the bad revision.
519
519
520 As a shortcut, you can also use the revision argument to mark a
520 As a shortcut, you can also use the revision argument to mark a
521 revision as good or bad without checking it out first.
521 revision as good or bad without checking it out first.
522
522
523 If you supply a command, it will be used for automatic bisection.
523 If you supply a command, it will be used for automatic bisection.
524 The environment variable HG_NODE will contain the ID of the
524 The environment variable HG_NODE will contain the ID of the
525 changeset being tested. The exit status of the command will be
525 changeset being tested. The exit status of the command will be
526 used to mark revisions as good or bad: status 0 means good, 125
526 used to mark revisions as good or bad: status 0 means good, 125
527 means to skip the revision, 127 (command not found) will abort the
527 means to skip the revision, 127 (command not found) will abort the
528 bisection, and any other non-zero exit status means the revision
528 bisection, and any other non-zero exit status means the revision
529 is bad.
529 is bad.
530
530
531 .. container:: verbose
531 .. container:: verbose
532
532
533 Some examples:
533 Some examples:
534
534
535 - start a bisection with known bad revision 12, and good revision 34::
535 - start a bisection with known bad revision 12, and good revision 34::
536
536
537 hg bisect --bad 34
537 hg bisect --bad 34
538 hg bisect --good 12
538 hg bisect --good 12
539
539
540 - advance the current bisection by marking current revision as good or
540 - advance the current bisection by marking current revision as good or
541 bad::
541 bad::
542
542
543 hg bisect --good
543 hg bisect --good
544 hg bisect --bad
544 hg bisect --bad
545
545
546 - mark the current revision, or a known revision, to be skipped (e.g. if
546 - mark the current revision, or a known revision, to be skipped (e.g. if
547 that revision is not usable because of another issue)::
547 that revision is not usable because of another issue)::
548
548
549 hg bisect --skip
549 hg bisect --skip
550 hg bisect --skip 23
550 hg bisect --skip 23
551
551
552 - skip all revisions that do not touch directories ``foo`` or ``bar``
552 - skip all revisions that do not touch directories ``foo`` or ``bar``
553
553
554 hg bisect --skip '!( file("path:foo") & file("path:bar") )'
554 hg bisect --skip '!( file("path:foo") & file("path:bar") )'
555
555
556 - forget the current bisection::
556 - forget the current bisection::
557
557
558 hg bisect --reset
558 hg bisect --reset
559
559
560 - use 'make && make tests' to automatically find the first broken
560 - use 'make && make tests' to automatically find the first broken
561 revision::
561 revision::
562
562
563 hg bisect --reset
563 hg bisect --reset
564 hg bisect --bad 34
564 hg bisect --bad 34
565 hg bisect --good 12
565 hg bisect --good 12
566 hg bisect --command 'make && make tests'
566 hg bisect --command 'make && make tests'
567
567
568 - see all changesets whose states are already known in the current
568 - see all changesets whose states are already known in the current
569 bisection::
569 bisection::
570
570
571 hg log -r "bisect(pruned)"
571 hg log -r "bisect(pruned)"
572
572
573 - see the changeset currently being bisected (especially useful
573 - see the changeset currently being bisected (especially useful
574 if running with -U/--noupdate)::
574 if running with -U/--noupdate)::
575
575
576 hg log -r "bisect(current)"
576 hg log -r "bisect(current)"
577
577
578 - see all changesets that took part in the current bisection::
578 - see all changesets that took part in the current bisection::
579
579
580 hg log -r "bisect(range)"
580 hg log -r "bisect(range)"
581
581
582 - with the graphlog extension, you can even get a nice graph::
582 - with the graphlog extension, you can even get a nice graph::
583
583
584 hg log --graph -r "bisect(range)"
584 hg log --graph -r "bisect(range)"
585
585
586 See :hg:`help revsets` for more about the `bisect()` keyword.
586 See :hg:`help revsets` for more about the `bisect()` keyword.
587
587
588 Returns 0 on success.
588 Returns 0 on success.
589 """
589 """
590 def extendbisectrange(nodes, good):
590 def extendbisectrange(nodes, good):
591 # bisect is incomplete when it ends on a merge node and
591 # bisect is incomplete when it ends on a merge node and
592 # one of the parent was not checked.
592 # one of the parent was not checked.
593 parents = repo[nodes[0]].parents()
593 parents = repo[nodes[0]].parents()
594 if len(parents) > 1:
594 if len(parents) > 1:
595 side = good and state['bad'] or state['good']
595 side = good and state['bad'] or state['good']
596 num = len(set(i.node() for i in parents) & set(side))
596 num = len(set(i.node() for i in parents) & set(side))
597 if num == 1:
597 if num == 1:
598 return parents[0].ancestor(parents[1])
598 return parents[0].ancestor(parents[1])
599 return None
599 return None
600
600
601 def print_result(nodes, good):
601 def print_result(nodes, good):
602 displayer = cmdutil.show_changeset(ui, repo, {})
602 displayer = cmdutil.show_changeset(ui, repo, {})
603 if len(nodes) == 1:
603 if len(nodes) == 1:
604 # narrowed it down to a single revision
604 # narrowed it down to a single revision
605 if good:
605 if good:
606 ui.write(_("The first good revision is:\n"))
606 ui.write(_("The first good revision is:\n"))
607 else:
607 else:
608 ui.write(_("The first bad revision is:\n"))
608 ui.write(_("The first bad revision is:\n"))
609 displayer.show(repo[nodes[0]])
609 displayer.show(repo[nodes[0]])
610 extendnode = extendbisectrange(nodes, good)
610 extendnode = extendbisectrange(nodes, good)
611 if extendnode is not None:
611 if extendnode is not None:
612 ui.write(_('Not all ancestors of this changeset have been'
612 ui.write(_('Not all ancestors of this changeset have been'
613 ' checked.\nUse bisect --extend to continue the '
613 ' checked.\nUse bisect --extend to continue the '
614 'bisection from\nthe common ancestor, %s.\n')
614 'bisection from\nthe common ancestor, %s.\n')
615 % extendnode)
615 % extendnode)
616 else:
616 else:
617 # multiple possible revisions
617 # multiple possible revisions
618 if good:
618 if good:
619 ui.write(_("Due to skipped revisions, the first "
619 ui.write(_("Due to skipped revisions, the first "
620 "good revision could be any of:\n"))
620 "good revision could be any of:\n"))
621 else:
621 else:
622 ui.write(_("Due to skipped revisions, the first "
622 ui.write(_("Due to skipped revisions, the first "
623 "bad revision could be any of:\n"))
623 "bad revision could be any of:\n"))
624 for n in nodes:
624 for n in nodes:
625 displayer.show(repo[n])
625 displayer.show(repo[n])
626 displayer.close()
626 displayer.close()
627
627
628 def check_state(state, interactive=True):
628 def check_state(state, interactive=True):
629 if not state['good'] or not state['bad']:
629 if not state['good'] or not state['bad']:
630 if (good or bad or skip or reset) and interactive:
630 if (good or bad or skip or reset) and interactive:
631 return
631 return
632 if not state['good']:
632 if not state['good']:
633 raise util.Abort(_('cannot bisect (no known good revisions)'))
633 raise util.Abort(_('cannot bisect (no known good revisions)'))
634 else:
634 else:
635 raise util.Abort(_('cannot bisect (no known bad revisions)'))
635 raise util.Abort(_('cannot bisect (no known bad revisions)'))
636 return True
636 return True
637
637
638 # backward compatibility
638 # backward compatibility
639 if rev in "good bad reset init".split():
639 if rev in "good bad reset init".split():
640 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
640 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
641 cmd, rev, extra = rev, extra, None
641 cmd, rev, extra = rev, extra, None
642 if cmd == "good":
642 if cmd == "good":
643 good = True
643 good = True
644 elif cmd == "bad":
644 elif cmd == "bad":
645 bad = True
645 bad = True
646 else:
646 else:
647 reset = True
647 reset = True
648 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
648 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
649 raise util.Abort(_('incompatible arguments'))
649 raise util.Abort(_('incompatible arguments'))
650
650
651 if reset:
651 if reset:
652 p = repo.join("bisect.state")
652 p = repo.join("bisect.state")
653 if os.path.exists(p):
653 if os.path.exists(p):
654 os.unlink(p)
654 os.unlink(p)
655 return
655 return
656
656
657 state = hbisect.load_state(repo)
657 state = hbisect.load_state(repo)
658
658
659 if command:
659 if command:
660 changesets = 1
660 changesets = 1
661 try:
661 try:
662 node = state['current'][0]
662 node = state['current'][0]
663 except LookupError:
663 except LookupError:
664 if noupdate:
664 if noupdate:
665 raise util.Abort(_('current bisect revision is unknown - '
665 raise util.Abort(_('current bisect revision is unknown - '
666 'start a new bisect to fix'))
666 'start a new bisect to fix'))
667 node, p2 = repo.dirstate.parents()
667 node, p2 = repo.dirstate.parents()
668 if p2 != nullid:
668 if p2 != nullid:
669 raise util.Abort(_('current bisect revision is a merge'))
669 raise util.Abort(_('current bisect revision is a merge'))
670 try:
670 try:
671 while changesets:
671 while changesets:
672 # update state
672 # update state
673 state['current'] = [node]
673 state['current'] = [node]
674 hbisect.save_state(repo, state)
674 hbisect.save_state(repo, state)
675 status = util.system(command,
675 status = util.system(command,
676 environ={'HG_NODE': hex(node)},
676 environ={'HG_NODE': hex(node)},
677 out=ui.fout)
677 out=ui.fout)
678 if status == 125:
678 if status == 125:
679 transition = "skip"
679 transition = "skip"
680 elif status == 0:
680 elif status == 0:
681 transition = "good"
681 transition = "good"
682 # status < 0 means process was killed
682 # status < 0 means process was killed
683 elif status == 127:
683 elif status == 127:
684 raise util.Abort(_("failed to execute %s") % command)
684 raise util.Abort(_("failed to execute %s") % command)
685 elif status < 0:
685 elif status < 0:
686 raise util.Abort(_("%s killed") % command)
686 raise util.Abort(_("%s killed") % command)
687 else:
687 else:
688 transition = "bad"
688 transition = "bad"
689 ctx = scmutil.revsingle(repo, rev, node)
689 ctx = scmutil.revsingle(repo, rev, node)
690 rev = None # clear for future iterations
690 rev = None # clear for future iterations
691 state[transition].append(ctx.node())
691 state[transition].append(ctx.node())
692 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
692 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
693 check_state(state, interactive=False)
693 check_state(state, interactive=False)
694 # bisect
694 # bisect
695 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
695 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
696 # update to next check
696 # update to next check
697 node = nodes[0]
697 node = nodes[0]
698 if not noupdate:
698 if not noupdate:
699 cmdutil.bailifchanged(repo)
699 cmdutil.bailifchanged(repo)
700 hg.clean(repo, node, show_stats=False)
700 hg.clean(repo, node, show_stats=False)
701 finally:
701 finally:
702 state['current'] = [node]
702 state['current'] = [node]
703 hbisect.save_state(repo, state)
703 hbisect.save_state(repo, state)
704 print_result(nodes, good)
704 print_result(nodes, good)
705 return
705 return
706
706
707 # update state
707 # update state
708
708
709 if rev:
709 if rev:
710 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
710 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
711 else:
711 else:
712 nodes = [repo.lookup('.')]
712 nodes = [repo.lookup('.')]
713
713
714 if good or bad or skip:
714 if good or bad or skip:
715 if good:
715 if good:
716 state['good'] += nodes
716 state['good'] += nodes
717 elif bad:
717 elif bad:
718 state['bad'] += nodes
718 state['bad'] += nodes
719 elif skip:
719 elif skip:
720 state['skip'] += nodes
720 state['skip'] += nodes
721 hbisect.save_state(repo, state)
721 hbisect.save_state(repo, state)
722
722
723 if not check_state(state):
723 if not check_state(state):
724 return
724 return
725
725
726 # actually bisect
726 # actually bisect
727 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
727 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
728 if extend:
728 if extend:
729 if not changesets:
729 if not changesets:
730 extendnode = extendbisectrange(nodes, good)
730 extendnode = extendbisectrange(nodes, good)
731 if extendnode is not None:
731 if extendnode is not None:
732 ui.write(_("Extending search to changeset %d:%s\n"
732 ui.write(_("Extending search to changeset %d:%s\n"
733 % (extendnode.rev(), extendnode)))
733 % (extendnode.rev(), extendnode)))
734 state['current'] = [extendnode.node()]
734 state['current'] = [extendnode.node()]
735 hbisect.save_state(repo, state)
735 hbisect.save_state(repo, state)
736 if noupdate:
736 if noupdate:
737 return
737 return
738 cmdutil.bailifchanged(repo)
738 cmdutil.bailifchanged(repo)
739 return hg.clean(repo, extendnode.node())
739 return hg.clean(repo, extendnode.node())
740 raise util.Abort(_("nothing to extend"))
740 raise util.Abort(_("nothing to extend"))
741
741
742 if changesets == 0:
742 if changesets == 0:
743 print_result(nodes, good)
743 print_result(nodes, good)
744 else:
744 else:
745 assert len(nodes) == 1 # only a single node can be tested next
745 assert len(nodes) == 1 # only a single node can be tested next
746 node = nodes[0]
746 node = nodes[0]
747 # compute the approximate number of remaining tests
747 # compute the approximate number of remaining tests
748 tests, size = 0, 2
748 tests, size = 0, 2
749 while size <= changesets:
749 while size <= changesets:
750 tests, size = tests + 1, size * 2
750 tests, size = tests + 1, size * 2
751 rev = repo.changelog.rev(node)
751 rev = repo.changelog.rev(node)
752 ui.write(_("Testing changeset %d:%s "
752 ui.write(_("Testing changeset %d:%s "
753 "(%d changesets remaining, ~%d tests)\n")
753 "(%d changesets remaining, ~%d tests)\n")
754 % (rev, short(node), changesets, tests))
754 % (rev, short(node), changesets, tests))
755 state['current'] = [node]
755 state['current'] = [node]
756 hbisect.save_state(repo, state)
756 hbisect.save_state(repo, state)
757 if not noupdate:
757 if not noupdate:
758 cmdutil.bailifchanged(repo)
758 cmdutil.bailifchanged(repo)
759 return hg.clean(repo, node)
759 return hg.clean(repo, node)
760
760
761 @command('bookmarks',
761 @command('bookmarks',
762 [('f', 'force', False, _('force')),
762 [('f', 'force', False, _('force')),
763 ('r', 'rev', '', _('revision'), _('REV')),
763 ('r', 'rev', '', _('revision'), _('REV')),
764 ('d', 'delete', False, _('delete a given bookmark')),
764 ('d', 'delete', False, _('delete a given bookmark')),
765 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
765 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
766 ('i', 'inactive', False, _('mark a bookmark inactive'))],
766 ('i', 'inactive', False, _('mark a bookmark inactive'))],
767 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
767 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
768 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
768 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
769 rename=None, inactive=False):
769 rename=None, inactive=False):
770 '''track a line of development with movable markers
770 '''track a line of development with movable markers
771
771
772 Bookmarks are pointers to certain commits that move when committing.
772 Bookmarks are pointers to certain commits that move when committing.
773 Bookmarks are local. They can be renamed, copied and deleted. It is
773 Bookmarks are local. They can be renamed, copied and deleted. It is
774 possible to use :hg:`merge NAME` to merge from a given bookmark, and
774 possible to use :hg:`merge NAME` to merge from a given bookmark, and
775 :hg:`update NAME` to update to a given bookmark.
775 :hg:`update NAME` to update to a given bookmark.
776
776
777 You can use :hg:`bookmark NAME` to set a bookmark on the working
777 You can use :hg:`bookmark NAME` to set a bookmark on the working
778 directory's parent revision with the given name. If you specify
778 directory's parent revision with the given name. If you specify
779 a revision using -r REV (where REV may be an existing bookmark),
779 a revision using -r REV (where REV may be an existing bookmark),
780 the bookmark is assigned to that revision.
780 the bookmark is assigned to that revision.
781
781
782 Bookmarks can be pushed and pulled between repositories (see :hg:`help
782 Bookmarks can be pushed and pulled between repositories (see :hg:`help
783 push` and :hg:`help pull`). This requires both the local and remote
783 push` and :hg:`help pull`). This requires both the local and remote
784 repositories to support bookmarks. For versions prior to 1.8, this means
784 repositories to support bookmarks. For versions prior to 1.8, this means
785 the bookmarks extension must be enabled.
785 the bookmarks extension must be enabled.
786
786
787 With -i/--inactive, the new bookmark will not be made the active
787 With -i/--inactive, the new bookmark will not be made the active
788 bookmark. If -r/--rev is given, the new bookmark will not be made
788 bookmark. If -r/--rev is given, the new bookmark will not be made
789 active even if -i/--inactive is not given. If no NAME is given, the
789 active even if -i/--inactive is not given. If no NAME is given, the
790 current active bookmark will be marked inactive.
790 current active bookmark will be marked inactive.
791 '''
791 '''
792 hexfn = ui.debugflag and hex or short
792 hexfn = ui.debugflag and hex or short
793 marks = repo._bookmarks
793 marks = repo._bookmarks
794 cur = repo.changectx('.').node()
794 cur = repo.changectx('.').node()
795
795
796 def checkformat(mark):
796 def checkformat(mark):
797 mark = mark.strip()
797 mark = mark.strip()
798 if not mark:
798 if not mark:
799 raise util.Abort(_("bookmark names cannot consist entirely of "
799 raise util.Abort(_("bookmark names cannot consist entirely of "
800 "whitespace"))
800 "whitespace"))
801 scmutil.checknewlabel(repo, mark, 'bookmark')
801 scmutil.checknewlabel(repo, mark, 'bookmark')
802 return mark
802 return mark
803
803
804 def checkconflict(repo, mark, force=False):
804 def checkconflict(repo, mark, force=False):
805 if mark in marks and not force:
805 if mark in marks and not force:
806 raise util.Abort(_("bookmark '%s' already exists "
806 raise util.Abort(_("bookmark '%s' already exists "
807 "(use -f to force)") % mark)
807 "(use -f to force)") % mark)
808 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
808 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
809 and not force):
809 and not force):
810 raise util.Abort(
810 raise util.Abort(
811 _("a bookmark cannot have the name of an existing branch"))
811 _("a bookmark cannot have the name of an existing branch"))
812
812
813 if delete and rename:
813 if delete and rename:
814 raise util.Abort(_("--delete and --rename are incompatible"))
814 raise util.Abort(_("--delete and --rename are incompatible"))
815 if delete and rev:
815 if delete and rev:
816 raise util.Abort(_("--rev is incompatible with --delete"))
816 raise util.Abort(_("--rev is incompatible with --delete"))
817 if rename and rev:
817 if rename and rev:
818 raise util.Abort(_("--rev is incompatible with --rename"))
818 raise util.Abort(_("--rev is incompatible with --rename"))
819 if mark is None and (delete or rev):
819 if mark is None and (delete or rev):
820 raise util.Abort(_("bookmark name required"))
820 raise util.Abort(_("bookmark name required"))
821
821
822 if delete:
822 if delete:
823 if mark not in marks:
823 if mark not in marks:
824 raise util.Abort(_("bookmark '%s' does not exist") % mark)
824 raise util.Abort(_("bookmark '%s' does not exist") % mark)
825 if mark == repo._bookmarkcurrent:
825 if mark == repo._bookmarkcurrent:
826 bookmarks.setcurrent(repo, None)
826 bookmarks.setcurrent(repo, None)
827 del marks[mark]
827 del marks[mark]
828 marks.write()
828 marks.write()
829
829
830 elif rename:
830 elif rename:
831 if mark is None:
831 if mark is None:
832 raise util.Abort(_("new bookmark name required"))
832 raise util.Abort(_("new bookmark name required"))
833 mark = checkformat(mark)
833 mark = checkformat(mark)
834 if rename not in marks:
834 if rename not in marks:
835 raise util.Abort(_("bookmark '%s' does not exist") % rename)
835 raise util.Abort(_("bookmark '%s' does not exist") % rename)
836 checkconflict(repo, mark, force)
836 checkconflict(repo, mark, force)
837 marks[mark] = marks[rename]
837 marks[mark] = marks[rename]
838 if repo._bookmarkcurrent == rename and not inactive:
838 if repo._bookmarkcurrent == rename and not inactive:
839 bookmarks.setcurrent(repo, mark)
839 bookmarks.setcurrent(repo, mark)
840 del marks[rename]
840 del marks[rename]
841 marks.write()
841 marks.write()
842
842
843 elif mark is not None:
843 elif mark is not None:
844 mark = checkformat(mark)
844 mark = checkformat(mark)
845 if inactive and mark == repo._bookmarkcurrent:
845 if inactive and mark == repo._bookmarkcurrent:
846 bookmarks.setcurrent(repo, None)
846 bookmarks.setcurrent(repo, None)
847 return
847 return
848 checkconflict(repo, mark, force)
848 checkconflict(repo, mark, force)
849 if rev:
849 if rev:
850 marks[mark] = scmutil.revsingle(repo, rev).node()
850 marks[mark] = scmutil.revsingle(repo, rev).node()
851 else:
851 else:
852 marks[mark] = cur
852 marks[mark] = cur
853 if not inactive and cur == marks[mark]:
853 if not inactive and cur == marks[mark]:
854 bookmarks.setcurrent(repo, mark)
854 bookmarks.setcurrent(repo, mark)
855 marks.write()
855 marks.write()
856
856
857 # Same message whether trying to deactivate the current bookmark (-i
857 # Same message whether trying to deactivate the current bookmark (-i
858 # with no NAME) or listing bookmarks
858 # with no NAME) or listing bookmarks
859 elif len(marks) == 0:
859 elif len(marks) == 0:
860 ui.status(_("no bookmarks set\n"))
860 ui.status(_("no bookmarks set\n"))
861
861
862 elif inactive:
862 elif inactive:
863 if not repo._bookmarkcurrent:
863 if not repo._bookmarkcurrent:
864 ui.status(_("no active bookmark\n"))
864 ui.status(_("no active bookmark\n"))
865 else:
865 else:
866 bookmarks.setcurrent(repo, None)
866 bookmarks.setcurrent(repo, None)
867
867
868 else: # show bookmarks
868 else: # show bookmarks
869 for bmark, n in sorted(marks.iteritems()):
869 for bmark, n in sorted(marks.iteritems()):
870 current = repo._bookmarkcurrent
870 current = repo._bookmarkcurrent
871 if bmark == current and n == cur:
871 if bmark == current and n == cur:
872 prefix, label = '*', 'bookmarks.current'
872 prefix, label = '*', 'bookmarks.current'
873 else:
873 else:
874 prefix, label = ' ', ''
874 prefix, label = ' ', ''
875
875
876 if ui.quiet:
876 if ui.quiet:
877 ui.write("%s\n" % bmark, label=label)
877 ui.write("%s\n" % bmark, label=label)
878 else:
878 else:
879 ui.write(" %s %-25s %d:%s\n" % (
879 ui.write(" %s %-25s %d:%s\n" % (
880 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
880 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
881 label=label)
881 label=label)
882
882
883 @command('branch',
883 @command('branch',
884 [('f', 'force', None,
884 [('f', 'force', None,
885 _('set branch name even if it shadows an existing branch')),
885 _('set branch name even if it shadows an existing branch')),
886 ('C', 'clean', None, _('reset branch name to parent branch name'))],
886 ('C', 'clean', None, _('reset branch name to parent branch name'))],
887 _('[-fC] [NAME]'))
887 _('[-fC] [NAME]'))
888 def branch(ui, repo, label=None, **opts):
888 def branch(ui, repo, label=None, **opts):
889 """set or show the current branch name
889 """set or show the current branch name
890
890
891 .. note::
891 .. note::
892 Branch names are permanent and global. Use :hg:`bookmark` to create a
892 Branch names are permanent and global. Use :hg:`bookmark` to create a
893 light-weight bookmark instead. See :hg:`help glossary` for more
893 light-weight bookmark instead. See :hg:`help glossary` for more
894 information about named branches and bookmarks.
894 information about named branches and bookmarks.
895
895
896 With no argument, show the current branch name. With one argument,
896 With no argument, show the current branch name. With one argument,
897 set the working directory branch name (the branch will not exist
897 set the working directory branch name (the branch will not exist
898 in the repository until the next commit). Standard practice
898 in the repository until the next commit). Standard practice
899 recommends that primary development take place on the 'default'
899 recommends that primary development take place on the 'default'
900 branch.
900 branch.
901
901
902 Unless -f/--force is specified, branch will not let you set a
902 Unless -f/--force is specified, branch will not let you set a
903 branch name that already exists, even if it's inactive.
903 branch name that already exists, even if it's inactive.
904
904
905 Use -C/--clean to reset the working directory branch to that of
905 Use -C/--clean to reset the working directory branch to that of
906 the parent of the working directory, negating a previous branch
906 the parent of the working directory, negating a previous branch
907 change.
907 change.
908
908
909 Use the command :hg:`update` to switch to an existing branch. Use
909 Use the command :hg:`update` to switch to an existing branch. Use
910 :hg:`commit --close-branch` to mark this branch as closed.
910 :hg:`commit --close-branch` to mark this branch as closed.
911
911
912 Returns 0 on success.
912 Returns 0 on success.
913 """
913 """
914 if not opts.get('clean') and not label:
914 if not opts.get('clean') and not label:
915 ui.write("%s\n" % repo.dirstate.branch())
915 ui.write("%s\n" % repo.dirstate.branch())
916 return
916 return
917
917
918 wlock = repo.wlock()
918 wlock = repo.wlock()
919 try:
919 try:
920 if opts.get('clean'):
920 if opts.get('clean'):
921 label = repo[None].p1().branch()
921 label = repo[None].p1().branch()
922 repo.dirstate.setbranch(label)
922 repo.dirstate.setbranch(label)
923 ui.status(_('reset working directory to branch %s\n') % label)
923 ui.status(_('reset working directory to branch %s\n') % label)
924 elif label:
924 elif label:
925 if not opts.get('force') and label in repo.branchmap():
925 if not opts.get('force') and label in repo.branchmap():
926 if label not in [p.branch() for p in repo.parents()]:
926 if label not in [p.branch() for p in repo.parents()]:
927 raise util.Abort(_('a branch of the same name already'
927 raise util.Abort(_('a branch of the same name already'
928 ' exists'),
928 ' exists'),
929 # i18n: "it" refers to an existing branch
929 # i18n: "it" refers to an existing branch
930 hint=_("use 'hg update' to switch to it"))
930 hint=_("use 'hg update' to switch to it"))
931 scmutil.checknewlabel(repo, label, 'branch')
931 scmutil.checknewlabel(repo, label, 'branch')
932 repo.dirstate.setbranch(label)
932 repo.dirstate.setbranch(label)
933 ui.status(_('marked working directory as branch %s\n') % label)
933 ui.status(_('marked working directory as branch %s\n') % label)
934 ui.status(_('(branches are permanent and global, '
934 ui.status(_('(branches are permanent and global, '
935 'did you want a bookmark?)\n'))
935 'did you want a bookmark?)\n'))
936 finally:
936 finally:
937 wlock.release()
937 wlock.release()
938
938
939 @command('branches',
939 @command('branches',
940 [('a', 'active', False, _('show only branches that have unmerged heads')),
940 [('a', 'active', False, _('show only branches that have unmerged heads')),
941 ('c', 'closed', False, _('show normal and closed branches'))],
941 ('c', 'closed', False, _('show normal and closed branches'))],
942 _('[-ac]'))
942 _('[-ac]'))
943 def branches(ui, repo, active=False, closed=False):
943 def branches(ui, repo, active=False, closed=False):
944 """list repository named branches
944 """list repository named branches
945
945
946 List the repository's named branches, indicating which ones are
946 List the repository's named branches, indicating which ones are
947 inactive. If -c/--closed is specified, also list branches which have
947 inactive. If -c/--closed is specified, also list branches which have
948 been marked closed (see :hg:`commit --close-branch`).
948 been marked closed (see :hg:`commit --close-branch`).
949
949
950 If -a/--active is specified, only show active branches. A branch
950 If -a/--active is specified, only show active branches. A branch
951 is considered active if it contains repository heads.
951 is considered active if it contains repository heads.
952
952
953 Use the command :hg:`update` to switch to an existing branch.
953 Use the command :hg:`update` to switch to an existing branch.
954
954
955 Returns 0.
955 Returns 0.
956 """
956 """
957
957
958 hexfunc = ui.debugflag and hex or short
958 hexfunc = ui.debugflag and hex or short
959
959
960 activebranches = set([repo[n].branch() for n in repo.heads()])
960 activebranches = set([repo[n].branch() for n in repo.heads()])
961 branches = []
961 branches = []
962 for tag, heads in repo.branchmap().iteritems():
962 for tag, heads in repo.branchmap().iteritems():
963 for h in reversed(heads):
963 for h in reversed(heads):
964 ctx = repo[h]
964 ctx = repo[h]
965 isopen = not ctx.closesbranch()
965 isopen = not ctx.closesbranch()
966 if isopen:
966 if isopen:
967 tip = ctx
967 tip = ctx
968 break
968 break
969 else:
969 else:
970 tip = repo[heads[-1]]
970 tip = repo[heads[-1]]
971 isactive = tag in activebranches and isopen
971 isactive = tag in activebranches and isopen
972 branches.append((tip, isactive, isopen))
972 branches.append((tip, isactive, isopen))
973 branches.sort(key=lambda i: (i[1], i[0].rev(), i[0].branch(), i[2]),
973 branches.sort(key=lambda i: (i[1], i[0].rev(), i[0].branch(), i[2]),
974 reverse=True)
974 reverse=True)
975
975
976 for ctx, isactive, isopen in branches:
976 for ctx, isactive, isopen in branches:
977 if (not active) or isactive:
977 if (not active) or isactive:
978 if isactive:
978 if isactive:
979 label = 'branches.active'
979 label = 'branches.active'
980 notice = ''
980 notice = ''
981 elif not isopen:
981 elif not isopen:
982 if not closed:
982 if not closed:
983 continue
983 continue
984 label = 'branches.closed'
984 label = 'branches.closed'
985 notice = _(' (closed)')
985 notice = _(' (closed)')
986 else:
986 else:
987 label = 'branches.inactive'
987 label = 'branches.inactive'
988 notice = _(' (inactive)')
988 notice = _(' (inactive)')
989 if ctx.branch() == repo.dirstate.branch():
989 if ctx.branch() == repo.dirstate.branch():
990 label = 'branches.current'
990 label = 'branches.current'
991 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(ctx.branch()))
991 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(ctx.branch()))
992 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
992 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
993 'log.changeset changeset.%s' % ctx.phasestr())
993 'log.changeset changeset.%s' % ctx.phasestr())
994 tag = ui.label(ctx.branch(), label)
994 tag = ui.label(ctx.branch(), label)
995 if ui.quiet:
995 if ui.quiet:
996 ui.write("%s\n" % tag)
996 ui.write("%s\n" % tag)
997 else:
997 else:
998 ui.write("%s %s%s\n" % (tag, rev, notice))
998 ui.write("%s %s%s\n" % (tag, rev, notice))
999
999
1000 @command('bundle',
1000 @command('bundle',
1001 [('f', 'force', None, _('run even when the destination is unrelated')),
1001 [('f', 'force', None, _('run even when the destination is unrelated')),
1002 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1002 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1003 _('REV')),
1003 _('REV')),
1004 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1004 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1005 _('BRANCH')),
1005 _('BRANCH')),
1006 ('', 'base', [],
1006 ('', 'base', [],
1007 _('a base changeset assumed to be available at the destination'),
1007 _('a base changeset assumed to be available at the destination'),
1008 _('REV')),
1008 _('REV')),
1009 ('a', 'all', None, _('bundle all changesets in the repository')),
1009 ('a', 'all', None, _('bundle all changesets in the repository')),
1010 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1010 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1011 ] + remoteopts,
1011 ] + remoteopts,
1012 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1012 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1013 def bundle(ui, repo, fname, dest=None, **opts):
1013 def bundle(ui, repo, fname, dest=None, **opts):
1014 """create a changegroup file
1014 """create a changegroup file
1015
1015
1016 Generate a compressed changegroup file collecting changesets not
1016 Generate a compressed changegroup file collecting changesets not
1017 known to be in another repository.
1017 known to be in another repository.
1018
1018
1019 If you omit the destination repository, then hg assumes the
1019 If you omit the destination repository, then hg assumes the
1020 destination will have all the nodes you specify with --base
1020 destination will have all the nodes you specify with --base
1021 parameters. To create a bundle containing all changesets, use
1021 parameters. To create a bundle containing all changesets, use
1022 -a/--all (or --base null).
1022 -a/--all (or --base null).
1023
1023
1024 You can change compression method with the -t/--type option.
1024 You can change compression method with the -t/--type option.
1025 The available compression methods are: none, bzip2, and
1025 The available compression methods are: none, bzip2, and
1026 gzip (by default, bundles are compressed using bzip2).
1026 gzip (by default, bundles are compressed using bzip2).
1027
1027
1028 The bundle file can then be transferred using conventional means
1028 The bundle file can then be transferred using conventional means
1029 and applied to another repository with the unbundle or pull
1029 and applied to another repository with the unbundle or pull
1030 command. This is useful when direct push and pull are not
1030 command. This is useful when direct push and pull are not
1031 available or when exporting an entire repository is undesirable.
1031 available or when exporting an entire repository is undesirable.
1032
1032
1033 Applying bundles preserves all changeset contents including
1033 Applying bundles preserves all changeset contents including
1034 permissions, copy/rename information, and revision history.
1034 permissions, copy/rename information, and revision history.
1035
1035
1036 Returns 0 on success, 1 if no changes found.
1036 Returns 0 on success, 1 if no changes found.
1037 """
1037 """
1038 revs = None
1038 revs = None
1039 if 'rev' in opts:
1039 if 'rev' in opts:
1040 revs = scmutil.revrange(repo, opts['rev'])
1040 revs = scmutil.revrange(repo, opts['rev'])
1041
1041
1042 bundletype = opts.get('type', 'bzip2').lower()
1042 bundletype = opts.get('type', 'bzip2').lower()
1043 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1043 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1044 bundletype = btypes.get(bundletype)
1044 bundletype = btypes.get(bundletype)
1045 if bundletype not in changegroup.bundletypes:
1045 if bundletype not in changegroup.bundletypes:
1046 raise util.Abort(_('unknown bundle type specified with --type'))
1046 raise util.Abort(_('unknown bundle type specified with --type'))
1047
1047
1048 if opts.get('all'):
1048 if opts.get('all'):
1049 base = ['null']
1049 base = ['null']
1050 else:
1050 else:
1051 base = scmutil.revrange(repo, opts.get('base'))
1051 base = scmutil.revrange(repo, opts.get('base'))
1052 if base:
1052 if base:
1053 if dest:
1053 if dest:
1054 raise util.Abort(_("--base is incompatible with specifying "
1054 raise util.Abort(_("--base is incompatible with specifying "
1055 "a destination"))
1055 "a destination"))
1056 common = [repo.lookup(rev) for rev in base]
1056 common = [repo.lookup(rev) for rev in base]
1057 heads = revs and map(repo.lookup, revs) or revs
1057 heads = revs and map(repo.lookup, revs) or revs
1058 cg = repo.getbundle('bundle', heads=heads, common=common)
1058 cg = repo.getbundle('bundle', heads=heads, common=common)
1059 outgoing = None
1059 outgoing = None
1060 else:
1060 else:
1061 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1061 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1062 dest, branches = hg.parseurl(dest, opts.get('branch'))
1062 dest, branches = hg.parseurl(dest, opts.get('branch'))
1063 other = hg.peer(repo, opts, dest)
1063 other = hg.peer(repo, opts, dest)
1064 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1064 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1065 heads = revs and map(repo.lookup, revs) or revs
1065 heads = revs and map(repo.lookup, revs) or revs
1066 outgoing = discovery.findcommonoutgoing(repo, other,
1066 outgoing = discovery.findcommonoutgoing(repo, other,
1067 onlyheads=heads,
1067 onlyheads=heads,
1068 force=opts.get('force'),
1068 force=opts.get('force'),
1069 portable=True)
1069 portable=True)
1070 cg = repo.getlocalbundle('bundle', outgoing)
1070 cg = repo.getlocalbundle('bundle', outgoing)
1071 if not cg:
1071 if not cg:
1072 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1072 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1073 return 1
1073 return 1
1074
1074
1075 changegroup.writebundle(cg, fname, bundletype)
1075 changegroup.writebundle(cg, fname, bundletype)
1076
1076
1077 @command('cat',
1077 @command('cat',
1078 [('o', 'output', '',
1078 [('o', 'output', '',
1079 _('print output to file with formatted name'), _('FORMAT')),
1079 _('print output to file with formatted name'), _('FORMAT')),
1080 ('r', 'rev', '', _('print the given revision'), _('REV')),
1080 ('r', 'rev', '', _('print the given revision'), _('REV')),
1081 ('', 'decode', None, _('apply any matching decode filter')),
1081 ('', 'decode', None, _('apply any matching decode filter')),
1082 ] + walkopts,
1082 ] + walkopts,
1083 _('[OPTION]... FILE...'))
1083 _('[OPTION]... FILE...'))
1084 def cat(ui, repo, file1, *pats, **opts):
1084 def cat(ui, repo, file1, *pats, **opts):
1085 """output the current or given revision of files
1085 """output the current or given revision of files
1086
1086
1087 Print the specified files as they were at the given revision. If
1087 Print the specified files as they were at the given revision. If
1088 no revision is given, the parent of the working directory is used,
1088 no revision is given, the parent of the working directory is used,
1089 or tip if no revision is checked out.
1089 or tip if no revision is checked out.
1090
1090
1091 Output may be to a file, in which case the name of the file is
1091 Output may be to a file, in which case the name of the file is
1092 given using a format string. The formatting rules are the same as
1092 given using a format string. The formatting rules are the same as
1093 for the export command, with the following additions:
1093 for the export command, with the following additions:
1094
1094
1095 :``%s``: basename of file being printed
1095 :``%s``: basename of file being printed
1096 :``%d``: dirname of file being printed, or '.' if in repository root
1096 :``%d``: dirname of file being printed, or '.' if in repository root
1097 :``%p``: root-relative path name of file being printed
1097 :``%p``: root-relative path name of file being printed
1098
1098
1099 Returns 0 on success.
1099 Returns 0 on success.
1100 """
1100 """
1101 ctx = scmutil.revsingle(repo, opts.get('rev'))
1101 ctx = scmutil.revsingle(repo, opts.get('rev'))
1102 err = 1
1102 err = 1
1103 m = scmutil.match(ctx, (file1,) + pats, opts)
1103 m = scmutil.match(ctx, (file1,) + pats, opts)
1104 for abs in ctx.walk(m):
1104 for abs in ctx.walk(m):
1105 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1105 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1106 pathname=abs)
1106 pathname=abs)
1107 data = ctx[abs].data()
1107 data = ctx[abs].data()
1108 if opts.get('decode'):
1108 if opts.get('decode'):
1109 data = repo.wwritedata(abs, data)
1109 data = repo.wwritedata(abs, data)
1110 fp.write(data)
1110 fp.write(data)
1111 fp.close()
1111 fp.close()
1112 err = 0
1112 err = 0
1113 return err
1113 return err
1114
1114
1115 @command('^clone',
1115 @command('^clone',
1116 [('U', 'noupdate', None,
1116 [('U', 'noupdate', None,
1117 _('the clone will include an empty working copy (only a repository)')),
1117 _('the clone will include an empty working copy (only a repository)')),
1118 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1118 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1119 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1119 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1120 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1120 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1121 ('', 'pull', None, _('use pull protocol to copy metadata')),
1121 ('', 'pull', None, _('use pull protocol to copy metadata')),
1122 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1122 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1123 ] + remoteopts,
1123 ] + remoteopts,
1124 _('[OPTION]... SOURCE [DEST]'))
1124 _('[OPTION]... SOURCE [DEST]'))
1125 def clone(ui, source, dest=None, **opts):
1125 def clone(ui, source, dest=None, **opts):
1126 """make a copy of an existing repository
1126 """make a copy of an existing repository
1127
1127
1128 Create a copy of an existing repository in a new directory.
1128 Create a copy of an existing repository in a new directory.
1129
1129
1130 If no destination directory name is specified, it defaults to the
1130 If no destination directory name is specified, it defaults to the
1131 basename of the source.
1131 basename of the source.
1132
1132
1133 The location of the source is added to the new repository's
1133 The location of the source is added to the new repository's
1134 ``.hg/hgrc`` file, as the default to be used for future pulls.
1134 ``.hg/hgrc`` file, as the default to be used for future pulls.
1135
1135
1136 Only local paths and ``ssh://`` URLs are supported as
1136 Only local paths and ``ssh://`` URLs are supported as
1137 destinations. For ``ssh://`` destinations, no working directory or
1137 destinations. For ``ssh://`` destinations, no working directory or
1138 ``.hg/hgrc`` will be created on the remote side.
1138 ``.hg/hgrc`` will be created on the remote side.
1139
1139
1140 To pull only a subset of changesets, specify one or more revisions
1140 To pull only a subset of changesets, specify one or more revisions
1141 identifiers with -r/--rev or branches with -b/--branch. The
1141 identifiers with -r/--rev or branches with -b/--branch. The
1142 resulting clone will contain only the specified changesets and
1142 resulting clone will contain only the specified changesets and
1143 their ancestors. These options (or 'clone src#rev dest') imply
1143 their ancestors. These options (or 'clone src#rev dest') imply
1144 --pull, even for local source repositories. Note that specifying a
1144 --pull, even for local source repositories. Note that specifying a
1145 tag will include the tagged changeset but not the changeset
1145 tag will include the tagged changeset but not the changeset
1146 containing the tag.
1146 containing the tag.
1147
1147
1148 To check out a particular version, use -u/--update, or
1148 To check out a particular version, use -u/--update, or
1149 -U/--noupdate to create a clone with no working directory.
1149 -U/--noupdate to create a clone with no working directory.
1150
1150
1151 .. container:: verbose
1151 .. container:: verbose
1152
1152
1153 For efficiency, hardlinks are used for cloning whenever the
1153 For efficiency, hardlinks are used for cloning whenever the
1154 source and destination are on the same filesystem (note this
1154 source and destination are on the same filesystem (note this
1155 applies only to the repository data, not to the working
1155 applies only to the repository data, not to the working
1156 directory). Some filesystems, such as AFS, implement hardlinking
1156 directory). Some filesystems, such as AFS, implement hardlinking
1157 incorrectly, but do not report errors. In these cases, use the
1157 incorrectly, but do not report errors. In these cases, use the
1158 --pull option to avoid hardlinking.
1158 --pull option to avoid hardlinking.
1159
1159
1160 In some cases, you can clone repositories and the working
1160 In some cases, you can clone repositories and the working
1161 directory using full hardlinks with ::
1161 directory using full hardlinks with ::
1162
1162
1163 $ cp -al REPO REPOCLONE
1163 $ cp -al REPO REPOCLONE
1164
1164
1165 This is the fastest way to clone, but it is not always safe. The
1165 This is the fastest way to clone, but it is not always safe. The
1166 operation is not atomic (making sure REPO is not modified during
1166 operation is not atomic (making sure REPO is not modified during
1167 the operation is up to you) and you have to make sure your
1167 the operation is up to you) and you have to make sure your
1168 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1168 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1169 so). Also, this is not compatible with certain extensions that
1169 so). Also, this is not compatible with certain extensions that
1170 place their metadata under the .hg directory, such as mq.
1170 place their metadata under the .hg directory, such as mq.
1171
1171
1172 Mercurial will update the working directory to the first applicable
1172 Mercurial will update the working directory to the first applicable
1173 revision from this list:
1173 revision from this list:
1174
1174
1175 a) null if -U or the source repository has no changesets
1175 a) null if -U or the source repository has no changesets
1176 b) if -u . and the source repository is local, the first parent of
1176 b) if -u . and the source repository is local, the first parent of
1177 the source repository's working directory
1177 the source repository's working directory
1178 c) the changeset specified with -u (if a branch name, this means the
1178 c) the changeset specified with -u (if a branch name, this means the
1179 latest head of that branch)
1179 latest head of that branch)
1180 d) the changeset specified with -r
1180 d) the changeset specified with -r
1181 e) the tipmost head specified with -b
1181 e) the tipmost head specified with -b
1182 f) the tipmost head specified with the url#branch source syntax
1182 f) the tipmost head specified with the url#branch source syntax
1183 g) the tipmost head of the default branch
1183 g) the tipmost head of the default branch
1184 h) tip
1184 h) tip
1185
1185
1186 Examples:
1186 Examples:
1187
1187
1188 - clone a remote repository to a new directory named hg/::
1188 - clone a remote repository to a new directory named hg/::
1189
1189
1190 hg clone http://selenic.com/hg
1190 hg clone http://selenic.com/hg
1191
1191
1192 - create a lightweight local clone::
1192 - create a lightweight local clone::
1193
1193
1194 hg clone project/ project-feature/
1194 hg clone project/ project-feature/
1195
1195
1196 - clone from an absolute path on an ssh server (note double-slash)::
1196 - clone from an absolute path on an ssh server (note double-slash)::
1197
1197
1198 hg clone ssh://user@server//home/projects/alpha/
1198 hg clone ssh://user@server//home/projects/alpha/
1199
1199
1200 - do a high-speed clone over a LAN while checking out a
1200 - do a high-speed clone over a LAN while checking out a
1201 specified version::
1201 specified version::
1202
1202
1203 hg clone --uncompressed http://server/repo -u 1.5
1203 hg clone --uncompressed http://server/repo -u 1.5
1204
1204
1205 - create a repository without changesets after a particular revision::
1205 - create a repository without changesets after a particular revision::
1206
1206
1207 hg clone -r 04e544 experimental/ good/
1207 hg clone -r 04e544 experimental/ good/
1208
1208
1209 - clone (and track) a particular named branch::
1209 - clone (and track) a particular named branch::
1210
1210
1211 hg clone http://selenic.com/hg#stable
1211 hg clone http://selenic.com/hg#stable
1212
1212
1213 See :hg:`help urls` for details on specifying URLs.
1213 See :hg:`help urls` for details on specifying URLs.
1214
1214
1215 Returns 0 on success.
1215 Returns 0 on success.
1216 """
1216 """
1217 if opts.get('noupdate') and opts.get('updaterev'):
1217 if opts.get('noupdate') and opts.get('updaterev'):
1218 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1218 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1219
1219
1220 r = hg.clone(ui, opts, source, dest,
1220 r = hg.clone(ui, opts, source, dest,
1221 pull=opts.get('pull'),
1221 pull=opts.get('pull'),
1222 stream=opts.get('uncompressed'),
1222 stream=opts.get('uncompressed'),
1223 rev=opts.get('rev'),
1223 rev=opts.get('rev'),
1224 update=opts.get('updaterev') or not opts.get('noupdate'),
1224 update=opts.get('updaterev') or not opts.get('noupdate'),
1225 branch=opts.get('branch'))
1225 branch=opts.get('branch'))
1226
1226
1227 return r is None
1227 return r is None
1228
1228
1229 @command('^commit|ci',
1229 @command('^commit|ci',
1230 [('A', 'addremove', None,
1230 [('A', 'addremove', None,
1231 _('mark new/missing files as added/removed before committing')),
1231 _('mark new/missing files as added/removed before committing')),
1232 ('', 'close-branch', None,
1232 ('', 'close-branch', None,
1233 _('mark a branch as closed, hiding it from the branch list')),
1233 _('mark a branch as closed, hiding it from the branch list')),
1234 ('', 'amend', None, _('amend the parent of the working dir')),
1234 ('', 'amend', None, _('amend the parent of the working dir')),
1235 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1235 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1236 _('[OPTION]... [FILE]...'))
1236 _('[OPTION]... [FILE]...'))
1237 def commit(ui, repo, *pats, **opts):
1237 def commit(ui, repo, *pats, **opts):
1238 """commit the specified files or all outstanding changes
1238 """commit the specified files or all outstanding changes
1239
1239
1240 Commit changes to the given files into the repository. Unlike a
1240 Commit changes to the given files into the repository. Unlike a
1241 centralized SCM, this operation is a local operation. See
1241 centralized SCM, this operation is a local operation. See
1242 :hg:`push` for a way to actively distribute your changes.
1242 :hg:`push` for a way to actively distribute your changes.
1243
1243
1244 If a list of files is omitted, all changes reported by :hg:`status`
1244 If a list of files is omitted, all changes reported by :hg:`status`
1245 will be committed.
1245 will be committed.
1246
1246
1247 If you are committing the result of a merge, do not provide any
1247 If you are committing the result of a merge, do not provide any
1248 filenames or -I/-X filters.
1248 filenames or -I/-X filters.
1249
1249
1250 If no commit message is specified, Mercurial starts your
1250 If no commit message is specified, Mercurial starts your
1251 configured editor where you can enter a message. In case your
1251 configured editor where you can enter a message. In case your
1252 commit fails, you will find a backup of your message in
1252 commit fails, you will find a backup of your message in
1253 ``.hg/last-message.txt``.
1253 ``.hg/last-message.txt``.
1254
1254
1255 The --amend flag can be used to amend the parent of the
1255 The --amend flag can be used to amend the parent of the
1256 working directory with a new commit that contains the changes
1256 working directory with a new commit that contains the changes
1257 in the parent in addition to those currently reported by :hg:`status`,
1257 in the parent in addition to those currently reported by :hg:`status`,
1258 if there are any. The old commit is stored in a backup bundle in
1258 if there are any. The old commit is stored in a backup bundle in
1259 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1259 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1260 on how to restore it).
1260 on how to restore it).
1261
1261
1262 Message, user and date are taken from the amended commit unless
1262 Message, user and date are taken from the amended commit unless
1263 specified. When a message isn't specified on the command line,
1263 specified. When a message isn't specified on the command line,
1264 the editor will open with the message of the amended commit.
1264 the editor will open with the message of the amended commit.
1265
1265
1266 It is not possible to amend public changesets (see :hg:`help phases`)
1266 It is not possible to amend public changesets (see :hg:`help phases`)
1267 or changesets that have children.
1267 or changesets that have children.
1268
1268
1269 See :hg:`help dates` for a list of formats valid for -d/--date.
1269 See :hg:`help dates` for a list of formats valid for -d/--date.
1270
1270
1271 Returns 0 on success, 1 if nothing changed.
1271 Returns 0 on success, 1 if nothing changed.
1272 """
1272 """
1273 if opts.get('subrepos'):
1273 if opts.get('subrepos'):
1274 # Let --subrepos on the command line override config setting.
1274 # Let --subrepos on the command line override config setting.
1275 ui.setconfig('ui', 'commitsubrepos', True)
1275 ui.setconfig('ui', 'commitsubrepos', True)
1276
1276
1277 extra = {}
1277 extra = {}
1278 if opts.get('close_branch'):
1278 if opts.get('close_branch'):
1279 if repo['.'].node() not in repo.branchheads():
1279 if repo['.'].node() not in repo.branchheads():
1280 # The topo heads set is included in the branch heads set of the
1280 # The topo heads set is included in the branch heads set of the
1281 # current branch, so it's sufficient to test branchheads
1281 # current branch, so it's sufficient to test branchheads
1282 raise util.Abort(_('can only close branch heads'))
1282 raise util.Abort(_('can only close branch heads'))
1283 extra['close'] = 1
1283 extra['close'] = 1
1284
1284
1285 branch = repo[None].branch()
1285 branch = repo[None].branch()
1286 bheads = repo.branchheads(branch)
1286 bheads = repo.branchheads(branch)
1287
1287
1288 if opts.get('amend'):
1288 if opts.get('amend'):
1289 if ui.configbool('ui', 'commitsubrepos'):
1289 if ui.configbool('ui', 'commitsubrepos'):
1290 raise util.Abort(_('cannot amend recursively'))
1290 raise util.Abort(_('cannot amend recursively'))
1291
1291
1292 old = repo['.']
1292 old = repo['.']
1293 if old.phase() == phases.public:
1293 if old.phase() == phases.public:
1294 raise util.Abort(_('cannot amend public changesets'))
1294 raise util.Abort(_('cannot amend public changesets'))
1295 if len(old.parents()) > 1:
1295 if len(old.parents()) > 1:
1296 raise util.Abort(_('cannot amend merge changesets'))
1296 raise util.Abort(_('cannot amend merge changesets'))
1297 if len(repo[None].parents()) > 1:
1297 if len(repo[None].parents()) > 1:
1298 raise util.Abort(_('cannot amend while merging'))
1298 raise util.Abort(_('cannot amend while merging'))
1299 if old.children():
1299 if old.children():
1300 raise util.Abort(_('cannot amend changeset with children'))
1300 raise util.Abort(_('cannot amend changeset with children'))
1301
1301
1302 e = cmdutil.commiteditor
1302 e = cmdutil.commiteditor
1303 if opts.get('force_editor'):
1303 if opts.get('force_editor'):
1304 e = cmdutil.commitforceeditor
1304 e = cmdutil.commitforceeditor
1305
1305
1306 def commitfunc(ui, repo, message, match, opts):
1306 def commitfunc(ui, repo, message, match, opts):
1307 editor = e
1307 editor = e
1308 # message contains text from -m or -l, if it's empty,
1308 # message contains text from -m or -l, if it's empty,
1309 # open the editor with the old message
1309 # open the editor with the old message
1310 if not message:
1310 if not message:
1311 message = old.description()
1311 message = old.description()
1312 editor = cmdutil.commitforceeditor
1312 editor = cmdutil.commitforceeditor
1313 return repo.commit(message,
1313 return repo.commit(message,
1314 opts.get('user') or old.user(),
1314 opts.get('user') or old.user(),
1315 opts.get('date') or old.date(),
1315 opts.get('date') or old.date(),
1316 match,
1316 match,
1317 editor=editor,
1317 editor=editor,
1318 extra=extra)
1318 extra=extra)
1319
1319
1320 current = repo._bookmarkcurrent
1320 current = repo._bookmarkcurrent
1321 marks = old.bookmarks()
1321 marks = old.bookmarks()
1322 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1322 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1323 if node == old.node():
1323 if node == old.node():
1324 ui.status(_("nothing changed\n"))
1324 ui.status(_("nothing changed\n"))
1325 return 1
1325 return 1
1326 elif marks:
1326 elif marks:
1327 ui.debug('moving bookmarks %r from %s to %s\n' %
1327 ui.debug('moving bookmarks %r from %s to %s\n' %
1328 (marks, old.hex(), hex(node)))
1328 (marks, old.hex(), hex(node)))
1329 newmarks = repo._bookmarks
1329 newmarks = repo._bookmarks
1330 for bm in marks:
1330 for bm in marks:
1331 newmarks[bm] = node
1331 newmarks[bm] = node
1332 if bm == current:
1332 if bm == current:
1333 bookmarks.setcurrent(repo, bm)
1333 bookmarks.setcurrent(repo, bm)
1334 newmarks.write()
1334 newmarks.write()
1335 else:
1335 else:
1336 e = cmdutil.commiteditor
1336 e = cmdutil.commiteditor
1337 if opts.get('force_editor'):
1337 if opts.get('force_editor'):
1338 e = cmdutil.commitforceeditor
1338 e = cmdutil.commitforceeditor
1339
1339
1340 def commitfunc(ui, repo, message, match, opts):
1340 def commitfunc(ui, repo, message, match, opts):
1341 return repo.commit(message, opts.get('user'), opts.get('date'),
1341 return repo.commit(message, opts.get('user'), opts.get('date'),
1342 match, editor=e, extra=extra)
1342 match, editor=e, extra=extra)
1343
1343
1344 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1344 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1345
1345
1346 if not node:
1346 if not node:
1347 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1347 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1348 if stat[3]:
1348 if stat[3]:
1349 ui.status(_("nothing changed (%d missing files, see "
1349 ui.status(_("nothing changed (%d missing files, see "
1350 "'hg status')\n") % len(stat[3]))
1350 "'hg status')\n") % len(stat[3]))
1351 else:
1351 else:
1352 ui.status(_("nothing changed\n"))
1352 ui.status(_("nothing changed\n"))
1353 return 1
1353 return 1
1354
1354
1355 ctx = repo[node]
1355 ctx = repo[node]
1356 parents = ctx.parents()
1356 parents = ctx.parents()
1357
1357
1358 if (not opts.get('amend') and bheads and node not in bheads and not
1358 if (not opts.get('amend') and bheads and node not in bheads and not
1359 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1359 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1360 ui.status(_('created new head\n'))
1360 ui.status(_('created new head\n'))
1361 # The message is not printed for initial roots. For the other
1361 # The message is not printed for initial roots. For the other
1362 # changesets, it is printed in the following situations:
1362 # changesets, it is printed in the following situations:
1363 #
1363 #
1364 # Par column: for the 2 parents with ...
1364 # Par column: for the 2 parents with ...
1365 # N: null or no parent
1365 # N: null or no parent
1366 # B: parent is on another named branch
1366 # B: parent is on another named branch
1367 # C: parent is a regular non head changeset
1367 # C: parent is a regular non head changeset
1368 # H: parent was a branch head of the current branch
1368 # H: parent was a branch head of the current branch
1369 # Msg column: whether we print "created new head" message
1369 # Msg column: whether we print "created new head" message
1370 # In the following, it is assumed that there already exists some
1370 # In the following, it is assumed that there already exists some
1371 # initial branch heads of the current branch, otherwise nothing is
1371 # initial branch heads of the current branch, otherwise nothing is
1372 # printed anyway.
1372 # printed anyway.
1373 #
1373 #
1374 # Par Msg Comment
1374 # Par Msg Comment
1375 # N N y additional topo root
1375 # N N y additional topo root
1376 #
1376 #
1377 # B N y additional branch root
1377 # B N y additional branch root
1378 # C N y additional topo head
1378 # C N y additional topo head
1379 # H N n usual case
1379 # H N n usual case
1380 #
1380 #
1381 # B B y weird additional branch root
1381 # B B y weird additional branch root
1382 # C B y branch merge
1382 # C B y branch merge
1383 # H B n merge with named branch
1383 # H B n merge with named branch
1384 #
1384 #
1385 # C C y additional head from merge
1385 # C C y additional head from merge
1386 # C H n merge with a head
1386 # C H n merge with a head
1387 #
1387 #
1388 # H H n head merge: head count decreases
1388 # H H n head merge: head count decreases
1389
1389
1390 if not opts.get('close_branch'):
1390 if not opts.get('close_branch'):
1391 for r in parents:
1391 for r in parents:
1392 if r.closesbranch() and r.branch() == branch:
1392 if r.closesbranch() and r.branch() == branch:
1393 ui.status(_('reopening closed branch head %d\n') % r)
1393 ui.status(_('reopening closed branch head %d\n') % r)
1394
1394
1395 if ui.debugflag:
1395 if ui.debugflag:
1396 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1396 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1397 elif ui.verbose:
1397 elif ui.verbose:
1398 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1398 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1399
1399
1400 @command('copy|cp',
1400 @command('copy|cp',
1401 [('A', 'after', None, _('record a copy that has already occurred')),
1401 [('A', 'after', None, _('record a copy that has already occurred')),
1402 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1402 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1403 ] + walkopts + dryrunopts,
1403 ] + walkopts + dryrunopts,
1404 _('[OPTION]... [SOURCE]... DEST'))
1404 _('[OPTION]... [SOURCE]... DEST'))
1405 def copy(ui, repo, *pats, **opts):
1405 def copy(ui, repo, *pats, **opts):
1406 """mark files as copied for the next commit
1406 """mark files as copied for the next commit
1407
1407
1408 Mark dest as having copies of source files. If dest is a
1408 Mark dest as having copies of source files. If dest is a
1409 directory, copies are put in that directory. If dest is a file,
1409 directory, copies are put in that directory. If dest is a file,
1410 the source must be a single file.
1410 the source must be a single file.
1411
1411
1412 By default, this command copies the contents of files as they
1412 By default, this command copies the contents of files as they
1413 exist in the working directory. If invoked with -A/--after, the
1413 exist in the working directory. If invoked with -A/--after, the
1414 operation is recorded, but no copying is performed.
1414 operation is recorded, but no copying is performed.
1415
1415
1416 This command takes effect with the next commit. To undo a copy
1416 This command takes effect with the next commit. To undo a copy
1417 before that, see :hg:`revert`.
1417 before that, see :hg:`revert`.
1418
1418
1419 Returns 0 on success, 1 if errors are encountered.
1419 Returns 0 on success, 1 if errors are encountered.
1420 """
1420 """
1421 wlock = repo.wlock(False)
1421 wlock = repo.wlock(False)
1422 try:
1422 try:
1423 return cmdutil.copy(ui, repo, pats, opts)
1423 return cmdutil.copy(ui, repo, pats, opts)
1424 finally:
1424 finally:
1425 wlock.release()
1425 wlock.release()
1426
1426
1427 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1427 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1428 def debugancestor(ui, repo, *args):
1428 def debugancestor(ui, repo, *args):
1429 """find the ancestor revision of two revisions in a given index"""
1429 """find the ancestor revision of two revisions in a given index"""
1430 if len(args) == 3:
1430 if len(args) == 3:
1431 index, rev1, rev2 = args
1431 index, rev1, rev2 = args
1432 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1432 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1433 lookup = r.lookup
1433 lookup = r.lookup
1434 elif len(args) == 2:
1434 elif len(args) == 2:
1435 if not repo:
1435 if not repo:
1436 raise util.Abort(_("there is no Mercurial repository here "
1436 raise util.Abort(_("there is no Mercurial repository here "
1437 "(.hg not found)"))
1437 "(.hg not found)"))
1438 rev1, rev2 = args
1438 rev1, rev2 = args
1439 r = repo.changelog
1439 r = repo.changelog
1440 lookup = repo.lookup
1440 lookup = repo.lookup
1441 else:
1441 else:
1442 raise util.Abort(_('either two or three arguments required'))
1442 raise util.Abort(_('either two or three arguments required'))
1443 a = r.ancestor(lookup(rev1), lookup(rev2))
1443 a = r.ancestor(lookup(rev1), lookup(rev2))
1444 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1444 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1445
1445
1446 @command('debugbuilddag',
1446 @command('debugbuilddag',
1447 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1447 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1448 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1448 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1449 ('n', 'new-file', None, _('add new file at each rev'))],
1449 ('n', 'new-file', None, _('add new file at each rev'))],
1450 _('[OPTION]... [TEXT]'))
1450 _('[OPTION]... [TEXT]'))
1451 def debugbuilddag(ui, repo, text=None,
1451 def debugbuilddag(ui, repo, text=None,
1452 mergeable_file=False,
1452 mergeable_file=False,
1453 overwritten_file=False,
1453 overwritten_file=False,
1454 new_file=False):
1454 new_file=False):
1455 """builds a repo with a given DAG from scratch in the current empty repo
1455 """builds a repo with a given DAG from scratch in the current empty repo
1456
1456
1457 The description of the DAG is read from stdin if not given on the
1457 The description of the DAG is read from stdin if not given on the
1458 command line.
1458 command line.
1459
1459
1460 Elements:
1460 Elements:
1461
1461
1462 - "+n" is a linear run of n nodes based on the current default parent
1462 - "+n" is a linear run of n nodes based on the current default parent
1463 - "." is a single node based on the current default parent
1463 - "." is a single node based on the current default parent
1464 - "$" resets the default parent to null (implied at the start);
1464 - "$" resets the default parent to null (implied at the start);
1465 otherwise the default parent is always the last node created
1465 otherwise the default parent is always the last node created
1466 - "<p" sets the default parent to the backref p
1466 - "<p" sets the default parent to the backref p
1467 - "*p" is a fork at parent p, which is a backref
1467 - "*p" is a fork at parent p, which is a backref
1468 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1468 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1469 - "/p2" is a merge of the preceding node and p2
1469 - "/p2" is a merge of the preceding node and p2
1470 - ":tag" defines a local tag for the preceding node
1470 - ":tag" defines a local tag for the preceding node
1471 - "@branch" sets the named branch for subsequent nodes
1471 - "@branch" sets the named branch for subsequent nodes
1472 - "#...\\n" is a comment up to the end of the line
1472 - "#...\\n" is a comment up to the end of the line
1473
1473
1474 Whitespace between the above elements is ignored.
1474 Whitespace between the above elements is ignored.
1475
1475
1476 A backref is either
1476 A backref is either
1477
1477
1478 - a number n, which references the node curr-n, where curr is the current
1478 - a number n, which references the node curr-n, where curr is the current
1479 node, or
1479 node, or
1480 - the name of a local tag you placed earlier using ":tag", or
1480 - the name of a local tag you placed earlier using ":tag", or
1481 - empty to denote the default parent.
1481 - empty to denote the default parent.
1482
1482
1483 All string valued-elements are either strictly alphanumeric, or must
1483 All string valued-elements are either strictly alphanumeric, or must
1484 be enclosed in double quotes ("..."), with "\\" as escape character.
1484 be enclosed in double quotes ("..."), with "\\" as escape character.
1485 """
1485 """
1486
1486
1487 if text is None:
1487 if text is None:
1488 ui.status(_("reading DAG from stdin\n"))
1488 ui.status(_("reading DAG from stdin\n"))
1489 text = ui.fin.read()
1489 text = ui.fin.read()
1490
1490
1491 cl = repo.changelog
1491 cl = repo.changelog
1492 if len(cl) > 0:
1492 if len(cl) > 0:
1493 raise util.Abort(_('repository is not empty'))
1493 raise util.Abort(_('repository is not empty'))
1494
1494
1495 # determine number of revs in DAG
1495 # determine number of revs in DAG
1496 total = 0
1496 total = 0
1497 for type, data in dagparser.parsedag(text):
1497 for type, data in dagparser.parsedag(text):
1498 if type == 'n':
1498 if type == 'n':
1499 total += 1
1499 total += 1
1500
1500
1501 if mergeable_file:
1501 if mergeable_file:
1502 linesperrev = 2
1502 linesperrev = 2
1503 # make a file with k lines per rev
1503 # make a file with k lines per rev
1504 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1504 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1505 initialmergedlines.append("")
1505 initialmergedlines.append("")
1506
1506
1507 tags = []
1507 tags = []
1508
1508
1509 lock = tr = None
1509 lock = tr = None
1510 try:
1510 try:
1511 lock = repo.lock()
1511 lock = repo.lock()
1512 tr = repo.transaction("builddag")
1512 tr = repo.transaction("builddag")
1513
1513
1514 at = -1
1514 at = -1
1515 atbranch = 'default'
1515 atbranch = 'default'
1516 nodeids = []
1516 nodeids = []
1517 id = 0
1517 id = 0
1518 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1518 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1519 for type, data in dagparser.parsedag(text):
1519 for type, data in dagparser.parsedag(text):
1520 if type == 'n':
1520 if type == 'n':
1521 ui.note(('node %s\n' % str(data)))
1521 ui.note(('node %s\n' % str(data)))
1522 id, ps = data
1522 id, ps = data
1523
1523
1524 files = []
1524 files = []
1525 fctxs = {}
1525 fctxs = {}
1526
1526
1527 p2 = None
1527 p2 = None
1528 if mergeable_file:
1528 if mergeable_file:
1529 fn = "mf"
1529 fn = "mf"
1530 p1 = repo[ps[0]]
1530 p1 = repo[ps[0]]
1531 if len(ps) > 1:
1531 if len(ps) > 1:
1532 p2 = repo[ps[1]]
1532 p2 = repo[ps[1]]
1533 pa = p1.ancestor(p2)
1533 pa = p1.ancestor(p2)
1534 base, local, other = [x[fn].data() for x in pa, p1, p2]
1534 base, local, other = [x[fn].data() for x in pa, p1, p2]
1535 m3 = simplemerge.Merge3Text(base, local, other)
1535 m3 = simplemerge.Merge3Text(base, local, other)
1536 ml = [l.strip() for l in m3.merge_lines()]
1536 ml = [l.strip() for l in m3.merge_lines()]
1537 ml.append("")
1537 ml.append("")
1538 elif at > 0:
1538 elif at > 0:
1539 ml = p1[fn].data().split("\n")
1539 ml = p1[fn].data().split("\n")
1540 else:
1540 else:
1541 ml = initialmergedlines
1541 ml = initialmergedlines
1542 ml[id * linesperrev] += " r%i" % id
1542 ml[id * linesperrev] += " r%i" % id
1543 mergedtext = "\n".join(ml)
1543 mergedtext = "\n".join(ml)
1544 files.append(fn)
1544 files.append(fn)
1545 fctxs[fn] = context.memfilectx(fn, mergedtext)
1545 fctxs[fn] = context.memfilectx(fn, mergedtext)
1546
1546
1547 if overwritten_file:
1547 if overwritten_file:
1548 fn = "of"
1548 fn = "of"
1549 files.append(fn)
1549 files.append(fn)
1550 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1550 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1551
1551
1552 if new_file:
1552 if new_file:
1553 fn = "nf%i" % id
1553 fn = "nf%i" % id
1554 files.append(fn)
1554 files.append(fn)
1555 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1555 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1556 if len(ps) > 1:
1556 if len(ps) > 1:
1557 if not p2:
1557 if not p2:
1558 p2 = repo[ps[1]]
1558 p2 = repo[ps[1]]
1559 for fn in p2:
1559 for fn in p2:
1560 if fn.startswith("nf"):
1560 if fn.startswith("nf"):
1561 files.append(fn)
1561 files.append(fn)
1562 fctxs[fn] = p2[fn]
1562 fctxs[fn] = p2[fn]
1563
1563
1564 def fctxfn(repo, cx, path):
1564 def fctxfn(repo, cx, path):
1565 return fctxs.get(path)
1565 return fctxs.get(path)
1566
1566
1567 if len(ps) == 0 or ps[0] < 0:
1567 if len(ps) == 0 or ps[0] < 0:
1568 pars = [None, None]
1568 pars = [None, None]
1569 elif len(ps) == 1:
1569 elif len(ps) == 1:
1570 pars = [nodeids[ps[0]], None]
1570 pars = [nodeids[ps[0]], None]
1571 else:
1571 else:
1572 pars = [nodeids[p] for p in ps]
1572 pars = [nodeids[p] for p in ps]
1573 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1573 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1574 date=(id, 0),
1574 date=(id, 0),
1575 user="debugbuilddag",
1575 user="debugbuilddag",
1576 extra={'branch': atbranch})
1576 extra={'branch': atbranch})
1577 nodeid = repo.commitctx(cx)
1577 nodeid = repo.commitctx(cx)
1578 nodeids.append(nodeid)
1578 nodeids.append(nodeid)
1579 at = id
1579 at = id
1580 elif type == 'l':
1580 elif type == 'l':
1581 id, name = data
1581 id, name = data
1582 ui.note(('tag %s\n' % name))
1582 ui.note(('tag %s\n' % name))
1583 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1583 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1584 elif type == 'a':
1584 elif type == 'a':
1585 ui.note(('branch %s\n' % data))
1585 ui.note(('branch %s\n' % data))
1586 atbranch = data
1586 atbranch = data
1587 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1587 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1588 tr.close()
1588 tr.close()
1589
1589
1590 if tags:
1590 if tags:
1591 repo.opener.write("localtags", "".join(tags))
1591 repo.opener.write("localtags", "".join(tags))
1592 finally:
1592 finally:
1593 ui.progress(_('building'), None)
1593 ui.progress(_('building'), None)
1594 release(tr, lock)
1594 release(tr, lock)
1595
1595
1596 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1596 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1597 def debugbundle(ui, bundlepath, all=None, **opts):
1597 def debugbundle(ui, bundlepath, all=None, **opts):
1598 """lists the contents of a bundle"""
1598 """lists the contents of a bundle"""
1599 f = hg.openpath(ui, bundlepath)
1599 f = hg.openpath(ui, bundlepath)
1600 try:
1600 try:
1601 gen = changegroup.readbundle(f, bundlepath)
1601 gen = changegroup.readbundle(f, bundlepath)
1602 if all:
1602 if all:
1603 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1603 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1604
1604
1605 def showchunks(named):
1605 def showchunks(named):
1606 ui.write("\n%s\n" % named)
1606 ui.write("\n%s\n" % named)
1607 chain = None
1607 chain = None
1608 while True:
1608 while True:
1609 chunkdata = gen.deltachunk(chain)
1609 chunkdata = gen.deltachunk(chain)
1610 if not chunkdata:
1610 if not chunkdata:
1611 break
1611 break
1612 node = chunkdata['node']
1612 node = chunkdata['node']
1613 p1 = chunkdata['p1']
1613 p1 = chunkdata['p1']
1614 p2 = chunkdata['p2']
1614 p2 = chunkdata['p2']
1615 cs = chunkdata['cs']
1615 cs = chunkdata['cs']
1616 deltabase = chunkdata['deltabase']
1616 deltabase = chunkdata['deltabase']
1617 delta = chunkdata['delta']
1617 delta = chunkdata['delta']
1618 ui.write("%s %s %s %s %s %s\n" %
1618 ui.write("%s %s %s %s %s %s\n" %
1619 (hex(node), hex(p1), hex(p2),
1619 (hex(node), hex(p1), hex(p2),
1620 hex(cs), hex(deltabase), len(delta)))
1620 hex(cs), hex(deltabase), len(delta)))
1621 chain = node
1621 chain = node
1622
1622
1623 chunkdata = gen.changelogheader()
1623 chunkdata = gen.changelogheader()
1624 showchunks("changelog")
1624 showchunks("changelog")
1625 chunkdata = gen.manifestheader()
1625 chunkdata = gen.manifestheader()
1626 showchunks("manifest")
1626 showchunks("manifest")
1627 while True:
1627 while True:
1628 chunkdata = gen.filelogheader()
1628 chunkdata = gen.filelogheader()
1629 if not chunkdata:
1629 if not chunkdata:
1630 break
1630 break
1631 fname = chunkdata['filename']
1631 fname = chunkdata['filename']
1632 showchunks(fname)
1632 showchunks(fname)
1633 else:
1633 else:
1634 chunkdata = gen.changelogheader()
1634 chunkdata = gen.changelogheader()
1635 chain = None
1635 chain = None
1636 while True:
1636 while True:
1637 chunkdata = gen.deltachunk(chain)
1637 chunkdata = gen.deltachunk(chain)
1638 if not chunkdata:
1638 if not chunkdata:
1639 break
1639 break
1640 node = chunkdata['node']
1640 node = chunkdata['node']
1641 ui.write("%s\n" % hex(node))
1641 ui.write("%s\n" % hex(node))
1642 chain = node
1642 chain = node
1643 finally:
1643 finally:
1644 f.close()
1644 f.close()
1645
1645
1646 @command('debugcheckstate', [], '')
1646 @command('debugcheckstate', [], '')
1647 def debugcheckstate(ui, repo):
1647 def debugcheckstate(ui, repo):
1648 """validate the correctness of the current dirstate"""
1648 """validate the correctness of the current dirstate"""
1649 parent1, parent2 = repo.dirstate.parents()
1649 parent1, parent2 = repo.dirstate.parents()
1650 m1 = repo[parent1].manifest()
1650 m1 = repo[parent1].manifest()
1651 m2 = repo[parent2].manifest()
1651 m2 = repo[parent2].manifest()
1652 errors = 0
1652 errors = 0
1653 for f in repo.dirstate:
1653 for f in repo.dirstate:
1654 state = repo.dirstate[f]
1654 state = repo.dirstate[f]
1655 if state in "nr" and f not in m1:
1655 if state in "nr" and f not in m1:
1656 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1656 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1657 errors += 1
1657 errors += 1
1658 if state in "a" and f in m1:
1658 if state in "a" and f in m1:
1659 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1659 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1660 errors += 1
1660 errors += 1
1661 if state in "m" and f not in m1 and f not in m2:
1661 if state in "m" and f not in m1 and f not in m2:
1662 ui.warn(_("%s in state %s, but not in either manifest\n") %
1662 ui.warn(_("%s in state %s, but not in either manifest\n") %
1663 (f, state))
1663 (f, state))
1664 errors += 1
1664 errors += 1
1665 for f in m1:
1665 for f in m1:
1666 state = repo.dirstate[f]
1666 state = repo.dirstate[f]
1667 if state not in "nrm":
1667 if state not in "nrm":
1668 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1668 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1669 errors += 1
1669 errors += 1
1670 if errors:
1670 if errors:
1671 error = _(".hg/dirstate inconsistent with current parent's manifest")
1671 error = _(".hg/dirstate inconsistent with current parent's manifest")
1672 raise util.Abort(error)
1672 raise util.Abort(error)
1673
1673
1674 @command('debugcommands', [], _('[COMMAND]'))
1674 @command('debugcommands', [], _('[COMMAND]'))
1675 def debugcommands(ui, cmd='', *args):
1675 def debugcommands(ui, cmd='', *args):
1676 """list all available commands and options"""
1676 """list all available commands and options"""
1677 for cmd, vals in sorted(table.iteritems()):
1677 for cmd, vals in sorted(table.iteritems()):
1678 cmd = cmd.split('|')[0].strip('^')
1678 cmd = cmd.split('|')[0].strip('^')
1679 opts = ', '.join([i[1] for i in vals[1]])
1679 opts = ', '.join([i[1] for i in vals[1]])
1680 ui.write('%s: %s\n' % (cmd, opts))
1680 ui.write('%s: %s\n' % (cmd, opts))
1681
1681
1682 @command('debugcomplete',
1682 @command('debugcomplete',
1683 [('o', 'options', None, _('show the command options'))],
1683 [('o', 'options', None, _('show the command options'))],
1684 _('[-o] CMD'))
1684 _('[-o] CMD'))
1685 def debugcomplete(ui, cmd='', **opts):
1685 def debugcomplete(ui, cmd='', **opts):
1686 """returns the completion list associated with the given command"""
1686 """returns the completion list associated with the given command"""
1687
1687
1688 if opts.get('options'):
1688 if opts.get('options'):
1689 options = []
1689 options = []
1690 otables = [globalopts]
1690 otables = [globalopts]
1691 if cmd:
1691 if cmd:
1692 aliases, entry = cmdutil.findcmd(cmd, table, False)
1692 aliases, entry = cmdutil.findcmd(cmd, table, False)
1693 otables.append(entry[1])
1693 otables.append(entry[1])
1694 for t in otables:
1694 for t in otables:
1695 for o in t:
1695 for o in t:
1696 if "(DEPRECATED)" in o[3]:
1696 if "(DEPRECATED)" in o[3]:
1697 continue
1697 continue
1698 if o[0]:
1698 if o[0]:
1699 options.append('-%s' % o[0])
1699 options.append('-%s' % o[0])
1700 options.append('--%s' % o[1])
1700 options.append('--%s' % o[1])
1701 ui.write("%s\n" % "\n".join(options))
1701 ui.write("%s\n" % "\n".join(options))
1702 return
1702 return
1703
1703
1704 cmdlist = cmdutil.findpossible(cmd, table)
1704 cmdlist = cmdutil.findpossible(cmd, table)
1705 if ui.verbose:
1705 if ui.verbose:
1706 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1706 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1707 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1707 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1708
1708
1709 @command('debugdag',
1709 @command('debugdag',
1710 [('t', 'tags', None, _('use tags as labels')),
1710 [('t', 'tags', None, _('use tags as labels')),
1711 ('b', 'branches', None, _('annotate with branch names')),
1711 ('b', 'branches', None, _('annotate with branch names')),
1712 ('', 'dots', None, _('use dots for runs')),
1712 ('', 'dots', None, _('use dots for runs')),
1713 ('s', 'spaces', None, _('separate elements by spaces'))],
1713 ('s', 'spaces', None, _('separate elements by spaces'))],
1714 _('[OPTION]... [FILE [REV]...]'))
1714 _('[OPTION]... [FILE [REV]...]'))
1715 def debugdag(ui, repo, file_=None, *revs, **opts):
1715 def debugdag(ui, repo, file_=None, *revs, **opts):
1716 """format the changelog or an index DAG as a concise textual description
1716 """format the changelog or an index DAG as a concise textual description
1717
1717
1718 If you pass a revlog index, the revlog's DAG is emitted. If you list
1718 If you pass a revlog index, the revlog's DAG is emitted. If you list
1719 revision numbers, they get labeled in the output as rN.
1719 revision numbers, they get labeled in the output as rN.
1720
1720
1721 Otherwise, the changelog DAG of the current repo is emitted.
1721 Otherwise, the changelog DAG of the current repo is emitted.
1722 """
1722 """
1723 spaces = opts.get('spaces')
1723 spaces = opts.get('spaces')
1724 dots = opts.get('dots')
1724 dots = opts.get('dots')
1725 if file_:
1725 if file_:
1726 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1726 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1727 revs = set((int(r) for r in revs))
1727 revs = set((int(r) for r in revs))
1728 def events():
1728 def events():
1729 for r in rlog:
1729 for r in rlog:
1730 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1730 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1731 if p != -1)))
1731 if p != -1)))
1732 if r in revs:
1732 if r in revs:
1733 yield 'l', (r, "r%i" % r)
1733 yield 'l', (r, "r%i" % r)
1734 elif repo:
1734 elif repo:
1735 cl = repo.changelog
1735 cl = repo.changelog
1736 tags = opts.get('tags')
1736 tags = opts.get('tags')
1737 branches = opts.get('branches')
1737 branches = opts.get('branches')
1738 if tags:
1738 if tags:
1739 labels = {}
1739 labels = {}
1740 for l, n in repo.tags().items():
1740 for l, n in repo.tags().items():
1741 labels.setdefault(cl.rev(n), []).append(l)
1741 labels.setdefault(cl.rev(n), []).append(l)
1742 def events():
1742 def events():
1743 b = "default"
1743 b = "default"
1744 for r in cl:
1744 for r in cl:
1745 if branches:
1745 if branches:
1746 newb = cl.read(cl.node(r))[5]['branch']
1746 newb = cl.read(cl.node(r))[5]['branch']
1747 if newb != b:
1747 if newb != b:
1748 yield 'a', newb
1748 yield 'a', newb
1749 b = newb
1749 b = newb
1750 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1750 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1751 if p != -1)))
1751 if p != -1)))
1752 if tags:
1752 if tags:
1753 ls = labels.get(r)
1753 ls = labels.get(r)
1754 if ls:
1754 if ls:
1755 for l in ls:
1755 for l in ls:
1756 yield 'l', (r, l)
1756 yield 'l', (r, l)
1757 else:
1757 else:
1758 raise util.Abort(_('need repo for changelog dag'))
1758 raise util.Abort(_('need repo for changelog dag'))
1759
1759
1760 for line in dagparser.dagtextlines(events(),
1760 for line in dagparser.dagtextlines(events(),
1761 addspaces=spaces,
1761 addspaces=spaces,
1762 wraplabels=True,
1762 wraplabels=True,
1763 wrapannotations=True,
1763 wrapannotations=True,
1764 wrapnonlinear=dots,
1764 wrapnonlinear=dots,
1765 usedots=dots,
1765 usedots=dots,
1766 maxlinewidth=70):
1766 maxlinewidth=70):
1767 ui.write(line)
1767 ui.write(line)
1768 ui.write("\n")
1768 ui.write("\n")
1769
1769
1770 @command('debugdata',
1770 @command('debugdata',
1771 [('c', 'changelog', False, _('open changelog')),
1771 [('c', 'changelog', False, _('open changelog')),
1772 ('m', 'manifest', False, _('open manifest'))],
1772 ('m', 'manifest', False, _('open manifest'))],
1773 _('-c|-m|FILE REV'))
1773 _('-c|-m|FILE REV'))
1774 def debugdata(ui, repo, file_, rev = None, **opts):
1774 def debugdata(ui, repo, file_, rev = None, **opts):
1775 """dump the contents of a data file revision"""
1775 """dump the contents of a data file revision"""
1776 if opts.get('changelog') or opts.get('manifest'):
1776 if opts.get('changelog') or opts.get('manifest'):
1777 file_, rev = None, file_
1777 file_, rev = None, file_
1778 elif rev is None:
1778 elif rev is None:
1779 raise error.CommandError('debugdata', _('invalid arguments'))
1779 raise error.CommandError('debugdata', _('invalid arguments'))
1780 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1780 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1781 try:
1781 try:
1782 ui.write(r.revision(r.lookup(rev)))
1782 ui.write(r.revision(r.lookup(rev)))
1783 except KeyError:
1783 except KeyError:
1784 raise util.Abort(_('invalid revision identifier %s') % rev)
1784 raise util.Abort(_('invalid revision identifier %s') % rev)
1785
1785
1786 @command('debugdate',
1786 @command('debugdate',
1787 [('e', 'extended', None, _('try extended date formats'))],
1787 [('e', 'extended', None, _('try extended date formats'))],
1788 _('[-e] DATE [RANGE]'))
1788 _('[-e] DATE [RANGE]'))
1789 def debugdate(ui, date, range=None, **opts):
1789 def debugdate(ui, date, range=None, **opts):
1790 """parse and display a date"""
1790 """parse and display a date"""
1791 if opts["extended"]:
1791 if opts["extended"]:
1792 d = util.parsedate(date, util.extendeddateformats)
1792 d = util.parsedate(date, util.extendeddateformats)
1793 else:
1793 else:
1794 d = util.parsedate(date)
1794 d = util.parsedate(date)
1795 ui.write(("internal: %s %s\n") % d)
1795 ui.write(("internal: %s %s\n") % d)
1796 ui.write(("standard: %s\n") % util.datestr(d))
1796 ui.write(("standard: %s\n") % util.datestr(d))
1797 if range:
1797 if range:
1798 m = util.matchdate(range)
1798 m = util.matchdate(range)
1799 ui.write(("match: %s\n") % m(d[0]))
1799 ui.write(("match: %s\n") % m(d[0]))
1800
1800
1801 @command('debugdiscovery',
1801 @command('debugdiscovery',
1802 [('', 'old', None, _('use old-style discovery')),
1802 [('', 'old', None, _('use old-style discovery')),
1803 ('', 'nonheads', None,
1803 ('', 'nonheads', None,
1804 _('use old-style discovery with non-heads included')),
1804 _('use old-style discovery with non-heads included')),
1805 ] + remoteopts,
1805 ] + remoteopts,
1806 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1806 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1807 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1807 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1808 """runs the changeset discovery protocol in isolation"""
1808 """runs the changeset discovery protocol in isolation"""
1809 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1809 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1810 opts.get('branch'))
1810 opts.get('branch'))
1811 remote = hg.peer(repo, opts, remoteurl)
1811 remote = hg.peer(repo, opts, remoteurl)
1812 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1812 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1813
1813
1814 # make sure tests are repeatable
1814 # make sure tests are repeatable
1815 random.seed(12323)
1815 random.seed(12323)
1816
1816
1817 def doit(localheads, remoteheads, remote=remote):
1817 def doit(localheads, remoteheads, remote=remote):
1818 if opts.get('old'):
1818 if opts.get('old'):
1819 if localheads:
1819 if localheads:
1820 raise util.Abort('cannot use localheads with old style '
1820 raise util.Abort('cannot use localheads with old style '
1821 'discovery')
1821 'discovery')
1822 if not util.safehasattr(remote, 'branches'):
1822 if not util.safehasattr(remote, 'branches'):
1823 # enable in-client legacy support
1823 # enable in-client legacy support
1824 remote = localrepo.locallegacypeer(remote.local())
1824 remote = localrepo.locallegacypeer(remote.local())
1825 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1825 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1826 force=True)
1826 force=True)
1827 common = set(common)
1827 common = set(common)
1828 if not opts.get('nonheads'):
1828 if not opts.get('nonheads'):
1829 ui.write(("unpruned common: %s\n") % " ".join([short(n)
1829 ui.write(("unpruned common: %s\n") % " ".join([short(n)
1830 for n in common]))
1830 for n in common]))
1831 dag = dagutil.revlogdag(repo.changelog)
1831 dag = dagutil.revlogdag(repo.changelog)
1832 all = dag.ancestorset(dag.internalizeall(common))
1832 all = dag.ancestorset(dag.internalizeall(common))
1833 common = dag.externalizeall(dag.headsetofconnecteds(all))
1833 common = dag.externalizeall(dag.headsetofconnecteds(all))
1834 else:
1834 else:
1835 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1835 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1836 common = set(common)
1836 common = set(common)
1837 rheads = set(hds)
1837 rheads = set(hds)
1838 lheads = set(repo.heads())
1838 lheads = set(repo.heads())
1839 ui.write(("common heads: %s\n") % " ".join([short(n) for n in common]))
1839 ui.write(("common heads: %s\n") % " ".join([short(n) for n in common]))
1840 if lheads <= common:
1840 if lheads <= common:
1841 ui.write(("local is subset\n"))
1841 ui.write(("local is subset\n"))
1842 elif rheads <= common:
1842 elif rheads <= common:
1843 ui.write(("remote is subset\n"))
1843 ui.write(("remote is subset\n"))
1844
1844
1845 serverlogs = opts.get('serverlog')
1845 serverlogs = opts.get('serverlog')
1846 if serverlogs:
1846 if serverlogs:
1847 for filename in serverlogs:
1847 for filename in serverlogs:
1848 logfile = open(filename, 'r')
1848 logfile = open(filename, 'r')
1849 try:
1849 try:
1850 line = logfile.readline()
1850 line = logfile.readline()
1851 while line:
1851 while line:
1852 parts = line.strip().split(';')
1852 parts = line.strip().split(';')
1853 op = parts[1]
1853 op = parts[1]
1854 if op == 'cg':
1854 if op == 'cg':
1855 pass
1855 pass
1856 elif op == 'cgss':
1856 elif op == 'cgss':
1857 doit(parts[2].split(' '), parts[3].split(' '))
1857 doit(parts[2].split(' '), parts[3].split(' '))
1858 elif op == 'unb':
1858 elif op == 'unb':
1859 doit(parts[3].split(' '), parts[2].split(' '))
1859 doit(parts[3].split(' '), parts[2].split(' '))
1860 line = logfile.readline()
1860 line = logfile.readline()
1861 finally:
1861 finally:
1862 logfile.close()
1862 logfile.close()
1863
1863
1864 else:
1864 else:
1865 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1865 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1866 opts.get('remote_head'))
1866 opts.get('remote_head'))
1867 localrevs = opts.get('local_head')
1867 localrevs = opts.get('local_head')
1868 doit(localrevs, remoterevs)
1868 doit(localrevs, remoterevs)
1869
1869
1870 @command('debugfileset',
1870 @command('debugfileset',
1871 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1871 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1872 _('[-r REV] FILESPEC'))
1872 _('[-r REV] FILESPEC'))
1873 def debugfileset(ui, repo, expr, **opts):
1873 def debugfileset(ui, repo, expr, **opts):
1874 '''parse and apply a fileset specification'''
1874 '''parse and apply a fileset specification'''
1875 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1875 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1876 if ui.verbose:
1876 if ui.verbose:
1877 tree = fileset.parse(expr)[0]
1877 tree = fileset.parse(expr)[0]
1878 ui.note(tree, "\n")
1878 ui.note(tree, "\n")
1879
1879
1880 for f in fileset.getfileset(ctx, expr):
1880 for f in fileset.getfileset(ctx, expr):
1881 ui.write("%s\n" % f)
1881 ui.write("%s\n" % f)
1882
1882
1883 @command('debugfsinfo', [], _('[PATH]'))
1883 @command('debugfsinfo', [], _('[PATH]'))
1884 def debugfsinfo(ui, path = "."):
1884 def debugfsinfo(ui, path = "."):
1885 """show information detected about current filesystem"""
1885 """show information detected about current filesystem"""
1886 util.writefile('.debugfsinfo', '')
1886 util.writefile('.debugfsinfo', '')
1887 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1887 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1888 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1888 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1889 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
1889 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
1890 and 'yes' or 'no'))
1890 and 'yes' or 'no'))
1891 os.unlink('.debugfsinfo')
1891 os.unlink('.debugfsinfo')
1892
1892
1893 @command('debuggetbundle',
1893 @command('debuggetbundle',
1894 [('H', 'head', [], _('id of head node'), _('ID')),
1894 [('H', 'head', [], _('id of head node'), _('ID')),
1895 ('C', 'common', [], _('id of common node'), _('ID')),
1895 ('C', 'common', [], _('id of common node'), _('ID')),
1896 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1896 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1897 _('REPO FILE [-H|-C ID]...'))
1897 _('REPO FILE [-H|-C ID]...'))
1898 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1898 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1899 """retrieves a bundle from a repo
1899 """retrieves a bundle from a repo
1900
1900
1901 Every ID must be a full-length hex node id string. Saves the bundle to the
1901 Every ID must be a full-length hex node id string. Saves the bundle to the
1902 given file.
1902 given file.
1903 """
1903 """
1904 repo = hg.peer(ui, opts, repopath)
1904 repo = hg.peer(ui, opts, repopath)
1905 if not repo.capable('getbundle'):
1905 if not repo.capable('getbundle'):
1906 raise util.Abort("getbundle() not supported by target repository")
1906 raise util.Abort("getbundle() not supported by target repository")
1907 args = {}
1907 args = {}
1908 if common:
1908 if common:
1909 args['common'] = [bin(s) for s in common]
1909 args['common'] = [bin(s) for s in common]
1910 if head:
1910 if head:
1911 args['heads'] = [bin(s) for s in head]
1911 args['heads'] = [bin(s) for s in head]
1912 bundle = repo.getbundle('debug', **args)
1912 bundle = repo.getbundle('debug', **args)
1913
1913
1914 bundletype = opts.get('type', 'bzip2').lower()
1914 bundletype = opts.get('type', 'bzip2').lower()
1915 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1915 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1916 bundletype = btypes.get(bundletype)
1916 bundletype = btypes.get(bundletype)
1917 if bundletype not in changegroup.bundletypes:
1917 if bundletype not in changegroup.bundletypes:
1918 raise util.Abort(_('unknown bundle type specified with --type'))
1918 raise util.Abort(_('unknown bundle type specified with --type'))
1919 changegroup.writebundle(bundle, bundlepath, bundletype)
1919 changegroup.writebundle(bundle, bundlepath, bundletype)
1920
1920
1921 @command('debugignore', [], '')
1921 @command('debugignore', [], '')
1922 def debugignore(ui, repo, *values, **opts):
1922 def debugignore(ui, repo, *values, **opts):
1923 """display the combined ignore pattern"""
1923 """display the combined ignore pattern"""
1924 ignore = repo.dirstate._ignore
1924 ignore = repo.dirstate._ignore
1925 includepat = getattr(ignore, 'includepat', None)
1925 includepat = getattr(ignore, 'includepat', None)
1926 if includepat is not None:
1926 if includepat is not None:
1927 ui.write("%s\n" % includepat)
1927 ui.write("%s\n" % includepat)
1928 else:
1928 else:
1929 raise util.Abort(_("no ignore patterns found"))
1929 raise util.Abort(_("no ignore patterns found"))
1930
1930
1931 @command('debugindex',
1931 @command('debugindex',
1932 [('c', 'changelog', False, _('open changelog')),
1932 [('c', 'changelog', False, _('open changelog')),
1933 ('m', 'manifest', False, _('open manifest')),
1933 ('m', 'manifest', False, _('open manifest')),
1934 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1934 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1935 _('[-f FORMAT] -c|-m|FILE'))
1935 _('[-f FORMAT] -c|-m|FILE'))
1936 def debugindex(ui, repo, file_ = None, **opts):
1936 def debugindex(ui, repo, file_ = None, **opts):
1937 """dump the contents of an index file"""
1937 """dump the contents of an index file"""
1938 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1938 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1939 format = opts.get('format', 0)
1939 format = opts.get('format', 0)
1940 if format not in (0, 1):
1940 if format not in (0, 1):
1941 raise util.Abort(_("unknown format %d") % format)
1941 raise util.Abort(_("unknown format %d") % format)
1942
1942
1943 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1943 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1944 if generaldelta:
1944 if generaldelta:
1945 basehdr = ' delta'
1945 basehdr = ' delta'
1946 else:
1946 else:
1947 basehdr = ' base'
1947 basehdr = ' base'
1948
1948
1949 if format == 0:
1949 if format == 0:
1950 ui.write(" rev offset length " + basehdr + " linkrev"
1950 ui.write(" rev offset length " + basehdr + " linkrev"
1951 " nodeid p1 p2\n")
1951 " nodeid p1 p2\n")
1952 elif format == 1:
1952 elif format == 1:
1953 ui.write(" rev flag offset length"
1953 ui.write(" rev flag offset length"
1954 " size " + basehdr + " link p1 p2"
1954 " size " + basehdr + " link p1 p2"
1955 " nodeid\n")
1955 " nodeid\n")
1956
1956
1957 for i in r:
1957 for i in r:
1958 node = r.node(i)
1958 node = r.node(i)
1959 if generaldelta:
1959 if generaldelta:
1960 base = r.deltaparent(i)
1960 base = r.deltaparent(i)
1961 else:
1961 else:
1962 base = r.chainbase(i)
1962 base = r.chainbase(i)
1963 if format == 0:
1963 if format == 0:
1964 try:
1964 try:
1965 pp = r.parents(node)
1965 pp = r.parents(node)
1966 except Exception:
1966 except Exception:
1967 pp = [nullid, nullid]
1967 pp = [nullid, nullid]
1968 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1968 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1969 i, r.start(i), r.length(i), base, r.linkrev(i),
1969 i, r.start(i), r.length(i), base, r.linkrev(i),
1970 short(node), short(pp[0]), short(pp[1])))
1970 short(node), short(pp[0]), short(pp[1])))
1971 elif format == 1:
1971 elif format == 1:
1972 pr = r.parentrevs(i)
1972 pr = r.parentrevs(i)
1973 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1973 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1974 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1974 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1975 base, r.linkrev(i), pr[0], pr[1], short(node)))
1975 base, r.linkrev(i), pr[0], pr[1], short(node)))
1976
1976
1977 @command('debugindexdot', [], _('FILE'))
1977 @command('debugindexdot', [], _('FILE'))
1978 def debugindexdot(ui, repo, file_):
1978 def debugindexdot(ui, repo, file_):
1979 """dump an index DAG as a graphviz dot file"""
1979 """dump an index DAG as a graphviz dot file"""
1980 r = None
1980 r = None
1981 if repo:
1981 if repo:
1982 filelog = repo.file(file_)
1982 filelog = repo.file(file_)
1983 if len(filelog):
1983 if len(filelog):
1984 r = filelog
1984 r = filelog
1985 if not r:
1985 if not r:
1986 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1986 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1987 ui.write(("digraph G {\n"))
1987 ui.write(("digraph G {\n"))
1988 for i in r:
1988 for i in r:
1989 node = r.node(i)
1989 node = r.node(i)
1990 pp = r.parents(node)
1990 pp = r.parents(node)
1991 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1991 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1992 if pp[1] != nullid:
1992 if pp[1] != nullid:
1993 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1993 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1994 ui.write("}\n")
1994 ui.write("}\n")
1995
1995
1996 @command('debuginstall', [], '')
1996 @command('debuginstall', [], '')
1997 def debuginstall(ui):
1997 def debuginstall(ui):
1998 '''test Mercurial installation
1998 '''test Mercurial installation
1999
1999
2000 Returns 0 on success.
2000 Returns 0 on success.
2001 '''
2001 '''
2002
2002
2003 def writetemp(contents):
2003 def writetemp(contents):
2004 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2004 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2005 f = os.fdopen(fd, "wb")
2005 f = os.fdopen(fd, "wb")
2006 f.write(contents)
2006 f.write(contents)
2007 f.close()
2007 f.close()
2008 return name
2008 return name
2009
2009
2010 problems = 0
2010 problems = 0
2011
2011
2012 # encoding
2012 # encoding
2013 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2013 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2014 try:
2014 try:
2015 encoding.fromlocal("test")
2015 encoding.fromlocal("test")
2016 except util.Abort, inst:
2016 except util.Abort, inst:
2017 ui.write(" %s\n" % inst)
2017 ui.write(" %s\n" % inst)
2018 ui.write(_(" (check that your locale is properly set)\n"))
2018 ui.write(_(" (check that your locale is properly set)\n"))
2019 problems += 1
2019 problems += 1
2020
2020
2021 # Python lib
2021 # Python lib
2022 ui.status(_("checking Python lib (%s)...\n")
2022 ui.status(_("checking Python lib (%s)...\n")
2023 % os.path.dirname(os.__file__))
2023 % os.path.dirname(os.__file__))
2024
2024
2025 # compiled modules
2025 # compiled modules
2026 ui.status(_("checking installed modules (%s)...\n")
2026 ui.status(_("checking installed modules (%s)...\n")
2027 % os.path.dirname(__file__))
2027 % os.path.dirname(__file__))
2028 try:
2028 try:
2029 import bdiff, mpatch, base85, osutil
2029 import bdiff, mpatch, base85, osutil
2030 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2030 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2031 except Exception, inst:
2031 except Exception, inst:
2032 ui.write(" %s\n" % inst)
2032 ui.write(" %s\n" % inst)
2033 ui.write(_(" One or more extensions could not be found"))
2033 ui.write(_(" One or more extensions could not be found"))
2034 ui.write(_(" (check that you compiled the extensions)\n"))
2034 ui.write(_(" (check that you compiled the extensions)\n"))
2035 problems += 1
2035 problems += 1
2036
2036
2037 # templates
2037 # templates
2038 import templater
2038 import templater
2039 p = templater.templatepath()
2039 p = templater.templatepath()
2040 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2040 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2041 try:
2041 try:
2042 templater.templater(templater.templatepath("map-cmdline.default"))
2042 templater.templater(templater.templatepath("map-cmdline.default"))
2043 except Exception, inst:
2043 except Exception, inst:
2044 ui.write(" %s\n" % inst)
2044 ui.write(" %s\n" % inst)
2045 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2045 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2046 problems += 1
2046 problems += 1
2047
2047
2048 # editor
2048 # editor
2049 ui.status(_("checking commit editor...\n"))
2049 ui.status(_("checking commit editor...\n"))
2050 editor = ui.geteditor()
2050 editor = ui.geteditor()
2051 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2051 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2052 if not cmdpath:
2052 if not cmdpath:
2053 if editor == 'vi':
2053 if editor == 'vi':
2054 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2054 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2055 ui.write(_(" (specify a commit editor in your configuration"
2055 ui.write(_(" (specify a commit editor in your configuration"
2056 " file)\n"))
2056 " file)\n"))
2057 else:
2057 else:
2058 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2058 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2059 ui.write(_(" (specify a commit editor in your configuration"
2059 ui.write(_(" (specify a commit editor in your configuration"
2060 " file)\n"))
2060 " file)\n"))
2061 problems += 1
2061 problems += 1
2062
2062
2063 # check username
2063 # check username
2064 ui.status(_("checking username...\n"))
2064 ui.status(_("checking username...\n"))
2065 try:
2065 try:
2066 ui.username()
2066 ui.username()
2067 except util.Abort, e:
2067 except util.Abort, e:
2068 ui.write(" %s\n" % e)
2068 ui.write(" %s\n" % e)
2069 ui.write(_(" (specify a username in your configuration file)\n"))
2069 ui.write(_(" (specify a username in your configuration file)\n"))
2070 problems += 1
2070 problems += 1
2071
2071
2072 if not problems:
2072 if not problems:
2073 ui.status(_("no problems detected\n"))
2073 ui.status(_("no problems detected\n"))
2074 else:
2074 else:
2075 ui.write(_("%s problems detected,"
2075 ui.write(_("%s problems detected,"
2076 " please check your install!\n") % problems)
2076 " please check your install!\n") % problems)
2077
2077
2078 return problems
2078 return problems
2079
2079
2080 @command('debugknown', [], _('REPO ID...'))
2080 @command('debugknown', [], _('REPO ID...'))
2081 def debugknown(ui, repopath, *ids, **opts):
2081 def debugknown(ui, repopath, *ids, **opts):
2082 """test whether node ids are known to a repo
2082 """test whether node ids are known to a repo
2083
2083
2084 Every ID must be a full-length hex node id string. Returns a list of 0s
2084 Every ID must be a full-length hex node id string. Returns a list of 0s
2085 and 1s indicating unknown/known.
2085 and 1s indicating unknown/known.
2086 """
2086 """
2087 repo = hg.peer(ui, opts, repopath)
2087 repo = hg.peer(ui, opts, repopath)
2088 if not repo.capable('known'):
2088 if not repo.capable('known'):
2089 raise util.Abort("known() not supported by target repository")
2089 raise util.Abort("known() not supported by target repository")
2090 flags = repo.known([bin(s) for s in ids])
2090 flags = repo.known([bin(s) for s in ids])
2091 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2091 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2092
2092
2093 @command('debugobsolete',
2093 @command('debugobsolete',
2094 [('', 'flags', 0, _('markers flag')),
2094 [('', 'flags', 0, _('markers flag')),
2095 ] + commitopts2,
2095 ] + commitopts2,
2096 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2096 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2097 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2097 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2098 """create arbitrary obsolete marker"""
2098 """create arbitrary obsolete marker"""
2099 def parsenodeid(s):
2099 def parsenodeid(s):
2100 try:
2100 try:
2101 # We do not use revsingle/revrange functions here to accept
2101 # We do not use revsingle/revrange functions here to accept
2102 # arbitrary node identifiers, possibly not present in the
2102 # arbitrary node identifiers, possibly not present in the
2103 # local repository.
2103 # local repository.
2104 n = bin(s)
2104 n = bin(s)
2105 if len(n) != len(nullid):
2105 if len(n) != len(nullid):
2106 raise TypeError()
2106 raise TypeError()
2107 return n
2107 return n
2108 except TypeError:
2108 except TypeError:
2109 raise util.Abort('changeset references must be full hexadecimal '
2109 raise util.Abort('changeset references must be full hexadecimal '
2110 'node identifiers')
2110 'node identifiers')
2111
2111
2112 if precursor is not None:
2112 if precursor is not None:
2113 metadata = {}
2113 metadata = {}
2114 if 'date' in opts:
2114 if 'date' in opts:
2115 metadata['date'] = opts['date']
2115 metadata['date'] = opts['date']
2116 metadata['user'] = opts['user'] or ui.username()
2116 metadata['user'] = opts['user'] or ui.username()
2117 succs = tuple(parsenodeid(succ) for succ in successors)
2117 succs = tuple(parsenodeid(succ) for succ in successors)
2118 l = repo.lock()
2118 l = repo.lock()
2119 try:
2119 try:
2120 tr = repo.transaction('debugobsolete')
2120 tr = repo.transaction('debugobsolete')
2121 try:
2121 try:
2122 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2122 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2123 opts['flags'], metadata)
2123 opts['flags'], metadata)
2124 tr.close()
2124 tr.close()
2125 finally:
2125 finally:
2126 tr.release()
2126 tr.release()
2127 finally:
2127 finally:
2128 l.release()
2128 l.release()
2129 else:
2129 else:
2130 for m in obsolete.allmarkers(repo):
2130 for m in obsolete.allmarkers(repo):
2131 ui.write(hex(m.precnode()))
2131 ui.write(hex(m.precnode()))
2132 for repl in m.succnodes():
2132 for repl in m.succnodes():
2133 ui.write(' ')
2133 ui.write(' ')
2134 ui.write(hex(repl))
2134 ui.write(hex(repl))
2135 ui.write(' %X ' % m._data[2])
2135 ui.write(' %X ' % m._data[2])
2136 ui.write(m.metadata())
2136 ui.write(m.metadata())
2137 ui.write('\n')
2137 ui.write('\n')
2138
2138
2139 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2139 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2140 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2140 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2141 '''access the pushkey key/value protocol
2141 '''access the pushkey key/value protocol
2142
2142
2143 With two args, list the keys in the given namespace.
2143 With two args, list the keys in the given namespace.
2144
2144
2145 With five args, set a key to new if it currently is set to old.
2145 With five args, set a key to new if it currently is set to old.
2146 Reports success or failure.
2146 Reports success or failure.
2147 '''
2147 '''
2148
2148
2149 target = hg.peer(ui, {}, repopath)
2149 target = hg.peer(ui, {}, repopath)
2150 if keyinfo:
2150 if keyinfo:
2151 key, old, new = keyinfo
2151 key, old, new = keyinfo
2152 r = target.pushkey(namespace, key, old, new)
2152 r = target.pushkey(namespace, key, old, new)
2153 ui.status(str(r) + '\n')
2153 ui.status(str(r) + '\n')
2154 return not r
2154 return not r
2155 else:
2155 else:
2156 for k, v in target.listkeys(namespace).iteritems():
2156 for k, v in target.listkeys(namespace).iteritems():
2157 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2157 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2158 v.encode('string-escape')))
2158 v.encode('string-escape')))
2159
2159
2160 @command('debugpvec', [], _('A B'))
2160 @command('debugpvec', [], _('A B'))
2161 def debugpvec(ui, repo, a, b=None):
2161 def debugpvec(ui, repo, a, b=None):
2162 ca = scmutil.revsingle(repo, a)
2162 ca = scmutil.revsingle(repo, a)
2163 cb = scmutil.revsingle(repo, b)
2163 cb = scmutil.revsingle(repo, b)
2164 pa = pvec.ctxpvec(ca)
2164 pa = pvec.ctxpvec(ca)
2165 pb = pvec.ctxpvec(cb)
2165 pb = pvec.ctxpvec(cb)
2166 if pa == pb:
2166 if pa == pb:
2167 rel = "="
2167 rel = "="
2168 elif pa > pb:
2168 elif pa > pb:
2169 rel = ">"
2169 rel = ">"
2170 elif pa < pb:
2170 elif pa < pb:
2171 rel = "<"
2171 rel = "<"
2172 elif pa | pb:
2172 elif pa | pb:
2173 rel = "|"
2173 rel = "|"
2174 ui.write(_("a: %s\n") % pa)
2174 ui.write(_("a: %s\n") % pa)
2175 ui.write(_("b: %s\n") % pb)
2175 ui.write(_("b: %s\n") % pb)
2176 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2176 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2177 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2177 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2178 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2178 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2179 pa.distance(pb), rel))
2179 pa.distance(pb), rel))
2180
2180
2181 @command('debugrebuildstate',
2181 @command('debugrebuildstate',
2182 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2182 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2183 _('[-r REV] [REV]'))
2183 _('[-r REV] [REV]'))
2184 def debugrebuildstate(ui, repo, rev="tip"):
2184 def debugrebuildstate(ui, repo, rev="tip"):
2185 """rebuild the dirstate as it would look like for the given revision"""
2185 """rebuild the dirstate as it would look like for the given revision"""
2186 ctx = scmutil.revsingle(repo, rev)
2186 ctx = scmutil.revsingle(repo, rev)
2187 wlock = repo.wlock()
2187 wlock = repo.wlock()
2188 try:
2188 try:
2189 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2189 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2190 finally:
2190 finally:
2191 wlock.release()
2191 wlock.release()
2192
2192
2193 @command('debugrename',
2193 @command('debugrename',
2194 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2194 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2195 _('[-r REV] FILE'))
2195 _('[-r REV] FILE'))
2196 def debugrename(ui, repo, file1, *pats, **opts):
2196 def debugrename(ui, repo, file1, *pats, **opts):
2197 """dump rename information"""
2197 """dump rename information"""
2198
2198
2199 ctx = scmutil.revsingle(repo, opts.get('rev'))
2199 ctx = scmutil.revsingle(repo, opts.get('rev'))
2200 m = scmutil.match(ctx, (file1,) + pats, opts)
2200 m = scmutil.match(ctx, (file1,) + pats, opts)
2201 for abs in ctx.walk(m):
2201 for abs in ctx.walk(m):
2202 fctx = ctx[abs]
2202 fctx = ctx[abs]
2203 o = fctx.filelog().renamed(fctx.filenode())
2203 o = fctx.filelog().renamed(fctx.filenode())
2204 rel = m.rel(abs)
2204 rel = m.rel(abs)
2205 if o:
2205 if o:
2206 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2206 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2207 else:
2207 else:
2208 ui.write(_("%s not renamed\n") % rel)
2208 ui.write(_("%s not renamed\n") % rel)
2209
2209
2210 @command('debugrevlog',
2210 @command('debugrevlog',
2211 [('c', 'changelog', False, _('open changelog')),
2211 [('c', 'changelog', False, _('open changelog')),
2212 ('m', 'manifest', False, _('open manifest')),
2212 ('m', 'manifest', False, _('open manifest')),
2213 ('d', 'dump', False, _('dump index data'))],
2213 ('d', 'dump', False, _('dump index data'))],
2214 _('-c|-m|FILE'))
2214 _('-c|-m|FILE'))
2215 def debugrevlog(ui, repo, file_ = None, **opts):
2215 def debugrevlog(ui, repo, file_ = None, **opts):
2216 """show data and statistics about a revlog"""
2216 """show data and statistics about a revlog"""
2217 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2217 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2218
2218
2219 if opts.get("dump"):
2219 if opts.get("dump"):
2220 numrevs = len(r)
2220 numrevs = len(r)
2221 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2221 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2222 " rawsize totalsize compression heads\n")
2222 " rawsize totalsize compression heads\n")
2223 ts = 0
2223 ts = 0
2224 heads = set()
2224 heads = set()
2225 for rev in xrange(numrevs):
2225 for rev in xrange(numrevs):
2226 dbase = r.deltaparent(rev)
2226 dbase = r.deltaparent(rev)
2227 if dbase == -1:
2227 if dbase == -1:
2228 dbase = rev
2228 dbase = rev
2229 cbase = r.chainbase(rev)
2229 cbase = r.chainbase(rev)
2230 p1, p2 = r.parentrevs(rev)
2230 p1, p2 = r.parentrevs(rev)
2231 rs = r.rawsize(rev)
2231 rs = r.rawsize(rev)
2232 ts = ts + rs
2232 ts = ts + rs
2233 heads -= set(r.parentrevs(rev))
2233 heads -= set(r.parentrevs(rev))
2234 heads.add(rev)
2234 heads.add(rev)
2235 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2235 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2236 (rev, p1, p2, r.start(rev), r.end(rev),
2236 (rev, p1, p2, r.start(rev), r.end(rev),
2237 r.start(dbase), r.start(cbase),
2237 r.start(dbase), r.start(cbase),
2238 r.start(p1), r.start(p2),
2238 r.start(p1), r.start(p2),
2239 rs, ts, ts / r.end(rev), len(heads)))
2239 rs, ts, ts / r.end(rev), len(heads)))
2240 return 0
2240 return 0
2241
2241
2242 v = r.version
2242 v = r.version
2243 format = v & 0xFFFF
2243 format = v & 0xFFFF
2244 flags = []
2244 flags = []
2245 gdelta = False
2245 gdelta = False
2246 if v & revlog.REVLOGNGINLINEDATA:
2246 if v & revlog.REVLOGNGINLINEDATA:
2247 flags.append('inline')
2247 flags.append('inline')
2248 if v & revlog.REVLOGGENERALDELTA:
2248 if v & revlog.REVLOGGENERALDELTA:
2249 gdelta = True
2249 gdelta = True
2250 flags.append('generaldelta')
2250 flags.append('generaldelta')
2251 if not flags:
2251 if not flags:
2252 flags = ['(none)']
2252 flags = ['(none)']
2253
2253
2254 nummerges = 0
2254 nummerges = 0
2255 numfull = 0
2255 numfull = 0
2256 numprev = 0
2256 numprev = 0
2257 nump1 = 0
2257 nump1 = 0
2258 nump2 = 0
2258 nump2 = 0
2259 numother = 0
2259 numother = 0
2260 nump1prev = 0
2260 nump1prev = 0
2261 nump2prev = 0
2261 nump2prev = 0
2262 chainlengths = []
2262 chainlengths = []
2263
2263
2264 datasize = [None, 0, 0L]
2264 datasize = [None, 0, 0L]
2265 fullsize = [None, 0, 0L]
2265 fullsize = [None, 0, 0L]
2266 deltasize = [None, 0, 0L]
2266 deltasize = [None, 0, 0L]
2267
2267
2268 def addsize(size, l):
2268 def addsize(size, l):
2269 if l[0] is None or size < l[0]:
2269 if l[0] is None or size < l[0]:
2270 l[0] = size
2270 l[0] = size
2271 if size > l[1]:
2271 if size > l[1]:
2272 l[1] = size
2272 l[1] = size
2273 l[2] += size
2273 l[2] += size
2274
2274
2275 numrevs = len(r)
2275 numrevs = len(r)
2276 for rev in xrange(numrevs):
2276 for rev in xrange(numrevs):
2277 p1, p2 = r.parentrevs(rev)
2277 p1, p2 = r.parentrevs(rev)
2278 delta = r.deltaparent(rev)
2278 delta = r.deltaparent(rev)
2279 if format > 0:
2279 if format > 0:
2280 addsize(r.rawsize(rev), datasize)
2280 addsize(r.rawsize(rev), datasize)
2281 if p2 != nullrev:
2281 if p2 != nullrev:
2282 nummerges += 1
2282 nummerges += 1
2283 size = r.length(rev)
2283 size = r.length(rev)
2284 if delta == nullrev:
2284 if delta == nullrev:
2285 chainlengths.append(0)
2285 chainlengths.append(0)
2286 numfull += 1
2286 numfull += 1
2287 addsize(size, fullsize)
2287 addsize(size, fullsize)
2288 else:
2288 else:
2289 chainlengths.append(chainlengths[delta] + 1)
2289 chainlengths.append(chainlengths[delta] + 1)
2290 addsize(size, deltasize)
2290 addsize(size, deltasize)
2291 if delta == rev - 1:
2291 if delta == rev - 1:
2292 numprev += 1
2292 numprev += 1
2293 if delta == p1:
2293 if delta == p1:
2294 nump1prev += 1
2294 nump1prev += 1
2295 elif delta == p2:
2295 elif delta == p2:
2296 nump2prev += 1
2296 nump2prev += 1
2297 elif delta == p1:
2297 elif delta == p1:
2298 nump1 += 1
2298 nump1 += 1
2299 elif delta == p2:
2299 elif delta == p2:
2300 nump2 += 1
2300 nump2 += 1
2301 elif delta != nullrev:
2301 elif delta != nullrev:
2302 numother += 1
2302 numother += 1
2303
2303
2304 # Adjust size min value for empty cases
2304 # Adjust size min value for empty cases
2305 for size in (datasize, fullsize, deltasize):
2305 for size in (datasize, fullsize, deltasize):
2306 if size[0] is None:
2306 if size[0] is None:
2307 size[0] = 0
2307 size[0] = 0
2308
2308
2309 numdeltas = numrevs - numfull
2309 numdeltas = numrevs - numfull
2310 numoprev = numprev - nump1prev - nump2prev
2310 numoprev = numprev - nump1prev - nump2prev
2311 totalrawsize = datasize[2]
2311 totalrawsize = datasize[2]
2312 datasize[2] /= numrevs
2312 datasize[2] /= numrevs
2313 fulltotal = fullsize[2]
2313 fulltotal = fullsize[2]
2314 fullsize[2] /= numfull
2314 fullsize[2] /= numfull
2315 deltatotal = deltasize[2]
2315 deltatotal = deltasize[2]
2316 if numrevs - numfull > 0:
2316 if numrevs - numfull > 0:
2317 deltasize[2] /= numrevs - numfull
2317 deltasize[2] /= numrevs - numfull
2318 totalsize = fulltotal + deltatotal
2318 totalsize = fulltotal + deltatotal
2319 avgchainlen = sum(chainlengths) / numrevs
2319 avgchainlen = sum(chainlengths) / numrevs
2320 compratio = totalrawsize / totalsize
2320 compratio = totalrawsize / totalsize
2321
2321
2322 basedfmtstr = '%%%dd\n'
2322 basedfmtstr = '%%%dd\n'
2323 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2323 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2324
2324
2325 def dfmtstr(max):
2325 def dfmtstr(max):
2326 return basedfmtstr % len(str(max))
2326 return basedfmtstr % len(str(max))
2327 def pcfmtstr(max, padding=0):
2327 def pcfmtstr(max, padding=0):
2328 return basepcfmtstr % (len(str(max)), ' ' * padding)
2328 return basepcfmtstr % (len(str(max)), ' ' * padding)
2329
2329
2330 def pcfmt(value, total):
2330 def pcfmt(value, total):
2331 return (value, 100 * float(value) / total)
2331 return (value, 100 * float(value) / total)
2332
2332
2333 ui.write(('format : %d\n') % format)
2333 ui.write(('format : %d\n') % format)
2334 ui.write(('flags : %s\n') % ', '.join(flags))
2334 ui.write(('flags : %s\n') % ', '.join(flags))
2335
2335
2336 ui.write('\n')
2336 ui.write('\n')
2337 fmt = pcfmtstr(totalsize)
2337 fmt = pcfmtstr(totalsize)
2338 fmt2 = dfmtstr(totalsize)
2338 fmt2 = dfmtstr(totalsize)
2339 ui.write(('revisions : ') + fmt2 % numrevs)
2339 ui.write(('revisions : ') + fmt2 % numrevs)
2340 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2340 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2341 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2341 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2342 ui.write(('revisions : ') + fmt2 % numrevs)
2342 ui.write(('revisions : ') + fmt2 % numrevs)
2343 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2343 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2344 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2344 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2345 ui.write(('revision size : ') + fmt2 % totalsize)
2345 ui.write(('revision size : ') + fmt2 % totalsize)
2346 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2346 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2347 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2347 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2348
2348
2349 ui.write('\n')
2349 ui.write('\n')
2350 fmt = dfmtstr(max(avgchainlen, compratio))
2350 fmt = dfmtstr(max(avgchainlen, compratio))
2351 ui.write(('avg chain length : ') + fmt % avgchainlen)
2351 ui.write(('avg chain length : ') + fmt % avgchainlen)
2352 ui.write(('compression ratio : ') + fmt % compratio)
2352 ui.write(('compression ratio : ') + fmt % compratio)
2353
2353
2354 if format > 0:
2354 if format > 0:
2355 ui.write('\n')
2355 ui.write('\n')
2356 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2356 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2357 % tuple(datasize))
2357 % tuple(datasize))
2358 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2358 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2359 % tuple(fullsize))
2359 % tuple(fullsize))
2360 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2360 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2361 % tuple(deltasize))
2361 % tuple(deltasize))
2362
2362
2363 if numdeltas > 0:
2363 if numdeltas > 0:
2364 ui.write('\n')
2364 ui.write('\n')
2365 fmt = pcfmtstr(numdeltas)
2365 fmt = pcfmtstr(numdeltas)
2366 fmt2 = pcfmtstr(numdeltas, 4)
2366 fmt2 = pcfmtstr(numdeltas, 4)
2367 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2367 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2368 if numprev > 0:
2368 if numprev > 0:
2369 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2369 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2370 numprev))
2370 numprev))
2371 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2371 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2372 numprev))
2372 numprev))
2373 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2373 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2374 numprev))
2374 numprev))
2375 if gdelta:
2375 if gdelta:
2376 ui.write(('deltas against p1 : ')
2376 ui.write(('deltas against p1 : ')
2377 + fmt % pcfmt(nump1, numdeltas))
2377 + fmt % pcfmt(nump1, numdeltas))
2378 ui.write(('deltas against p2 : ')
2378 ui.write(('deltas against p2 : ')
2379 + fmt % pcfmt(nump2, numdeltas))
2379 + fmt % pcfmt(nump2, numdeltas))
2380 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2380 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2381 numdeltas))
2381 numdeltas))
2382
2382
2383 @command('debugrevspec', [], ('REVSPEC'))
2383 @command('debugrevspec', [], ('REVSPEC'))
2384 def debugrevspec(ui, repo, expr):
2384 def debugrevspec(ui, repo, expr):
2385 """parse and apply a revision specification
2385 """parse and apply a revision specification
2386
2386
2387 Use --verbose to print the parsed tree before and after aliases
2387 Use --verbose to print the parsed tree before and after aliases
2388 expansion.
2388 expansion.
2389 """
2389 """
2390 if ui.verbose:
2390 if ui.verbose:
2391 tree = revset.parse(expr)[0]
2391 tree = revset.parse(expr)[0]
2392 ui.note(revset.prettyformat(tree), "\n")
2392 ui.note(revset.prettyformat(tree), "\n")
2393 newtree = revset.findaliases(ui, tree)
2393 newtree = revset.findaliases(ui, tree)
2394 if newtree != tree:
2394 if newtree != tree:
2395 ui.note(revset.prettyformat(newtree), "\n")
2395 ui.note(revset.prettyformat(newtree), "\n")
2396 func = revset.match(ui, expr)
2396 func = revset.match(ui, expr)
2397 for c in func(repo, range(len(repo))):
2397 for c in func(repo, range(len(repo))):
2398 ui.write("%s\n" % c)
2398 ui.write("%s\n" % c)
2399
2399
2400 @command('debugsetparents', [], _('REV1 [REV2]'))
2400 @command('debugsetparents', [], _('REV1 [REV2]'))
2401 def debugsetparents(ui, repo, rev1, rev2=None):
2401 def debugsetparents(ui, repo, rev1, rev2=None):
2402 """manually set the parents of the current working directory
2402 """manually set the parents of the current working directory
2403
2403
2404 This is useful for writing repository conversion tools, but should
2404 This is useful for writing repository conversion tools, but should
2405 be used with care.
2405 be used with care.
2406
2406
2407 Returns 0 on success.
2407 Returns 0 on success.
2408 """
2408 """
2409
2409
2410 r1 = scmutil.revsingle(repo, rev1).node()
2410 r1 = scmutil.revsingle(repo, rev1).node()
2411 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2411 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2412
2412
2413 wlock = repo.wlock()
2413 wlock = repo.wlock()
2414 try:
2414 try:
2415 repo.setparents(r1, r2)
2415 repo.setparents(r1, r2)
2416 finally:
2416 finally:
2417 wlock.release()
2417 wlock.release()
2418
2418
2419 @command('debugstate',
2419 @command('debugstate',
2420 [('', 'nodates', None, _('do not display the saved mtime')),
2420 [('', 'nodates', None, _('do not display the saved mtime')),
2421 ('', 'datesort', None, _('sort by saved mtime'))],
2421 ('', 'datesort', None, _('sort by saved mtime'))],
2422 _('[OPTION]...'))
2422 _('[OPTION]...'))
2423 def debugstate(ui, repo, nodates=None, datesort=None):
2423 def debugstate(ui, repo, nodates=None, datesort=None):
2424 """show the contents of the current dirstate"""
2424 """show the contents of the current dirstate"""
2425 timestr = ""
2425 timestr = ""
2426 showdate = not nodates
2426 showdate = not nodates
2427 if datesort:
2427 if datesort:
2428 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2428 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2429 else:
2429 else:
2430 keyfunc = None # sort by filename
2430 keyfunc = None # sort by filename
2431 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2431 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2432 if showdate:
2432 if showdate:
2433 if ent[3] == -1:
2433 if ent[3] == -1:
2434 # Pad or slice to locale representation
2434 # Pad or slice to locale representation
2435 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2435 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2436 time.localtime(0)))
2436 time.localtime(0)))
2437 timestr = 'unset'
2437 timestr = 'unset'
2438 timestr = (timestr[:locale_len] +
2438 timestr = (timestr[:locale_len] +
2439 ' ' * (locale_len - len(timestr)))
2439 ' ' * (locale_len - len(timestr)))
2440 else:
2440 else:
2441 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2441 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2442 time.localtime(ent[3]))
2442 time.localtime(ent[3]))
2443 if ent[1] & 020000:
2443 if ent[1] & 020000:
2444 mode = 'lnk'
2444 mode = 'lnk'
2445 else:
2445 else:
2446 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2446 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2447 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2447 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2448 for f in repo.dirstate.copies():
2448 for f in repo.dirstate.copies():
2449 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2449 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2450
2450
2451 @command('debugsub',
2451 @command('debugsub',
2452 [('r', 'rev', '',
2452 [('r', 'rev', '',
2453 _('revision to check'), _('REV'))],
2453 _('revision to check'), _('REV'))],
2454 _('[-r REV] [REV]'))
2454 _('[-r REV] [REV]'))
2455 def debugsub(ui, repo, rev=None):
2455 def debugsub(ui, repo, rev=None):
2456 ctx = scmutil.revsingle(repo, rev, None)
2456 ctx = scmutil.revsingle(repo, rev, None)
2457 for k, v in sorted(ctx.substate.items()):
2457 for k, v in sorted(ctx.substate.items()):
2458 ui.write(('path %s\n') % k)
2458 ui.write(('path %s\n') % k)
2459 ui.write((' source %s\n') % v[0])
2459 ui.write((' source %s\n') % v[0])
2460 ui.write((' revision %s\n') % v[1])
2460 ui.write((' revision %s\n') % v[1])
2461
2461
2462 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2462 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2463 def debugwalk(ui, repo, *pats, **opts):
2463 def debugwalk(ui, repo, *pats, **opts):
2464 """show how files match on given patterns"""
2464 """show how files match on given patterns"""
2465 m = scmutil.match(repo[None], pats, opts)
2465 m = scmutil.match(repo[None], pats, opts)
2466 items = list(repo.walk(m))
2466 items = list(repo.walk(m))
2467 if not items:
2467 if not items:
2468 return
2468 return
2469 f = lambda fn: fn
2469 f = lambda fn: fn
2470 if ui.configbool('ui', 'slash') and os.sep != '/':
2470 if ui.configbool('ui', 'slash') and os.sep != '/':
2471 f = lambda fn: util.normpath(fn)
2471 f = lambda fn: util.normpath(fn)
2472 fmt = 'f %%-%ds %%-%ds %%s' % (
2472 fmt = 'f %%-%ds %%-%ds %%s' % (
2473 max([len(abs) for abs in items]),
2473 max([len(abs) for abs in items]),
2474 max([len(m.rel(abs)) for abs in items]))
2474 max([len(m.rel(abs)) for abs in items]))
2475 for abs in items:
2475 for abs in items:
2476 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2476 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2477 ui.write("%s\n" % line.rstrip())
2477 ui.write("%s\n" % line.rstrip())
2478
2478
2479 @command('debugwireargs',
2479 @command('debugwireargs',
2480 [('', 'three', '', 'three'),
2480 [('', 'three', '', 'three'),
2481 ('', 'four', '', 'four'),
2481 ('', 'four', '', 'four'),
2482 ('', 'five', '', 'five'),
2482 ('', 'five', '', 'five'),
2483 ] + remoteopts,
2483 ] + remoteopts,
2484 _('REPO [OPTIONS]... [ONE [TWO]]'))
2484 _('REPO [OPTIONS]... [ONE [TWO]]'))
2485 def debugwireargs(ui, repopath, *vals, **opts):
2485 def debugwireargs(ui, repopath, *vals, **opts):
2486 repo = hg.peer(ui, opts, repopath)
2486 repo = hg.peer(ui, opts, repopath)
2487 for opt in remoteopts:
2487 for opt in remoteopts:
2488 del opts[opt[1]]
2488 del opts[opt[1]]
2489 args = {}
2489 args = {}
2490 for k, v in opts.iteritems():
2490 for k, v in opts.iteritems():
2491 if v:
2491 if v:
2492 args[k] = v
2492 args[k] = v
2493 # run twice to check that we don't mess up the stream for the next command
2493 # run twice to check that we don't mess up the stream for the next command
2494 res1 = repo.debugwireargs(*vals, **args)
2494 res1 = repo.debugwireargs(*vals, **args)
2495 res2 = repo.debugwireargs(*vals, **args)
2495 res2 = repo.debugwireargs(*vals, **args)
2496 ui.write("%s\n" % res1)
2496 ui.write("%s\n" % res1)
2497 if res1 != res2:
2497 if res1 != res2:
2498 ui.warn("%s\n" % res2)
2498 ui.warn("%s\n" % res2)
2499
2499
2500 @command('^diff',
2500 @command('^diff',
2501 [('r', 'rev', [], _('revision'), _('REV')),
2501 [('r', 'rev', [], _('revision'), _('REV')),
2502 ('c', 'change', '', _('change made by revision'), _('REV'))
2502 ('c', 'change', '', _('change made by revision'), _('REV'))
2503 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2503 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2504 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2504 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2505 def diff(ui, repo, *pats, **opts):
2505 def diff(ui, repo, *pats, **opts):
2506 """diff repository (or selected files)
2506 """diff repository (or selected files)
2507
2507
2508 Show differences between revisions for the specified files.
2508 Show differences between revisions for the specified files.
2509
2509
2510 Differences between files are shown using the unified diff format.
2510 Differences between files are shown using the unified diff format.
2511
2511
2512 .. note::
2512 .. note::
2513 diff may generate unexpected results for merges, as it will
2513 diff may generate unexpected results for merges, as it will
2514 default to comparing against the working directory's first
2514 default to comparing against the working directory's first
2515 parent changeset if no revisions are specified.
2515 parent changeset if no revisions are specified.
2516
2516
2517 When two revision arguments are given, then changes are shown
2517 When two revision arguments are given, then changes are shown
2518 between those revisions. If only one revision is specified then
2518 between those revisions. If only one revision is specified then
2519 that revision is compared to the working directory, and, when no
2519 that revision is compared to the working directory, and, when no
2520 revisions are specified, the working directory files are compared
2520 revisions are specified, the working directory files are compared
2521 to its parent.
2521 to its parent.
2522
2522
2523 Alternatively you can specify -c/--change with a revision to see
2523 Alternatively you can specify -c/--change with a revision to see
2524 the changes in that changeset relative to its first parent.
2524 the changes in that changeset relative to its first parent.
2525
2525
2526 Without the -a/--text option, diff will avoid generating diffs of
2526 Without the -a/--text option, diff will avoid generating diffs of
2527 files it detects as binary. With -a, diff will generate a diff
2527 files it detects as binary. With -a, diff will generate a diff
2528 anyway, probably with undesirable results.
2528 anyway, probably with undesirable results.
2529
2529
2530 Use the -g/--git option to generate diffs in the git extended diff
2530 Use the -g/--git option to generate diffs in the git extended diff
2531 format. For more information, read :hg:`help diffs`.
2531 format. For more information, read :hg:`help diffs`.
2532
2532
2533 .. container:: verbose
2533 .. container:: verbose
2534
2534
2535 Examples:
2535 Examples:
2536
2536
2537 - compare a file in the current working directory to its parent::
2537 - compare a file in the current working directory to its parent::
2538
2538
2539 hg diff foo.c
2539 hg diff foo.c
2540
2540
2541 - compare two historical versions of a directory, with rename info::
2541 - compare two historical versions of a directory, with rename info::
2542
2542
2543 hg diff --git -r 1.0:1.2 lib/
2543 hg diff --git -r 1.0:1.2 lib/
2544
2544
2545 - get change stats relative to the last change on some date::
2545 - get change stats relative to the last change on some date::
2546
2546
2547 hg diff --stat -r "date('may 2')"
2547 hg diff --stat -r "date('may 2')"
2548
2548
2549 - diff all newly-added files that contain a keyword::
2549 - diff all newly-added files that contain a keyword::
2550
2550
2551 hg diff "set:added() and grep(GNU)"
2551 hg diff "set:added() and grep(GNU)"
2552
2552
2553 - compare a revision and its parents::
2553 - compare a revision and its parents::
2554
2554
2555 hg diff -c 9353 # compare against first parent
2555 hg diff -c 9353 # compare against first parent
2556 hg diff -r 9353^:9353 # same using revset syntax
2556 hg diff -r 9353^:9353 # same using revset syntax
2557 hg diff -r 9353^2:9353 # compare against the second parent
2557 hg diff -r 9353^2:9353 # compare against the second parent
2558
2558
2559 Returns 0 on success.
2559 Returns 0 on success.
2560 """
2560 """
2561
2561
2562 revs = opts.get('rev')
2562 revs = opts.get('rev')
2563 change = opts.get('change')
2563 change = opts.get('change')
2564 stat = opts.get('stat')
2564 stat = opts.get('stat')
2565 reverse = opts.get('reverse')
2565 reverse = opts.get('reverse')
2566
2566
2567 if revs and change:
2567 if revs and change:
2568 msg = _('cannot specify --rev and --change at the same time')
2568 msg = _('cannot specify --rev and --change at the same time')
2569 raise util.Abort(msg)
2569 raise util.Abort(msg)
2570 elif change:
2570 elif change:
2571 node2 = scmutil.revsingle(repo, change, None).node()
2571 node2 = scmutil.revsingle(repo, change, None).node()
2572 node1 = repo[node2].p1().node()
2572 node1 = repo[node2].p1().node()
2573 else:
2573 else:
2574 node1, node2 = scmutil.revpair(repo, revs)
2574 node1, node2 = scmutil.revpair(repo, revs)
2575
2575
2576 if reverse:
2576 if reverse:
2577 node1, node2 = node2, node1
2577 node1, node2 = node2, node1
2578
2578
2579 diffopts = patch.diffopts(ui, opts)
2579 diffopts = patch.diffopts(ui, opts)
2580 m = scmutil.match(repo[node2], pats, opts)
2580 m = scmutil.match(repo[node2], pats, opts)
2581 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2581 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2582 listsubrepos=opts.get('subrepos'))
2582 listsubrepos=opts.get('subrepos'))
2583
2583
2584 @command('^export',
2584 @command('^export',
2585 [('o', 'output', '',
2585 [('o', 'output', '',
2586 _('print output to file with formatted name'), _('FORMAT')),
2586 _('print output to file with formatted name'), _('FORMAT')),
2587 ('', 'switch-parent', None, _('diff against the second parent')),
2587 ('', 'switch-parent', None, _('diff against the second parent')),
2588 ('r', 'rev', [], _('revisions to export'), _('REV')),
2588 ('r', 'rev', [], _('revisions to export'), _('REV')),
2589 ] + diffopts,
2589 ] + diffopts,
2590 _('[OPTION]... [-o OUTFILESPEC] [-r] REV...'))
2590 _('[OPTION]... [-o OUTFILESPEC] [-r] REV...'))
2591 def export(ui, repo, *changesets, **opts):
2591 def export(ui, repo, *changesets, **opts):
2592 """dump the header and diffs for one or more changesets
2592 """dump the header and diffs for one or more changesets
2593
2593
2594 Print the changeset header and diffs for one or more revisions.
2594 Print the changeset header and diffs for one or more revisions.
2595
2595
2596 The information shown in the changeset header is: author, date,
2596 The information shown in the changeset header is: author, date,
2597 branch name (if non-default), changeset hash, parent(s) and commit
2597 branch name (if non-default), changeset hash, parent(s) and commit
2598 comment.
2598 comment.
2599
2599
2600 .. note::
2600 .. note::
2601 export may generate unexpected diff output for merge
2601 export may generate unexpected diff output for merge
2602 changesets, as it will compare the merge changeset against its
2602 changesets, as it will compare the merge changeset against its
2603 first parent only.
2603 first parent only.
2604
2604
2605 Output may be to a file, in which case the name of the file is
2605 Output may be to a file, in which case the name of the file is
2606 given using a format string. The formatting rules are as follows:
2606 given using a format string. The formatting rules are as follows:
2607
2607
2608 :``%%``: literal "%" character
2608 :``%%``: literal "%" character
2609 :``%H``: changeset hash (40 hexadecimal digits)
2609 :``%H``: changeset hash (40 hexadecimal digits)
2610 :``%N``: number of patches being generated
2610 :``%N``: number of patches being generated
2611 :``%R``: changeset revision number
2611 :``%R``: changeset revision number
2612 :``%b``: basename of the exporting repository
2612 :``%b``: basename of the exporting repository
2613 :``%h``: short-form changeset hash (12 hexadecimal digits)
2613 :``%h``: short-form changeset hash (12 hexadecimal digits)
2614 :``%m``: first line of the commit message (only alphanumeric characters)
2614 :``%m``: first line of the commit message (only alphanumeric characters)
2615 :``%n``: zero-padded sequence number, starting at 1
2615 :``%n``: zero-padded sequence number, starting at 1
2616 :``%r``: zero-padded changeset revision number
2616 :``%r``: zero-padded changeset revision number
2617
2617
2618 Without the -a/--text option, export will avoid generating diffs
2618 Without the -a/--text option, export will avoid generating diffs
2619 of files it detects as binary. With -a, export will generate a
2619 of files it detects as binary. With -a, export will generate a
2620 diff anyway, probably with undesirable results.
2620 diff anyway, probably with undesirable results.
2621
2621
2622 Use the -g/--git option to generate diffs in the git extended diff
2622 Use the -g/--git option to generate diffs in the git extended diff
2623 format. See :hg:`help diffs` for more information.
2623 format. See :hg:`help diffs` for more information.
2624
2624
2625 With the --switch-parent option, the diff will be against the
2625 With the --switch-parent option, the diff will be against the
2626 second parent. It can be useful to review a merge.
2626 second parent. It can be useful to review a merge.
2627
2627
2628 .. container:: verbose
2628 .. container:: verbose
2629
2629
2630 Examples:
2630 Examples:
2631
2631
2632 - use export and import to transplant a bugfix to the current
2632 - use export and import to transplant a bugfix to the current
2633 branch::
2633 branch::
2634
2634
2635 hg export -r 9353 | hg import -
2635 hg export -r 9353 | hg import -
2636
2636
2637 - export all the changesets between two revisions to a file with
2637 - export all the changesets between two revisions to a file with
2638 rename information::
2638 rename information::
2639
2639
2640 hg export --git -r 123:150 > changes.txt
2640 hg export --git -r 123:150 > changes.txt
2641
2641
2642 - split outgoing changes into a series of patches with
2642 - split outgoing changes into a series of patches with
2643 descriptive names::
2643 descriptive names::
2644
2644
2645 hg export -r "outgoing()" -o "%n-%m.patch"
2645 hg export -r "outgoing()" -o "%n-%m.patch"
2646
2646
2647 Returns 0 on success.
2647 Returns 0 on success.
2648 """
2648 """
2649 changesets += tuple(opts.get('rev', []))
2649 changesets += tuple(opts.get('rev', []))
2650 revs = scmutil.revrange(repo, changesets)
2650 revs = scmutil.revrange(repo, changesets)
2651 if not revs:
2651 if not revs:
2652 raise util.Abort(_("export requires at least one changeset"))
2652 raise util.Abort(_("export requires at least one changeset"))
2653 if len(revs) > 1:
2653 if len(revs) > 1:
2654 ui.note(_('exporting patches:\n'))
2654 ui.note(_('exporting patches:\n'))
2655 else:
2655 else:
2656 ui.note(_('exporting patch:\n'))
2656 ui.note(_('exporting patch:\n'))
2657 cmdutil.export(repo, revs, template=opts.get('output'),
2657 cmdutil.export(repo, revs, template=opts.get('output'),
2658 switch_parent=opts.get('switch_parent'),
2658 switch_parent=opts.get('switch_parent'),
2659 opts=patch.diffopts(ui, opts))
2659 opts=patch.diffopts(ui, opts))
2660
2660
2661 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2661 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2662 def forget(ui, repo, *pats, **opts):
2662 def forget(ui, repo, *pats, **opts):
2663 """forget the specified files on the next commit
2663 """forget the specified files on the next commit
2664
2664
2665 Mark the specified files so they will no longer be tracked
2665 Mark the specified files so they will no longer be tracked
2666 after the next commit.
2666 after the next commit.
2667
2667
2668 This only removes files from the current branch, not from the
2668 This only removes files from the current branch, not from the
2669 entire project history, and it does not delete them from the
2669 entire project history, and it does not delete them from the
2670 working directory.
2670 working directory.
2671
2671
2672 To undo a forget before the next commit, see :hg:`add`.
2672 To undo a forget before the next commit, see :hg:`add`.
2673
2673
2674 .. container:: verbose
2674 .. container:: verbose
2675
2675
2676 Examples:
2676 Examples:
2677
2677
2678 - forget newly-added binary files::
2678 - forget newly-added binary files::
2679
2679
2680 hg forget "set:added() and binary()"
2680 hg forget "set:added() and binary()"
2681
2681
2682 - forget files that would be excluded by .hgignore::
2682 - forget files that would be excluded by .hgignore::
2683
2683
2684 hg forget "set:hgignore()"
2684 hg forget "set:hgignore()"
2685
2685
2686 Returns 0 on success.
2686 Returns 0 on success.
2687 """
2687 """
2688
2688
2689 if not pats:
2689 if not pats:
2690 raise util.Abort(_('no files specified'))
2690 raise util.Abort(_('no files specified'))
2691
2691
2692 m = scmutil.match(repo[None], pats, opts)
2692 m = scmutil.match(repo[None], pats, opts)
2693 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2693 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2694 return rejected and 1 or 0
2694 return rejected and 1 or 0
2695
2695
2696 @command(
2696 @command(
2697 'graft',
2697 'graft',
2698 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2698 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2699 ('c', 'continue', False, _('resume interrupted graft')),
2699 ('c', 'continue', False, _('resume interrupted graft')),
2700 ('e', 'edit', False, _('invoke editor on commit messages')),
2700 ('e', 'edit', False, _('invoke editor on commit messages')),
2701 ('', 'log', None, _('append graft info to log message')),
2701 ('', 'log', None, _('append graft info to log message')),
2702 ('D', 'currentdate', False,
2702 ('D', 'currentdate', False,
2703 _('record the current date as commit date')),
2703 _('record the current date as commit date')),
2704 ('U', 'currentuser', False,
2704 ('U', 'currentuser', False,
2705 _('record the current user as committer'), _('DATE'))]
2705 _('record the current user as committer'), _('DATE'))]
2706 + commitopts2 + mergetoolopts + dryrunopts,
2706 + commitopts2 + mergetoolopts + dryrunopts,
2707 _('[OPTION]... [-r] REV...'))
2707 _('[OPTION]... [-r] REV...'))
2708 def graft(ui, repo, *revs, **opts):
2708 def graft(ui, repo, *revs, **opts):
2709 '''copy changes from other branches onto the current branch
2709 '''copy changes from other branches onto the current branch
2710
2710
2711 This command uses Mercurial's merge logic to copy individual
2711 This command uses Mercurial's merge logic to copy individual
2712 changes from other branches without merging branches in the
2712 changes from other branches without merging branches in the
2713 history graph. This is sometimes known as 'backporting' or
2713 history graph. This is sometimes known as 'backporting' or
2714 'cherry-picking'. By default, graft will copy user, date, and
2714 'cherry-picking'. By default, graft will copy user, date, and
2715 description from the source changesets.
2715 description from the source changesets.
2716
2716
2717 Changesets that are ancestors of the current revision, that have
2717 Changesets that are ancestors of the current revision, that have
2718 already been grafted, or that are merges will be skipped.
2718 already been grafted, or that are merges will be skipped.
2719
2719
2720 If --log is specified, log messages will have a comment appended
2720 If --log is specified, log messages will have a comment appended
2721 of the form::
2721 of the form::
2722
2722
2723 (grafted from CHANGESETHASH)
2723 (grafted from CHANGESETHASH)
2724
2724
2725 If a graft merge results in conflicts, the graft process is
2725 If a graft merge results in conflicts, the graft process is
2726 interrupted so that the current merge can be manually resolved.
2726 interrupted so that the current merge can be manually resolved.
2727 Once all conflicts are addressed, the graft process can be
2727 Once all conflicts are addressed, the graft process can be
2728 continued with the -c/--continue option.
2728 continued with the -c/--continue option.
2729
2729
2730 .. note::
2730 .. note::
2731 The -c/--continue option does not reapply earlier options.
2731 The -c/--continue option does not reapply earlier options.
2732
2732
2733 .. container:: verbose
2733 .. container:: verbose
2734
2734
2735 Examples:
2735 Examples:
2736
2736
2737 - copy a single change to the stable branch and edit its description::
2737 - copy a single change to the stable branch and edit its description::
2738
2738
2739 hg update stable
2739 hg update stable
2740 hg graft --edit 9393
2740 hg graft --edit 9393
2741
2741
2742 - graft a range of changesets with one exception, updating dates::
2742 - graft a range of changesets with one exception, updating dates::
2743
2743
2744 hg graft -D "2085::2093 and not 2091"
2744 hg graft -D "2085::2093 and not 2091"
2745
2745
2746 - continue a graft after resolving conflicts::
2746 - continue a graft after resolving conflicts::
2747
2747
2748 hg graft -c
2748 hg graft -c
2749
2749
2750 - show the source of a grafted changeset::
2750 - show the source of a grafted changeset::
2751
2751
2752 hg log --debug -r tip
2752 hg log --debug -r tip
2753
2753
2754 Returns 0 on successful completion.
2754 Returns 0 on successful completion.
2755 '''
2755 '''
2756
2756
2757 revs = list(revs)
2757 revs = list(revs)
2758 revs.extend(opts['rev'])
2758 revs.extend(opts['rev'])
2759
2759
2760 if not opts.get('user') and opts.get('currentuser'):
2760 if not opts.get('user') and opts.get('currentuser'):
2761 opts['user'] = ui.username()
2761 opts['user'] = ui.username()
2762 if not opts.get('date') and opts.get('currentdate'):
2762 if not opts.get('date') and opts.get('currentdate'):
2763 opts['date'] = "%d %d" % util.makedate()
2763 opts['date'] = "%d %d" % util.makedate()
2764
2764
2765 editor = None
2765 editor = None
2766 if opts.get('edit'):
2766 if opts.get('edit'):
2767 editor = cmdutil.commitforceeditor
2767 editor = cmdutil.commitforceeditor
2768
2768
2769 cont = False
2769 cont = False
2770 if opts['continue']:
2770 if opts['continue']:
2771 cont = True
2771 cont = True
2772 if revs:
2772 if revs:
2773 raise util.Abort(_("can't specify --continue and revisions"))
2773 raise util.Abort(_("can't specify --continue and revisions"))
2774 # read in unfinished revisions
2774 # read in unfinished revisions
2775 try:
2775 try:
2776 nodes = repo.opener.read('graftstate').splitlines()
2776 nodes = repo.opener.read('graftstate').splitlines()
2777 revs = [repo[node].rev() for node in nodes]
2777 revs = [repo[node].rev() for node in nodes]
2778 except IOError, inst:
2778 except IOError, inst:
2779 if inst.errno != errno.ENOENT:
2779 if inst.errno != errno.ENOENT:
2780 raise
2780 raise
2781 raise util.Abort(_("no graft state found, can't continue"))
2781 raise util.Abort(_("no graft state found, can't continue"))
2782 else:
2782 else:
2783 cmdutil.bailifchanged(repo)
2783 cmdutil.bailifchanged(repo)
2784 if not revs:
2784 if not revs:
2785 raise util.Abort(_('no revisions specified'))
2785 raise util.Abort(_('no revisions specified'))
2786 revs = scmutil.revrange(repo, revs)
2786 revs = scmutil.revrange(repo, revs)
2787
2787
2788 # check for merges
2788 # check for merges
2789 for rev in repo.revs('%ld and merge()', revs):
2789 for rev in repo.revs('%ld and merge()', revs):
2790 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2790 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2791 revs.remove(rev)
2791 revs.remove(rev)
2792 if not revs:
2792 if not revs:
2793 return -1
2793 return -1
2794
2794
2795 # check for ancestors of dest branch
2795 # check for ancestors of dest branch
2796 for rev in repo.revs('::. and %ld', revs):
2796 for rev in repo.revs('::. and %ld', revs):
2797 ui.warn(_('skipping ancestor revision %s\n') % rev)
2797 ui.warn(_('skipping ancestor revision %s\n') % rev)
2798 revs.remove(rev)
2798 revs.remove(rev)
2799 if not revs:
2799 if not revs:
2800 return -1
2800 return -1
2801
2801
2802 # analyze revs for earlier grafts
2802 # analyze revs for earlier grafts
2803 ids = {}
2803 ids = {}
2804 for ctx in repo.set("%ld", revs):
2804 for ctx in repo.set("%ld", revs):
2805 ids[ctx.hex()] = ctx.rev()
2805 ids[ctx.hex()] = ctx.rev()
2806 n = ctx.extra().get('source')
2806 n = ctx.extra().get('source')
2807 if n:
2807 if n:
2808 ids[n] = ctx.rev()
2808 ids[n] = ctx.rev()
2809
2809
2810 # check ancestors for earlier grafts
2810 # check ancestors for earlier grafts
2811 ui.debug('scanning for duplicate grafts\n')
2811 ui.debug('scanning for duplicate grafts\n')
2812 for ctx in repo.set("::. - ::%ld", revs):
2812 for ctx in repo.set("::. - ::%ld", revs):
2813 n = ctx.extra().get('source')
2813 n = ctx.extra().get('source')
2814 if n in ids:
2814 if n in ids:
2815 r = repo[n].rev()
2815 r = repo[n].rev()
2816 if r in revs:
2816 if r in revs:
2817 ui.warn(_('skipping already grafted revision %s\n') % r)
2817 ui.warn(_('skipping already grafted revision %s\n') % r)
2818 revs.remove(r)
2818 revs.remove(r)
2819 elif ids[n] in revs:
2819 elif ids[n] in revs:
2820 ui.warn(_('skipping already grafted revision %s '
2820 ui.warn(_('skipping already grafted revision %s '
2821 '(same origin %d)\n') % (ids[n], r))
2821 '(same origin %d)\n') % (ids[n], r))
2822 revs.remove(ids[n])
2822 revs.remove(ids[n])
2823 elif ctx.hex() in ids:
2823 elif ctx.hex() in ids:
2824 r = ids[ctx.hex()]
2824 r = ids[ctx.hex()]
2825 ui.warn(_('skipping already grafted revision %s '
2825 ui.warn(_('skipping already grafted revision %s '
2826 '(was grafted from %d)\n') % (r, ctx.rev()))
2826 '(was grafted from %d)\n') % (r, ctx.rev()))
2827 revs.remove(r)
2827 revs.remove(r)
2828 if not revs:
2828 if not revs:
2829 return -1
2829 return -1
2830
2830
2831 wlock = repo.wlock()
2831 wlock = repo.wlock()
2832 try:
2832 try:
2833 current = repo['.']
2833 for pos, ctx in enumerate(repo.set("%ld", revs)):
2834 for pos, ctx in enumerate(repo.set("%ld", revs)):
2834 current = repo['.']
2835
2835
2836 ui.status(_('grafting revision %s\n') % ctx.rev())
2836 ui.status(_('grafting revision %s\n') % ctx.rev())
2837 if opts.get('dry_run'):
2837 if opts.get('dry_run'):
2838 continue
2838 continue
2839
2839
2840 source = ctx.extra().get('source')
2840 source = ctx.extra().get('source')
2841 if not source:
2841 if not source:
2842 source = ctx.hex()
2842 source = ctx.hex()
2843 extra = {'source': source}
2843 extra = {'source': source}
2844 user = ctx.user()
2844 user = ctx.user()
2845 if opts.get('user'):
2845 if opts.get('user'):
2846 user = opts['user']
2846 user = opts['user']
2847 date = ctx.date()
2847 date = ctx.date()
2848 if opts.get('date'):
2848 if opts.get('date'):
2849 date = opts['date']
2849 date = opts['date']
2850 message = ctx.description()
2850 message = ctx.description()
2851 if opts.get('log'):
2851 if opts.get('log'):
2852 message += '\n(grafted from %s)' % ctx.hex()
2852 message += '\n(grafted from %s)' % ctx.hex()
2853
2853
2854 # we don't merge the first commit when continuing
2854 # we don't merge the first commit when continuing
2855 if not cont:
2855 if not cont:
2856 # perform the graft merge with p1(rev) as 'ancestor'
2856 # perform the graft merge with p1(rev) as 'ancestor'
2857 try:
2857 try:
2858 # ui.forcemerge is an internal variable, do not document
2858 # ui.forcemerge is an internal variable, do not document
2859 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2859 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2860 stats = mergemod.update(repo, ctx.node(), True, True, False,
2860 stats = mergemod.update(repo, ctx.node(), True, True, False,
2861 ctx.p1().node())
2861 ctx.p1().node())
2862 finally:
2862 finally:
2863 repo.ui.setconfig('ui', 'forcemerge', '')
2863 repo.ui.setconfig('ui', 'forcemerge', '')
2864 # report any conflicts
2864 # report any conflicts
2865 if stats and stats[3] > 0:
2865 if stats and stats[3] > 0:
2866 # write out state for --continue
2866 # write out state for --continue
2867 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2867 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2868 repo.opener.write('graftstate', ''.join(nodelines))
2868 repo.opener.write('graftstate', ''.join(nodelines))
2869 raise util.Abort(
2869 raise util.Abort(
2870 _("unresolved conflicts, can't continue"),
2870 _("unresolved conflicts, can't continue"),
2871 hint=_('use hg resolve and hg graft --continue'))
2871 hint=_('use hg resolve and hg graft --continue'))
2872 else:
2872 else:
2873 cont = False
2873 cont = False
2874
2874
2875 # drop the second merge parent
2875 # drop the second merge parent
2876 repo.setparents(current.node(), nullid)
2876 repo.setparents(current.node(), nullid)
2877 repo.dirstate.write()
2877 repo.dirstate.write()
2878 # fix up dirstate for copies and renames
2878 # fix up dirstate for copies and renames
2879 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2879 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2880
2880
2881 # commit
2881 # commit
2882 node = repo.commit(text=message, user=user,
2882 node = repo.commit(text=message, user=user,
2883 date=date, extra=extra, editor=editor)
2883 date=date, extra=extra, editor=editor)
2884 if node is None:
2884 if node is None:
2885 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2885 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2886 else:
2887 current = repo[node]
2886 finally:
2888 finally:
2887 wlock.release()
2889 wlock.release()
2888
2890
2889 # remove state when we complete successfully
2891 # remove state when we complete successfully
2890 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2892 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2891 util.unlinkpath(repo.join('graftstate'))
2893 util.unlinkpath(repo.join('graftstate'))
2892
2894
2893 return 0
2895 return 0
2894
2896
2895 @command('grep',
2897 @command('grep',
2896 [('0', 'print0', None, _('end fields with NUL')),
2898 [('0', 'print0', None, _('end fields with NUL')),
2897 ('', 'all', None, _('print all revisions that match')),
2899 ('', 'all', None, _('print all revisions that match')),
2898 ('a', 'text', None, _('treat all files as text')),
2900 ('a', 'text', None, _('treat all files as text')),
2899 ('f', 'follow', None,
2901 ('f', 'follow', None,
2900 _('follow changeset history,'
2902 _('follow changeset history,'
2901 ' or file history across copies and renames')),
2903 ' or file history across copies and renames')),
2902 ('i', 'ignore-case', None, _('ignore case when matching')),
2904 ('i', 'ignore-case', None, _('ignore case when matching')),
2903 ('l', 'files-with-matches', None,
2905 ('l', 'files-with-matches', None,
2904 _('print only filenames and revisions that match')),
2906 _('print only filenames and revisions that match')),
2905 ('n', 'line-number', None, _('print matching line numbers')),
2907 ('n', 'line-number', None, _('print matching line numbers')),
2906 ('r', 'rev', [],
2908 ('r', 'rev', [],
2907 _('only search files changed within revision range'), _('REV')),
2909 _('only search files changed within revision range'), _('REV')),
2908 ('u', 'user', None, _('list the author (long with -v)')),
2910 ('u', 'user', None, _('list the author (long with -v)')),
2909 ('d', 'date', None, _('list the date (short with -q)')),
2911 ('d', 'date', None, _('list the date (short with -q)')),
2910 ] + walkopts,
2912 ] + walkopts,
2911 _('[OPTION]... PATTERN [FILE]...'))
2913 _('[OPTION]... PATTERN [FILE]...'))
2912 def grep(ui, repo, pattern, *pats, **opts):
2914 def grep(ui, repo, pattern, *pats, **opts):
2913 """search for a pattern in specified files and revisions
2915 """search for a pattern in specified files and revisions
2914
2916
2915 Search revisions of files for a regular expression.
2917 Search revisions of files for a regular expression.
2916
2918
2917 This command behaves differently than Unix grep. It only accepts
2919 This command behaves differently than Unix grep. It only accepts
2918 Python/Perl regexps. It searches repository history, not the
2920 Python/Perl regexps. It searches repository history, not the
2919 working directory. It always prints the revision number in which a
2921 working directory. It always prints the revision number in which a
2920 match appears.
2922 match appears.
2921
2923
2922 By default, grep only prints output for the first revision of a
2924 By default, grep only prints output for the first revision of a
2923 file in which it finds a match. To get it to print every revision
2925 file in which it finds a match. To get it to print every revision
2924 that contains a change in match status ("-" for a match that
2926 that contains a change in match status ("-" for a match that
2925 becomes a non-match, or "+" for a non-match that becomes a match),
2927 becomes a non-match, or "+" for a non-match that becomes a match),
2926 use the --all flag.
2928 use the --all flag.
2927
2929
2928 Returns 0 if a match is found, 1 otherwise.
2930 Returns 0 if a match is found, 1 otherwise.
2929 """
2931 """
2930 reflags = re.M
2932 reflags = re.M
2931 if opts.get('ignore_case'):
2933 if opts.get('ignore_case'):
2932 reflags |= re.I
2934 reflags |= re.I
2933 try:
2935 try:
2934 regexp = re.compile(pattern, reflags)
2936 regexp = re.compile(pattern, reflags)
2935 except re.error, inst:
2937 except re.error, inst:
2936 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2938 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2937 return 1
2939 return 1
2938 sep, eol = ':', '\n'
2940 sep, eol = ':', '\n'
2939 if opts.get('print0'):
2941 if opts.get('print0'):
2940 sep = eol = '\0'
2942 sep = eol = '\0'
2941
2943
2942 getfile = util.lrucachefunc(repo.file)
2944 getfile = util.lrucachefunc(repo.file)
2943
2945
2944 def matchlines(body):
2946 def matchlines(body):
2945 begin = 0
2947 begin = 0
2946 linenum = 0
2948 linenum = 0
2947 while begin < len(body):
2949 while begin < len(body):
2948 match = regexp.search(body, begin)
2950 match = regexp.search(body, begin)
2949 if not match:
2951 if not match:
2950 break
2952 break
2951 mstart, mend = match.span()
2953 mstart, mend = match.span()
2952 linenum += body.count('\n', begin, mstart) + 1
2954 linenum += body.count('\n', begin, mstart) + 1
2953 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2955 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2954 begin = body.find('\n', mend) + 1 or len(body) + 1
2956 begin = body.find('\n', mend) + 1 or len(body) + 1
2955 lend = begin - 1
2957 lend = begin - 1
2956 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2958 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2957
2959
2958 class linestate(object):
2960 class linestate(object):
2959 def __init__(self, line, linenum, colstart, colend):
2961 def __init__(self, line, linenum, colstart, colend):
2960 self.line = line
2962 self.line = line
2961 self.linenum = linenum
2963 self.linenum = linenum
2962 self.colstart = colstart
2964 self.colstart = colstart
2963 self.colend = colend
2965 self.colend = colend
2964
2966
2965 def __hash__(self):
2967 def __hash__(self):
2966 return hash((self.linenum, self.line))
2968 return hash((self.linenum, self.line))
2967
2969
2968 def __eq__(self, other):
2970 def __eq__(self, other):
2969 return self.line == other.line
2971 return self.line == other.line
2970
2972
2971 matches = {}
2973 matches = {}
2972 copies = {}
2974 copies = {}
2973 def grepbody(fn, rev, body):
2975 def grepbody(fn, rev, body):
2974 matches[rev].setdefault(fn, [])
2976 matches[rev].setdefault(fn, [])
2975 m = matches[rev][fn]
2977 m = matches[rev][fn]
2976 for lnum, cstart, cend, line in matchlines(body):
2978 for lnum, cstart, cend, line in matchlines(body):
2977 s = linestate(line, lnum, cstart, cend)
2979 s = linestate(line, lnum, cstart, cend)
2978 m.append(s)
2980 m.append(s)
2979
2981
2980 def difflinestates(a, b):
2982 def difflinestates(a, b):
2981 sm = difflib.SequenceMatcher(None, a, b)
2983 sm = difflib.SequenceMatcher(None, a, b)
2982 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2984 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2983 if tag == 'insert':
2985 if tag == 'insert':
2984 for i in xrange(blo, bhi):
2986 for i in xrange(blo, bhi):
2985 yield ('+', b[i])
2987 yield ('+', b[i])
2986 elif tag == 'delete':
2988 elif tag == 'delete':
2987 for i in xrange(alo, ahi):
2989 for i in xrange(alo, ahi):
2988 yield ('-', a[i])
2990 yield ('-', a[i])
2989 elif tag == 'replace':
2991 elif tag == 'replace':
2990 for i in xrange(alo, ahi):
2992 for i in xrange(alo, ahi):
2991 yield ('-', a[i])
2993 yield ('-', a[i])
2992 for i in xrange(blo, bhi):
2994 for i in xrange(blo, bhi):
2993 yield ('+', b[i])
2995 yield ('+', b[i])
2994
2996
2995 def display(fn, ctx, pstates, states):
2997 def display(fn, ctx, pstates, states):
2996 rev = ctx.rev()
2998 rev = ctx.rev()
2997 datefunc = ui.quiet and util.shortdate or util.datestr
2999 datefunc = ui.quiet and util.shortdate or util.datestr
2998 found = False
3000 found = False
2999 filerevmatches = {}
3001 filerevmatches = {}
3000 def binary():
3002 def binary():
3001 flog = getfile(fn)
3003 flog = getfile(fn)
3002 return util.binary(flog.read(ctx.filenode(fn)))
3004 return util.binary(flog.read(ctx.filenode(fn)))
3003
3005
3004 if opts.get('all'):
3006 if opts.get('all'):
3005 iter = difflinestates(pstates, states)
3007 iter = difflinestates(pstates, states)
3006 else:
3008 else:
3007 iter = [('', l) for l in states]
3009 iter = [('', l) for l in states]
3008 for change, l in iter:
3010 for change, l in iter:
3009 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3011 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3010 before, match, after = None, None, None
3012 before, match, after = None, None, None
3011
3013
3012 if opts.get('line_number'):
3014 if opts.get('line_number'):
3013 cols.append((str(l.linenum), 'grep.linenumber'))
3015 cols.append((str(l.linenum), 'grep.linenumber'))
3014 if opts.get('all'):
3016 if opts.get('all'):
3015 cols.append((change, 'grep.change'))
3017 cols.append((change, 'grep.change'))
3016 if opts.get('user'):
3018 if opts.get('user'):
3017 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3019 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3018 if opts.get('date'):
3020 if opts.get('date'):
3019 cols.append((datefunc(ctx.date()), 'grep.date'))
3021 cols.append((datefunc(ctx.date()), 'grep.date'))
3020 if opts.get('files_with_matches'):
3022 if opts.get('files_with_matches'):
3021 c = (fn, rev)
3023 c = (fn, rev)
3022 if c in filerevmatches:
3024 if c in filerevmatches:
3023 continue
3025 continue
3024 filerevmatches[c] = 1
3026 filerevmatches[c] = 1
3025 else:
3027 else:
3026 before = l.line[:l.colstart]
3028 before = l.line[:l.colstart]
3027 match = l.line[l.colstart:l.colend]
3029 match = l.line[l.colstart:l.colend]
3028 after = l.line[l.colend:]
3030 after = l.line[l.colend:]
3029 for col, label in cols[:-1]:
3031 for col, label in cols[:-1]:
3030 ui.write(col, label=label)
3032 ui.write(col, label=label)
3031 ui.write(sep, label='grep.sep')
3033 ui.write(sep, label='grep.sep')
3032 ui.write(cols[-1][0], label=cols[-1][1])
3034 ui.write(cols[-1][0], label=cols[-1][1])
3033 if before is not None:
3035 if before is not None:
3034 ui.write(sep, label='grep.sep')
3036 ui.write(sep, label='grep.sep')
3035 if not opts.get('text') and binary():
3037 if not opts.get('text') and binary():
3036 ui.write(" Binary file matches")
3038 ui.write(" Binary file matches")
3037 else:
3039 else:
3038 ui.write(before)
3040 ui.write(before)
3039 ui.write(match, label='grep.match')
3041 ui.write(match, label='grep.match')
3040 ui.write(after)
3042 ui.write(after)
3041 ui.write(eol)
3043 ui.write(eol)
3042 found = True
3044 found = True
3043 return found
3045 return found
3044
3046
3045 skip = {}
3047 skip = {}
3046 revfiles = {}
3048 revfiles = {}
3047 matchfn = scmutil.match(repo[None], pats, opts)
3049 matchfn = scmutil.match(repo[None], pats, opts)
3048 found = False
3050 found = False
3049 follow = opts.get('follow')
3051 follow = opts.get('follow')
3050
3052
3051 def prep(ctx, fns):
3053 def prep(ctx, fns):
3052 rev = ctx.rev()
3054 rev = ctx.rev()
3053 pctx = ctx.p1()
3055 pctx = ctx.p1()
3054 parent = pctx.rev()
3056 parent = pctx.rev()
3055 matches.setdefault(rev, {})
3057 matches.setdefault(rev, {})
3056 matches.setdefault(parent, {})
3058 matches.setdefault(parent, {})
3057 files = revfiles.setdefault(rev, [])
3059 files = revfiles.setdefault(rev, [])
3058 for fn in fns:
3060 for fn in fns:
3059 flog = getfile(fn)
3061 flog = getfile(fn)
3060 try:
3062 try:
3061 fnode = ctx.filenode(fn)
3063 fnode = ctx.filenode(fn)
3062 except error.LookupError:
3064 except error.LookupError:
3063 continue
3065 continue
3064
3066
3065 copied = flog.renamed(fnode)
3067 copied = flog.renamed(fnode)
3066 copy = follow and copied and copied[0]
3068 copy = follow and copied and copied[0]
3067 if copy:
3069 if copy:
3068 copies.setdefault(rev, {})[fn] = copy
3070 copies.setdefault(rev, {})[fn] = copy
3069 if fn in skip:
3071 if fn in skip:
3070 if copy:
3072 if copy:
3071 skip[copy] = True
3073 skip[copy] = True
3072 continue
3074 continue
3073 files.append(fn)
3075 files.append(fn)
3074
3076
3075 if fn not in matches[rev]:
3077 if fn not in matches[rev]:
3076 grepbody(fn, rev, flog.read(fnode))
3078 grepbody(fn, rev, flog.read(fnode))
3077
3079
3078 pfn = copy or fn
3080 pfn = copy or fn
3079 if pfn not in matches[parent]:
3081 if pfn not in matches[parent]:
3080 try:
3082 try:
3081 fnode = pctx.filenode(pfn)
3083 fnode = pctx.filenode(pfn)
3082 grepbody(pfn, parent, flog.read(fnode))
3084 grepbody(pfn, parent, flog.read(fnode))
3083 except error.LookupError:
3085 except error.LookupError:
3084 pass
3086 pass
3085
3087
3086 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3088 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3087 rev = ctx.rev()
3089 rev = ctx.rev()
3088 parent = ctx.p1().rev()
3090 parent = ctx.p1().rev()
3089 for fn in sorted(revfiles.get(rev, [])):
3091 for fn in sorted(revfiles.get(rev, [])):
3090 states = matches[rev][fn]
3092 states = matches[rev][fn]
3091 copy = copies.get(rev, {}).get(fn)
3093 copy = copies.get(rev, {}).get(fn)
3092 if fn in skip:
3094 if fn in skip:
3093 if copy:
3095 if copy:
3094 skip[copy] = True
3096 skip[copy] = True
3095 continue
3097 continue
3096 pstates = matches.get(parent, {}).get(copy or fn, [])
3098 pstates = matches.get(parent, {}).get(copy or fn, [])
3097 if pstates or states:
3099 if pstates or states:
3098 r = display(fn, ctx, pstates, states)
3100 r = display(fn, ctx, pstates, states)
3099 found = found or r
3101 found = found or r
3100 if r and not opts.get('all'):
3102 if r and not opts.get('all'):
3101 skip[fn] = True
3103 skip[fn] = True
3102 if copy:
3104 if copy:
3103 skip[copy] = True
3105 skip[copy] = True
3104 del matches[rev]
3106 del matches[rev]
3105 del revfiles[rev]
3107 del revfiles[rev]
3106
3108
3107 return not found
3109 return not found
3108
3110
3109 @command('heads',
3111 @command('heads',
3110 [('r', 'rev', '',
3112 [('r', 'rev', '',
3111 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3113 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3112 ('t', 'topo', False, _('show topological heads only')),
3114 ('t', 'topo', False, _('show topological heads only')),
3113 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3115 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3114 ('c', 'closed', False, _('show normal and closed branch heads')),
3116 ('c', 'closed', False, _('show normal and closed branch heads')),
3115 ] + templateopts,
3117 ] + templateopts,
3116 _('[-ct] [-r STARTREV] [REV]...'))
3118 _('[-ct] [-r STARTREV] [REV]...'))
3117 def heads(ui, repo, *branchrevs, **opts):
3119 def heads(ui, repo, *branchrevs, **opts):
3118 """show current repository heads or show branch heads
3120 """show current repository heads or show branch heads
3119
3121
3120 With no arguments, show all repository branch heads.
3122 With no arguments, show all repository branch heads.
3121
3123
3122 Repository "heads" are changesets with no child changesets. They are
3124 Repository "heads" are changesets with no child changesets. They are
3123 where development generally takes place and are the usual targets
3125 where development generally takes place and are the usual targets
3124 for update and merge operations. Branch heads are changesets that have
3126 for update and merge operations. Branch heads are changesets that have
3125 no child changeset on the same branch.
3127 no child changeset on the same branch.
3126
3128
3127 If one or more REVs are given, only branch heads on the branches
3129 If one or more REVs are given, only branch heads on the branches
3128 associated with the specified changesets are shown. This means
3130 associated with the specified changesets are shown. This means
3129 that you can use :hg:`heads foo` to see the heads on a branch
3131 that you can use :hg:`heads foo` to see the heads on a branch
3130 named ``foo``.
3132 named ``foo``.
3131
3133
3132 If -c/--closed is specified, also show branch heads marked closed
3134 If -c/--closed is specified, also show branch heads marked closed
3133 (see :hg:`commit --close-branch`).
3135 (see :hg:`commit --close-branch`).
3134
3136
3135 If STARTREV is specified, only those heads that are descendants of
3137 If STARTREV is specified, only those heads that are descendants of
3136 STARTREV will be displayed.
3138 STARTREV will be displayed.
3137
3139
3138 If -t/--topo is specified, named branch mechanics will be ignored and only
3140 If -t/--topo is specified, named branch mechanics will be ignored and only
3139 changesets without children will be shown.
3141 changesets without children will be shown.
3140
3142
3141 Returns 0 if matching heads are found, 1 if not.
3143 Returns 0 if matching heads are found, 1 if not.
3142 """
3144 """
3143
3145
3144 start = None
3146 start = None
3145 if 'rev' in opts:
3147 if 'rev' in opts:
3146 start = scmutil.revsingle(repo, opts['rev'], None).node()
3148 start = scmutil.revsingle(repo, opts['rev'], None).node()
3147
3149
3148 if opts.get('topo'):
3150 if opts.get('topo'):
3149 heads = [repo[h] for h in repo.heads(start)]
3151 heads = [repo[h] for h in repo.heads(start)]
3150 else:
3152 else:
3151 heads = []
3153 heads = []
3152 for branch in repo.branchmap():
3154 for branch in repo.branchmap():
3153 heads += repo.branchheads(branch, start, opts.get('closed'))
3155 heads += repo.branchheads(branch, start, opts.get('closed'))
3154 heads = [repo[h] for h in heads]
3156 heads = [repo[h] for h in heads]
3155
3157
3156 if branchrevs:
3158 if branchrevs:
3157 branches = set(repo[br].branch() for br in branchrevs)
3159 branches = set(repo[br].branch() for br in branchrevs)
3158 heads = [h for h in heads if h.branch() in branches]
3160 heads = [h for h in heads if h.branch() in branches]
3159
3161
3160 if opts.get('active') and branchrevs:
3162 if opts.get('active') and branchrevs:
3161 dagheads = repo.heads(start)
3163 dagheads = repo.heads(start)
3162 heads = [h for h in heads if h.node() in dagheads]
3164 heads = [h for h in heads if h.node() in dagheads]
3163
3165
3164 if branchrevs:
3166 if branchrevs:
3165 haveheads = set(h.branch() for h in heads)
3167 haveheads = set(h.branch() for h in heads)
3166 if branches - haveheads:
3168 if branches - haveheads:
3167 headless = ', '.join(b for b in branches - haveheads)
3169 headless = ', '.join(b for b in branches - haveheads)
3168 msg = _('no open branch heads found on branches %s')
3170 msg = _('no open branch heads found on branches %s')
3169 if opts.get('rev'):
3171 if opts.get('rev'):
3170 msg += _(' (started at %s)') % opts['rev']
3172 msg += _(' (started at %s)') % opts['rev']
3171 ui.warn((msg + '\n') % headless)
3173 ui.warn((msg + '\n') % headless)
3172
3174
3173 if not heads:
3175 if not heads:
3174 return 1
3176 return 1
3175
3177
3176 heads = sorted(heads, key=lambda x: -x.rev())
3178 heads = sorted(heads, key=lambda x: -x.rev())
3177 displayer = cmdutil.show_changeset(ui, repo, opts)
3179 displayer = cmdutil.show_changeset(ui, repo, opts)
3178 for ctx in heads:
3180 for ctx in heads:
3179 displayer.show(ctx)
3181 displayer.show(ctx)
3180 displayer.close()
3182 displayer.close()
3181
3183
3182 @command('help',
3184 @command('help',
3183 [('e', 'extension', None, _('show only help for extensions')),
3185 [('e', 'extension', None, _('show only help for extensions')),
3184 ('c', 'command', None, _('show only help for commands')),
3186 ('c', 'command', None, _('show only help for commands')),
3185 ('k', 'keyword', '', _('show topics matching keyword')),
3187 ('k', 'keyword', '', _('show topics matching keyword')),
3186 ],
3188 ],
3187 _('[-ec] [TOPIC]'))
3189 _('[-ec] [TOPIC]'))
3188 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3190 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3189 """show help for a given topic or a help overview
3191 """show help for a given topic or a help overview
3190
3192
3191 With no arguments, print a list of commands with short help messages.
3193 With no arguments, print a list of commands with short help messages.
3192
3194
3193 Given a topic, extension, or command name, print help for that
3195 Given a topic, extension, or command name, print help for that
3194 topic.
3196 topic.
3195
3197
3196 Returns 0 if successful.
3198 Returns 0 if successful.
3197 """
3199 """
3198
3200
3199 textwidth = min(ui.termwidth(), 80) - 2
3201 textwidth = min(ui.termwidth(), 80) - 2
3200
3202
3201 def helpcmd(name):
3203 def helpcmd(name):
3202 try:
3204 try:
3203 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3205 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3204 except error.AmbiguousCommand, inst:
3206 except error.AmbiguousCommand, inst:
3205 # py3k fix: except vars can't be used outside the scope of the
3207 # py3k fix: except vars can't be used outside the scope of the
3206 # except block, nor can be used inside a lambda. python issue4617
3208 # except block, nor can be used inside a lambda. python issue4617
3207 prefix = inst.args[0]
3209 prefix = inst.args[0]
3208 select = lambda c: c.lstrip('^').startswith(prefix)
3210 select = lambda c: c.lstrip('^').startswith(prefix)
3209 rst = helplist(select)
3211 rst = helplist(select)
3210 return rst
3212 return rst
3211
3213
3212 rst = []
3214 rst = []
3213
3215
3214 # check if it's an invalid alias and display its error if it is
3216 # check if it's an invalid alias and display its error if it is
3215 if getattr(entry[0], 'badalias', False):
3217 if getattr(entry[0], 'badalias', False):
3216 if not unknowncmd:
3218 if not unknowncmd:
3217 ui.pushbuffer()
3219 ui.pushbuffer()
3218 entry[0](ui)
3220 entry[0](ui)
3219 rst.append(ui.popbuffer())
3221 rst.append(ui.popbuffer())
3220 return rst
3222 return rst
3221
3223
3222 # synopsis
3224 # synopsis
3223 if len(entry) > 2:
3225 if len(entry) > 2:
3224 if entry[2].startswith('hg'):
3226 if entry[2].startswith('hg'):
3225 rst.append("%s\n" % entry[2])
3227 rst.append("%s\n" % entry[2])
3226 else:
3228 else:
3227 rst.append('hg %s %s\n' % (aliases[0], entry[2]))
3229 rst.append('hg %s %s\n' % (aliases[0], entry[2]))
3228 else:
3230 else:
3229 rst.append('hg %s\n' % aliases[0])
3231 rst.append('hg %s\n' % aliases[0])
3230 # aliases
3232 # aliases
3231 if full and not ui.quiet and len(aliases) > 1:
3233 if full and not ui.quiet and len(aliases) > 1:
3232 rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
3234 rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
3233 rst.append('\n')
3235 rst.append('\n')
3234
3236
3235 # description
3237 # description
3236 doc = gettext(entry[0].__doc__)
3238 doc = gettext(entry[0].__doc__)
3237 if not doc:
3239 if not doc:
3238 doc = _("(no help text available)")
3240 doc = _("(no help text available)")
3239 if util.safehasattr(entry[0], 'definition'): # aliased command
3241 if util.safehasattr(entry[0], 'definition'): # aliased command
3240 if entry[0].definition.startswith('!'): # shell alias
3242 if entry[0].definition.startswith('!'): # shell alias
3241 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3243 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3242 else:
3244 else:
3243 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3245 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3244 doc = doc.splitlines(True)
3246 doc = doc.splitlines(True)
3245 if ui.quiet or not full:
3247 if ui.quiet or not full:
3246 rst.append(doc[0])
3248 rst.append(doc[0])
3247 else:
3249 else:
3248 rst.extend(doc)
3250 rst.extend(doc)
3249 rst.append('\n')
3251 rst.append('\n')
3250
3252
3251 # check if this command shadows a non-trivial (multi-line)
3253 # check if this command shadows a non-trivial (multi-line)
3252 # extension help text
3254 # extension help text
3253 try:
3255 try:
3254 mod = extensions.find(name)
3256 mod = extensions.find(name)
3255 doc = gettext(mod.__doc__) or ''
3257 doc = gettext(mod.__doc__) or ''
3256 if '\n' in doc.strip():
3258 if '\n' in doc.strip():
3257 msg = _('use "hg help -e %s" to show help for '
3259 msg = _('use "hg help -e %s" to show help for '
3258 'the %s extension') % (name, name)
3260 'the %s extension') % (name, name)
3259 rst.append('\n%s\n' % msg)
3261 rst.append('\n%s\n' % msg)
3260 except KeyError:
3262 except KeyError:
3261 pass
3263 pass
3262
3264
3263 # options
3265 # options
3264 if not ui.quiet and entry[1]:
3266 if not ui.quiet and entry[1]:
3265 rst.append('\n%s\n\n' % _("options:"))
3267 rst.append('\n%s\n\n' % _("options:"))
3266 rst.append(help.optrst(entry[1], ui.verbose))
3268 rst.append(help.optrst(entry[1], ui.verbose))
3267
3269
3268 if ui.verbose:
3270 if ui.verbose:
3269 rst.append('\n%s\n\n' % _("global options:"))
3271 rst.append('\n%s\n\n' % _("global options:"))
3270 rst.append(help.optrst(globalopts, ui.verbose))
3272 rst.append(help.optrst(globalopts, ui.verbose))
3271
3273
3272 if not ui.verbose:
3274 if not ui.verbose:
3273 if not full:
3275 if not full:
3274 rst.append(_('\nuse "hg help %s" to show the full help text\n')
3276 rst.append(_('\nuse "hg help %s" to show the full help text\n')
3275 % name)
3277 % name)
3276 elif not ui.quiet:
3278 elif not ui.quiet:
3277 omitted = _('use "hg -v help %s" to show more complete'
3279 omitted = _('use "hg -v help %s" to show more complete'
3278 ' help and the global options') % name
3280 ' help and the global options') % name
3279 notomitted = _('use "hg -v help %s" to show'
3281 notomitted = _('use "hg -v help %s" to show'
3280 ' the global options') % name
3282 ' the global options') % name
3281 help.indicateomitted(rst, omitted, notomitted)
3283 help.indicateomitted(rst, omitted, notomitted)
3282
3284
3283 return rst
3285 return rst
3284
3286
3285
3287
3286 def helplist(select=None):
3288 def helplist(select=None):
3287 # list of commands
3289 # list of commands
3288 if name == "shortlist":
3290 if name == "shortlist":
3289 header = _('basic commands:\n\n')
3291 header = _('basic commands:\n\n')
3290 else:
3292 else:
3291 header = _('list of commands:\n\n')
3293 header = _('list of commands:\n\n')
3292
3294
3293 h = {}
3295 h = {}
3294 cmds = {}
3296 cmds = {}
3295 for c, e in table.iteritems():
3297 for c, e in table.iteritems():
3296 f = c.split("|", 1)[0]
3298 f = c.split("|", 1)[0]
3297 if select and not select(f):
3299 if select and not select(f):
3298 continue
3300 continue
3299 if (not select and name != 'shortlist' and
3301 if (not select and name != 'shortlist' and
3300 e[0].__module__ != __name__):
3302 e[0].__module__ != __name__):
3301 continue
3303 continue
3302 if name == "shortlist" and not f.startswith("^"):
3304 if name == "shortlist" and not f.startswith("^"):
3303 continue
3305 continue
3304 f = f.lstrip("^")
3306 f = f.lstrip("^")
3305 if not ui.debugflag and f.startswith("debug"):
3307 if not ui.debugflag and f.startswith("debug"):
3306 continue
3308 continue
3307 doc = e[0].__doc__
3309 doc = e[0].__doc__
3308 if doc and 'DEPRECATED' in doc and not ui.verbose:
3310 if doc and 'DEPRECATED' in doc and not ui.verbose:
3309 continue
3311 continue
3310 doc = gettext(doc)
3312 doc = gettext(doc)
3311 if not doc:
3313 if not doc:
3312 doc = _("(no help text available)")
3314 doc = _("(no help text available)")
3313 h[f] = doc.splitlines()[0].rstrip()
3315 h[f] = doc.splitlines()[0].rstrip()
3314 cmds[f] = c.lstrip("^")
3316 cmds[f] = c.lstrip("^")
3315
3317
3316 rst = []
3318 rst = []
3317 if not h:
3319 if not h:
3318 if not ui.quiet:
3320 if not ui.quiet:
3319 rst.append(_('no commands defined\n'))
3321 rst.append(_('no commands defined\n'))
3320 return rst
3322 return rst
3321
3323
3322 if not ui.quiet:
3324 if not ui.quiet:
3323 rst.append(header)
3325 rst.append(header)
3324 fns = sorted(h)
3326 fns = sorted(h)
3325 for f in fns:
3327 for f in fns:
3326 if ui.verbose:
3328 if ui.verbose:
3327 commands = cmds[f].replace("|",", ")
3329 commands = cmds[f].replace("|",", ")
3328 rst.append(" :%s: %s\n" % (commands, h[f]))
3330 rst.append(" :%s: %s\n" % (commands, h[f]))
3329 else:
3331 else:
3330 rst.append(' :%s: %s\n' % (f, h[f]))
3332 rst.append(' :%s: %s\n' % (f, h[f]))
3331
3333
3332 if not name:
3334 if not name:
3333 exts = help.listexts(_('enabled extensions:'), extensions.enabled())
3335 exts = help.listexts(_('enabled extensions:'), extensions.enabled())
3334 if exts:
3336 if exts:
3335 rst.append('\n')
3337 rst.append('\n')
3336 rst.extend(exts)
3338 rst.extend(exts)
3337
3339
3338 rst.append(_("\nadditional help topics:\n\n"))
3340 rst.append(_("\nadditional help topics:\n\n"))
3339 topics = []
3341 topics = []
3340 for names, header, doc in help.helptable:
3342 for names, header, doc in help.helptable:
3341 topics.append((names[0], header))
3343 topics.append((names[0], header))
3342 for t, desc in topics:
3344 for t, desc in topics:
3343 rst.append(" :%s: %s\n" % (t, desc))
3345 rst.append(" :%s: %s\n" % (t, desc))
3344
3346
3345 optlist = []
3347 optlist = []
3346 if not ui.quiet:
3348 if not ui.quiet:
3347 if ui.verbose:
3349 if ui.verbose:
3348 optlist.append((_("global options:"), globalopts))
3350 optlist.append((_("global options:"), globalopts))
3349 if name == 'shortlist':
3351 if name == 'shortlist':
3350 optlist.append((_('use "hg help" for the full list '
3352 optlist.append((_('use "hg help" for the full list '
3351 'of commands'), ()))
3353 'of commands'), ()))
3352 else:
3354 else:
3353 if name == 'shortlist':
3355 if name == 'shortlist':
3354 msg = _('use "hg help" for the full list of commands '
3356 msg = _('use "hg help" for the full list of commands '
3355 'or "hg -v" for details')
3357 'or "hg -v" for details')
3356 elif name and not full:
3358 elif name and not full:
3357 msg = _('use "hg help %s" to show the full help '
3359 msg = _('use "hg help %s" to show the full help '
3358 'text') % name
3360 'text') % name
3359 else:
3361 else:
3360 msg = _('use "hg -v help%s" to show builtin aliases and '
3362 msg = _('use "hg -v help%s" to show builtin aliases and '
3361 'global options') % (name and " " + name or "")
3363 'global options') % (name and " " + name or "")
3362 optlist.append((msg, ()))
3364 optlist.append((msg, ()))
3363
3365
3364 if optlist:
3366 if optlist:
3365 for title, options in optlist:
3367 for title, options in optlist:
3366 rst.append('\n%s\n' % title)
3368 rst.append('\n%s\n' % title)
3367 if options:
3369 if options:
3368 rst.append('\n%s\n' % help.optrst(options, ui.verbose))
3370 rst.append('\n%s\n' % help.optrst(options, ui.verbose))
3369 return rst
3371 return rst
3370
3372
3371 def helptopic(name):
3373 def helptopic(name):
3372 for names, header, doc in help.helptable:
3374 for names, header, doc in help.helptable:
3373 if name in names:
3375 if name in names:
3374 break
3376 break
3375 else:
3377 else:
3376 raise error.UnknownCommand(name)
3378 raise error.UnknownCommand(name)
3377
3379
3378 rst = ["%s\n\n" % header]
3380 rst = ["%s\n\n" % header]
3379 # description
3381 # description
3380 if not doc:
3382 if not doc:
3381 rst.append(" %s\n" % _("(no help text available)"))
3383 rst.append(" %s\n" % _("(no help text available)"))
3382 if util.safehasattr(doc, '__call__'):
3384 if util.safehasattr(doc, '__call__'):
3383 rst += [" %s\n" % l for l in doc().splitlines()]
3385 rst += [" %s\n" % l for l in doc().splitlines()]
3384
3386
3385 if not ui.verbose:
3387 if not ui.verbose:
3386 omitted = (_('use "hg help -v %s" to show more complete help') %
3388 omitted = (_('use "hg help -v %s" to show more complete help') %
3387 name)
3389 name)
3388 help.indicateomitted(rst, omitted)
3390 help.indicateomitted(rst, omitted)
3389
3391
3390 try:
3392 try:
3391 cmdutil.findcmd(name, table)
3393 cmdutil.findcmd(name, table)
3392 rst.append(_('\nuse "hg help -c %s" to see help for '
3394 rst.append(_('\nuse "hg help -c %s" to see help for '
3393 'the %s command\n') % (name, name))
3395 'the %s command\n') % (name, name))
3394 except error.UnknownCommand:
3396 except error.UnknownCommand:
3395 pass
3397 pass
3396 return rst
3398 return rst
3397
3399
3398 def helpext(name):
3400 def helpext(name):
3399 try:
3401 try:
3400 mod = extensions.find(name)
3402 mod = extensions.find(name)
3401 doc = gettext(mod.__doc__) or _('no help text available')
3403 doc = gettext(mod.__doc__) or _('no help text available')
3402 except KeyError:
3404 except KeyError:
3403 mod = None
3405 mod = None
3404 doc = extensions.disabledext(name)
3406 doc = extensions.disabledext(name)
3405 if not doc:
3407 if not doc:
3406 raise error.UnknownCommand(name)
3408 raise error.UnknownCommand(name)
3407
3409
3408 if '\n' not in doc:
3410 if '\n' not in doc:
3409 head, tail = doc, ""
3411 head, tail = doc, ""
3410 else:
3412 else:
3411 head, tail = doc.split('\n', 1)
3413 head, tail = doc.split('\n', 1)
3412 rst = [_('%s extension - %s\n\n') % (name.split('.')[-1], head)]
3414 rst = [_('%s extension - %s\n\n') % (name.split('.')[-1], head)]
3413 if tail:
3415 if tail:
3414 rst.extend(tail.splitlines(True))
3416 rst.extend(tail.splitlines(True))
3415 rst.append('\n')
3417 rst.append('\n')
3416
3418
3417 if not ui.verbose:
3419 if not ui.verbose:
3418 omitted = (_('use "hg help -v %s" to show more complete help') %
3420 omitted = (_('use "hg help -v %s" to show more complete help') %
3419 name)
3421 name)
3420 help.indicateomitted(rst, omitted)
3422 help.indicateomitted(rst, omitted)
3421
3423
3422 if mod:
3424 if mod:
3423 try:
3425 try:
3424 ct = mod.cmdtable
3426 ct = mod.cmdtable
3425 except AttributeError:
3427 except AttributeError:
3426 ct = {}
3428 ct = {}
3427 modcmds = set([c.split('|', 1)[0] for c in ct])
3429 modcmds = set([c.split('|', 1)[0] for c in ct])
3428 rst.extend(helplist(modcmds.__contains__))
3430 rst.extend(helplist(modcmds.__contains__))
3429 else:
3431 else:
3430 rst.append(_('use "hg help extensions" for information on enabling '
3432 rst.append(_('use "hg help extensions" for information on enabling '
3431 'extensions\n'))
3433 'extensions\n'))
3432 return rst
3434 return rst
3433
3435
3434 def helpextcmd(name):
3436 def helpextcmd(name):
3435 cmd, ext, mod = extensions.disabledcmd(ui, name,
3437 cmd, ext, mod = extensions.disabledcmd(ui, name,
3436 ui.configbool('ui', 'strict'))
3438 ui.configbool('ui', 'strict'))
3437 doc = gettext(mod.__doc__).splitlines()[0]
3439 doc = gettext(mod.__doc__).splitlines()[0]
3438
3440
3439 rst = help.listexts(_("'%s' is provided by the following "
3441 rst = help.listexts(_("'%s' is provided by the following "
3440 "extension:") % cmd, {ext: doc}, indent=4)
3442 "extension:") % cmd, {ext: doc}, indent=4)
3441 rst.append('\n')
3443 rst.append('\n')
3442 rst.append(_('use "hg help extensions" for information on enabling '
3444 rst.append(_('use "hg help extensions" for information on enabling '
3443 'extensions\n'))
3445 'extensions\n'))
3444 return rst
3446 return rst
3445
3447
3446
3448
3447 rst = []
3449 rst = []
3448 kw = opts.get('keyword')
3450 kw = opts.get('keyword')
3449 if kw:
3451 if kw:
3450 matches = help.topicmatch(kw)
3452 matches = help.topicmatch(kw)
3451 for t, title in (('topics', _('Topics')),
3453 for t, title in (('topics', _('Topics')),
3452 ('commands', _('Commands')),
3454 ('commands', _('Commands')),
3453 ('extensions', _('Extensions')),
3455 ('extensions', _('Extensions')),
3454 ('extensioncommands', _('Extension Commands'))):
3456 ('extensioncommands', _('Extension Commands'))):
3455 if matches[t]:
3457 if matches[t]:
3456 rst.append('%s:\n\n' % title)
3458 rst.append('%s:\n\n' % title)
3457 rst.extend(minirst.maketable(sorted(matches[t]), 1))
3459 rst.extend(minirst.maketable(sorted(matches[t]), 1))
3458 rst.append('\n')
3460 rst.append('\n')
3459 elif name and name != 'shortlist':
3461 elif name and name != 'shortlist':
3460 i = None
3462 i = None
3461 if unknowncmd:
3463 if unknowncmd:
3462 queries = (helpextcmd,)
3464 queries = (helpextcmd,)
3463 elif opts.get('extension'):
3465 elif opts.get('extension'):
3464 queries = (helpext,)
3466 queries = (helpext,)
3465 elif opts.get('command'):
3467 elif opts.get('command'):
3466 queries = (helpcmd,)
3468 queries = (helpcmd,)
3467 else:
3469 else:
3468 queries = (helptopic, helpcmd, helpext, helpextcmd)
3470 queries = (helptopic, helpcmd, helpext, helpextcmd)
3469 for f in queries:
3471 for f in queries:
3470 try:
3472 try:
3471 rst = f(name)
3473 rst = f(name)
3472 i = None
3474 i = None
3473 break
3475 break
3474 except error.UnknownCommand, inst:
3476 except error.UnknownCommand, inst:
3475 i = inst
3477 i = inst
3476 if i:
3478 if i:
3477 raise i
3479 raise i
3478 else:
3480 else:
3479 # program name
3481 # program name
3480 if not ui.quiet:
3482 if not ui.quiet:
3481 rst = [_("Mercurial Distributed SCM\n"), '\n']
3483 rst = [_("Mercurial Distributed SCM\n"), '\n']
3482 rst.extend(helplist())
3484 rst.extend(helplist())
3483
3485
3484 keep = ui.verbose and ['verbose'] or []
3486 keep = ui.verbose and ['verbose'] or []
3485 text = ''.join(rst)
3487 text = ''.join(rst)
3486 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3488 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3487 if 'verbose' in pruned:
3489 if 'verbose' in pruned:
3488 keep.append('omitted')
3490 keep.append('omitted')
3489 else:
3491 else:
3490 keep.append('notomitted')
3492 keep.append('notomitted')
3491 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3493 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3492 ui.write(formatted)
3494 ui.write(formatted)
3493
3495
3494
3496
3495 @command('identify|id',
3497 @command('identify|id',
3496 [('r', 'rev', '',
3498 [('r', 'rev', '',
3497 _('identify the specified revision'), _('REV')),
3499 _('identify the specified revision'), _('REV')),
3498 ('n', 'num', None, _('show local revision number')),
3500 ('n', 'num', None, _('show local revision number')),
3499 ('i', 'id', None, _('show global revision id')),
3501 ('i', 'id', None, _('show global revision id')),
3500 ('b', 'branch', None, _('show branch')),
3502 ('b', 'branch', None, _('show branch')),
3501 ('t', 'tags', None, _('show tags')),
3503 ('t', 'tags', None, _('show tags')),
3502 ('B', 'bookmarks', None, _('show bookmarks')),
3504 ('B', 'bookmarks', None, _('show bookmarks')),
3503 ] + remoteopts,
3505 ] + remoteopts,
3504 _('[-nibtB] [-r REV] [SOURCE]'))
3506 _('[-nibtB] [-r REV] [SOURCE]'))
3505 def identify(ui, repo, source=None, rev=None,
3507 def identify(ui, repo, source=None, rev=None,
3506 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3508 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3507 """identify the working copy or specified revision
3509 """identify the working copy or specified revision
3508
3510
3509 Print a summary identifying the repository state at REV using one or
3511 Print a summary identifying the repository state at REV using one or
3510 two parent hash identifiers, followed by a "+" if the working
3512 two parent hash identifiers, followed by a "+" if the working
3511 directory has uncommitted changes, the branch name (if not default),
3513 directory has uncommitted changes, the branch name (if not default),
3512 a list of tags, and a list of bookmarks.
3514 a list of tags, and a list of bookmarks.
3513
3515
3514 When REV is not given, print a summary of the current state of the
3516 When REV is not given, print a summary of the current state of the
3515 repository.
3517 repository.
3516
3518
3517 Specifying a path to a repository root or Mercurial bundle will
3519 Specifying a path to a repository root or Mercurial bundle will
3518 cause lookup to operate on that repository/bundle.
3520 cause lookup to operate on that repository/bundle.
3519
3521
3520 .. container:: verbose
3522 .. container:: verbose
3521
3523
3522 Examples:
3524 Examples:
3523
3525
3524 - generate a build identifier for the working directory::
3526 - generate a build identifier for the working directory::
3525
3527
3526 hg id --id > build-id.dat
3528 hg id --id > build-id.dat
3527
3529
3528 - find the revision corresponding to a tag::
3530 - find the revision corresponding to a tag::
3529
3531
3530 hg id -n -r 1.3
3532 hg id -n -r 1.3
3531
3533
3532 - check the most recent revision of a remote repository::
3534 - check the most recent revision of a remote repository::
3533
3535
3534 hg id -r tip http://selenic.com/hg/
3536 hg id -r tip http://selenic.com/hg/
3535
3537
3536 Returns 0 if successful.
3538 Returns 0 if successful.
3537 """
3539 """
3538
3540
3539 if not repo and not source:
3541 if not repo and not source:
3540 raise util.Abort(_("there is no Mercurial repository here "
3542 raise util.Abort(_("there is no Mercurial repository here "
3541 "(.hg not found)"))
3543 "(.hg not found)"))
3542
3544
3543 hexfunc = ui.debugflag and hex or short
3545 hexfunc = ui.debugflag and hex or short
3544 default = not (num or id or branch or tags or bookmarks)
3546 default = not (num or id or branch or tags or bookmarks)
3545 output = []
3547 output = []
3546 revs = []
3548 revs = []
3547
3549
3548 if source:
3550 if source:
3549 source, branches = hg.parseurl(ui.expandpath(source))
3551 source, branches = hg.parseurl(ui.expandpath(source))
3550 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3552 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3551 repo = peer.local()
3553 repo = peer.local()
3552 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3554 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3553
3555
3554 if not repo:
3556 if not repo:
3555 if num or branch or tags:
3557 if num or branch or tags:
3556 raise util.Abort(
3558 raise util.Abort(
3557 _("can't query remote revision number, branch, or tags"))
3559 _("can't query remote revision number, branch, or tags"))
3558 if not rev and revs:
3560 if not rev and revs:
3559 rev = revs[0]
3561 rev = revs[0]
3560 if not rev:
3562 if not rev:
3561 rev = "tip"
3563 rev = "tip"
3562
3564
3563 remoterev = peer.lookup(rev)
3565 remoterev = peer.lookup(rev)
3564 if default or id:
3566 if default or id:
3565 output = [hexfunc(remoterev)]
3567 output = [hexfunc(remoterev)]
3566
3568
3567 def getbms():
3569 def getbms():
3568 bms = []
3570 bms = []
3569
3571
3570 if 'bookmarks' in peer.listkeys('namespaces'):
3572 if 'bookmarks' in peer.listkeys('namespaces'):
3571 hexremoterev = hex(remoterev)
3573 hexremoterev = hex(remoterev)
3572 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3574 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3573 if bmr == hexremoterev]
3575 if bmr == hexremoterev]
3574
3576
3575 return bms
3577 return bms
3576
3578
3577 if bookmarks:
3579 if bookmarks:
3578 output.extend(getbms())
3580 output.extend(getbms())
3579 elif default and not ui.quiet:
3581 elif default and not ui.quiet:
3580 # multiple bookmarks for a single parent separated by '/'
3582 # multiple bookmarks for a single parent separated by '/'
3581 bm = '/'.join(getbms())
3583 bm = '/'.join(getbms())
3582 if bm:
3584 if bm:
3583 output.append(bm)
3585 output.append(bm)
3584 else:
3586 else:
3585 if not rev:
3587 if not rev:
3586 ctx = repo[None]
3588 ctx = repo[None]
3587 parents = ctx.parents()
3589 parents = ctx.parents()
3588 changed = ""
3590 changed = ""
3589 if default or id or num:
3591 if default or id or num:
3590 if (util.any(repo.status())
3592 if (util.any(repo.status())
3591 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3593 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3592 changed = '+'
3594 changed = '+'
3593 if default or id:
3595 if default or id:
3594 output = ["%s%s" %
3596 output = ["%s%s" %
3595 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3597 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3596 if num:
3598 if num:
3597 output.append("%s%s" %
3599 output.append("%s%s" %
3598 ('+'.join([str(p.rev()) for p in parents]), changed))
3600 ('+'.join([str(p.rev()) for p in parents]), changed))
3599 else:
3601 else:
3600 ctx = scmutil.revsingle(repo, rev)
3602 ctx = scmutil.revsingle(repo, rev)
3601 if default or id:
3603 if default or id:
3602 output = [hexfunc(ctx.node())]
3604 output = [hexfunc(ctx.node())]
3603 if num:
3605 if num:
3604 output.append(str(ctx.rev()))
3606 output.append(str(ctx.rev()))
3605
3607
3606 if default and not ui.quiet:
3608 if default and not ui.quiet:
3607 b = ctx.branch()
3609 b = ctx.branch()
3608 if b != 'default':
3610 if b != 'default':
3609 output.append("(%s)" % b)
3611 output.append("(%s)" % b)
3610
3612
3611 # multiple tags for a single parent separated by '/'
3613 # multiple tags for a single parent separated by '/'
3612 t = '/'.join(ctx.tags())
3614 t = '/'.join(ctx.tags())
3613 if t:
3615 if t:
3614 output.append(t)
3616 output.append(t)
3615
3617
3616 # multiple bookmarks for a single parent separated by '/'
3618 # multiple bookmarks for a single parent separated by '/'
3617 bm = '/'.join(ctx.bookmarks())
3619 bm = '/'.join(ctx.bookmarks())
3618 if bm:
3620 if bm:
3619 output.append(bm)
3621 output.append(bm)
3620 else:
3622 else:
3621 if branch:
3623 if branch:
3622 output.append(ctx.branch())
3624 output.append(ctx.branch())
3623
3625
3624 if tags:
3626 if tags:
3625 output.extend(ctx.tags())
3627 output.extend(ctx.tags())
3626
3628
3627 if bookmarks:
3629 if bookmarks:
3628 output.extend(ctx.bookmarks())
3630 output.extend(ctx.bookmarks())
3629
3631
3630 ui.write("%s\n" % ' '.join(output))
3632 ui.write("%s\n" % ' '.join(output))
3631
3633
3632 @command('import|patch',
3634 @command('import|patch',
3633 [('p', 'strip', 1,
3635 [('p', 'strip', 1,
3634 _('directory strip option for patch. This has the same '
3636 _('directory strip option for patch. This has the same '
3635 'meaning as the corresponding patch option'), _('NUM')),
3637 'meaning as the corresponding patch option'), _('NUM')),
3636 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3638 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3637 ('e', 'edit', False, _('invoke editor on commit messages')),
3639 ('e', 'edit', False, _('invoke editor on commit messages')),
3638 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3640 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3639 ('', 'no-commit', None,
3641 ('', 'no-commit', None,
3640 _("don't commit, just update the working directory")),
3642 _("don't commit, just update the working directory")),
3641 ('', 'bypass', None,
3643 ('', 'bypass', None,
3642 _("apply patch without touching the working directory")),
3644 _("apply patch without touching the working directory")),
3643 ('', 'exact', None,
3645 ('', 'exact', None,
3644 _('apply patch to the nodes from which it was generated')),
3646 _('apply patch to the nodes from which it was generated')),
3645 ('', 'import-branch', None,
3647 ('', 'import-branch', None,
3646 _('use any branch information in patch (implied by --exact)'))] +
3648 _('use any branch information in patch (implied by --exact)'))] +
3647 commitopts + commitopts2 + similarityopts,
3649 commitopts + commitopts2 + similarityopts,
3648 _('[OPTION]... PATCH...'))
3650 _('[OPTION]... PATCH...'))
3649 def import_(ui, repo, patch1=None, *patches, **opts):
3651 def import_(ui, repo, patch1=None, *patches, **opts):
3650 """import an ordered set of patches
3652 """import an ordered set of patches
3651
3653
3652 Import a list of patches and commit them individually (unless
3654 Import a list of patches and commit them individually (unless
3653 --no-commit is specified).
3655 --no-commit is specified).
3654
3656
3655 If there are outstanding changes in the working directory, import
3657 If there are outstanding changes in the working directory, import
3656 will abort unless given the -f/--force flag.
3658 will abort unless given the -f/--force flag.
3657
3659
3658 You can import a patch straight from a mail message. Even patches
3660 You can import a patch straight from a mail message. Even patches
3659 as attachments work (to use the body part, it must have type
3661 as attachments work (to use the body part, it must have type
3660 text/plain or text/x-patch). From and Subject headers of email
3662 text/plain or text/x-patch). From and Subject headers of email
3661 message are used as default committer and commit message. All
3663 message are used as default committer and commit message. All
3662 text/plain body parts before first diff are added to commit
3664 text/plain body parts before first diff are added to commit
3663 message.
3665 message.
3664
3666
3665 If the imported patch was generated by :hg:`export`, user and
3667 If the imported patch was generated by :hg:`export`, user and
3666 description from patch override values from message headers and
3668 description from patch override values from message headers and
3667 body. Values given on command line with -m/--message and -u/--user
3669 body. Values given on command line with -m/--message and -u/--user
3668 override these.
3670 override these.
3669
3671
3670 If --exact is specified, import will set the working directory to
3672 If --exact is specified, import will set the working directory to
3671 the parent of each patch before applying it, and will abort if the
3673 the parent of each patch before applying it, and will abort if the
3672 resulting changeset has a different ID than the one recorded in
3674 resulting changeset has a different ID than the one recorded in
3673 the patch. This may happen due to character set problems or other
3675 the patch. This may happen due to character set problems or other
3674 deficiencies in the text patch format.
3676 deficiencies in the text patch format.
3675
3677
3676 Use --bypass to apply and commit patches directly to the
3678 Use --bypass to apply and commit patches directly to the
3677 repository, not touching the working directory. Without --exact,
3679 repository, not touching the working directory. Without --exact,
3678 patches will be applied on top of the working directory parent
3680 patches will be applied on top of the working directory parent
3679 revision.
3681 revision.
3680
3682
3681 With -s/--similarity, hg will attempt to discover renames and
3683 With -s/--similarity, hg will attempt to discover renames and
3682 copies in the patch in the same way as :hg:`addremove`.
3684 copies in the patch in the same way as :hg:`addremove`.
3683
3685
3684 To read a patch from standard input, use "-" as the patch name. If
3686 To read a patch from standard input, use "-" as the patch name. If
3685 a URL is specified, the patch will be downloaded from it.
3687 a URL is specified, the patch will be downloaded from it.
3686 See :hg:`help dates` for a list of formats valid for -d/--date.
3688 See :hg:`help dates` for a list of formats valid for -d/--date.
3687
3689
3688 .. container:: verbose
3690 .. container:: verbose
3689
3691
3690 Examples:
3692 Examples:
3691
3693
3692 - import a traditional patch from a website and detect renames::
3694 - import a traditional patch from a website and detect renames::
3693
3695
3694 hg import -s 80 http://example.com/bugfix.patch
3696 hg import -s 80 http://example.com/bugfix.patch
3695
3697
3696 - import a changeset from an hgweb server::
3698 - import a changeset from an hgweb server::
3697
3699
3698 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3700 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3699
3701
3700 - import all the patches in an Unix-style mbox::
3702 - import all the patches in an Unix-style mbox::
3701
3703
3702 hg import incoming-patches.mbox
3704 hg import incoming-patches.mbox
3703
3705
3704 - attempt to exactly restore an exported changeset (not always
3706 - attempt to exactly restore an exported changeset (not always
3705 possible)::
3707 possible)::
3706
3708
3707 hg import --exact proposed-fix.patch
3709 hg import --exact proposed-fix.patch
3708
3710
3709 Returns 0 on success.
3711 Returns 0 on success.
3710 """
3712 """
3711
3713
3712 if not patch1:
3714 if not patch1:
3713 raise util.Abort(_('need at least one patch to import'))
3715 raise util.Abort(_('need at least one patch to import'))
3714
3716
3715 patches = (patch1,) + patches
3717 patches = (patch1,) + patches
3716
3718
3717 date = opts.get('date')
3719 date = opts.get('date')
3718 if date:
3720 if date:
3719 opts['date'] = util.parsedate(date)
3721 opts['date'] = util.parsedate(date)
3720
3722
3721 editor = cmdutil.commiteditor
3723 editor = cmdutil.commiteditor
3722 if opts.get('edit'):
3724 if opts.get('edit'):
3723 editor = cmdutil.commitforceeditor
3725 editor = cmdutil.commitforceeditor
3724
3726
3725 update = not opts.get('bypass')
3727 update = not opts.get('bypass')
3726 if not update and opts.get('no_commit'):
3728 if not update and opts.get('no_commit'):
3727 raise util.Abort(_('cannot use --no-commit with --bypass'))
3729 raise util.Abort(_('cannot use --no-commit with --bypass'))
3728 try:
3730 try:
3729 sim = float(opts.get('similarity') or 0)
3731 sim = float(opts.get('similarity') or 0)
3730 except ValueError:
3732 except ValueError:
3731 raise util.Abort(_('similarity must be a number'))
3733 raise util.Abort(_('similarity must be a number'))
3732 if sim < 0 or sim > 100:
3734 if sim < 0 or sim > 100:
3733 raise util.Abort(_('similarity must be between 0 and 100'))
3735 raise util.Abort(_('similarity must be between 0 and 100'))
3734 if sim and not update:
3736 if sim and not update:
3735 raise util.Abort(_('cannot use --similarity with --bypass'))
3737 raise util.Abort(_('cannot use --similarity with --bypass'))
3736
3738
3737 if (opts.get('exact') or not opts.get('force')) and update:
3739 if (opts.get('exact') or not opts.get('force')) and update:
3738 cmdutil.bailifchanged(repo)
3740 cmdutil.bailifchanged(repo)
3739
3741
3740 base = opts["base"]
3742 base = opts["base"]
3741 strip = opts["strip"]
3743 strip = opts["strip"]
3742 wlock = lock = tr = None
3744 wlock = lock = tr = None
3743 msgs = []
3745 msgs = []
3744
3746
3745 def checkexact(repo, n, nodeid):
3747 def checkexact(repo, n, nodeid):
3746 if opts.get('exact') and hex(n) != nodeid:
3748 if opts.get('exact') and hex(n) != nodeid:
3747 repo.rollback()
3749 repo.rollback()
3748 raise util.Abort(_('patch is damaged or loses information'))
3750 raise util.Abort(_('patch is damaged or loses information'))
3749
3751
3750 def tryone(ui, hunk, parents):
3752 def tryone(ui, hunk, parents):
3751 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3753 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3752 patch.extract(ui, hunk)
3754 patch.extract(ui, hunk)
3753
3755
3754 if not tmpname:
3756 if not tmpname:
3755 return (None, None)
3757 return (None, None)
3756 msg = _('applied to working directory')
3758 msg = _('applied to working directory')
3757
3759
3758 try:
3760 try:
3759 cmdline_message = cmdutil.logmessage(ui, opts)
3761 cmdline_message = cmdutil.logmessage(ui, opts)
3760 if cmdline_message:
3762 if cmdline_message:
3761 # pickup the cmdline msg
3763 # pickup the cmdline msg
3762 message = cmdline_message
3764 message = cmdline_message
3763 elif message:
3765 elif message:
3764 # pickup the patch msg
3766 # pickup the patch msg
3765 message = message.strip()
3767 message = message.strip()
3766 else:
3768 else:
3767 # launch the editor
3769 # launch the editor
3768 message = None
3770 message = None
3769 ui.debug('message:\n%s\n' % message)
3771 ui.debug('message:\n%s\n' % message)
3770
3772
3771 if len(parents) == 1:
3773 if len(parents) == 1:
3772 parents.append(repo[nullid])
3774 parents.append(repo[nullid])
3773 if opts.get('exact'):
3775 if opts.get('exact'):
3774 if not nodeid or not p1:
3776 if not nodeid or not p1:
3775 raise util.Abort(_('not a Mercurial patch'))
3777 raise util.Abort(_('not a Mercurial patch'))
3776 p1 = repo[p1]
3778 p1 = repo[p1]
3777 p2 = repo[p2 or nullid]
3779 p2 = repo[p2 or nullid]
3778 elif p2:
3780 elif p2:
3779 try:
3781 try:
3780 p1 = repo[p1]
3782 p1 = repo[p1]
3781 p2 = repo[p2]
3783 p2 = repo[p2]
3782 # Without any options, consider p2 only if the
3784 # Without any options, consider p2 only if the
3783 # patch is being applied on top of the recorded
3785 # patch is being applied on top of the recorded
3784 # first parent.
3786 # first parent.
3785 if p1 != parents[0]:
3787 if p1 != parents[0]:
3786 p1 = parents[0]
3788 p1 = parents[0]
3787 p2 = repo[nullid]
3789 p2 = repo[nullid]
3788 except error.RepoError:
3790 except error.RepoError:
3789 p1, p2 = parents
3791 p1, p2 = parents
3790 else:
3792 else:
3791 p1, p2 = parents
3793 p1, p2 = parents
3792
3794
3793 n = None
3795 n = None
3794 if update:
3796 if update:
3795 if p1 != parents[0]:
3797 if p1 != parents[0]:
3796 hg.clean(repo, p1.node())
3798 hg.clean(repo, p1.node())
3797 if p2 != parents[1]:
3799 if p2 != parents[1]:
3798 repo.setparents(p1.node(), p2.node())
3800 repo.setparents(p1.node(), p2.node())
3799
3801
3800 if opts.get('exact') or opts.get('import_branch'):
3802 if opts.get('exact') or opts.get('import_branch'):
3801 repo.dirstate.setbranch(branch or 'default')
3803 repo.dirstate.setbranch(branch or 'default')
3802
3804
3803 files = set()
3805 files = set()
3804 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3806 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3805 eolmode=None, similarity=sim / 100.0)
3807 eolmode=None, similarity=sim / 100.0)
3806 files = list(files)
3808 files = list(files)
3807 if opts.get('no_commit'):
3809 if opts.get('no_commit'):
3808 if message:
3810 if message:
3809 msgs.append(message)
3811 msgs.append(message)
3810 else:
3812 else:
3811 if opts.get('exact') or p2:
3813 if opts.get('exact') or p2:
3812 # If you got here, you either use --force and know what
3814 # If you got here, you either use --force and know what
3813 # you are doing or used --exact or a merge patch while
3815 # you are doing or used --exact or a merge patch while
3814 # being updated to its first parent.
3816 # being updated to its first parent.
3815 m = None
3817 m = None
3816 else:
3818 else:
3817 m = scmutil.matchfiles(repo, files or [])
3819 m = scmutil.matchfiles(repo, files or [])
3818 n = repo.commit(message, opts.get('user') or user,
3820 n = repo.commit(message, opts.get('user') or user,
3819 opts.get('date') or date, match=m,
3821 opts.get('date') or date, match=m,
3820 editor=editor)
3822 editor=editor)
3821 checkexact(repo, n, nodeid)
3823 checkexact(repo, n, nodeid)
3822 else:
3824 else:
3823 if opts.get('exact') or opts.get('import_branch'):
3825 if opts.get('exact') or opts.get('import_branch'):
3824 branch = branch or 'default'
3826 branch = branch or 'default'
3825 else:
3827 else:
3826 branch = p1.branch()
3828 branch = p1.branch()
3827 store = patch.filestore()
3829 store = patch.filestore()
3828 try:
3830 try:
3829 files = set()
3831 files = set()
3830 try:
3832 try:
3831 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3833 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3832 files, eolmode=None)
3834 files, eolmode=None)
3833 except patch.PatchError, e:
3835 except patch.PatchError, e:
3834 raise util.Abort(str(e))
3836 raise util.Abort(str(e))
3835 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3837 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3836 message,
3838 message,
3837 opts.get('user') or user,
3839 opts.get('user') or user,
3838 opts.get('date') or date,
3840 opts.get('date') or date,
3839 branch, files, store,
3841 branch, files, store,
3840 editor=cmdutil.commiteditor)
3842 editor=cmdutil.commiteditor)
3841 repo.savecommitmessage(memctx.description())
3843 repo.savecommitmessage(memctx.description())
3842 n = memctx.commit()
3844 n = memctx.commit()
3843 checkexact(repo, n, nodeid)
3845 checkexact(repo, n, nodeid)
3844 finally:
3846 finally:
3845 store.close()
3847 store.close()
3846 if n:
3848 if n:
3847 # i18n: refers to a short changeset id
3849 # i18n: refers to a short changeset id
3848 msg = _('created %s') % short(n)
3850 msg = _('created %s') % short(n)
3849 return (msg, n)
3851 return (msg, n)
3850 finally:
3852 finally:
3851 os.unlink(tmpname)
3853 os.unlink(tmpname)
3852
3854
3853 try:
3855 try:
3854 try:
3856 try:
3855 wlock = repo.wlock()
3857 wlock = repo.wlock()
3856 if not opts.get('no_commit'):
3858 if not opts.get('no_commit'):
3857 lock = repo.lock()
3859 lock = repo.lock()
3858 tr = repo.transaction('import')
3860 tr = repo.transaction('import')
3859 parents = repo.parents()
3861 parents = repo.parents()
3860 for patchurl in patches:
3862 for patchurl in patches:
3861 if patchurl == '-':
3863 if patchurl == '-':
3862 ui.status(_('applying patch from stdin\n'))
3864 ui.status(_('applying patch from stdin\n'))
3863 patchfile = ui.fin
3865 patchfile = ui.fin
3864 patchurl = 'stdin' # for error message
3866 patchurl = 'stdin' # for error message
3865 else:
3867 else:
3866 patchurl = os.path.join(base, patchurl)
3868 patchurl = os.path.join(base, patchurl)
3867 ui.status(_('applying %s\n') % patchurl)
3869 ui.status(_('applying %s\n') % patchurl)
3868 patchfile = hg.openpath(ui, patchurl)
3870 patchfile = hg.openpath(ui, patchurl)
3869
3871
3870 haspatch = False
3872 haspatch = False
3871 for hunk in patch.split(patchfile):
3873 for hunk in patch.split(patchfile):
3872 (msg, node) = tryone(ui, hunk, parents)
3874 (msg, node) = tryone(ui, hunk, parents)
3873 if msg:
3875 if msg:
3874 haspatch = True
3876 haspatch = True
3875 ui.note(msg + '\n')
3877 ui.note(msg + '\n')
3876 if update or opts.get('exact'):
3878 if update or opts.get('exact'):
3877 parents = repo.parents()
3879 parents = repo.parents()
3878 else:
3880 else:
3879 parents = [repo[node]]
3881 parents = [repo[node]]
3880
3882
3881 if not haspatch:
3883 if not haspatch:
3882 raise util.Abort(_('%s: no diffs found') % patchurl)
3884 raise util.Abort(_('%s: no diffs found') % patchurl)
3883
3885
3884 if tr:
3886 if tr:
3885 tr.close()
3887 tr.close()
3886 if msgs:
3888 if msgs:
3887 repo.savecommitmessage('\n* * *\n'.join(msgs))
3889 repo.savecommitmessage('\n* * *\n'.join(msgs))
3888 except: # re-raises
3890 except: # re-raises
3889 # wlock.release() indirectly calls dirstate.write(): since
3891 # wlock.release() indirectly calls dirstate.write(): since
3890 # we're crashing, we do not want to change the working dir
3892 # we're crashing, we do not want to change the working dir
3891 # parent after all, so make sure it writes nothing
3893 # parent after all, so make sure it writes nothing
3892 repo.dirstate.invalidate()
3894 repo.dirstate.invalidate()
3893 raise
3895 raise
3894 finally:
3896 finally:
3895 if tr:
3897 if tr:
3896 tr.release()
3898 tr.release()
3897 release(lock, wlock)
3899 release(lock, wlock)
3898
3900
3899 @command('incoming|in',
3901 @command('incoming|in',
3900 [('f', 'force', None,
3902 [('f', 'force', None,
3901 _('run even if remote repository is unrelated')),
3903 _('run even if remote repository is unrelated')),
3902 ('n', 'newest-first', None, _('show newest record first')),
3904 ('n', 'newest-first', None, _('show newest record first')),
3903 ('', 'bundle', '',
3905 ('', 'bundle', '',
3904 _('file to store the bundles into'), _('FILE')),
3906 _('file to store the bundles into'), _('FILE')),
3905 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3907 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3906 ('B', 'bookmarks', False, _("compare bookmarks")),
3908 ('B', 'bookmarks', False, _("compare bookmarks")),
3907 ('b', 'branch', [],
3909 ('b', 'branch', [],
3908 _('a specific branch you would like to pull'), _('BRANCH')),
3910 _('a specific branch you would like to pull'), _('BRANCH')),
3909 ] + logopts + remoteopts + subrepoopts,
3911 ] + logopts + remoteopts + subrepoopts,
3910 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3912 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3911 def incoming(ui, repo, source="default", **opts):
3913 def incoming(ui, repo, source="default", **opts):
3912 """show new changesets found in source
3914 """show new changesets found in source
3913
3915
3914 Show new changesets found in the specified path/URL or the default
3916 Show new changesets found in the specified path/URL or the default
3915 pull location. These are the changesets that would have been pulled
3917 pull location. These are the changesets that would have been pulled
3916 if a pull at the time you issued this command.
3918 if a pull at the time you issued this command.
3917
3919
3918 For remote repository, using --bundle avoids downloading the
3920 For remote repository, using --bundle avoids downloading the
3919 changesets twice if the incoming is followed by a pull.
3921 changesets twice if the incoming is followed by a pull.
3920
3922
3921 See pull for valid source format details.
3923 See pull for valid source format details.
3922
3924
3923 Returns 0 if there are incoming changes, 1 otherwise.
3925 Returns 0 if there are incoming changes, 1 otherwise.
3924 """
3926 """
3925 if opts.get('graph'):
3927 if opts.get('graph'):
3926 cmdutil.checkunsupportedgraphflags([], opts)
3928 cmdutil.checkunsupportedgraphflags([], opts)
3927 def display(other, chlist, displayer):
3929 def display(other, chlist, displayer):
3928 revdag = cmdutil.graphrevs(other, chlist, opts)
3930 revdag = cmdutil.graphrevs(other, chlist, opts)
3929 showparents = [ctx.node() for ctx in repo[None].parents()]
3931 showparents = [ctx.node() for ctx in repo[None].parents()]
3930 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3932 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3931 graphmod.asciiedges)
3933 graphmod.asciiedges)
3932
3934
3933 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3935 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3934 return 0
3936 return 0
3935
3937
3936 if opts.get('bundle') and opts.get('subrepos'):
3938 if opts.get('bundle') and opts.get('subrepos'):
3937 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3939 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3938
3940
3939 if opts.get('bookmarks'):
3941 if opts.get('bookmarks'):
3940 source, branches = hg.parseurl(ui.expandpath(source),
3942 source, branches = hg.parseurl(ui.expandpath(source),
3941 opts.get('branch'))
3943 opts.get('branch'))
3942 other = hg.peer(repo, opts, source)
3944 other = hg.peer(repo, opts, source)
3943 if 'bookmarks' not in other.listkeys('namespaces'):
3945 if 'bookmarks' not in other.listkeys('namespaces'):
3944 ui.warn(_("remote doesn't support bookmarks\n"))
3946 ui.warn(_("remote doesn't support bookmarks\n"))
3945 return 0
3947 return 0
3946 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3948 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3947 return bookmarks.diff(ui, repo, other)
3949 return bookmarks.diff(ui, repo, other)
3948
3950
3949 repo._subtoppath = ui.expandpath(source)
3951 repo._subtoppath = ui.expandpath(source)
3950 try:
3952 try:
3951 return hg.incoming(ui, repo, source, opts)
3953 return hg.incoming(ui, repo, source, opts)
3952 finally:
3954 finally:
3953 del repo._subtoppath
3955 del repo._subtoppath
3954
3956
3955
3957
3956 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3958 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3957 def init(ui, dest=".", **opts):
3959 def init(ui, dest=".", **opts):
3958 """create a new repository in the given directory
3960 """create a new repository in the given directory
3959
3961
3960 Initialize a new repository in the given directory. If the given
3962 Initialize a new repository in the given directory. If the given
3961 directory does not exist, it will be created.
3963 directory does not exist, it will be created.
3962
3964
3963 If no directory is given, the current directory is used.
3965 If no directory is given, the current directory is used.
3964
3966
3965 It is possible to specify an ``ssh://`` URL as the destination.
3967 It is possible to specify an ``ssh://`` URL as the destination.
3966 See :hg:`help urls` for more information.
3968 See :hg:`help urls` for more information.
3967
3969
3968 Returns 0 on success.
3970 Returns 0 on success.
3969 """
3971 """
3970 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3972 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3971
3973
3972 @command('locate',
3974 @command('locate',
3973 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3975 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3974 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3976 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3975 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3977 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3976 ] + walkopts,
3978 ] + walkopts,
3977 _('[OPTION]... [PATTERN]...'))
3979 _('[OPTION]... [PATTERN]...'))
3978 def locate(ui, repo, *pats, **opts):
3980 def locate(ui, repo, *pats, **opts):
3979 """locate files matching specific patterns
3981 """locate files matching specific patterns
3980
3982
3981 Print files under Mercurial control in the working directory whose
3983 Print files under Mercurial control in the working directory whose
3982 names match the given patterns.
3984 names match the given patterns.
3983
3985
3984 By default, this command searches all directories in the working
3986 By default, this command searches all directories in the working
3985 directory. To search just the current directory and its
3987 directory. To search just the current directory and its
3986 subdirectories, use "--include .".
3988 subdirectories, use "--include .".
3987
3989
3988 If no patterns are given to match, this command prints the names
3990 If no patterns are given to match, this command prints the names
3989 of all files under Mercurial control in the working directory.
3991 of all files under Mercurial control in the working directory.
3990
3992
3991 If you want to feed the output of this command into the "xargs"
3993 If you want to feed the output of this command into the "xargs"
3992 command, use the -0 option to both this command and "xargs". This
3994 command, use the -0 option to both this command and "xargs". This
3993 will avoid the problem of "xargs" treating single filenames that
3995 will avoid the problem of "xargs" treating single filenames that
3994 contain whitespace as multiple filenames.
3996 contain whitespace as multiple filenames.
3995
3997
3996 Returns 0 if a match is found, 1 otherwise.
3998 Returns 0 if a match is found, 1 otherwise.
3997 """
3999 """
3998 end = opts.get('print0') and '\0' or '\n'
4000 end = opts.get('print0') and '\0' or '\n'
3999 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4001 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4000
4002
4001 ret = 1
4003 ret = 1
4002 m = scmutil.match(repo[rev], pats, opts, default='relglob')
4004 m = scmutil.match(repo[rev], pats, opts, default='relglob')
4003 m.bad = lambda x, y: False
4005 m.bad = lambda x, y: False
4004 for abs in repo[rev].walk(m):
4006 for abs in repo[rev].walk(m):
4005 if not rev and abs not in repo.dirstate:
4007 if not rev and abs not in repo.dirstate:
4006 continue
4008 continue
4007 if opts.get('fullpath'):
4009 if opts.get('fullpath'):
4008 ui.write(repo.wjoin(abs), end)
4010 ui.write(repo.wjoin(abs), end)
4009 else:
4011 else:
4010 ui.write(((pats and m.rel(abs)) or abs), end)
4012 ui.write(((pats and m.rel(abs)) or abs), end)
4011 ret = 0
4013 ret = 0
4012
4014
4013 return ret
4015 return ret
4014
4016
4015 @command('^log|history',
4017 @command('^log|history',
4016 [('f', 'follow', None,
4018 [('f', 'follow', None,
4017 _('follow changeset history, or file history across copies and renames')),
4019 _('follow changeset history, or file history across copies and renames')),
4018 ('', 'follow-first', None,
4020 ('', 'follow-first', None,
4019 _('only follow the first parent of merge changesets (DEPRECATED)')),
4021 _('only follow the first parent of merge changesets (DEPRECATED)')),
4020 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4022 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4021 ('C', 'copies', None, _('show copied files')),
4023 ('C', 'copies', None, _('show copied files')),
4022 ('k', 'keyword', [],
4024 ('k', 'keyword', [],
4023 _('do case-insensitive search for a given text'), _('TEXT')),
4025 _('do case-insensitive search for a given text'), _('TEXT')),
4024 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4026 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4025 ('', 'removed', None, _('include revisions where files were removed')),
4027 ('', 'removed', None, _('include revisions where files were removed')),
4026 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4028 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4027 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4029 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4028 ('', 'only-branch', [],
4030 ('', 'only-branch', [],
4029 _('show only changesets within the given named branch (DEPRECATED)'),
4031 _('show only changesets within the given named branch (DEPRECATED)'),
4030 _('BRANCH')),
4032 _('BRANCH')),
4031 ('b', 'branch', [],
4033 ('b', 'branch', [],
4032 _('show changesets within the given named branch'), _('BRANCH')),
4034 _('show changesets within the given named branch'), _('BRANCH')),
4033 ('P', 'prune', [],
4035 ('P', 'prune', [],
4034 _('do not display revision or any of its ancestors'), _('REV')),
4036 _('do not display revision or any of its ancestors'), _('REV')),
4035 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
4037 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
4036 ] + logopts + walkopts,
4038 ] + logopts + walkopts,
4037 _('[OPTION]... [FILE]'))
4039 _('[OPTION]... [FILE]'))
4038 def log(ui, repo, *pats, **opts):
4040 def log(ui, repo, *pats, **opts):
4039 """show revision history of entire repository or files
4041 """show revision history of entire repository or files
4040
4042
4041 Print the revision history of the specified files or the entire
4043 Print the revision history of the specified files or the entire
4042 project.
4044 project.
4043
4045
4044 If no revision range is specified, the default is ``tip:0`` unless
4046 If no revision range is specified, the default is ``tip:0`` unless
4045 --follow is set, in which case the working directory parent is
4047 --follow is set, in which case the working directory parent is
4046 used as the starting revision.
4048 used as the starting revision.
4047
4049
4048 File history is shown without following rename or copy history of
4050 File history is shown without following rename or copy history of
4049 files. Use -f/--follow with a filename to follow history across
4051 files. Use -f/--follow with a filename to follow history across
4050 renames and copies. --follow without a filename will only show
4052 renames and copies. --follow without a filename will only show
4051 ancestors or descendants of the starting revision.
4053 ancestors or descendants of the starting revision.
4052
4054
4053 By default this command prints revision number and changeset id,
4055 By default this command prints revision number and changeset id,
4054 tags, non-trivial parents, user, date and time, and a summary for
4056 tags, non-trivial parents, user, date and time, and a summary for
4055 each commit. When the -v/--verbose switch is used, the list of
4057 each commit. When the -v/--verbose switch is used, the list of
4056 changed files and full commit message are shown.
4058 changed files and full commit message are shown.
4057
4059
4058 .. note::
4060 .. note::
4059 log -p/--patch may generate unexpected diff output for merge
4061 log -p/--patch may generate unexpected diff output for merge
4060 changesets, as it will only compare the merge changeset against
4062 changesets, as it will only compare the merge changeset against
4061 its first parent. Also, only files different from BOTH parents
4063 its first parent. Also, only files different from BOTH parents
4062 will appear in files:.
4064 will appear in files:.
4063
4065
4064 .. note::
4066 .. note::
4065 for performance reasons, log FILE may omit duplicate changes
4067 for performance reasons, log FILE may omit duplicate changes
4066 made on branches and will not show deletions. To see all
4068 made on branches and will not show deletions. To see all
4067 changes including duplicates and deletions, use the --removed
4069 changes including duplicates and deletions, use the --removed
4068 switch.
4070 switch.
4069
4071
4070 .. container:: verbose
4072 .. container:: verbose
4071
4073
4072 Some examples:
4074 Some examples:
4073
4075
4074 - changesets with full descriptions and file lists::
4076 - changesets with full descriptions and file lists::
4075
4077
4076 hg log -v
4078 hg log -v
4077
4079
4078 - changesets ancestral to the working directory::
4080 - changesets ancestral to the working directory::
4079
4081
4080 hg log -f
4082 hg log -f
4081
4083
4082 - last 10 commits on the current branch::
4084 - last 10 commits on the current branch::
4083
4085
4084 hg log -l 10 -b .
4086 hg log -l 10 -b .
4085
4087
4086 - changesets showing all modifications of a file, including removals::
4088 - changesets showing all modifications of a file, including removals::
4087
4089
4088 hg log --removed file.c
4090 hg log --removed file.c
4089
4091
4090 - all changesets that touch a directory, with diffs, excluding merges::
4092 - all changesets that touch a directory, with diffs, excluding merges::
4091
4093
4092 hg log -Mp lib/
4094 hg log -Mp lib/
4093
4095
4094 - all revision numbers that match a keyword::
4096 - all revision numbers that match a keyword::
4095
4097
4096 hg log -k bug --template "{rev}\\n"
4098 hg log -k bug --template "{rev}\\n"
4097
4099
4098 - check if a given changeset is included is a tagged release::
4100 - check if a given changeset is included is a tagged release::
4099
4101
4100 hg log -r "a21ccf and ancestor(1.9)"
4102 hg log -r "a21ccf and ancestor(1.9)"
4101
4103
4102 - find all changesets by some user in a date range::
4104 - find all changesets by some user in a date range::
4103
4105
4104 hg log -k alice -d "may 2008 to jul 2008"
4106 hg log -k alice -d "may 2008 to jul 2008"
4105
4107
4106 - summary of all changesets after the last tag::
4108 - summary of all changesets after the last tag::
4107
4109
4108 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4110 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4109
4111
4110 See :hg:`help dates` for a list of formats valid for -d/--date.
4112 See :hg:`help dates` for a list of formats valid for -d/--date.
4111
4113
4112 See :hg:`help revisions` and :hg:`help revsets` for more about
4114 See :hg:`help revisions` and :hg:`help revsets` for more about
4113 specifying revisions.
4115 specifying revisions.
4114
4116
4115 See :hg:`help templates` for more about pre-packaged styles and
4117 See :hg:`help templates` for more about pre-packaged styles and
4116 specifying custom templates.
4118 specifying custom templates.
4117
4119
4118 Returns 0 on success.
4120 Returns 0 on success.
4119 """
4121 """
4120 if opts.get('graph'):
4122 if opts.get('graph'):
4121 return cmdutil.graphlog(ui, repo, *pats, **opts)
4123 return cmdutil.graphlog(ui, repo, *pats, **opts)
4122
4124
4123 matchfn = scmutil.match(repo[None], pats, opts)
4125 matchfn = scmutil.match(repo[None], pats, opts)
4124 limit = cmdutil.loglimit(opts)
4126 limit = cmdutil.loglimit(opts)
4125 count = 0
4127 count = 0
4126
4128
4127 getrenamed, endrev = None, None
4129 getrenamed, endrev = None, None
4128 if opts.get('copies'):
4130 if opts.get('copies'):
4129 if opts.get('rev'):
4131 if opts.get('rev'):
4130 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4132 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4131 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4133 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4132
4134
4133 df = False
4135 df = False
4134 if opts.get("date"):
4136 if opts.get("date"):
4135 df = util.matchdate(opts["date"])
4137 df = util.matchdate(opts["date"])
4136
4138
4137 branches = opts.get('branch', []) + opts.get('only_branch', [])
4139 branches = opts.get('branch', []) + opts.get('only_branch', [])
4138 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4140 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4139
4141
4140 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4142 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4141 def prep(ctx, fns):
4143 def prep(ctx, fns):
4142 rev = ctx.rev()
4144 rev = ctx.rev()
4143 parents = [p for p in repo.changelog.parentrevs(rev)
4145 parents = [p for p in repo.changelog.parentrevs(rev)
4144 if p != nullrev]
4146 if p != nullrev]
4145 if opts.get('no_merges') and len(parents) == 2:
4147 if opts.get('no_merges') and len(parents) == 2:
4146 return
4148 return
4147 if opts.get('only_merges') and len(parents) != 2:
4149 if opts.get('only_merges') and len(parents) != 2:
4148 return
4150 return
4149 if opts.get('branch') and ctx.branch() not in opts['branch']:
4151 if opts.get('branch') and ctx.branch() not in opts['branch']:
4150 return
4152 return
4151 if not opts.get('hidden') and ctx.hidden():
4153 if not opts.get('hidden') and ctx.hidden():
4152 return
4154 return
4153 if df and not df(ctx.date()[0]):
4155 if df and not df(ctx.date()[0]):
4154 return
4156 return
4155
4157
4156 lower = encoding.lower
4158 lower = encoding.lower
4157 if opts.get('user'):
4159 if opts.get('user'):
4158 luser = lower(ctx.user())
4160 luser = lower(ctx.user())
4159 for k in [lower(x) for x in opts['user']]:
4161 for k in [lower(x) for x in opts['user']]:
4160 if (k in luser):
4162 if (k in luser):
4161 break
4163 break
4162 else:
4164 else:
4163 return
4165 return
4164 if opts.get('keyword'):
4166 if opts.get('keyword'):
4165 luser = lower(ctx.user())
4167 luser = lower(ctx.user())
4166 ldesc = lower(ctx.description())
4168 ldesc = lower(ctx.description())
4167 lfiles = lower(" ".join(ctx.files()))
4169 lfiles = lower(" ".join(ctx.files()))
4168 for k in [lower(x) for x in opts['keyword']]:
4170 for k in [lower(x) for x in opts['keyword']]:
4169 if (k in luser or k in ldesc or k in lfiles):
4171 if (k in luser or k in ldesc or k in lfiles):
4170 break
4172 break
4171 else:
4173 else:
4172 return
4174 return
4173
4175
4174 copies = None
4176 copies = None
4175 if getrenamed is not None and rev:
4177 if getrenamed is not None and rev:
4176 copies = []
4178 copies = []
4177 for fn in ctx.files():
4179 for fn in ctx.files():
4178 rename = getrenamed(fn, rev)
4180 rename = getrenamed(fn, rev)
4179 if rename:
4181 if rename:
4180 copies.append((fn, rename[0]))
4182 copies.append((fn, rename[0]))
4181
4183
4182 revmatchfn = None
4184 revmatchfn = None
4183 if opts.get('patch') or opts.get('stat'):
4185 if opts.get('patch') or opts.get('stat'):
4184 if opts.get('follow') or opts.get('follow_first'):
4186 if opts.get('follow') or opts.get('follow_first'):
4185 # note: this might be wrong when following through merges
4187 # note: this might be wrong when following through merges
4186 revmatchfn = scmutil.match(repo[None], fns, default='path')
4188 revmatchfn = scmutil.match(repo[None], fns, default='path')
4187 else:
4189 else:
4188 revmatchfn = matchfn
4190 revmatchfn = matchfn
4189
4191
4190 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4192 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4191
4193
4192 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4194 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4193 if count == limit:
4195 if count == limit:
4194 break
4196 break
4195 if displayer.flush(ctx.rev()):
4197 if displayer.flush(ctx.rev()):
4196 count += 1
4198 count += 1
4197 displayer.close()
4199 displayer.close()
4198
4200
4199 @command('manifest',
4201 @command('manifest',
4200 [('r', 'rev', '', _('revision to display'), _('REV')),
4202 [('r', 'rev', '', _('revision to display'), _('REV')),
4201 ('', 'all', False, _("list files from all revisions"))],
4203 ('', 'all', False, _("list files from all revisions"))],
4202 _('[-r REV]'))
4204 _('[-r REV]'))
4203 def manifest(ui, repo, node=None, rev=None, **opts):
4205 def manifest(ui, repo, node=None, rev=None, **opts):
4204 """output the current or given revision of the project manifest
4206 """output the current or given revision of the project manifest
4205
4207
4206 Print a list of version controlled files for the given revision.
4208 Print a list of version controlled files for the given revision.
4207 If no revision is given, the first parent of the working directory
4209 If no revision is given, the first parent of the working directory
4208 is used, or the null revision if no revision is checked out.
4210 is used, or the null revision if no revision is checked out.
4209
4211
4210 With -v, print file permissions, symlink and executable bits.
4212 With -v, print file permissions, symlink and executable bits.
4211 With --debug, print file revision hashes.
4213 With --debug, print file revision hashes.
4212
4214
4213 If option --all is specified, the list of all files from all revisions
4215 If option --all is specified, the list of all files from all revisions
4214 is printed. This includes deleted and renamed files.
4216 is printed. This includes deleted and renamed files.
4215
4217
4216 Returns 0 on success.
4218 Returns 0 on success.
4217 """
4219 """
4218
4220
4219 fm = ui.formatter('manifest', opts)
4221 fm = ui.formatter('manifest', opts)
4220
4222
4221 if opts.get('all'):
4223 if opts.get('all'):
4222 if rev or node:
4224 if rev or node:
4223 raise util.Abort(_("can't specify a revision with --all"))
4225 raise util.Abort(_("can't specify a revision with --all"))
4224
4226
4225 res = []
4227 res = []
4226 prefix = "data/"
4228 prefix = "data/"
4227 suffix = ".i"
4229 suffix = ".i"
4228 plen = len(prefix)
4230 plen = len(prefix)
4229 slen = len(suffix)
4231 slen = len(suffix)
4230 lock = repo.lock()
4232 lock = repo.lock()
4231 try:
4233 try:
4232 for fn, b, size in repo.store.datafiles():
4234 for fn, b, size in repo.store.datafiles():
4233 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4235 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4234 res.append(fn[plen:-slen])
4236 res.append(fn[plen:-slen])
4235 finally:
4237 finally:
4236 lock.release()
4238 lock.release()
4237 for f in res:
4239 for f in res:
4238 fm.startitem()
4240 fm.startitem()
4239 fm.write("path", '%s\n', f)
4241 fm.write("path", '%s\n', f)
4240 fm.end()
4242 fm.end()
4241 return
4243 return
4242
4244
4243 if rev and node:
4245 if rev and node:
4244 raise util.Abort(_("please specify just one revision"))
4246 raise util.Abort(_("please specify just one revision"))
4245
4247
4246 if not node:
4248 if not node:
4247 node = rev
4249 node = rev
4248
4250
4249 char = {'l': '@', 'x': '*', '': ''}
4251 char = {'l': '@', 'x': '*', '': ''}
4250 mode = {'l': '644', 'x': '755', '': '644'}
4252 mode = {'l': '644', 'x': '755', '': '644'}
4251 ctx = scmutil.revsingle(repo, node)
4253 ctx = scmutil.revsingle(repo, node)
4252 mf = ctx.manifest()
4254 mf = ctx.manifest()
4253 for f in ctx:
4255 for f in ctx:
4254 fm.startitem()
4256 fm.startitem()
4255 fl = ctx[f].flags()
4257 fl = ctx[f].flags()
4256 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4258 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4257 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4259 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4258 fm.write('path', '%s\n', f)
4260 fm.write('path', '%s\n', f)
4259 fm.end()
4261 fm.end()
4260
4262
4261 @command('^merge',
4263 @command('^merge',
4262 [('f', 'force', None, _('force a merge with outstanding changes')),
4264 [('f', 'force', None, _('force a merge with outstanding changes')),
4263 ('r', 'rev', '', _('revision to merge'), _('REV')),
4265 ('r', 'rev', '', _('revision to merge'), _('REV')),
4264 ('P', 'preview', None,
4266 ('P', 'preview', None,
4265 _('review revisions to merge (no merge is performed)'))
4267 _('review revisions to merge (no merge is performed)'))
4266 ] + mergetoolopts,
4268 ] + mergetoolopts,
4267 _('[-P] [-f] [[-r] REV]'))
4269 _('[-P] [-f] [[-r] REV]'))
4268 def merge(ui, repo, node=None, **opts):
4270 def merge(ui, repo, node=None, **opts):
4269 """merge working directory with another revision
4271 """merge working directory with another revision
4270
4272
4271 The current working directory is updated with all changes made in
4273 The current working directory is updated with all changes made in
4272 the requested revision since the last common predecessor revision.
4274 the requested revision since the last common predecessor revision.
4273
4275
4274 Files that changed between either parent are marked as changed for
4276 Files that changed between either parent are marked as changed for
4275 the next commit and a commit must be performed before any further
4277 the next commit and a commit must be performed before any further
4276 updates to the repository are allowed. The next commit will have
4278 updates to the repository are allowed. The next commit will have
4277 two parents.
4279 two parents.
4278
4280
4279 ``--tool`` can be used to specify the merge tool used for file
4281 ``--tool`` can be used to specify the merge tool used for file
4280 merges. It overrides the HGMERGE environment variable and your
4282 merges. It overrides the HGMERGE environment variable and your
4281 configuration files. See :hg:`help merge-tools` for options.
4283 configuration files. See :hg:`help merge-tools` for options.
4282
4284
4283 If no revision is specified, the working directory's parent is a
4285 If no revision is specified, the working directory's parent is a
4284 head revision, and the current branch contains exactly one other
4286 head revision, and the current branch contains exactly one other
4285 head, the other head is merged with by default. Otherwise, an
4287 head, the other head is merged with by default. Otherwise, an
4286 explicit revision with which to merge with must be provided.
4288 explicit revision with which to merge with must be provided.
4287
4289
4288 :hg:`resolve` must be used to resolve unresolved files.
4290 :hg:`resolve` must be used to resolve unresolved files.
4289
4291
4290 To undo an uncommitted merge, use :hg:`update --clean .` which
4292 To undo an uncommitted merge, use :hg:`update --clean .` which
4291 will check out a clean copy of the original merge parent, losing
4293 will check out a clean copy of the original merge parent, losing
4292 all changes.
4294 all changes.
4293
4295
4294 Returns 0 on success, 1 if there are unresolved files.
4296 Returns 0 on success, 1 if there are unresolved files.
4295 """
4297 """
4296
4298
4297 if opts.get('rev') and node:
4299 if opts.get('rev') and node:
4298 raise util.Abort(_("please specify just one revision"))
4300 raise util.Abort(_("please specify just one revision"))
4299 if not node:
4301 if not node:
4300 node = opts.get('rev')
4302 node = opts.get('rev')
4301
4303
4302 if node:
4304 if node:
4303 node = scmutil.revsingle(repo, node).node()
4305 node = scmutil.revsingle(repo, node).node()
4304
4306
4305 if not node and repo._bookmarkcurrent:
4307 if not node and repo._bookmarkcurrent:
4306 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4308 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4307 curhead = repo[repo._bookmarkcurrent]
4309 curhead = repo[repo._bookmarkcurrent]
4308 if len(bmheads) == 2:
4310 if len(bmheads) == 2:
4309 if curhead == bmheads[0]:
4311 if curhead == bmheads[0]:
4310 node = bmheads[1]
4312 node = bmheads[1]
4311 else:
4313 else:
4312 node = bmheads[0]
4314 node = bmheads[0]
4313 elif len(bmheads) > 2:
4315 elif len(bmheads) > 2:
4314 raise util.Abort(_("multiple matching bookmarks to merge - "
4316 raise util.Abort(_("multiple matching bookmarks to merge - "
4315 "please merge with an explicit rev or bookmark"),
4317 "please merge with an explicit rev or bookmark"),
4316 hint=_("run 'hg heads' to see all heads"))
4318 hint=_("run 'hg heads' to see all heads"))
4317 elif len(bmheads) <= 1:
4319 elif len(bmheads) <= 1:
4318 raise util.Abort(_("no matching bookmark to merge - "
4320 raise util.Abort(_("no matching bookmark to merge - "
4319 "please merge with an explicit rev or bookmark"),
4321 "please merge with an explicit rev or bookmark"),
4320 hint=_("run 'hg heads' to see all heads"))
4322 hint=_("run 'hg heads' to see all heads"))
4321
4323
4322 if not node and not repo._bookmarkcurrent:
4324 if not node and not repo._bookmarkcurrent:
4323 branch = repo[None].branch()
4325 branch = repo[None].branch()
4324 bheads = repo.branchheads(branch)
4326 bheads = repo.branchheads(branch)
4325 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4327 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4326
4328
4327 if len(nbhs) > 2:
4329 if len(nbhs) > 2:
4328 raise util.Abort(_("branch '%s' has %d heads - "
4330 raise util.Abort(_("branch '%s' has %d heads - "
4329 "please merge with an explicit rev")
4331 "please merge with an explicit rev")
4330 % (branch, len(bheads)),
4332 % (branch, len(bheads)),
4331 hint=_("run 'hg heads .' to see heads"))
4333 hint=_("run 'hg heads .' to see heads"))
4332
4334
4333 parent = repo.dirstate.p1()
4335 parent = repo.dirstate.p1()
4334 if len(nbhs) <= 1:
4336 if len(nbhs) <= 1:
4335 if len(bheads) > 1:
4337 if len(bheads) > 1:
4336 raise util.Abort(_("heads are bookmarked - "
4338 raise util.Abort(_("heads are bookmarked - "
4337 "please merge with an explicit rev"),
4339 "please merge with an explicit rev"),
4338 hint=_("run 'hg heads' to see all heads"))
4340 hint=_("run 'hg heads' to see all heads"))
4339 if len(repo.heads()) > 1:
4341 if len(repo.heads()) > 1:
4340 raise util.Abort(_("branch '%s' has one head - "
4342 raise util.Abort(_("branch '%s' has one head - "
4341 "please merge with an explicit rev")
4343 "please merge with an explicit rev")
4342 % branch,
4344 % branch,
4343 hint=_("run 'hg heads' to see all heads"))
4345 hint=_("run 'hg heads' to see all heads"))
4344 msg, hint = _('nothing to merge'), None
4346 msg, hint = _('nothing to merge'), None
4345 if parent != repo.lookup(branch):
4347 if parent != repo.lookup(branch):
4346 hint = _("use 'hg update' instead")
4348 hint = _("use 'hg update' instead")
4347 raise util.Abort(msg, hint=hint)
4349 raise util.Abort(msg, hint=hint)
4348
4350
4349 if parent not in bheads:
4351 if parent not in bheads:
4350 raise util.Abort(_('working directory not at a head revision'),
4352 raise util.Abort(_('working directory not at a head revision'),
4351 hint=_("use 'hg update' or merge with an "
4353 hint=_("use 'hg update' or merge with an "
4352 "explicit revision"))
4354 "explicit revision"))
4353 if parent == nbhs[0]:
4355 if parent == nbhs[0]:
4354 node = nbhs[-1]
4356 node = nbhs[-1]
4355 else:
4357 else:
4356 node = nbhs[0]
4358 node = nbhs[0]
4357
4359
4358 if opts.get('preview'):
4360 if opts.get('preview'):
4359 # find nodes that are ancestors of p2 but not of p1
4361 # find nodes that are ancestors of p2 but not of p1
4360 p1 = repo.lookup('.')
4362 p1 = repo.lookup('.')
4361 p2 = repo.lookup(node)
4363 p2 = repo.lookup(node)
4362 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4364 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4363
4365
4364 displayer = cmdutil.show_changeset(ui, repo, opts)
4366 displayer = cmdutil.show_changeset(ui, repo, opts)
4365 for node in nodes:
4367 for node in nodes:
4366 displayer.show(repo[node])
4368 displayer.show(repo[node])
4367 displayer.close()
4369 displayer.close()
4368 return 0
4370 return 0
4369
4371
4370 try:
4372 try:
4371 # ui.forcemerge is an internal variable, do not document
4373 # ui.forcemerge is an internal variable, do not document
4372 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4374 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4373 return hg.merge(repo, node, force=opts.get('force'))
4375 return hg.merge(repo, node, force=opts.get('force'))
4374 finally:
4376 finally:
4375 ui.setconfig('ui', 'forcemerge', '')
4377 ui.setconfig('ui', 'forcemerge', '')
4376
4378
4377 @command('outgoing|out',
4379 @command('outgoing|out',
4378 [('f', 'force', None, _('run even when the destination is unrelated')),
4380 [('f', 'force', None, _('run even when the destination is unrelated')),
4379 ('r', 'rev', [],
4381 ('r', 'rev', [],
4380 _('a changeset intended to be included in the destination'), _('REV')),
4382 _('a changeset intended to be included in the destination'), _('REV')),
4381 ('n', 'newest-first', None, _('show newest record first')),
4383 ('n', 'newest-first', None, _('show newest record first')),
4382 ('B', 'bookmarks', False, _('compare bookmarks')),
4384 ('B', 'bookmarks', False, _('compare bookmarks')),
4383 ('b', 'branch', [], _('a specific branch you would like to push'),
4385 ('b', 'branch', [], _('a specific branch you would like to push'),
4384 _('BRANCH')),
4386 _('BRANCH')),
4385 ] + logopts + remoteopts + subrepoopts,
4387 ] + logopts + remoteopts + subrepoopts,
4386 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4388 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4387 def outgoing(ui, repo, dest=None, **opts):
4389 def outgoing(ui, repo, dest=None, **opts):
4388 """show changesets not found in the destination
4390 """show changesets not found in the destination
4389
4391
4390 Show changesets not found in the specified destination repository
4392 Show changesets not found in the specified destination repository
4391 or the default push location. These are the changesets that would
4393 or the default push location. These are the changesets that would
4392 be pushed if a push was requested.
4394 be pushed if a push was requested.
4393
4395
4394 See pull for details of valid destination formats.
4396 See pull for details of valid destination formats.
4395
4397
4396 Returns 0 if there are outgoing changes, 1 otherwise.
4398 Returns 0 if there are outgoing changes, 1 otherwise.
4397 """
4399 """
4398 if opts.get('graph'):
4400 if opts.get('graph'):
4399 cmdutil.checkunsupportedgraphflags([], opts)
4401 cmdutil.checkunsupportedgraphflags([], opts)
4400 o = hg._outgoing(ui, repo, dest, opts)
4402 o = hg._outgoing(ui, repo, dest, opts)
4401 if o is None:
4403 if o is None:
4402 return
4404 return
4403
4405
4404 revdag = cmdutil.graphrevs(repo, o, opts)
4406 revdag = cmdutil.graphrevs(repo, o, opts)
4405 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4407 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4406 showparents = [ctx.node() for ctx in repo[None].parents()]
4408 showparents = [ctx.node() for ctx in repo[None].parents()]
4407 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4409 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4408 graphmod.asciiedges)
4410 graphmod.asciiedges)
4409 return 0
4411 return 0
4410
4412
4411 if opts.get('bookmarks'):
4413 if opts.get('bookmarks'):
4412 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4414 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4413 dest, branches = hg.parseurl(dest, opts.get('branch'))
4415 dest, branches = hg.parseurl(dest, opts.get('branch'))
4414 other = hg.peer(repo, opts, dest)
4416 other = hg.peer(repo, opts, dest)
4415 if 'bookmarks' not in other.listkeys('namespaces'):
4417 if 'bookmarks' not in other.listkeys('namespaces'):
4416 ui.warn(_("remote doesn't support bookmarks\n"))
4418 ui.warn(_("remote doesn't support bookmarks\n"))
4417 return 0
4419 return 0
4418 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4420 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4419 return bookmarks.diff(ui, other, repo)
4421 return bookmarks.diff(ui, other, repo)
4420
4422
4421 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4423 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4422 try:
4424 try:
4423 return hg.outgoing(ui, repo, dest, opts)
4425 return hg.outgoing(ui, repo, dest, opts)
4424 finally:
4426 finally:
4425 del repo._subtoppath
4427 del repo._subtoppath
4426
4428
4427 @command('parents',
4429 @command('parents',
4428 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4430 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4429 ] + templateopts,
4431 ] + templateopts,
4430 _('[-r REV] [FILE]'))
4432 _('[-r REV] [FILE]'))
4431 def parents(ui, repo, file_=None, **opts):
4433 def parents(ui, repo, file_=None, **opts):
4432 """show the parents of the working directory or revision
4434 """show the parents of the working directory or revision
4433
4435
4434 Print the working directory's parent revisions. If a revision is
4436 Print the working directory's parent revisions. If a revision is
4435 given via -r/--rev, the parent of that revision will be printed.
4437 given via -r/--rev, the parent of that revision will be printed.
4436 If a file argument is given, the revision in which the file was
4438 If a file argument is given, the revision in which the file was
4437 last changed (before the working directory revision or the
4439 last changed (before the working directory revision or the
4438 argument to --rev if given) is printed.
4440 argument to --rev if given) is printed.
4439
4441
4440 Returns 0 on success.
4442 Returns 0 on success.
4441 """
4443 """
4442
4444
4443 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4445 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4444
4446
4445 if file_:
4447 if file_:
4446 m = scmutil.match(ctx, (file_,), opts)
4448 m = scmutil.match(ctx, (file_,), opts)
4447 if m.anypats() or len(m.files()) != 1:
4449 if m.anypats() or len(m.files()) != 1:
4448 raise util.Abort(_('can only specify an explicit filename'))
4450 raise util.Abort(_('can only specify an explicit filename'))
4449 file_ = m.files()[0]
4451 file_ = m.files()[0]
4450 filenodes = []
4452 filenodes = []
4451 for cp in ctx.parents():
4453 for cp in ctx.parents():
4452 if not cp:
4454 if not cp:
4453 continue
4455 continue
4454 try:
4456 try:
4455 filenodes.append(cp.filenode(file_))
4457 filenodes.append(cp.filenode(file_))
4456 except error.LookupError:
4458 except error.LookupError:
4457 pass
4459 pass
4458 if not filenodes:
4460 if not filenodes:
4459 raise util.Abort(_("'%s' not found in manifest!") % file_)
4461 raise util.Abort(_("'%s' not found in manifest!") % file_)
4460 fl = repo.file(file_)
4462 fl = repo.file(file_)
4461 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4463 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4462 else:
4464 else:
4463 p = [cp.node() for cp in ctx.parents()]
4465 p = [cp.node() for cp in ctx.parents()]
4464
4466
4465 displayer = cmdutil.show_changeset(ui, repo, opts)
4467 displayer = cmdutil.show_changeset(ui, repo, opts)
4466 for n in p:
4468 for n in p:
4467 if n != nullid:
4469 if n != nullid:
4468 displayer.show(repo[n])
4470 displayer.show(repo[n])
4469 displayer.close()
4471 displayer.close()
4470
4472
4471 @command('paths', [], _('[NAME]'))
4473 @command('paths', [], _('[NAME]'))
4472 def paths(ui, repo, search=None):
4474 def paths(ui, repo, search=None):
4473 """show aliases for remote repositories
4475 """show aliases for remote repositories
4474
4476
4475 Show definition of symbolic path name NAME. If no name is given,
4477 Show definition of symbolic path name NAME. If no name is given,
4476 show definition of all available names.
4478 show definition of all available names.
4477
4479
4478 Option -q/--quiet suppresses all output when searching for NAME
4480 Option -q/--quiet suppresses all output when searching for NAME
4479 and shows only the path names when listing all definitions.
4481 and shows only the path names when listing all definitions.
4480
4482
4481 Path names are defined in the [paths] section of your
4483 Path names are defined in the [paths] section of your
4482 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4484 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4483 repository, ``.hg/hgrc`` is used, too.
4485 repository, ``.hg/hgrc`` is used, too.
4484
4486
4485 The path names ``default`` and ``default-push`` have a special
4487 The path names ``default`` and ``default-push`` have a special
4486 meaning. When performing a push or pull operation, they are used
4488 meaning. When performing a push or pull operation, they are used
4487 as fallbacks if no location is specified on the command-line.
4489 as fallbacks if no location is specified on the command-line.
4488 When ``default-push`` is set, it will be used for push and
4490 When ``default-push`` is set, it will be used for push and
4489 ``default`` will be used for pull; otherwise ``default`` is used
4491 ``default`` will be used for pull; otherwise ``default`` is used
4490 as the fallback for both. When cloning a repository, the clone
4492 as the fallback for both. When cloning a repository, the clone
4491 source is written as ``default`` in ``.hg/hgrc``. Note that
4493 source is written as ``default`` in ``.hg/hgrc``. Note that
4492 ``default`` and ``default-push`` apply to all inbound (e.g.
4494 ``default`` and ``default-push`` apply to all inbound (e.g.
4493 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4495 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4494 :hg:`bundle`) operations.
4496 :hg:`bundle`) operations.
4495
4497
4496 See :hg:`help urls` for more information.
4498 See :hg:`help urls` for more information.
4497
4499
4498 Returns 0 on success.
4500 Returns 0 on success.
4499 """
4501 """
4500 if search:
4502 if search:
4501 for name, path in ui.configitems("paths"):
4503 for name, path in ui.configitems("paths"):
4502 if name == search:
4504 if name == search:
4503 ui.status("%s\n" % util.hidepassword(path))
4505 ui.status("%s\n" % util.hidepassword(path))
4504 return
4506 return
4505 if not ui.quiet:
4507 if not ui.quiet:
4506 ui.warn(_("not found!\n"))
4508 ui.warn(_("not found!\n"))
4507 return 1
4509 return 1
4508 else:
4510 else:
4509 for name, path in ui.configitems("paths"):
4511 for name, path in ui.configitems("paths"):
4510 if ui.quiet:
4512 if ui.quiet:
4511 ui.write("%s\n" % name)
4513 ui.write("%s\n" % name)
4512 else:
4514 else:
4513 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4515 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4514
4516
4515 @command('phase',
4517 @command('phase',
4516 [('p', 'public', False, _('set changeset phase to public')),
4518 [('p', 'public', False, _('set changeset phase to public')),
4517 ('d', 'draft', False, _('set changeset phase to draft')),
4519 ('d', 'draft', False, _('set changeset phase to draft')),
4518 ('s', 'secret', False, _('set changeset phase to secret')),
4520 ('s', 'secret', False, _('set changeset phase to secret')),
4519 ('f', 'force', False, _('allow to move boundary backward')),
4521 ('f', 'force', False, _('allow to move boundary backward')),
4520 ('r', 'rev', [], _('target revision'), _('REV')),
4522 ('r', 'rev', [], _('target revision'), _('REV')),
4521 ],
4523 ],
4522 _('[-p|-d|-s] [-f] [-r] REV...'))
4524 _('[-p|-d|-s] [-f] [-r] REV...'))
4523 def phase(ui, repo, *revs, **opts):
4525 def phase(ui, repo, *revs, **opts):
4524 """set or show the current phase name
4526 """set or show the current phase name
4525
4527
4526 With no argument, show the phase name of specified revisions.
4528 With no argument, show the phase name of specified revisions.
4527
4529
4528 With one of -p/--public, -d/--draft or -s/--secret, change the
4530 With one of -p/--public, -d/--draft or -s/--secret, change the
4529 phase value of the specified revisions.
4531 phase value of the specified revisions.
4530
4532
4531 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4533 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4532 lower phase to an higher phase. Phases are ordered as follows::
4534 lower phase to an higher phase. Phases are ordered as follows::
4533
4535
4534 public < draft < secret
4536 public < draft < secret
4535
4537
4536 Return 0 on success, 1 if no phases were changed or some could not
4538 Return 0 on success, 1 if no phases were changed or some could not
4537 be changed.
4539 be changed.
4538 """
4540 """
4539 # search for a unique phase argument
4541 # search for a unique phase argument
4540 targetphase = None
4542 targetphase = None
4541 for idx, name in enumerate(phases.phasenames):
4543 for idx, name in enumerate(phases.phasenames):
4542 if opts[name]:
4544 if opts[name]:
4543 if targetphase is not None:
4545 if targetphase is not None:
4544 raise util.Abort(_('only one phase can be specified'))
4546 raise util.Abort(_('only one phase can be specified'))
4545 targetphase = idx
4547 targetphase = idx
4546
4548
4547 # look for specified revision
4549 # look for specified revision
4548 revs = list(revs)
4550 revs = list(revs)
4549 revs.extend(opts['rev'])
4551 revs.extend(opts['rev'])
4550 if not revs:
4552 if not revs:
4551 raise util.Abort(_('no revisions specified'))
4553 raise util.Abort(_('no revisions specified'))
4552
4554
4553 revs = scmutil.revrange(repo, revs)
4555 revs = scmutil.revrange(repo, revs)
4554
4556
4555 lock = None
4557 lock = None
4556 ret = 0
4558 ret = 0
4557 if targetphase is None:
4559 if targetphase is None:
4558 # display
4560 # display
4559 for r in revs:
4561 for r in revs:
4560 ctx = repo[r]
4562 ctx = repo[r]
4561 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4563 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4562 else:
4564 else:
4563 lock = repo.lock()
4565 lock = repo.lock()
4564 try:
4566 try:
4565 # set phase
4567 # set phase
4566 if not revs:
4568 if not revs:
4567 raise util.Abort(_('empty revision set'))
4569 raise util.Abort(_('empty revision set'))
4568 nodes = [repo[r].node() for r in revs]
4570 nodes = [repo[r].node() for r in revs]
4569 olddata = repo._phasecache.getphaserevs(repo)[:]
4571 olddata = repo._phasecache.getphaserevs(repo)[:]
4570 phases.advanceboundary(repo, targetphase, nodes)
4572 phases.advanceboundary(repo, targetphase, nodes)
4571 if opts['force']:
4573 if opts['force']:
4572 phases.retractboundary(repo, targetphase, nodes)
4574 phases.retractboundary(repo, targetphase, nodes)
4573 finally:
4575 finally:
4574 lock.release()
4576 lock.release()
4575 newdata = repo._phasecache.getphaserevs(repo)
4577 newdata = repo._phasecache.getphaserevs(repo)
4576 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4578 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4577 rejected = [n for n in nodes
4579 rejected = [n for n in nodes
4578 if newdata[repo[n].rev()] < targetphase]
4580 if newdata[repo[n].rev()] < targetphase]
4579 if rejected:
4581 if rejected:
4580 ui.warn(_('cannot move %i changesets to a more permissive '
4582 ui.warn(_('cannot move %i changesets to a more permissive '
4581 'phase, use --force\n') % len(rejected))
4583 'phase, use --force\n') % len(rejected))
4582 ret = 1
4584 ret = 1
4583 if changes:
4585 if changes:
4584 msg = _('phase changed for %i changesets\n') % changes
4586 msg = _('phase changed for %i changesets\n') % changes
4585 if ret:
4587 if ret:
4586 ui.status(msg)
4588 ui.status(msg)
4587 else:
4589 else:
4588 ui.note(msg)
4590 ui.note(msg)
4589 else:
4591 else:
4590 ui.warn(_('no phases changed\n'))
4592 ui.warn(_('no phases changed\n'))
4591 ret = 1
4593 ret = 1
4592 return ret
4594 return ret
4593
4595
4594 def postincoming(ui, repo, modheads, optupdate, checkout):
4596 def postincoming(ui, repo, modheads, optupdate, checkout):
4595 if modheads == 0:
4597 if modheads == 0:
4596 return
4598 return
4597 if optupdate:
4599 if optupdate:
4598 movemarkfrom = repo['.'].node()
4600 movemarkfrom = repo['.'].node()
4599 try:
4601 try:
4600 ret = hg.update(repo, checkout)
4602 ret = hg.update(repo, checkout)
4601 except util.Abort, inst:
4603 except util.Abort, inst:
4602 ui.warn(_("not updating: %s\n") % str(inst))
4604 ui.warn(_("not updating: %s\n") % str(inst))
4603 return 0
4605 return 0
4604 if not ret and not checkout:
4606 if not ret and not checkout:
4605 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4607 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4606 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4608 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4607 return ret
4609 return ret
4608 if modheads > 1:
4610 if modheads > 1:
4609 currentbranchheads = len(repo.branchheads())
4611 currentbranchheads = len(repo.branchheads())
4610 if currentbranchheads == modheads:
4612 if currentbranchheads == modheads:
4611 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4613 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4612 elif currentbranchheads > 1:
4614 elif currentbranchheads > 1:
4613 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4615 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4614 "merge)\n"))
4616 "merge)\n"))
4615 else:
4617 else:
4616 ui.status(_("(run 'hg heads' to see heads)\n"))
4618 ui.status(_("(run 'hg heads' to see heads)\n"))
4617 else:
4619 else:
4618 ui.status(_("(run 'hg update' to get a working copy)\n"))
4620 ui.status(_("(run 'hg update' to get a working copy)\n"))
4619
4621
4620 @command('^pull',
4622 @command('^pull',
4621 [('u', 'update', None,
4623 [('u', 'update', None,
4622 _('update to new branch head if changesets were pulled')),
4624 _('update to new branch head if changesets were pulled')),
4623 ('f', 'force', None, _('run even when remote repository is unrelated')),
4625 ('f', 'force', None, _('run even when remote repository is unrelated')),
4624 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4626 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4625 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4627 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4626 ('b', 'branch', [], _('a specific branch you would like to pull'),
4628 ('b', 'branch', [], _('a specific branch you would like to pull'),
4627 _('BRANCH')),
4629 _('BRANCH')),
4628 ] + remoteopts,
4630 ] + remoteopts,
4629 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4631 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4630 def pull(ui, repo, source="default", **opts):
4632 def pull(ui, repo, source="default", **opts):
4631 """pull changes from the specified source
4633 """pull changes from the specified source
4632
4634
4633 Pull changes from a remote repository to a local one.
4635 Pull changes from a remote repository to a local one.
4634
4636
4635 This finds all changes from the repository at the specified path
4637 This finds all changes from the repository at the specified path
4636 or URL and adds them to a local repository (the current one unless
4638 or URL and adds them to a local repository (the current one unless
4637 -R is specified). By default, this does not update the copy of the
4639 -R is specified). By default, this does not update the copy of the
4638 project in the working directory.
4640 project in the working directory.
4639
4641
4640 Use :hg:`incoming` if you want to see what would have been added
4642 Use :hg:`incoming` if you want to see what would have been added
4641 by a pull at the time you issued this command. If you then decide
4643 by a pull at the time you issued this command. If you then decide
4642 to add those changes to the repository, you should use :hg:`pull
4644 to add those changes to the repository, you should use :hg:`pull
4643 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4645 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4644
4646
4645 If SOURCE is omitted, the 'default' path will be used.
4647 If SOURCE is omitted, the 'default' path will be used.
4646 See :hg:`help urls` for more information.
4648 See :hg:`help urls` for more information.
4647
4649
4648 Returns 0 on success, 1 if an update had unresolved files.
4650 Returns 0 on success, 1 if an update had unresolved files.
4649 """
4651 """
4650 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4652 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4651 other = hg.peer(repo, opts, source)
4653 other = hg.peer(repo, opts, source)
4652 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4654 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4653 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4655 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4654
4656
4655 if opts.get('bookmark'):
4657 if opts.get('bookmark'):
4656 if not revs:
4658 if not revs:
4657 revs = []
4659 revs = []
4658 rb = other.listkeys('bookmarks')
4660 rb = other.listkeys('bookmarks')
4659 for b in opts['bookmark']:
4661 for b in opts['bookmark']:
4660 if b not in rb:
4662 if b not in rb:
4661 raise util.Abort(_('remote bookmark %s not found!') % b)
4663 raise util.Abort(_('remote bookmark %s not found!') % b)
4662 revs.append(rb[b])
4664 revs.append(rb[b])
4663
4665
4664 if revs:
4666 if revs:
4665 try:
4667 try:
4666 revs = [other.lookup(rev) for rev in revs]
4668 revs = [other.lookup(rev) for rev in revs]
4667 except error.CapabilityError:
4669 except error.CapabilityError:
4668 err = _("other repository doesn't support revision lookup, "
4670 err = _("other repository doesn't support revision lookup, "
4669 "so a rev cannot be specified.")
4671 "so a rev cannot be specified.")
4670 raise util.Abort(err)
4672 raise util.Abort(err)
4671
4673
4672 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4674 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4673 bookmarks.updatefromremote(ui, repo, other, source)
4675 bookmarks.updatefromremote(ui, repo, other, source)
4674 if checkout:
4676 if checkout:
4675 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4677 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4676 repo._subtoppath = source
4678 repo._subtoppath = source
4677 try:
4679 try:
4678 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4680 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4679
4681
4680 finally:
4682 finally:
4681 del repo._subtoppath
4683 del repo._subtoppath
4682
4684
4683 # update specified bookmarks
4685 # update specified bookmarks
4684 if opts.get('bookmark'):
4686 if opts.get('bookmark'):
4685 marks = repo._bookmarks
4687 marks = repo._bookmarks
4686 for b in opts['bookmark']:
4688 for b in opts['bookmark']:
4687 # explicit pull overrides local bookmark if any
4689 # explicit pull overrides local bookmark if any
4688 ui.status(_("importing bookmark %s\n") % b)
4690 ui.status(_("importing bookmark %s\n") % b)
4689 marks[b] = repo[rb[b]].node()
4691 marks[b] = repo[rb[b]].node()
4690 marks.write()
4692 marks.write()
4691
4693
4692 return ret
4694 return ret
4693
4695
4694 @command('^push',
4696 @command('^push',
4695 [('f', 'force', None, _('force push')),
4697 [('f', 'force', None, _('force push')),
4696 ('r', 'rev', [],
4698 ('r', 'rev', [],
4697 _('a changeset intended to be included in the destination'),
4699 _('a changeset intended to be included in the destination'),
4698 _('REV')),
4700 _('REV')),
4699 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4701 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4700 ('b', 'branch', [],
4702 ('b', 'branch', [],
4701 _('a specific branch you would like to push'), _('BRANCH')),
4703 _('a specific branch you would like to push'), _('BRANCH')),
4702 ('', 'new-branch', False, _('allow pushing a new branch')),
4704 ('', 'new-branch', False, _('allow pushing a new branch')),
4703 ] + remoteopts,
4705 ] + remoteopts,
4704 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4706 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4705 def push(ui, repo, dest=None, **opts):
4707 def push(ui, repo, dest=None, **opts):
4706 """push changes to the specified destination
4708 """push changes to the specified destination
4707
4709
4708 Push changesets from the local repository to the specified
4710 Push changesets from the local repository to the specified
4709 destination.
4711 destination.
4710
4712
4711 This operation is symmetrical to pull: it is identical to a pull
4713 This operation is symmetrical to pull: it is identical to a pull
4712 in the destination repository from the current one.
4714 in the destination repository from the current one.
4713
4715
4714 By default, push will not allow creation of new heads at the
4716 By default, push will not allow creation of new heads at the
4715 destination, since multiple heads would make it unclear which head
4717 destination, since multiple heads would make it unclear which head
4716 to use. In this situation, it is recommended to pull and merge
4718 to use. In this situation, it is recommended to pull and merge
4717 before pushing.
4719 before pushing.
4718
4720
4719 Use --new-branch if you want to allow push to create a new named
4721 Use --new-branch if you want to allow push to create a new named
4720 branch that is not present at the destination. This allows you to
4722 branch that is not present at the destination. This allows you to
4721 only create a new branch without forcing other changes.
4723 only create a new branch without forcing other changes.
4722
4724
4723 Use -f/--force to override the default behavior and push all
4725 Use -f/--force to override the default behavior and push all
4724 changesets on all branches.
4726 changesets on all branches.
4725
4727
4726 If -r/--rev is used, the specified revision and all its ancestors
4728 If -r/--rev is used, the specified revision and all its ancestors
4727 will be pushed to the remote repository.
4729 will be pushed to the remote repository.
4728
4730
4729 If -B/--bookmark is used, the specified bookmarked revision, its
4731 If -B/--bookmark is used, the specified bookmarked revision, its
4730 ancestors, and the bookmark will be pushed to the remote
4732 ancestors, and the bookmark will be pushed to the remote
4731 repository.
4733 repository.
4732
4734
4733 Please see :hg:`help urls` for important details about ``ssh://``
4735 Please see :hg:`help urls` for important details about ``ssh://``
4734 URLs. If DESTINATION is omitted, a default path will be used.
4736 URLs. If DESTINATION is omitted, a default path will be used.
4735
4737
4736 Returns 0 if push was successful, 1 if nothing to push.
4738 Returns 0 if push was successful, 1 if nothing to push.
4737 """
4739 """
4738
4740
4739 if opts.get('bookmark'):
4741 if opts.get('bookmark'):
4740 for b in opts['bookmark']:
4742 for b in opts['bookmark']:
4741 # translate -B options to -r so changesets get pushed
4743 # translate -B options to -r so changesets get pushed
4742 if b in repo._bookmarks:
4744 if b in repo._bookmarks:
4743 opts.setdefault('rev', []).append(b)
4745 opts.setdefault('rev', []).append(b)
4744 else:
4746 else:
4745 # if we try to push a deleted bookmark, translate it to null
4747 # if we try to push a deleted bookmark, translate it to null
4746 # this lets simultaneous -r, -b options continue working
4748 # this lets simultaneous -r, -b options continue working
4747 opts.setdefault('rev', []).append("null")
4749 opts.setdefault('rev', []).append("null")
4748
4750
4749 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4751 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4750 dest, branches = hg.parseurl(dest, opts.get('branch'))
4752 dest, branches = hg.parseurl(dest, opts.get('branch'))
4751 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4753 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4752 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4754 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4753 other = hg.peer(repo, opts, dest)
4755 other = hg.peer(repo, opts, dest)
4754 if revs:
4756 if revs:
4755 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4757 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4756
4758
4757 repo._subtoppath = dest
4759 repo._subtoppath = dest
4758 try:
4760 try:
4759 # push subrepos depth-first for coherent ordering
4761 # push subrepos depth-first for coherent ordering
4760 c = repo['']
4762 c = repo['']
4761 subs = c.substate # only repos that are committed
4763 subs = c.substate # only repos that are committed
4762 for s in sorted(subs):
4764 for s in sorted(subs):
4763 if c.sub(s).push(opts) == 0:
4765 if c.sub(s).push(opts) == 0:
4764 return False
4766 return False
4765 finally:
4767 finally:
4766 del repo._subtoppath
4768 del repo._subtoppath
4767 result = repo.push(other, opts.get('force'), revs=revs,
4769 result = repo.push(other, opts.get('force'), revs=revs,
4768 newbranch=opts.get('new_branch'))
4770 newbranch=opts.get('new_branch'))
4769
4771
4770 result = not result
4772 result = not result
4771
4773
4772 if opts.get('bookmark'):
4774 if opts.get('bookmark'):
4773 rb = other.listkeys('bookmarks')
4775 rb = other.listkeys('bookmarks')
4774 for b in opts['bookmark']:
4776 for b in opts['bookmark']:
4775 # explicit push overrides remote bookmark if any
4777 # explicit push overrides remote bookmark if any
4776 if b in repo._bookmarks:
4778 if b in repo._bookmarks:
4777 ui.status(_("exporting bookmark %s\n") % b)
4779 ui.status(_("exporting bookmark %s\n") % b)
4778 new = repo[b].hex()
4780 new = repo[b].hex()
4779 elif b in rb:
4781 elif b in rb:
4780 ui.status(_("deleting remote bookmark %s\n") % b)
4782 ui.status(_("deleting remote bookmark %s\n") % b)
4781 new = '' # delete
4783 new = '' # delete
4782 else:
4784 else:
4783 ui.warn(_('bookmark %s does not exist on the local '
4785 ui.warn(_('bookmark %s does not exist on the local '
4784 'or remote repository!\n') % b)
4786 'or remote repository!\n') % b)
4785 return 2
4787 return 2
4786 old = rb.get(b, '')
4788 old = rb.get(b, '')
4787 r = other.pushkey('bookmarks', b, old, new)
4789 r = other.pushkey('bookmarks', b, old, new)
4788 if not r:
4790 if not r:
4789 ui.warn(_('updating bookmark %s failed!\n') % b)
4791 ui.warn(_('updating bookmark %s failed!\n') % b)
4790 if not result:
4792 if not result:
4791 result = 2
4793 result = 2
4792
4794
4793 return result
4795 return result
4794
4796
4795 @command('recover', [])
4797 @command('recover', [])
4796 def recover(ui, repo):
4798 def recover(ui, repo):
4797 """roll back an interrupted transaction
4799 """roll back an interrupted transaction
4798
4800
4799 Recover from an interrupted commit or pull.
4801 Recover from an interrupted commit or pull.
4800
4802
4801 This command tries to fix the repository status after an
4803 This command tries to fix the repository status after an
4802 interrupted operation. It should only be necessary when Mercurial
4804 interrupted operation. It should only be necessary when Mercurial
4803 suggests it.
4805 suggests it.
4804
4806
4805 Returns 0 if successful, 1 if nothing to recover or verify fails.
4807 Returns 0 if successful, 1 if nothing to recover or verify fails.
4806 """
4808 """
4807 if repo.recover():
4809 if repo.recover():
4808 return hg.verify(repo)
4810 return hg.verify(repo)
4809 return 1
4811 return 1
4810
4812
4811 @command('^remove|rm',
4813 @command('^remove|rm',
4812 [('A', 'after', None, _('record delete for missing files')),
4814 [('A', 'after', None, _('record delete for missing files')),
4813 ('f', 'force', None,
4815 ('f', 'force', None,
4814 _('remove (and delete) file even if added or modified')),
4816 _('remove (and delete) file even if added or modified')),
4815 ] + walkopts,
4817 ] + walkopts,
4816 _('[OPTION]... FILE...'))
4818 _('[OPTION]... FILE...'))
4817 def remove(ui, repo, *pats, **opts):
4819 def remove(ui, repo, *pats, **opts):
4818 """remove the specified files on the next commit
4820 """remove the specified files on the next commit
4819
4821
4820 Schedule the indicated files for removal from the current branch.
4822 Schedule the indicated files for removal from the current branch.
4821
4823
4822 This command schedules the files to be removed at the next commit.
4824 This command schedules the files to be removed at the next commit.
4823 To undo a remove before that, see :hg:`revert`. To undo added
4825 To undo a remove before that, see :hg:`revert`. To undo added
4824 files, see :hg:`forget`.
4826 files, see :hg:`forget`.
4825
4827
4826 .. container:: verbose
4828 .. container:: verbose
4827
4829
4828 -A/--after can be used to remove only files that have already
4830 -A/--after can be used to remove only files that have already
4829 been deleted, -f/--force can be used to force deletion, and -Af
4831 been deleted, -f/--force can be used to force deletion, and -Af
4830 can be used to remove files from the next revision without
4832 can be used to remove files from the next revision without
4831 deleting them from the working directory.
4833 deleting them from the working directory.
4832
4834
4833 The following table details the behavior of remove for different
4835 The following table details the behavior of remove for different
4834 file states (columns) and option combinations (rows). The file
4836 file states (columns) and option combinations (rows). The file
4835 states are Added [A], Clean [C], Modified [M] and Missing [!]
4837 states are Added [A], Clean [C], Modified [M] and Missing [!]
4836 (as reported by :hg:`status`). The actions are Warn, Remove
4838 (as reported by :hg:`status`). The actions are Warn, Remove
4837 (from branch) and Delete (from disk):
4839 (from branch) and Delete (from disk):
4838
4840
4839 ======= == == == ==
4841 ======= == == == ==
4840 A C M !
4842 A C M !
4841 ======= == == == ==
4843 ======= == == == ==
4842 none W RD W R
4844 none W RD W R
4843 -f R RD RD R
4845 -f R RD RD R
4844 -A W W W R
4846 -A W W W R
4845 -Af R R R R
4847 -Af R R R R
4846 ======= == == == ==
4848 ======= == == == ==
4847
4849
4848 Note that remove never deletes files in Added [A] state from the
4850 Note that remove never deletes files in Added [A] state from the
4849 working directory, not even if option --force is specified.
4851 working directory, not even if option --force is specified.
4850
4852
4851 Returns 0 on success, 1 if any warnings encountered.
4853 Returns 0 on success, 1 if any warnings encountered.
4852 """
4854 """
4853
4855
4854 ret = 0
4856 ret = 0
4855 after, force = opts.get('after'), opts.get('force')
4857 after, force = opts.get('after'), opts.get('force')
4856 if not pats and not after:
4858 if not pats and not after:
4857 raise util.Abort(_('no files specified'))
4859 raise util.Abort(_('no files specified'))
4858
4860
4859 m = scmutil.match(repo[None], pats, opts)
4861 m = scmutil.match(repo[None], pats, opts)
4860 s = repo.status(match=m, clean=True)
4862 s = repo.status(match=m, clean=True)
4861 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4863 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4862
4864
4863 # warn about failure to delete explicit files/dirs
4865 # warn about failure to delete explicit files/dirs
4864 wctx = repo[None]
4866 wctx = repo[None]
4865 for f in m.files():
4867 for f in m.files():
4866 if f in repo.dirstate or f in wctx.dirs():
4868 if f in repo.dirstate or f in wctx.dirs():
4867 continue
4869 continue
4868 if os.path.exists(m.rel(f)):
4870 if os.path.exists(m.rel(f)):
4869 if os.path.isdir(m.rel(f)):
4871 if os.path.isdir(m.rel(f)):
4870 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4872 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4871 else:
4873 else:
4872 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4874 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4873 # missing files will generate a warning elsewhere
4875 # missing files will generate a warning elsewhere
4874 ret = 1
4876 ret = 1
4875
4877
4876 if force:
4878 if force:
4877 list = modified + deleted + clean + added
4879 list = modified + deleted + clean + added
4878 elif after:
4880 elif after:
4879 list = deleted
4881 list = deleted
4880 for f in modified + added + clean:
4882 for f in modified + added + clean:
4881 ui.warn(_('not removing %s: file still exists (use -f'
4883 ui.warn(_('not removing %s: file still exists (use -f'
4882 ' to force removal)\n') % m.rel(f))
4884 ' to force removal)\n') % m.rel(f))
4883 ret = 1
4885 ret = 1
4884 else:
4886 else:
4885 list = deleted + clean
4887 list = deleted + clean
4886 for f in modified:
4888 for f in modified:
4887 ui.warn(_('not removing %s: file is modified (use -f'
4889 ui.warn(_('not removing %s: file is modified (use -f'
4888 ' to force removal)\n') % m.rel(f))
4890 ' to force removal)\n') % m.rel(f))
4889 ret = 1
4891 ret = 1
4890 for f in added:
4892 for f in added:
4891 ui.warn(_('not removing %s: file has been marked for add'
4893 ui.warn(_('not removing %s: file has been marked for add'
4892 ' (use forget to undo)\n') % m.rel(f))
4894 ' (use forget to undo)\n') % m.rel(f))
4893 ret = 1
4895 ret = 1
4894
4896
4895 for f in sorted(list):
4897 for f in sorted(list):
4896 if ui.verbose or not m.exact(f):
4898 if ui.verbose or not m.exact(f):
4897 ui.status(_('removing %s\n') % m.rel(f))
4899 ui.status(_('removing %s\n') % m.rel(f))
4898
4900
4899 wlock = repo.wlock()
4901 wlock = repo.wlock()
4900 try:
4902 try:
4901 if not after:
4903 if not after:
4902 for f in list:
4904 for f in list:
4903 if f in added:
4905 if f in added:
4904 continue # we never unlink added files on remove
4906 continue # we never unlink added files on remove
4905 try:
4907 try:
4906 util.unlinkpath(repo.wjoin(f))
4908 util.unlinkpath(repo.wjoin(f))
4907 except OSError, inst:
4909 except OSError, inst:
4908 if inst.errno != errno.ENOENT:
4910 if inst.errno != errno.ENOENT:
4909 raise
4911 raise
4910 repo[None].forget(list)
4912 repo[None].forget(list)
4911 finally:
4913 finally:
4912 wlock.release()
4914 wlock.release()
4913
4915
4914 return ret
4916 return ret
4915
4917
4916 @command('rename|move|mv',
4918 @command('rename|move|mv',
4917 [('A', 'after', None, _('record a rename that has already occurred')),
4919 [('A', 'after', None, _('record a rename that has already occurred')),
4918 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4920 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4919 ] + walkopts + dryrunopts,
4921 ] + walkopts + dryrunopts,
4920 _('[OPTION]... SOURCE... DEST'))
4922 _('[OPTION]... SOURCE... DEST'))
4921 def rename(ui, repo, *pats, **opts):
4923 def rename(ui, repo, *pats, **opts):
4922 """rename files; equivalent of copy + remove
4924 """rename files; equivalent of copy + remove
4923
4925
4924 Mark dest as copies of sources; mark sources for deletion. If dest
4926 Mark dest as copies of sources; mark sources for deletion. If dest
4925 is a directory, copies are put in that directory. If dest is a
4927 is a directory, copies are put in that directory. If dest is a
4926 file, there can only be one source.
4928 file, there can only be one source.
4927
4929
4928 By default, this command copies the contents of files as they
4930 By default, this command copies the contents of files as they
4929 exist in the working directory. If invoked with -A/--after, the
4931 exist in the working directory. If invoked with -A/--after, the
4930 operation is recorded, but no copying is performed.
4932 operation is recorded, but no copying is performed.
4931
4933
4932 This command takes effect at the next commit. To undo a rename
4934 This command takes effect at the next commit. To undo a rename
4933 before that, see :hg:`revert`.
4935 before that, see :hg:`revert`.
4934
4936
4935 Returns 0 on success, 1 if errors are encountered.
4937 Returns 0 on success, 1 if errors are encountered.
4936 """
4938 """
4937 wlock = repo.wlock(False)
4939 wlock = repo.wlock(False)
4938 try:
4940 try:
4939 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4941 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4940 finally:
4942 finally:
4941 wlock.release()
4943 wlock.release()
4942
4944
4943 @command('resolve',
4945 @command('resolve',
4944 [('a', 'all', None, _('select all unresolved files')),
4946 [('a', 'all', None, _('select all unresolved files')),
4945 ('l', 'list', None, _('list state of files needing merge')),
4947 ('l', 'list', None, _('list state of files needing merge')),
4946 ('m', 'mark', None, _('mark files as resolved')),
4948 ('m', 'mark', None, _('mark files as resolved')),
4947 ('u', 'unmark', None, _('mark files as unresolved')),
4949 ('u', 'unmark', None, _('mark files as unresolved')),
4948 ('n', 'no-status', None, _('hide status prefix'))]
4950 ('n', 'no-status', None, _('hide status prefix'))]
4949 + mergetoolopts + walkopts,
4951 + mergetoolopts + walkopts,
4950 _('[OPTION]... [FILE]...'))
4952 _('[OPTION]... [FILE]...'))
4951 def resolve(ui, repo, *pats, **opts):
4953 def resolve(ui, repo, *pats, **opts):
4952 """redo merges or set/view the merge status of files
4954 """redo merges or set/view the merge status of files
4953
4955
4954 Merges with unresolved conflicts are often the result of
4956 Merges with unresolved conflicts are often the result of
4955 non-interactive merging using the ``internal:merge`` configuration
4957 non-interactive merging using the ``internal:merge`` configuration
4956 setting, or a command-line merge tool like ``diff3``. The resolve
4958 setting, or a command-line merge tool like ``diff3``. The resolve
4957 command is used to manage the files involved in a merge, after
4959 command is used to manage the files involved in a merge, after
4958 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4960 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4959 working directory must have two parents). See :hg:`help
4961 working directory must have two parents). See :hg:`help
4960 merge-tools` for information on configuring merge tools.
4962 merge-tools` for information on configuring merge tools.
4961
4963
4962 The resolve command can be used in the following ways:
4964 The resolve command can be used in the following ways:
4963
4965
4964 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4966 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4965 files, discarding any previous merge attempts. Re-merging is not
4967 files, discarding any previous merge attempts. Re-merging is not
4966 performed for files already marked as resolved. Use ``--all/-a``
4968 performed for files already marked as resolved. Use ``--all/-a``
4967 to select all unresolved files. ``--tool`` can be used to specify
4969 to select all unresolved files. ``--tool`` can be used to specify
4968 the merge tool used for the given files. It overrides the HGMERGE
4970 the merge tool used for the given files. It overrides the HGMERGE
4969 environment variable and your configuration files. Previous file
4971 environment variable and your configuration files. Previous file
4970 contents are saved with a ``.orig`` suffix.
4972 contents are saved with a ``.orig`` suffix.
4971
4973
4972 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4974 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4973 (e.g. after having manually fixed-up the files). The default is
4975 (e.g. after having manually fixed-up the files). The default is
4974 to mark all unresolved files.
4976 to mark all unresolved files.
4975
4977
4976 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4978 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4977 default is to mark all resolved files.
4979 default is to mark all resolved files.
4978
4980
4979 - :hg:`resolve -l`: list files which had or still have conflicts.
4981 - :hg:`resolve -l`: list files which had or still have conflicts.
4980 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4982 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4981
4983
4982 Note that Mercurial will not let you commit files with unresolved
4984 Note that Mercurial will not let you commit files with unresolved
4983 merge conflicts. You must use :hg:`resolve -m ...` before you can
4985 merge conflicts. You must use :hg:`resolve -m ...` before you can
4984 commit after a conflicting merge.
4986 commit after a conflicting merge.
4985
4987
4986 Returns 0 on success, 1 if any files fail a resolve attempt.
4988 Returns 0 on success, 1 if any files fail a resolve attempt.
4987 """
4989 """
4988
4990
4989 all, mark, unmark, show, nostatus = \
4991 all, mark, unmark, show, nostatus = \
4990 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4992 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4991
4993
4992 if (show and (mark or unmark)) or (mark and unmark):
4994 if (show and (mark or unmark)) or (mark and unmark):
4993 raise util.Abort(_("too many options specified"))
4995 raise util.Abort(_("too many options specified"))
4994 if pats and all:
4996 if pats and all:
4995 raise util.Abort(_("can't specify --all and patterns"))
4997 raise util.Abort(_("can't specify --all and patterns"))
4996 if not (all or pats or show or mark or unmark):
4998 if not (all or pats or show or mark or unmark):
4997 raise util.Abort(_('no files or directories specified; '
4999 raise util.Abort(_('no files or directories specified; '
4998 'use --all to remerge all files'))
5000 'use --all to remerge all files'))
4999
5001
5000 ms = mergemod.mergestate(repo)
5002 ms = mergemod.mergestate(repo)
5001 m = scmutil.match(repo[None], pats, opts)
5003 m = scmutil.match(repo[None], pats, opts)
5002 ret = 0
5004 ret = 0
5003
5005
5004 for f in ms:
5006 for f in ms:
5005 if m(f):
5007 if m(f):
5006 if show:
5008 if show:
5007 if nostatus:
5009 if nostatus:
5008 ui.write("%s\n" % f)
5010 ui.write("%s\n" % f)
5009 else:
5011 else:
5010 ui.write("%s %s\n" % (ms[f].upper(), f),
5012 ui.write("%s %s\n" % (ms[f].upper(), f),
5011 label='resolve.' +
5013 label='resolve.' +
5012 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5014 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5013 elif mark:
5015 elif mark:
5014 ms.mark(f, "r")
5016 ms.mark(f, "r")
5015 elif unmark:
5017 elif unmark:
5016 ms.mark(f, "u")
5018 ms.mark(f, "u")
5017 else:
5019 else:
5018 wctx = repo[None]
5020 wctx = repo[None]
5019 mctx = wctx.parents()[-1]
5021 mctx = wctx.parents()[-1]
5020
5022
5021 # backup pre-resolve (merge uses .orig for its own purposes)
5023 # backup pre-resolve (merge uses .orig for its own purposes)
5022 a = repo.wjoin(f)
5024 a = repo.wjoin(f)
5023 util.copyfile(a, a + ".resolve")
5025 util.copyfile(a, a + ".resolve")
5024
5026
5025 try:
5027 try:
5026 # resolve file
5028 # resolve file
5027 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
5029 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
5028 if ms.resolve(f, wctx, mctx):
5030 if ms.resolve(f, wctx, mctx):
5029 ret = 1
5031 ret = 1
5030 finally:
5032 finally:
5031 ui.setconfig('ui', 'forcemerge', '')
5033 ui.setconfig('ui', 'forcemerge', '')
5032 ms.commit()
5034 ms.commit()
5033
5035
5034 # replace filemerge's .orig file with our resolve file
5036 # replace filemerge's .orig file with our resolve file
5035 util.rename(a + ".resolve", a + ".orig")
5037 util.rename(a + ".resolve", a + ".orig")
5036
5038
5037 ms.commit()
5039 ms.commit()
5038 return ret
5040 return ret
5039
5041
5040 @command('revert',
5042 @command('revert',
5041 [('a', 'all', None, _('revert all changes when no arguments given')),
5043 [('a', 'all', None, _('revert all changes when no arguments given')),
5042 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5044 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5043 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5045 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5044 ('C', 'no-backup', None, _('do not save backup copies of files')),
5046 ('C', 'no-backup', None, _('do not save backup copies of files')),
5045 ] + walkopts + dryrunopts,
5047 ] + walkopts + dryrunopts,
5046 _('[OPTION]... [-r REV] [NAME]...'))
5048 _('[OPTION]... [-r REV] [NAME]...'))
5047 def revert(ui, repo, *pats, **opts):
5049 def revert(ui, repo, *pats, **opts):
5048 """restore files to their checkout state
5050 """restore files to their checkout state
5049
5051
5050 .. note::
5052 .. note::
5051
5053
5052 To check out earlier revisions, you should use :hg:`update REV`.
5054 To check out earlier revisions, you should use :hg:`update REV`.
5053 To cancel an uncommitted merge (and lose your changes), use
5055 To cancel an uncommitted merge (and lose your changes), use
5054 :hg:`update --clean .`.
5056 :hg:`update --clean .`.
5055
5057
5056 With no revision specified, revert the specified files or directories
5058 With no revision specified, revert the specified files or directories
5057 to the contents they had in the parent of the working directory.
5059 to the contents they had in the parent of the working directory.
5058 This restores the contents of files to an unmodified
5060 This restores the contents of files to an unmodified
5059 state and unschedules adds, removes, copies, and renames. If the
5061 state and unschedules adds, removes, copies, and renames. If the
5060 working directory has two parents, you must explicitly specify a
5062 working directory has two parents, you must explicitly specify a
5061 revision.
5063 revision.
5062
5064
5063 Using the -r/--rev or -d/--date options, revert the given files or
5065 Using the -r/--rev or -d/--date options, revert the given files or
5064 directories to their states as of a specific revision. Because
5066 directories to their states as of a specific revision. Because
5065 revert does not change the working directory parents, this will
5067 revert does not change the working directory parents, this will
5066 cause these files to appear modified. This can be helpful to "back
5068 cause these files to appear modified. This can be helpful to "back
5067 out" some or all of an earlier change. See :hg:`backout` for a
5069 out" some or all of an earlier change. See :hg:`backout` for a
5068 related method.
5070 related method.
5069
5071
5070 Modified files are saved with a .orig suffix before reverting.
5072 Modified files are saved with a .orig suffix before reverting.
5071 To disable these backups, use --no-backup.
5073 To disable these backups, use --no-backup.
5072
5074
5073 See :hg:`help dates` for a list of formats valid for -d/--date.
5075 See :hg:`help dates` for a list of formats valid for -d/--date.
5074
5076
5075 Returns 0 on success.
5077 Returns 0 on success.
5076 """
5078 """
5077
5079
5078 if opts.get("date"):
5080 if opts.get("date"):
5079 if opts.get("rev"):
5081 if opts.get("rev"):
5080 raise util.Abort(_("you can't specify a revision and a date"))
5082 raise util.Abort(_("you can't specify a revision and a date"))
5081 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5083 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5082
5084
5083 parent, p2 = repo.dirstate.parents()
5085 parent, p2 = repo.dirstate.parents()
5084 if not opts.get('rev') and p2 != nullid:
5086 if not opts.get('rev') and p2 != nullid:
5085 # revert after merge is a trap for new users (issue2915)
5087 # revert after merge is a trap for new users (issue2915)
5086 raise util.Abort(_('uncommitted merge with no revision specified'),
5088 raise util.Abort(_('uncommitted merge with no revision specified'),
5087 hint=_('use "hg update" or see "hg help revert"'))
5089 hint=_('use "hg update" or see "hg help revert"'))
5088
5090
5089 ctx = scmutil.revsingle(repo, opts.get('rev'))
5091 ctx = scmutil.revsingle(repo, opts.get('rev'))
5090
5092
5091 if not pats and not opts.get('all'):
5093 if not pats and not opts.get('all'):
5092 msg = _("no files or directories specified")
5094 msg = _("no files or directories specified")
5093 if p2 != nullid:
5095 if p2 != nullid:
5094 hint = _("uncommitted merge, use --all to discard all changes,"
5096 hint = _("uncommitted merge, use --all to discard all changes,"
5095 " or 'hg update -C .' to abort the merge")
5097 " or 'hg update -C .' to abort the merge")
5096 raise util.Abort(msg, hint=hint)
5098 raise util.Abort(msg, hint=hint)
5097 dirty = util.any(repo.status())
5099 dirty = util.any(repo.status())
5098 node = ctx.node()
5100 node = ctx.node()
5099 if node != parent:
5101 if node != parent:
5100 if dirty:
5102 if dirty:
5101 hint = _("uncommitted changes, use --all to discard all"
5103 hint = _("uncommitted changes, use --all to discard all"
5102 " changes, or 'hg update %s' to update") % ctx.rev()
5104 " changes, or 'hg update %s' to update") % ctx.rev()
5103 else:
5105 else:
5104 hint = _("use --all to revert all files,"
5106 hint = _("use --all to revert all files,"
5105 " or 'hg update %s' to update") % ctx.rev()
5107 " or 'hg update %s' to update") % ctx.rev()
5106 elif dirty:
5108 elif dirty:
5107 hint = _("uncommitted changes, use --all to discard all changes")
5109 hint = _("uncommitted changes, use --all to discard all changes")
5108 else:
5110 else:
5109 hint = _("use --all to revert all files")
5111 hint = _("use --all to revert all files")
5110 raise util.Abort(msg, hint=hint)
5112 raise util.Abort(msg, hint=hint)
5111
5113
5112 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5114 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5113
5115
5114 @command('rollback', dryrunopts +
5116 @command('rollback', dryrunopts +
5115 [('f', 'force', False, _('ignore safety measures'))])
5117 [('f', 'force', False, _('ignore safety measures'))])
5116 def rollback(ui, repo, **opts):
5118 def rollback(ui, repo, **opts):
5117 """roll back the last transaction (dangerous)
5119 """roll back the last transaction (dangerous)
5118
5120
5119 This command should be used with care. There is only one level of
5121 This command should be used with care. There is only one level of
5120 rollback, and there is no way to undo a rollback. It will also
5122 rollback, and there is no way to undo a rollback. It will also
5121 restore the dirstate at the time of the last transaction, losing
5123 restore the dirstate at the time of the last transaction, losing
5122 any dirstate changes since that time. This command does not alter
5124 any dirstate changes since that time. This command does not alter
5123 the working directory.
5125 the working directory.
5124
5126
5125 Transactions are used to encapsulate the effects of all commands
5127 Transactions are used to encapsulate the effects of all commands
5126 that create new changesets or propagate existing changesets into a
5128 that create new changesets or propagate existing changesets into a
5127 repository.
5129 repository.
5128
5130
5129 .. container:: verbose
5131 .. container:: verbose
5130
5132
5131 For example, the following commands are transactional, and their
5133 For example, the following commands are transactional, and their
5132 effects can be rolled back:
5134 effects can be rolled back:
5133
5135
5134 - commit
5136 - commit
5135 - import
5137 - import
5136 - pull
5138 - pull
5137 - push (with this repository as the destination)
5139 - push (with this repository as the destination)
5138 - unbundle
5140 - unbundle
5139
5141
5140 To avoid permanent data loss, rollback will refuse to rollback a
5142 To avoid permanent data loss, rollback will refuse to rollback a
5141 commit transaction if it isn't checked out. Use --force to
5143 commit transaction if it isn't checked out. Use --force to
5142 override this protection.
5144 override this protection.
5143
5145
5144 This command is not intended for use on public repositories. Once
5146 This command is not intended for use on public repositories. Once
5145 changes are visible for pull by other users, rolling a transaction
5147 changes are visible for pull by other users, rolling a transaction
5146 back locally is ineffective (someone else may already have pulled
5148 back locally is ineffective (someone else may already have pulled
5147 the changes). Furthermore, a race is possible with readers of the
5149 the changes). Furthermore, a race is possible with readers of the
5148 repository; for example an in-progress pull from the repository
5150 repository; for example an in-progress pull from the repository
5149 may fail if a rollback is performed.
5151 may fail if a rollback is performed.
5150
5152
5151 Returns 0 on success, 1 if no rollback data is available.
5153 Returns 0 on success, 1 if no rollback data is available.
5152 """
5154 """
5153 return repo.rollback(dryrun=opts.get('dry_run'),
5155 return repo.rollback(dryrun=opts.get('dry_run'),
5154 force=opts.get('force'))
5156 force=opts.get('force'))
5155
5157
5156 @command('root', [])
5158 @command('root', [])
5157 def root(ui, repo):
5159 def root(ui, repo):
5158 """print the root (top) of the current working directory
5160 """print the root (top) of the current working directory
5159
5161
5160 Print the root directory of the current repository.
5162 Print the root directory of the current repository.
5161
5163
5162 Returns 0 on success.
5164 Returns 0 on success.
5163 """
5165 """
5164 ui.write(repo.root + "\n")
5166 ui.write(repo.root + "\n")
5165
5167
5166 @command('^serve',
5168 @command('^serve',
5167 [('A', 'accesslog', '', _('name of access log file to write to'),
5169 [('A', 'accesslog', '', _('name of access log file to write to'),
5168 _('FILE')),
5170 _('FILE')),
5169 ('d', 'daemon', None, _('run server in background')),
5171 ('d', 'daemon', None, _('run server in background')),
5170 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5172 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5171 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5173 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5172 # use string type, then we can check if something was passed
5174 # use string type, then we can check if something was passed
5173 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5175 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5174 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5176 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5175 _('ADDR')),
5177 _('ADDR')),
5176 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5178 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5177 _('PREFIX')),
5179 _('PREFIX')),
5178 ('n', 'name', '',
5180 ('n', 'name', '',
5179 _('name to show in web pages (default: working directory)'), _('NAME')),
5181 _('name to show in web pages (default: working directory)'), _('NAME')),
5180 ('', 'web-conf', '',
5182 ('', 'web-conf', '',
5181 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5183 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5182 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5184 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5183 _('FILE')),
5185 _('FILE')),
5184 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5186 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5185 ('', 'stdio', None, _('for remote clients')),
5187 ('', 'stdio', None, _('for remote clients')),
5186 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5188 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5187 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5189 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5188 ('', 'style', '', _('template style to use'), _('STYLE')),
5190 ('', 'style', '', _('template style to use'), _('STYLE')),
5189 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5191 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5190 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5192 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5191 _('[OPTION]...'))
5193 _('[OPTION]...'))
5192 def serve(ui, repo, **opts):
5194 def serve(ui, repo, **opts):
5193 """start stand-alone webserver
5195 """start stand-alone webserver
5194
5196
5195 Start a local HTTP repository browser and pull server. You can use
5197 Start a local HTTP repository browser and pull server. You can use
5196 this for ad-hoc sharing and browsing of repositories. It is
5198 this for ad-hoc sharing and browsing of repositories. It is
5197 recommended to use a real web server to serve a repository for
5199 recommended to use a real web server to serve a repository for
5198 longer periods of time.
5200 longer periods of time.
5199
5201
5200 Please note that the server does not implement access control.
5202 Please note that the server does not implement access control.
5201 This means that, by default, anybody can read from the server and
5203 This means that, by default, anybody can read from the server and
5202 nobody can write to it by default. Set the ``web.allow_push``
5204 nobody can write to it by default. Set the ``web.allow_push``
5203 option to ``*`` to allow everybody to push to the server. You
5205 option to ``*`` to allow everybody to push to the server. You
5204 should use a real web server if you need to authenticate users.
5206 should use a real web server if you need to authenticate users.
5205
5207
5206 By default, the server logs accesses to stdout and errors to
5208 By default, the server logs accesses to stdout and errors to
5207 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5209 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5208 files.
5210 files.
5209
5211
5210 To have the server choose a free port number to listen on, specify
5212 To have the server choose a free port number to listen on, specify
5211 a port number of 0; in this case, the server will print the port
5213 a port number of 0; in this case, the server will print the port
5212 number it uses.
5214 number it uses.
5213
5215
5214 Returns 0 on success.
5216 Returns 0 on success.
5215 """
5217 """
5216
5218
5217 if opts["stdio"] and opts["cmdserver"]:
5219 if opts["stdio"] and opts["cmdserver"]:
5218 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5220 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5219
5221
5220 def checkrepo():
5222 def checkrepo():
5221 if repo is None:
5223 if repo is None:
5222 raise error.RepoError(_("there is no Mercurial repository here"
5224 raise error.RepoError(_("there is no Mercurial repository here"
5223 " (.hg not found)"))
5225 " (.hg not found)"))
5224
5226
5225 if opts["stdio"]:
5227 if opts["stdio"]:
5226 checkrepo()
5228 checkrepo()
5227 s = sshserver.sshserver(ui, repo)
5229 s = sshserver.sshserver(ui, repo)
5228 s.serve_forever()
5230 s.serve_forever()
5229
5231
5230 if opts["cmdserver"]:
5232 if opts["cmdserver"]:
5231 checkrepo()
5233 checkrepo()
5232 s = commandserver.server(ui, repo, opts["cmdserver"])
5234 s = commandserver.server(ui, repo, opts["cmdserver"])
5233 return s.serve()
5235 return s.serve()
5234
5236
5235 # this way we can check if something was given in the command-line
5237 # this way we can check if something was given in the command-line
5236 if opts.get('port'):
5238 if opts.get('port'):
5237 opts['port'] = util.getport(opts.get('port'))
5239 opts['port'] = util.getport(opts.get('port'))
5238
5240
5239 baseui = repo and repo.baseui or ui
5241 baseui = repo and repo.baseui or ui
5240 optlist = ("name templates style address port prefix ipv6"
5242 optlist = ("name templates style address port prefix ipv6"
5241 " accesslog errorlog certificate encoding")
5243 " accesslog errorlog certificate encoding")
5242 for o in optlist.split():
5244 for o in optlist.split():
5243 val = opts.get(o, '')
5245 val = opts.get(o, '')
5244 if val in (None, ''): # should check against default options instead
5246 if val in (None, ''): # should check against default options instead
5245 continue
5247 continue
5246 baseui.setconfig("web", o, val)
5248 baseui.setconfig("web", o, val)
5247 if repo and repo.ui != baseui:
5249 if repo and repo.ui != baseui:
5248 repo.ui.setconfig("web", o, val)
5250 repo.ui.setconfig("web", o, val)
5249
5251
5250 o = opts.get('web_conf') or opts.get('webdir_conf')
5252 o = opts.get('web_conf') or opts.get('webdir_conf')
5251 if not o:
5253 if not o:
5252 if not repo:
5254 if not repo:
5253 raise error.RepoError(_("there is no Mercurial repository"
5255 raise error.RepoError(_("there is no Mercurial repository"
5254 " here (.hg not found)"))
5256 " here (.hg not found)"))
5255 o = repo.root
5257 o = repo.root
5256
5258
5257 app = hgweb.hgweb(o, baseui=ui)
5259 app = hgweb.hgweb(o, baseui=ui)
5258
5260
5259 class service(object):
5261 class service(object):
5260 def init(self):
5262 def init(self):
5261 util.setsignalhandler()
5263 util.setsignalhandler()
5262 self.httpd = hgweb.server.create_server(ui, app)
5264 self.httpd = hgweb.server.create_server(ui, app)
5263
5265
5264 if opts['port'] and not ui.verbose:
5266 if opts['port'] and not ui.verbose:
5265 return
5267 return
5266
5268
5267 if self.httpd.prefix:
5269 if self.httpd.prefix:
5268 prefix = self.httpd.prefix.strip('/') + '/'
5270 prefix = self.httpd.prefix.strip('/') + '/'
5269 else:
5271 else:
5270 prefix = ''
5272 prefix = ''
5271
5273
5272 port = ':%d' % self.httpd.port
5274 port = ':%d' % self.httpd.port
5273 if port == ':80':
5275 if port == ':80':
5274 port = ''
5276 port = ''
5275
5277
5276 bindaddr = self.httpd.addr
5278 bindaddr = self.httpd.addr
5277 if bindaddr == '0.0.0.0':
5279 if bindaddr == '0.0.0.0':
5278 bindaddr = '*'
5280 bindaddr = '*'
5279 elif ':' in bindaddr: # IPv6
5281 elif ':' in bindaddr: # IPv6
5280 bindaddr = '[%s]' % bindaddr
5282 bindaddr = '[%s]' % bindaddr
5281
5283
5282 fqaddr = self.httpd.fqaddr
5284 fqaddr = self.httpd.fqaddr
5283 if ':' in fqaddr:
5285 if ':' in fqaddr:
5284 fqaddr = '[%s]' % fqaddr
5286 fqaddr = '[%s]' % fqaddr
5285 if opts['port']:
5287 if opts['port']:
5286 write = ui.status
5288 write = ui.status
5287 else:
5289 else:
5288 write = ui.write
5290 write = ui.write
5289 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5291 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5290 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5292 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5291
5293
5292 def run(self):
5294 def run(self):
5293 self.httpd.serve_forever()
5295 self.httpd.serve_forever()
5294
5296
5295 service = service()
5297 service = service()
5296
5298
5297 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5299 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5298
5300
5299 @command('showconfig|debugconfig',
5301 @command('showconfig|debugconfig',
5300 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5302 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5301 _('[-u] [NAME]...'))
5303 _('[-u] [NAME]...'))
5302 def showconfig(ui, repo, *values, **opts):
5304 def showconfig(ui, repo, *values, **opts):
5303 """show combined config settings from all hgrc files
5305 """show combined config settings from all hgrc files
5304
5306
5305 With no arguments, print names and values of all config items.
5307 With no arguments, print names and values of all config items.
5306
5308
5307 With one argument of the form section.name, print just the value
5309 With one argument of the form section.name, print just the value
5308 of that config item.
5310 of that config item.
5309
5311
5310 With multiple arguments, print names and values of all config
5312 With multiple arguments, print names and values of all config
5311 items with matching section names.
5313 items with matching section names.
5312
5314
5313 With --debug, the source (filename and line number) is printed
5315 With --debug, the source (filename and line number) is printed
5314 for each config item.
5316 for each config item.
5315
5317
5316 Returns 0 on success.
5318 Returns 0 on success.
5317 """
5319 """
5318
5320
5319 for f in scmutil.rcpath():
5321 for f in scmutil.rcpath():
5320 ui.debug('read config from: %s\n' % f)
5322 ui.debug('read config from: %s\n' % f)
5321 untrusted = bool(opts.get('untrusted'))
5323 untrusted = bool(opts.get('untrusted'))
5322 if values:
5324 if values:
5323 sections = [v for v in values if '.' not in v]
5325 sections = [v for v in values if '.' not in v]
5324 items = [v for v in values if '.' in v]
5326 items = [v for v in values if '.' in v]
5325 if len(items) > 1 or items and sections:
5327 if len(items) > 1 or items and sections:
5326 raise util.Abort(_('only one config item permitted'))
5328 raise util.Abort(_('only one config item permitted'))
5327 for section, name, value in ui.walkconfig(untrusted=untrusted):
5329 for section, name, value in ui.walkconfig(untrusted=untrusted):
5328 value = str(value).replace('\n', '\\n')
5330 value = str(value).replace('\n', '\\n')
5329 sectname = section + '.' + name
5331 sectname = section + '.' + name
5330 if values:
5332 if values:
5331 for v in values:
5333 for v in values:
5332 if v == section:
5334 if v == section:
5333 ui.debug('%s: ' %
5335 ui.debug('%s: ' %
5334 ui.configsource(section, name, untrusted))
5336 ui.configsource(section, name, untrusted))
5335 ui.write('%s=%s\n' % (sectname, value))
5337 ui.write('%s=%s\n' % (sectname, value))
5336 elif v == sectname:
5338 elif v == sectname:
5337 ui.debug('%s: ' %
5339 ui.debug('%s: ' %
5338 ui.configsource(section, name, untrusted))
5340 ui.configsource(section, name, untrusted))
5339 ui.write(value, '\n')
5341 ui.write(value, '\n')
5340 else:
5342 else:
5341 ui.debug('%s: ' %
5343 ui.debug('%s: ' %
5342 ui.configsource(section, name, untrusted))
5344 ui.configsource(section, name, untrusted))
5343 ui.write('%s=%s\n' % (sectname, value))
5345 ui.write('%s=%s\n' % (sectname, value))
5344
5346
5345 @command('^status|st',
5347 @command('^status|st',
5346 [('A', 'all', None, _('show status of all files')),
5348 [('A', 'all', None, _('show status of all files')),
5347 ('m', 'modified', None, _('show only modified files')),
5349 ('m', 'modified', None, _('show only modified files')),
5348 ('a', 'added', None, _('show only added files')),
5350 ('a', 'added', None, _('show only added files')),
5349 ('r', 'removed', None, _('show only removed files')),
5351 ('r', 'removed', None, _('show only removed files')),
5350 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5352 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5351 ('c', 'clean', None, _('show only files without changes')),
5353 ('c', 'clean', None, _('show only files without changes')),
5352 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5354 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5353 ('i', 'ignored', None, _('show only ignored files')),
5355 ('i', 'ignored', None, _('show only ignored files')),
5354 ('n', 'no-status', None, _('hide status prefix')),
5356 ('n', 'no-status', None, _('hide status prefix')),
5355 ('C', 'copies', None, _('show source of copied files')),
5357 ('C', 'copies', None, _('show source of copied files')),
5356 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5358 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5357 ('', 'rev', [], _('show difference from revision'), _('REV')),
5359 ('', 'rev', [], _('show difference from revision'), _('REV')),
5358 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5360 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5359 ] + walkopts + subrepoopts,
5361 ] + walkopts + subrepoopts,
5360 _('[OPTION]... [FILE]...'))
5362 _('[OPTION]... [FILE]...'))
5361 def status(ui, repo, *pats, **opts):
5363 def status(ui, repo, *pats, **opts):
5362 """show changed files in the working directory
5364 """show changed files in the working directory
5363
5365
5364 Show status of files in the repository. If names are given, only
5366 Show status of files in the repository. If names are given, only
5365 files that match are shown. Files that are clean or ignored or
5367 files that match are shown. Files that are clean or ignored or
5366 the source of a copy/move operation, are not listed unless
5368 the source of a copy/move operation, are not listed unless
5367 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5369 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5368 Unless options described with "show only ..." are given, the
5370 Unless options described with "show only ..." are given, the
5369 options -mardu are used.
5371 options -mardu are used.
5370
5372
5371 Option -q/--quiet hides untracked (unknown and ignored) files
5373 Option -q/--quiet hides untracked (unknown and ignored) files
5372 unless explicitly requested with -u/--unknown or -i/--ignored.
5374 unless explicitly requested with -u/--unknown or -i/--ignored.
5373
5375
5374 .. note::
5376 .. note::
5375 status may appear to disagree with diff if permissions have
5377 status may appear to disagree with diff if permissions have
5376 changed or a merge has occurred. The standard diff format does
5378 changed or a merge has occurred. The standard diff format does
5377 not report permission changes and diff only reports changes
5379 not report permission changes and diff only reports changes
5378 relative to one merge parent.
5380 relative to one merge parent.
5379
5381
5380 If one revision is given, it is used as the base revision.
5382 If one revision is given, it is used as the base revision.
5381 If two revisions are given, the differences between them are
5383 If two revisions are given, the differences between them are
5382 shown. The --change option can also be used as a shortcut to list
5384 shown. The --change option can also be used as a shortcut to list
5383 the changed files of a revision from its first parent.
5385 the changed files of a revision from its first parent.
5384
5386
5385 The codes used to show the status of files are::
5387 The codes used to show the status of files are::
5386
5388
5387 M = modified
5389 M = modified
5388 A = added
5390 A = added
5389 R = removed
5391 R = removed
5390 C = clean
5392 C = clean
5391 ! = missing (deleted by non-hg command, but still tracked)
5393 ! = missing (deleted by non-hg command, but still tracked)
5392 ? = not tracked
5394 ? = not tracked
5393 I = ignored
5395 I = ignored
5394 = origin of the previous file listed as A (added)
5396 = origin of the previous file listed as A (added)
5395
5397
5396 .. container:: verbose
5398 .. container:: verbose
5397
5399
5398 Examples:
5400 Examples:
5399
5401
5400 - show changes in the working directory relative to a
5402 - show changes in the working directory relative to a
5401 changeset::
5403 changeset::
5402
5404
5403 hg status --rev 9353
5405 hg status --rev 9353
5404
5406
5405 - show all changes including copies in an existing changeset::
5407 - show all changes including copies in an existing changeset::
5406
5408
5407 hg status --copies --change 9353
5409 hg status --copies --change 9353
5408
5410
5409 - get a NUL separated list of added files, suitable for xargs::
5411 - get a NUL separated list of added files, suitable for xargs::
5410
5412
5411 hg status -an0
5413 hg status -an0
5412
5414
5413 Returns 0 on success.
5415 Returns 0 on success.
5414 """
5416 """
5415
5417
5416 revs = opts.get('rev')
5418 revs = opts.get('rev')
5417 change = opts.get('change')
5419 change = opts.get('change')
5418
5420
5419 if revs and change:
5421 if revs and change:
5420 msg = _('cannot specify --rev and --change at the same time')
5422 msg = _('cannot specify --rev and --change at the same time')
5421 raise util.Abort(msg)
5423 raise util.Abort(msg)
5422 elif change:
5424 elif change:
5423 node2 = scmutil.revsingle(repo, change, None).node()
5425 node2 = scmutil.revsingle(repo, change, None).node()
5424 node1 = repo[node2].p1().node()
5426 node1 = repo[node2].p1().node()
5425 else:
5427 else:
5426 node1, node2 = scmutil.revpair(repo, revs)
5428 node1, node2 = scmutil.revpair(repo, revs)
5427
5429
5428 cwd = (pats and repo.getcwd()) or ''
5430 cwd = (pats and repo.getcwd()) or ''
5429 end = opts.get('print0') and '\0' or '\n'
5431 end = opts.get('print0') and '\0' or '\n'
5430 copy = {}
5432 copy = {}
5431 states = 'modified added removed deleted unknown ignored clean'.split()
5433 states = 'modified added removed deleted unknown ignored clean'.split()
5432 show = [k for k in states if opts.get(k)]
5434 show = [k for k in states if opts.get(k)]
5433 if opts.get('all'):
5435 if opts.get('all'):
5434 show += ui.quiet and (states[:4] + ['clean']) or states
5436 show += ui.quiet and (states[:4] + ['clean']) or states
5435 if not show:
5437 if not show:
5436 show = ui.quiet and states[:4] or states[:5]
5438 show = ui.quiet and states[:4] or states[:5]
5437
5439
5438 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5440 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5439 'ignored' in show, 'clean' in show, 'unknown' in show,
5441 'ignored' in show, 'clean' in show, 'unknown' in show,
5440 opts.get('subrepos'))
5442 opts.get('subrepos'))
5441 changestates = zip(states, 'MAR!?IC', stat)
5443 changestates = zip(states, 'MAR!?IC', stat)
5442
5444
5443 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5445 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5444 copy = copies.pathcopies(repo[node1], repo[node2])
5446 copy = copies.pathcopies(repo[node1], repo[node2])
5445
5447
5446 fm = ui.formatter('status', opts)
5448 fm = ui.formatter('status', opts)
5447 fmt = '%s' + end
5449 fmt = '%s' + end
5448 showchar = not opts.get('no_status')
5450 showchar = not opts.get('no_status')
5449
5451
5450 for state, char, files in changestates:
5452 for state, char, files in changestates:
5451 if state in show:
5453 if state in show:
5452 label = 'status.' + state
5454 label = 'status.' + state
5453 for f in files:
5455 for f in files:
5454 fm.startitem()
5456 fm.startitem()
5455 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5457 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5456 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5458 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5457 if f in copy:
5459 if f in copy:
5458 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5460 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5459 label='status.copied')
5461 label='status.copied')
5460 fm.end()
5462 fm.end()
5461
5463
5462 @command('^summary|sum',
5464 @command('^summary|sum',
5463 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5465 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5464 def summary(ui, repo, **opts):
5466 def summary(ui, repo, **opts):
5465 """summarize working directory state
5467 """summarize working directory state
5466
5468
5467 This generates a brief summary of the working directory state,
5469 This generates a brief summary of the working directory state,
5468 including parents, branch, commit status, and available updates.
5470 including parents, branch, commit status, and available updates.
5469
5471
5470 With the --remote option, this will check the default paths for
5472 With the --remote option, this will check the default paths for
5471 incoming and outgoing changes. This can be time-consuming.
5473 incoming and outgoing changes. This can be time-consuming.
5472
5474
5473 Returns 0 on success.
5475 Returns 0 on success.
5474 """
5476 """
5475
5477
5476 ctx = repo[None]
5478 ctx = repo[None]
5477 parents = ctx.parents()
5479 parents = ctx.parents()
5478 pnode = parents[0].node()
5480 pnode = parents[0].node()
5479 marks = []
5481 marks = []
5480
5482
5481 for p in parents:
5483 for p in parents:
5482 # label with log.changeset (instead of log.parent) since this
5484 # label with log.changeset (instead of log.parent) since this
5483 # shows a working directory parent *changeset*:
5485 # shows a working directory parent *changeset*:
5484 # i18n: column positioning for "hg summary"
5486 # i18n: column positioning for "hg summary"
5485 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5487 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5486 label='log.changeset changeset.%s' % p.phasestr())
5488 label='log.changeset changeset.%s' % p.phasestr())
5487 ui.write(' '.join(p.tags()), label='log.tag')
5489 ui.write(' '.join(p.tags()), label='log.tag')
5488 if p.bookmarks():
5490 if p.bookmarks():
5489 marks.extend(p.bookmarks())
5491 marks.extend(p.bookmarks())
5490 if p.rev() == -1:
5492 if p.rev() == -1:
5491 if not len(repo):
5493 if not len(repo):
5492 ui.write(_(' (empty repository)'))
5494 ui.write(_(' (empty repository)'))
5493 else:
5495 else:
5494 ui.write(_(' (no revision checked out)'))
5496 ui.write(_(' (no revision checked out)'))
5495 ui.write('\n')
5497 ui.write('\n')
5496 if p.description():
5498 if p.description():
5497 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5499 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5498 label='log.summary')
5500 label='log.summary')
5499
5501
5500 branch = ctx.branch()
5502 branch = ctx.branch()
5501 bheads = repo.branchheads(branch)
5503 bheads = repo.branchheads(branch)
5502 # i18n: column positioning for "hg summary"
5504 # i18n: column positioning for "hg summary"
5503 m = _('branch: %s\n') % branch
5505 m = _('branch: %s\n') % branch
5504 if branch != 'default':
5506 if branch != 'default':
5505 ui.write(m, label='log.branch')
5507 ui.write(m, label='log.branch')
5506 else:
5508 else:
5507 ui.status(m, label='log.branch')
5509 ui.status(m, label='log.branch')
5508
5510
5509 if marks:
5511 if marks:
5510 current = repo._bookmarkcurrent
5512 current = repo._bookmarkcurrent
5511 # i18n: column positioning for "hg summary"
5513 # i18n: column positioning for "hg summary"
5512 ui.write(_('bookmarks:'), label='log.bookmark')
5514 ui.write(_('bookmarks:'), label='log.bookmark')
5513 if current is not None:
5515 if current is not None:
5514 try:
5516 try:
5515 marks.remove(current)
5517 marks.remove(current)
5516 ui.write(' *' + current, label='bookmarks.current')
5518 ui.write(' *' + current, label='bookmarks.current')
5517 except ValueError:
5519 except ValueError:
5518 # current bookmark not in parent ctx marks
5520 # current bookmark not in parent ctx marks
5519 pass
5521 pass
5520 for m in marks:
5522 for m in marks:
5521 ui.write(' ' + m, label='log.bookmark')
5523 ui.write(' ' + m, label='log.bookmark')
5522 ui.write('\n', label='log.bookmark')
5524 ui.write('\n', label='log.bookmark')
5523
5525
5524 st = list(repo.status(unknown=True))[:6]
5526 st = list(repo.status(unknown=True))[:6]
5525
5527
5526 c = repo.dirstate.copies()
5528 c = repo.dirstate.copies()
5527 copied, renamed = [], []
5529 copied, renamed = [], []
5528 for d, s in c.iteritems():
5530 for d, s in c.iteritems():
5529 if s in st[2]:
5531 if s in st[2]:
5530 st[2].remove(s)
5532 st[2].remove(s)
5531 renamed.append(d)
5533 renamed.append(d)
5532 else:
5534 else:
5533 copied.append(d)
5535 copied.append(d)
5534 if d in st[1]:
5536 if d in st[1]:
5535 st[1].remove(d)
5537 st[1].remove(d)
5536 st.insert(3, renamed)
5538 st.insert(3, renamed)
5537 st.insert(4, copied)
5539 st.insert(4, copied)
5538
5540
5539 ms = mergemod.mergestate(repo)
5541 ms = mergemod.mergestate(repo)
5540 st.append([f for f in ms if ms[f] == 'u'])
5542 st.append([f for f in ms if ms[f] == 'u'])
5541
5543
5542 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5544 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5543 st.append(subs)
5545 st.append(subs)
5544
5546
5545 labels = [ui.label(_('%d modified'), 'status.modified'),
5547 labels = [ui.label(_('%d modified'), 'status.modified'),
5546 ui.label(_('%d added'), 'status.added'),
5548 ui.label(_('%d added'), 'status.added'),
5547 ui.label(_('%d removed'), 'status.removed'),
5549 ui.label(_('%d removed'), 'status.removed'),
5548 ui.label(_('%d renamed'), 'status.copied'),
5550 ui.label(_('%d renamed'), 'status.copied'),
5549 ui.label(_('%d copied'), 'status.copied'),
5551 ui.label(_('%d copied'), 'status.copied'),
5550 ui.label(_('%d deleted'), 'status.deleted'),
5552 ui.label(_('%d deleted'), 'status.deleted'),
5551 ui.label(_('%d unknown'), 'status.unknown'),
5553 ui.label(_('%d unknown'), 'status.unknown'),
5552 ui.label(_('%d ignored'), 'status.ignored'),
5554 ui.label(_('%d ignored'), 'status.ignored'),
5553 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5555 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5554 ui.label(_('%d subrepos'), 'status.modified')]
5556 ui.label(_('%d subrepos'), 'status.modified')]
5555 t = []
5557 t = []
5556 for s, l in zip(st, labels):
5558 for s, l in zip(st, labels):
5557 if s:
5559 if s:
5558 t.append(l % len(s))
5560 t.append(l % len(s))
5559
5561
5560 t = ', '.join(t)
5562 t = ', '.join(t)
5561 cleanworkdir = False
5563 cleanworkdir = False
5562
5564
5563 if len(parents) > 1:
5565 if len(parents) > 1:
5564 t += _(' (merge)')
5566 t += _(' (merge)')
5565 elif branch != parents[0].branch():
5567 elif branch != parents[0].branch():
5566 t += _(' (new branch)')
5568 t += _(' (new branch)')
5567 elif (parents[0].closesbranch() and
5569 elif (parents[0].closesbranch() and
5568 pnode in repo.branchheads(branch, closed=True)):
5570 pnode in repo.branchheads(branch, closed=True)):
5569 t += _(' (head closed)')
5571 t += _(' (head closed)')
5570 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5572 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5571 t += _(' (clean)')
5573 t += _(' (clean)')
5572 cleanworkdir = True
5574 cleanworkdir = True
5573 elif pnode not in bheads:
5575 elif pnode not in bheads:
5574 t += _(' (new branch head)')
5576 t += _(' (new branch head)')
5575
5577
5576 if cleanworkdir:
5578 if cleanworkdir:
5577 # i18n: column positioning for "hg summary"
5579 # i18n: column positioning for "hg summary"
5578 ui.status(_('commit: %s\n') % t.strip())
5580 ui.status(_('commit: %s\n') % t.strip())
5579 else:
5581 else:
5580 # i18n: column positioning for "hg summary"
5582 # i18n: column positioning for "hg summary"
5581 ui.write(_('commit: %s\n') % t.strip())
5583 ui.write(_('commit: %s\n') % t.strip())
5582
5584
5583 # all ancestors of branch heads - all ancestors of parent = new csets
5585 # all ancestors of branch heads - all ancestors of parent = new csets
5584 new = [0] * len(repo)
5586 new = [0] * len(repo)
5585 cl = repo.changelog
5587 cl = repo.changelog
5586 for a in [cl.rev(n) for n in bheads]:
5588 for a in [cl.rev(n) for n in bheads]:
5587 new[a] = 1
5589 new[a] = 1
5588 for a in cl.ancestors([cl.rev(n) for n in bheads]):
5590 for a in cl.ancestors([cl.rev(n) for n in bheads]):
5589 new[a] = 1
5591 new[a] = 1
5590 for a in [p.rev() for p in parents]:
5592 for a in [p.rev() for p in parents]:
5591 if a >= 0:
5593 if a >= 0:
5592 new[a] = 0
5594 new[a] = 0
5593 for a in cl.ancestors([p.rev() for p in parents]):
5595 for a in cl.ancestors([p.rev() for p in parents]):
5594 new[a] = 0
5596 new[a] = 0
5595 new = sum(new)
5597 new = sum(new)
5596
5598
5597 if new == 0:
5599 if new == 0:
5598 # i18n: column positioning for "hg summary"
5600 # i18n: column positioning for "hg summary"
5599 ui.status(_('update: (current)\n'))
5601 ui.status(_('update: (current)\n'))
5600 elif pnode not in bheads:
5602 elif pnode not in bheads:
5601 # i18n: column positioning for "hg summary"
5603 # i18n: column positioning for "hg summary"
5602 ui.write(_('update: %d new changesets (update)\n') % new)
5604 ui.write(_('update: %d new changesets (update)\n') % new)
5603 else:
5605 else:
5604 # i18n: column positioning for "hg summary"
5606 # i18n: column positioning for "hg summary"
5605 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5607 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5606 (new, len(bheads)))
5608 (new, len(bheads)))
5607
5609
5608 if opts.get('remote'):
5610 if opts.get('remote'):
5609 t = []
5611 t = []
5610 source, branches = hg.parseurl(ui.expandpath('default'))
5612 source, branches = hg.parseurl(ui.expandpath('default'))
5611 other = hg.peer(repo, {}, source)
5613 other = hg.peer(repo, {}, source)
5612 revs, checkout = hg.addbranchrevs(repo, other, branches,
5614 revs, checkout = hg.addbranchrevs(repo, other, branches,
5613 opts.get('rev'))
5615 opts.get('rev'))
5614 ui.debug('comparing with %s\n' % util.hidepassword(source))
5616 ui.debug('comparing with %s\n' % util.hidepassword(source))
5615 repo.ui.pushbuffer()
5617 repo.ui.pushbuffer()
5616 commoninc = discovery.findcommonincoming(repo, other)
5618 commoninc = discovery.findcommonincoming(repo, other)
5617 _common, incoming, _rheads = commoninc
5619 _common, incoming, _rheads = commoninc
5618 repo.ui.popbuffer()
5620 repo.ui.popbuffer()
5619 if incoming:
5621 if incoming:
5620 t.append(_('1 or more incoming'))
5622 t.append(_('1 or more incoming'))
5621
5623
5622 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5624 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5623 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5625 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5624 if source != dest:
5626 if source != dest:
5625 other = hg.peer(repo, {}, dest)
5627 other = hg.peer(repo, {}, dest)
5626 commoninc = None
5628 commoninc = None
5627 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5629 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5628 repo.ui.pushbuffer()
5630 repo.ui.pushbuffer()
5629 outgoing = discovery.findcommonoutgoing(repo, other,
5631 outgoing = discovery.findcommonoutgoing(repo, other,
5630 commoninc=commoninc)
5632 commoninc=commoninc)
5631 repo.ui.popbuffer()
5633 repo.ui.popbuffer()
5632 o = outgoing.missing
5634 o = outgoing.missing
5633 if o:
5635 if o:
5634 t.append(_('%d outgoing') % len(o))
5636 t.append(_('%d outgoing') % len(o))
5635 if 'bookmarks' in other.listkeys('namespaces'):
5637 if 'bookmarks' in other.listkeys('namespaces'):
5636 lmarks = repo.listkeys('bookmarks')
5638 lmarks = repo.listkeys('bookmarks')
5637 rmarks = other.listkeys('bookmarks')
5639 rmarks = other.listkeys('bookmarks')
5638 diff = set(rmarks) - set(lmarks)
5640 diff = set(rmarks) - set(lmarks)
5639 if len(diff) > 0:
5641 if len(diff) > 0:
5640 t.append(_('%d incoming bookmarks') % len(diff))
5642 t.append(_('%d incoming bookmarks') % len(diff))
5641 diff = set(lmarks) - set(rmarks)
5643 diff = set(lmarks) - set(rmarks)
5642 if len(diff) > 0:
5644 if len(diff) > 0:
5643 t.append(_('%d outgoing bookmarks') % len(diff))
5645 t.append(_('%d outgoing bookmarks') % len(diff))
5644
5646
5645 if t:
5647 if t:
5646 # i18n: column positioning for "hg summary"
5648 # i18n: column positioning for "hg summary"
5647 ui.write(_('remote: %s\n') % (', '.join(t)))
5649 ui.write(_('remote: %s\n') % (', '.join(t)))
5648 else:
5650 else:
5649 # i18n: column positioning for "hg summary"
5651 # i18n: column positioning for "hg summary"
5650 ui.status(_('remote: (synced)\n'))
5652 ui.status(_('remote: (synced)\n'))
5651
5653
5652 @command('tag',
5654 @command('tag',
5653 [('f', 'force', None, _('force tag')),
5655 [('f', 'force', None, _('force tag')),
5654 ('l', 'local', None, _('make the tag local')),
5656 ('l', 'local', None, _('make the tag local')),
5655 ('r', 'rev', '', _('revision to tag'), _('REV')),
5657 ('r', 'rev', '', _('revision to tag'), _('REV')),
5656 ('', 'remove', None, _('remove a tag')),
5658 ('', 'remove', None, _('remove a tag')),
5657 # -l/--local is already there, commitopts cannot be used
5659 # -l/--local is already there, commitopts cannot be used
5658 ('e', 'edit', None, _('edit commit message')),
5660 ('e', 'edit', None, _('edit commit message')),
5659 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5661 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5660 ] + commitopts2,
5662 ] + commitopts2,
5661 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5663 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5662 def tag(ui, repo, name1, *names, **opts):
5664 def tag(ui, repo, name1, *names, **opts):
5663 """add one or more tags for the current or given revision
5665 """add one or more tags for the current or given revision
5664
5666
5665 Name a particular revision using <name>.
5667 Name a particular revision using <name>.
5666
5668
5667 Tags are used to name particular revisions of the repository and are
5669 Tags are used to name particular revisions of the repository and are
5668 very useful to compare different revisions, to go back to significant
5670 very useful to compare different revisions, to go back to significant
5669 earlier versions or to mark branch points as releases, etc. Changing
5671 earlier versions or to mark branch points as releases, etc. Changing
5670 an existing tag is normally disallowed; use -f/--force to override.
5672 an existing tag is normally disallowed; use -f/--force to override.
5671
5673
5672 If no revision is given, the parent of the working directory is
5674 If no revision is given, the parent of the working directory is
5673 used, or tip if no revision is checked out.
5675 used, or tip if no revision is checked out.
5674
5676
5675 To facilitate version control, distribution, and merging of tags,
5677 To facilitate version control, distribution, and merging of tags,
5676 they are stored as a file named ".hgtags" which is managed similarly
5678 they are stored as a file named ".hgtags" which is managed similarly
5677 to other project files and can be hand-edited if necessary. This
5679 to other project files and can be hand-edited if necessary. This
5678 also means that tagging creates a new commit. The file
5680 also means that tagging creates a new commit. The file
5679 ".hg/localtags" is used for local tags (not shared among
5681 ".hg/localtags" is used for local tags (not shared among
5680 repositories).
5682 repositories).
5681
5683
5682 Tag commits are usually made at the head of a branch. If the parent
5684 Tag commits are usually made at the head of a branch. If the parent
5683 of the working directory is not a branch head, :hg:`tag` aborts; use
5685 of the working directory is not a branch head, :hg:`tag` aborts; use
5684 -f/--force to force the tag commit to be based on a non-head
5686 -f/--force to force the tag commit to be based on a non-head
5685 changeset.
5687 changeset.
5686
5688
5687 See :hg:`help dates` for a list of formats valid for -d/--date.
5689 See :hg:`help dates` for a list of formats valid for -d/--date.
5688
5690
5689 Since tag names have priority over branch names during revision
5691 Since tag names have priority over branch names during revision
5690 lookup, using an existing branch name as a tag name is discouraged.
5692 lookup, using an existing branch name as a tag name is discouraged.
5691
5693
5692 Returns 0 on success.
5694 Returns 0 on success.
5693 """
5695 """
5694 wlock = lock = None
5696 wlock = lock = None
5695 try:
5697 try:
5696 wlock = repo.wlock()
5698 wlock = repo.wlock()
5697 lock = repo.lock()
5699 lock = repo.lock()
5698 rev_ = "."
5700 rev_ = "."
5699 names = [t.strip() for t in (name1,) + names]
5701 names = [t.strip() for t in (name1,) + names]
5700 if len(names) != len(set(names)):
5702 if len(names) != len(set(names)):
5701 raise util.Abort(_('tag names must be unique'))
5703 raise util.Abort(_('tag names must be unique'))
5702 for n in names:
5704 for n in names:
5703 scmutil.checknewlabel(repo, n, 'tag')
5705 scmutil.checknewlabel(repo, n, 'tag')
5704 if not n:
5706 if not n:
5705 raise util.Abort(_('tag names cannot consist entirely of '
5707 raise util.Abort(_('tag names cannot consist entirely of '
5706 'whitespace'))
5708 'whitespace'))
5707 if opts.get('rev') and opts.get('remove'):
5709 if opts.get('rev') and opts.get('remove'):
5708 raise util.Abort(_("--rev and --remove are incompatible"))
5710 raise util.Abort(_("--rev and --remove are incompatible"))
5709 if opts.get('rev'):
5711 if opts.get('rev'):
5710 rev_ = opts['rev']
5712 rev_ = opts['rev']
5711 message = opts.get('message')
5713 message = opts.get('message')
5712 if opts.get('remove'):
5714 if opts.get('remove'):
5713 expectedtype = opts.get('local') and 'local' or 'global'
5715 expectedtype = opts.get('local') and 'local' or 'global'
5714 for n in names:
5716 for n in names:
5715 if not repo.tagtype(n):
5717 if not repo.tagtype(n):
5716 raise util.Abort(_("tag '%s' does not exist") % n)
5718 raise util.Abort(_("tag '%s' does not exist") % n)
5717 if repo.tagtype(n) != expectedtype:
5719 if repo.tagtype(n) != expectedtype:
5718 if expectedtype == 'global':
5720 if expectedtype == 'global':
5719 raise util.Abort(_("tag '%s' is not a global tag") % n)
5721 raise util.Abort(_("tag '%s' is not a global tag") % n)
5720 else:
5722 else:
5721 raise util.Abort(_("tag '%s' is not a local tag") % n)
5723 raise util.Abort(_("tag '%s' is not a local tag") % n)
5722 rev_ = nullid
5724 rev_ = nullid
5723 if not message:
5725 if not message:
5724 # we don't translate commit messages
5726 # we don't translate commit messages
5725 message = 'Removed tag %s' % ', '.join(names)
5727 message = 'Removed tag %s' % ', '.join(names)
5726 elif not opts.get('force'):
5728 elif not opts.get('force'):
5727 for n in names:
5729 for n in names:
5728 if n in repo.tags():
5730 if n in repo.tags():
5729 raise util.Abort(_("tag '%s' already exists "
5731 raise util.Abort(_("tag '%s' already exists "
5730 "(use -f to force)") % n)
5732 "(use -f to force)") % n)
5731 if not opts.get('local'):
5733 if not opts.get('local'):
5732 p1, p2 = repo.dirstate.parents()
5734 p1, p2 = repo.dirstate.parents()
5733 if p2 != nullid:
5735 if p2 != nullid:
5734 raise util.Abort(_('uncommitted merge'))
5736 raise util.Abort(_('uncommitted merge'))
5735 bheads = repo.branchheads()
5737 bheads = repo.branchheads()
5736 if not opts.get('force') and bheads and p1 not in bheads:
5738 if not opts.get('force') and bheads and p1 not in bheads:
5737 raise util.Abort(_('not at a branch head (use -f to force)'))
5739 raise util.Abort(_('not at a branch head (use -f to force)'))
5738 r = scmutil.revsingle(repo, rev_).node()
5740 r = scmutil.revsingle(repo, rev_).node()
5739
5741
5740 if not message:
5742 if not message:
5741 # we don't translate commit messages
5743 # we don't translate commit messages
5742 message = ('Added tag %s for changeset %s' %
5744 message = ('Added tag %s for changeset %s' %
5743 (', '.join(names), short(r)))
5745 (', '.join(names), short(r)))
5744
5746
5745 date = opts.get('date')
5747 date = opts.get('date')
5746 if date:
5748 if date:
5747 date = util.parsedate(date)
5749 date = util.parsedate(date)
5748
5750
5749 if opts.get('edit'):
5751 if opts.get('edit'):
5750 message = ui.edit(message, ui.username())
5752 message = ui.edit(message, ui.username())
5751
5753
5752 # don't allow tagging the null rev
5754 # don't allow tagging the null rev
5753 if (not opts.get('remove') and
5755 if (not opts.get('remove') and
5754 scmutil.revsingle(repo, rev_).rev() == nullrev):
5756 scmutil.revsingle(repo, rev_).rev() == nullrev):
5755 raise util.Abort(_("null revision specified"))
5757 raise util.Abort(_("null revision specified"))
5756
5758
5757 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5759 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5758 finally:
5760 finally:
5759 release(lock, wlock)
5761 release(lock, wlock)
5760
5762
5761 @command('tags', [], '')
5763 @command('tags', [], '')
5762 def tags(ui, repo, **opts):
5764 def tags(ui, repo, **opts):
5763 """list repository tags
5765 """list repository tags
5764
5766
5765 This lists both regular and local tags. When the -v/--verbose
5767 This lists both regular and local tags. When the -v/--verbose
5766 switch is used, a third column "local" is printed for local tags.
5768 switch is used, a third column "local" is printed for local tags.
5767
5769
5768 Returns 0 on success.
5770 Returns 0 on success.
5769 """
5771 """
5770
5772
5771 fm = ui.formatter('tags', opts)
5773 fm = ui.formatter('tags', opts)
5772 hexfunc = ui.debugflag and hex or short
5774 hexfunc = ui.debugflag and hex or short
5773 tagtype = ""
5775 tagtype = ""
5774
5776
5775 for t, n in reversed(repo.tagslist()):
5777 for t, n in reversed(repo.tagslist()):
5776 hn = hexfunc(n)
5778 hn = hexfunc(n)
5777 label = 'tags.normal'
5779 label = 'tags.normal'
5778 tagtype = ''
5780 tagtype = ''
5779 if repo.tagtype(t) == 'local':
5781 if repo.tagtype(t) == 'local':
5780 label = 'tags.local'
5782 label = 'tags.local'
5781 tagtype = 'local'
5783 tagtype = 'local'
5782
5784
5783 fm.startitem()
5785 fm.startitem()
5784 fm.write('tag', '%s', t, label=label)
5786 fm.write('tag', '%s', t, label=label)
5785 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5787 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5786 fm.condwrite(not ui.quiet, 'rev id', fmt,
5788 fm.condwrite(not ui.quiet, 'rev id', fmt,
5787 repo.changelog.rev(n), hn, label=label)
5789 repo.changelog.rev(n), hn, label=label)
5788 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5790 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5789 tagtype, label=label)
5791 tagtype, label=label)
5790 fm.plain('\n')
5792 fm.plain('\n')
5791 fm.end()
5793 fm.end()
5792
5794
5793 @command('tip',
5795 @command('tip',
5794 [('p', 'patch', None, _('show patch')),
5796 [('p', 'patch', None, _('show patch')),
5795 ('g', 'git', None, _('use git extended diff format')),
5797 ('g', 'git', None, _('use git extended diff format')),
5796 ] + templateopts,
5798 ] + templateopts,
5797 _('[-p] [-g]'))
5799 _('[-p] [-g]'))
5798 def tip(ui, repo, **opts):
5800 def tip(ui, repo, **opts):
5799 """show the tip revision
5801 """show the tip revision
5800
5802
5801 The tip revision (usually just called the tip) is the changeset
5803 The tip revision (usually just called the tip) is the changeset
5802 most recently added to the repository (and therefore the most
5804 most recently added to the repository (and therefore the most
5803 recently changed head).
5805 recently changed head).
5804
5806
5805 If you have just made a commit, that commit will be the tip. If
5807 If you have just made a commit, that commit will be the tip. If
5806 you have just pulled changes from another repository, the tip of
5808 you have just pulled changes from another repository, the tip of
5807 that repository becomes the current tip. The "tip" tag is special
5809 that repository becomes the current tip. The "tip" tag is special
5808 and cannot be renamed or assigned to a different changeset.
5810 and cannot be renamed or assigned to a different changeset.
5809
5811
5810 Returns 0 on success.
5812 Returns 0 on success.
5811 """
5813 """
5812 displayer = cmdutil.show_changeset(ui, repo, opts)
5814 displayer = cmdutil.show_changeset(ui, repo, opts)
5813 displayer.show(repo[len(repo) - 1])
5815 displayer.show(repo[len(repo) - 1])
5814 displayer.close()
5816 displayer.close()
5815
5817
5816 @command('unbundle',
5818 @command('unbundle',
5817 [('u', 'update', None,
5819 [('u', 'update', None,
5818 _('update to new branch head if changesets were unbundled'))],
5820 _('update to new branch head if changesets were unbundled'))],
5819 _('[-u] FILE...'))
5821 _('[-u] FILE...'))
5820 def unbundle(ui, repo, fname1, *fnames, **opts):
5822 def unbundle(ui, repo, fname1, *fnames, **opts):
5821 """apply one or more changegroup files
5823 """apply one or more changegroup files
5822
5824
5823 Apply one or more compressed changegroup files generated by the
5825 Apply one or more compressed changegroup files generated by the
5824 bundle command.
5826 bundle command.
5825
5827
5826 Returns 0 on success, 1 if an update has unresolved files.
5828 Returns 0 on success, 1 if an update has unresolved files.
5827 """
5829 """
5828 fnames = (fname1,) + fnames
5830 fnames = (fname1,) + fnames
5829
5831
5830 lock = repo.lock()
5832 lock = repo.lock()
5831 wc = repo['.']
5833 wc = repo['.']
5832 try:
5834 try:
5833 for fname in fnames:
5835 for fname in fnames:
5834 f = hg.openpath(ui, fname)
5836 f = hg.openpath(ui, fname)
5835 gen = changegroup.readbundle(f, fname)
5837 gen = changegroup.readbundle(f, fname)
5836 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5838 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5837 finally:
5839 finally:
5838 lock.release()
5840 lock.release()
5839 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5841 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5840 return postincoming(ui, repo, modheads, opts.get('update'), None)
5842 return postincoming(ui, repo, modheads, opts.get('update'), None)
5841
5843
5842 @command('^update|up|checkout|co',
5844 @command('^update|up|checkout|co',
5843 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5845 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5844 ('c', 'check', None,
5846 ('c', 'check', None,
5845 _('update across branches if no uncommitted changes')),
5847 _('update across branches if no uncommitted changes')),
5846 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5848 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5847 ('r', 'rev', '', _('revision'), _('REV'))],
5849 ('r', 'rev', '', _('revision'), _('REV'))],
5848 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5850 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5849 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5851 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5850 """update working directory (or switch revisions)
5852 """update working directory (or switch revisions)
5851
5853
5852 Update the repository's working directory to the specified
5854 Update the repository's working directory to the specified
5853 changeset. If no changeset is specified, update to the tip of the
5855 changeset. If no changeset is specified, update to the tip of the
5854 current named branch and move the current bookmark (see :hg:`help
5856 current named branch and move the current bookmark (see :hg:`help
5855 bookmarks`).
5857 bookmarks`).
5856
5858
5857 Update sets the working directory's parent revision to the specified
5859 Update sets the working directory's parent revision to the specified
5858 changeset (see :hg:`help parents`).
5860 changeset (see :hg:`help parents`).
5859
5861
5860 If the changeset is not a descendant or ancestor of the working
5862 If the changeset is not a descendant or ancestor of the working
5861 directory's parent, the update is aborted. With the -c/--check
5863 directory's parent, the update is aborted. With the -c/--check
5862 option, the working directory is checked for uncommitted changes; if
5864 option, the working directory is checked for uncommitted changes; if
5863 none are found, the working directory is updated to the specified
5865 none are found, the working directory is updated to the specified
5864 changeset.
5866 changeset.
5865
5867
5866 .. container:: verbose
5868 .. container:: verbose
5867
5869
5868 The following rules apply when the working directory contains
5870 The following rules apply when the working directory contains
5869 uncommitted changes:
5871 uncommitted changes:
5870
5872
5871 1. If neither -c/--check nor -C/--clean is specified, and if
5873 1. If neither -c/--check nor -C/--clean is specified, and if
5872 the requested changeset is an ancestor or descendant of
5874 the requested changeset is an ancestor or descendant of
5873 the working directory's parent, the uncommitted changes
5875 the working directory's parent, the uncommitted changes
5874 are merged into the requested changeset and the merged
5876 are merged into the requested changeset and the merged
5875 result is left uncommitted. If the requested changeset is
5877 result is left uncommitted. If the requested changeset is
5876 not an ancestor or descendant (that is, it is on another
5878 not an ancestor or descendant (that is, it is on another
5877 branch), the update is aborted and the uncommitted changes
5879 branch), the update is aborted and the uncommitted changes
5878 are preserved.
5880 are preserved.
5879
5881
5880 2. With the -c/--check option, the update is aborted and the
5882 2. With the -c/--check option, the update is aborted and the
5881 uncommitted changes are preserved.
5883 uncommitted changes are preserved.
5882
5884
5883 3. With the -C/--clean option, uncommitted changes are discarded and
5885 3. With the -C/--clean option, uncommitted changes are discarded and
5884 the working directory is updated to the requested changeset.
5886 the working directory is updated to the requested changeset.
5885
5887
5886 To cancel an uncommitted merge (and lose your changes), use
5888 To cancel an uncommitted merge (and lose your changes), use
5887 :hg:`update --clean .`.
5889 :hg:`update --clean .`.
5888
5890
5889 Use null as the changeset to remove the working directory (like
5891 Use null as the changeset to remove the working directory (like
5890 :hg:`clone -U`).
5892 :hg:`clone -U`).
5891
5893
5892 If you want to revert just one file to an older revision, use
5894 If you want to revert just one file to an older revision, use
5893 :hg:`revert [-r REV] NAME`.
5895 :hg:`revert [-r REV] NAME`.
5894
5896
5895 See :hg:`help dates` for a list of formats valid for -d/--date.
5897 See :hg:`help dates` for a list of formats valid for -d/--date.
5896
5898
5897 Returns 0 on success, 1 if there are unresolved files.
5899 Returns 0 on success, 1 if there are unresolved files.
5898 """
5900 """
5899 if rev and node:
5901 if rev and node:
5900 raise util.Abort(_("please specify just one revision"))
5902 raise util.Abort(_("please specify just one revision"))
5901
5903
5902 if rev is None or rev == '':
5904 if rev is None or rev == '':
5903 rev = node
5905 rev = node
5904
5906
5905 # with no argument, we also move the current bookmark, if any
5907 # with no argument, we also move the current bookmark, if any
5906 movemarkfrom = None
5908 movemarkfrom = None
5907 if rev is None:
5909 if rev is None:
5908 movemarkfrom = repo['.'].node()
5910 movemarkfrom = repo['.'].node()
5909
5911
5910 # if we defined a bookmark, we have to remember the original bookmark name
5912 # if we defined a bookmark, we have to remember the original bookmark name
5911 brev = rev
5913 brev = rev
5912 rev = scmutil.revsingle(repo, rev, rev).rev()
5914 rev = scmutil.revsingle(repo, rev, rev).rev()
5913
5915
5914 if check and clean:
5916 if check and clean:
5915 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5917 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5916
5918
5917 if date:
5919 if date:
5918 if rev is not None:
5920 if rev is not None:
5919 raise util.Abort(_("you can't specify a revision and a date"))
5921 raise util.Abort(_("you can't specify a revision and a date"))
5920 rev = cmdutil.finddate(ui, repo, date)
5922 rev = cmdutil.finddate(ui, repo, date)
5921
5923
5922 if check:
5924 if check:
5923 c = repo[None]
5925 c = repo[None]
5924 if c.dirty(merge=False, branch=False, missing=True):
5926 if c.dirty(merge=False, branch=False, missing=True):
5925 raise util.Abort(_("uncommitted local changes"))
5927 raise util.Abort(_("uncommitted local changes"))
5926 if rev is None:
5928 if rev is None:
5927 rev = repo[repo[None].branch()].rev()
5929 rev = repo[repo[None].branch()].rev()
5928 mergemod._checkunknown(repo, repo[None], repo[rev])
5930 mergemod._checkunknown(repo, repo[None], repo[rev])
5929
5931
5930 if clean:
5932 if clean:
5931 ret = hg.clean(repo, rev)
5933 ret = hg.clean(repo, rev)
5932 else:
5934 else:
5933 ret = hg.update(repo, rev)
5935 ret = hg.update(repo, rev)
5934
5936
5935 if not ret and movemarkfrom:
5937 if not ret and movemarkfrom:
5936 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5938 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5937 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5939 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5938 elif brev in repo._bookmarks:
5940 elif brev in repo._bookmarks:
5939 bookmarks.setcurrent(repo, brev)
5941 bookmarks.setcurrent(repo, brev)
5940 elif brev:
5942 elif brev:
5941 bookmarks.unsetcurrent(repo)
5943 bookmarks.unsetcurrent(repo)
5942
5944
5943 return ret
5945 return ret
5944
5946
5945 @command('verify', [])
5947 @command('verify', [])
5946 def verify(ui, repo):
5948 def verify(ui, repo):
5947 """verify the integrity of the repository
5949 """verify the integrity of the repository
5948
5950
5949 Verify the integrity of the current repository.
5951 Verify the integrity of the current repository.
5950
5952
5951 This will perform an extensive check of the repository's
5953 This will perform an extensive check of the repository's
5952 integrity, validating the hashes and checksums of each entry in
5954 integrity, validating the hashes and checksums of each entry in
5953 the changelog, manifest, and tracked files, as well as the
5955 the changelog, manifest, and tracked files, as well as the
5954 integrity of their crosslinks and indices.
5956 integrity of their crosslinks and indices.
5955
5957
5956 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5958 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5957 for more information about recovery from corruption of the
5959 for more information about recovery from corruption of the
5958 repository.
5960 repository.
5959
5961
5960 Returns 0 on success, 1 if errors are encountered.
5962 Returns 0 on success, 1 if errors are encountered.
5961 """
5963 """
5962 return hg.verify(repo)
5964 return hg.verify(repo)
5963
5965
5964 @command('version', [])
5966 @command('version', [])
5965 def version_(ui):
5967 def version_(ui):
5966 """output version and copyright information"""
5968 """output version and copyright information"""
5967 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5969 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5968 % util.version())
5970 % util.version())
5969 ui.status(_(
5971 ui.status(_(
5970 "(see http://mercurial.selenic.com for more information)\n"
5972 "(see http://mercurial.selenic.com for more information)\n"
5971 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5973 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5972 "This is free software; see the source for copying conditions. "
5974 "This is free software; see the source for copying conditions. "
5973 "There is NO\nwarranty; "
5975 "There is NO\nwarranty; "
5974 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5976 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5975 ))
5977 ))
5976
5978
5977 norepo = ("clone init version help debugcommands debugcomplete"
5979 norepo = ("clone init version help debugcommands debugcomplete"
5978 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5980 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5979 " debugknown debuggetbundle debugbundle")
5981 " debugknown debuggetbundle debugbundle")
5980 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5982 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5981 " debugdata debugindex debugindexdot debugrevlog")
5983 " debugdata debugindex debugindexdot debugrevlog")
5982 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5984 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5983 " remove resolve status debugwalk")
5985 " remove resolve status debugwalk")
General Comments 0
You need to be logged in to leave comments. Login now