##// END OF EJS Templates
graft: add initial implementation
Matt Mackall -
r15238:2d710c12 default
parent child Browse files
Show More
@@ -1,5475 +1,5544 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, url, encoding, templatekw, discovery
13 import patch, help, url, 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
18 import dagparser, context, simplemerge
19 import random, setdiscovery, treediscovery, dagutil
19 import random, setdiscovery, treediscovery, dagutil
20
20
21 table = {}
21 table = {}
22
22
23 command = cmdutil.command(table)
23 command = cmdutil.command(table)
24
24
25 # common command options
25 # common command options
26
26
27 globalopts = [
27 globalopts = [
28 ('R', 'repository', '',
28 ('R', 'repository', '',
29 _('repository root directory or name of overlay bundle file'),
29 _('repository root directory or name of overlay bundle file'),
30 _('REPO')),
30 _('REPO')),
31 ('', 'cwd', '',
31 ('', 'cwd', '',
32 _('change working directory'), _('DIR')),
32 _('change working directory'), _('DIR')),
33 ('y', 'noninteractive', None,
33 ('y', 'noninteractive', None,
34 _('do not prompt, automatically pick the first choice for all prompts')),
34 _('do not prompt, automatically pick the first choice for all prompts')),
35 ('q', 'quiet', None, _('suppress output')),
35 ('q', 'quiet', None, _('suppress output')),
36 ('v', 'verbose', None, _('enable additional output')),
36 ('v', 'verbose', None, _('enable additional output')),
37 ('', 'config', [],
37 ('', 'config', [],
38 _('set/override config option (use \'section.name=value\')'),
38 _('set/override config option (use \'section.name=value\')'),
39 _('CONFIG')),
39 _('CONFIG')),
40 ('', 'debug', None, _('enable debugging output')),
40 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debugger', None, _('start debugger')),
41 ('', 'debugger', None, _('start debugger')),
42 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 _('ENCODE')),
43 _('ENCODE')),
44 ('', 'encodingmode', encoding.encodingmode,
44 ('', 'encodingmode', encoding.encodingmode,
45 _('set the charset encoding mode'), _('MODE')),
45 _('set the charset encoding mode'), _('MODE')),
46 ('', 'traceback', None, _('always print a traceback on exception')),
46 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'time', None, _('time how long the command takes')),
47 ('', 'time', None, _('time how long the command takes')),
48 ('', 'profile', None, _('print command execution profile')),
48 ('', 'profile', None, _('print command execution profile')),
49 ('', 'version', None, _('output version information and exit')),
49 ('', 'version', None, _('output version information and exit')),
50 ('h', 'help', None, _('display help and exit')),
50 ('h', 'help', None, _('display help and exit')),
51 ]
51 ]
52
52
53 dryrunopts = [('n', 'dry-run', None,
53 dryrunopts = [('n', 'dry-run', None,
54 _('do not perform actions, just print output'))]
54 _('do not perform actions, just print output'))]
55
55
56 remoteopts = [
56 remoteopts = [
57 ('e', 'ssh', '',
57 ('e', 'ssh', '',
58 _('specify ssh command to use'), _('CMD')),
58 _('specify ssh command to use'), _('CMD')),
59 ('', 'remotecmd', '',
59 ('', 'remotecmd', '',
60 _('specify hg command to run on the remote side'), _('CMD')),
60 _('specify hg command to run on the remote side'), _('CMD')),
61 ('', 'insecure', None,
61 ('', 'insecure', None,
62 _('do not verify server certificate (ignoring web.cacerts config)')),
62 _('do not verify server certificate (ignoring web.cacerts config)')),
63 ]
63 ]
64
64
65 walkopts = [
65 walkopts = [
66 ('I', 'include', [],
66 ('I', 'include', [],
67 _('include names matching the given patterns'), _('PATTERN')),
67 _('include names matching the given patterns'), _('PATTERN')),
68 ('X', 'exclude', [],
68 ('X', 'exclude', [],
69 _('exclude names matching the given patterns'), _('PATTERN')),
69 _('exclude names matching the given patterns'), _('PATTERN')),
70 ]
70 ]
71
71
72 commitopts = [
72 commitopts = [
73 ('m', 'message', '',
73 ('m', 'message', '',
74 _('use text as commit message'), _('TEXT')),
74 _('use text as commit message'), _('TEXT')),
75 ('l', 'logfile', '',
75 ('l', 'logfile', '',
76 _('read commit message from file'), _('FILE')),
76 _('read commit message from file'), _('FILE')),
77 ]
77 ]
78
78
79 commitopts2 = [
79 commitopts2 = [
80 ('d', 'date', '',
80 ('d', 'date', '',
81 _('record the specified date as commit date'), _('DATE')),
81 _('record the specified date as commit date'), _('DATE')),
82 ('u', 'user', '',
82 ('u', 'user', '',
83 _('record the specified user as committer'), _('USER')),
83 _('record the specified user as committer'), _('USER')),
84 ]
84 ]
85
85
86 templateopts = [
86 templateopts = [
87 ('', 'style', '',
87 ('', 'style', '',
88 _('display using template map file'), _('STYLE')),
88 _('display using template map file'), _('STYLE')),
89 ('', 'template', '',
89 ('', 'template', '',
90 _('display with template'), _('TEMPLATE')),
90 _('display with template'), _('TEMPLATE')),
91 ]
91 ]
92
92
93 logopts = [
93 logopts = [
94 ('p', 'patch', None, _('show patch')),
94 ('p', 'patch', None, _('show patch')),
95 ('g', 'git', None, _('use git extended diff format')),
95 ('g', 'git', None, _('use git extended diff format')),
96 ('l', 'limit', '',
96 ('l', 'limit', '',
97 _('limit number of changes displayed'), _('NUM')),
97 _('limit number of changes displayed'), _('NUM')),
98 ('M', 'no-merges', None, _('do not show merges')),
98 ('M', 'no-merges', None, _('do not show merges')),
99 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ] + templateopts
100 ] + templateopts
101
101
102 diffopts = [
102 diffopts = [
103 ('a', 'text', None, _('treat all files as text')),
103 ('a', 'text', None, _('treat all files as text')),
104 ('g', 'git', None, _('use git extended diff format')),
104 ('g', 'git', None, _('use git extended diff format')),
105 ('', 'nodates', None, _('omit dates from diff headers'))
105 ('', 'nodates', None, _('omit dates from diff headers'))
106 ]
106 ]
107
107
108 diffopts2 = [
108 diffopts2 = [
109 ('p', 'show-function', None, _('show which function each change is in')),
109 ('p', 'show-function', None, _('show which function each change is in')),
110 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 ('', 'reverse', None, _('produce a diff that undoes the changes')),
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 ('U', 'unified', '',
117 ('U', 'unified', '',
118 _('number of lines of context to show'), _('NUM')),
118 _('number of lines of context to show'), _('NUM')),
119 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ('', 'stat', None, _('output diffstat-style summary of changes')),
120 ]
120 ]
121
121
122 mergetoolopts = [
122 mergetoolopts = [
123 ('t', 'tool', '', _('specify merge tool')),
123 ('t', 'tool', '', _('specify merge tool')),
124 ]
124 ]
125
125
126 similarityopts = [
126 similarityopts = [
127 ('s', 'similarity', '',
127 ('s', 'similarity', '',
128 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
128 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
129 ]
129 ]
130
130
131 subrepoopts = [
131 subrepoopts = [
132 ('S', 'subrepos', None,
132 ('S', 'subrepos', None,
133 _('recurse into subrepositories'))
133 _('recurse into subrepositories'))
134 ]
134 ]
135
135
136 # Commands start here, listed alphabetically
136 # Commands start here, listed alphabetically
137
137
138 @command('^add',
138 @command('^add',
139 walkopts + subrepoopts + dryrunopts,
139 walkopts + subrepoopts + dryrunopts,
140 _('[OPTION]... [FILE]...'))
140 _('[OPTION]... [FILE]...'))
141 def add(ui, repo, *pats, **opts):
141 def add(ui, repo, *pats, **opts):
142 """add the specified files on the next commit
142 """add the specified files on the next commit
143
143
144 Schedule files to be version controlled and added to the
144 Schedule files to be version controlled and added to the
145 repository.
145 repository.
146
146
147 The files will be added to the repository at the next commit. To
147 The files will be added to the repository at the next commit. To
148 undo an add before that, see :hg:`forget`.
148 undo an add before that, see :hg:`forget`.
149
149
150 If no names are given, add all files to the repository.
150 If no names are given, add all files to the repository.
151
151
152 .. container:: verbose
152 .. container:: verbose
153
153
154 An example showing how new (unknown) files are added
154 An example showing how new (unknown) files are added
155 automatically by :hg:`add`::
155 automatically by :hg:`add`::
156
156
157 $ ls
157 $ ls
158 foo.c
158 foo.c
159 $ hg status
159 $ hg status
160 ? foo.c
160 ? foo.c
161 $ hg add
161 $ hg add
162 adding foo.c
162 adding foo.c
163 $ hg status
163 $ hg status
164 A foo.c
164 A foo.c
165
165
166 Returns 0 if all files are successfully added.
166 Returns 0 if all files are successfully added.
167 """
167 """
168
168
169 m = scmutil.match(repo[None], pats, opts)
169 m = scmutil.match(repo[None], pats, opts)
170 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
170 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
171 opts.get('subrepos'), prefix="")
171 opts.get('subrepos'), prefix="")
172 return rejected and 1 or 0
172 return rejected and 1 or 0
173
173
174 @command('addremove',
174 @command('addremove',
175 similarityopts + walkopts + dryrunopts,
175 similarityopts + walkopts + dryrunopts,
176 _('[OPTION]... [FILE]...'))
176 _('[OPTION]... [FILE]...'))
177 def addremove(ui, repo, *pats, **opts):
177 def addremove(ui, repo, *pats, **opts):
178 """add all new files, delete all missing files
178 """add all new files, delete all missing files
179
179
180 Add all new files and remove all missing files from the
180 Add all new files and remove all missing files from the
181 repository.
181 repository.
182
182
183 New files are ignored if they match any of the patterns in
183 New files are ignored if they match any of the patterns in
184 ``.hgignore``. As with add, these changes take effect at the next
184 ``.hgignore``. As with add, these changes take effect at the next
185 commit.
185 commit.
186
186
187 Use the -s/--similarity option to detect renamed files. With a
187 Use the -s/--similarity option to detect renamed files. With a
188 parameter greater than 0, this compares every removed file with
188 parameter greater than 0, this compares every removed file with
189 every added file and records those similar enough as renames. This
189 every added file and records those similar enough as renames. This
190 option takes a percentage between 0 (disabled) and 100 (files must
190 option takes a percentage between 0 (disabled) and 100 (files must
191 be identical) as its parameter. Detecting renamed files this way
191 be identical) as its parameter. Detecting renamed files this way
192 can be expensive. After using this option, :hg:`status -C` can be
192 can be expensive. After using this option, :hg:`status -C` can be
193 used to check which files were identified as moved or renamed.
193 used to check which files were identified as moved or renamed.
194
194
195 Returns 0 if all files are successfully added.
195 Returns 0 if all files are successfully added.
196 """
196 """
197 try:
197 try:
198 sim = float(opts.get('similarity') or 100)
198 sim = float(opts.get('similarity') or 100)
199 except ValueError:
199 except ValueError:
200 raise util.Abort(_('similarity must be a number'))
200 raise util.Abort(_('similarity must be a number'))
201 if sim < 0 or sim > 100:
201 if sim < 0 or sim > 100:
202 raise util.Abort(_('similarity must be between 0 and 100'))
202 raise util.Abort(_('similarity must be between 0 and 100'))
203 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
203 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
204
204
205 @command('^annotate|blame',
205 @command('^annotate|blame',
206 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
206 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
207 ('', 'follow', None,
207 ('', 'follow', None,
208 _('follow copies/renames and list the filename (DEPRECATED)')),
208 _('follow copies/renames and list the filename (DEPRECATED)')),
209 ('', 'no-follow', None, _("don't follow copies and renames")),
209 ('', 'no-follow', None, _("don't follow copies and renames")),
210 ('a', 'text', None, _('treat all files as text')),
210 ('a', 'text', None, _('treat all files as text')),
211 ('u', 'user', None, _('list the author (long with -v)')),
211 ('u', 'user', None, _('list the author (long with -v)')),
212 ('f', 'file', None, _('list the filename')),
212 ('f', 'file', None, _('list the filename')),
213 ('d', 'date', None, _('list the date (short with -q)')),
213 ('d', 'date', None, _('list the date (short with -q)')),
214 ('n', 'number', None, _('list the revision number (default)')),
214 ('n', 'number', None, _('list the revision number (default)')),
215 ('c', 'changeset', None, _('list the changeset')),
215 ('c', 'changeset', None, _('list the changeset')),
216 ('l', 'line-number', None, _('show line number at the first appearance'))
216 ('l', 'line-number', None, _('show line number at the first appearance'))
217 ] + walkopts,
217 ] + walkopts,
218 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
218 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
219 def annotate(ui, repo, *pats, **opts):
219 def annotate(ui, repo, *pats, **opts):
220 """show changeset information by line for each file
220 """show changeset information by line for each file
221
221
222 List changes in files, showing the revision id responsible for
222 List changes in files, showing the revision id responsible for
223 each line
223 each line
224
224
225 This command is useful for discovering when a change was made and
225 This command is useful for discovering when a change was made and
226 by whom.
226 by whom.
227
227
228 Without the -a/--text option, annotate will avoid processing files
228 Without the -a/--text option, annotate will avoid processing files
229 it detects as binary. With -a, annotate will annotate the file
229 it detects as binary. With -a, annotate will annotate the file
230 anyway, although the results will probably be neither useful
230 anyway, although the results will probably be neither useful
231 nor desirable.
231 nor desirable.
232
232
233 Returns 0 on success.
233 Returns 0 on success.
234 """
234 """
235 if opts.get('follow'):
235 if opts.get('follow'):
236 # --follow is deprecated and now just an alias for -f/--file
236 # --follow is deprecated and now just an alias for -f/--file
237 # to mimic the behavior of Mercurial before version 1.5
237 # to mimic the behavior of Mercurial before version 1.5
238 opts['file'] = True
238 opts['file'] = True
239
239
240 datefunc = ui.quiet and util.shortdate or util.datestr
240 datefunc = ui.quiet and util.shortdate or util.datestr
241 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
241 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
242
242
243 if not pats:
243 if not pats:
244 raise util.Abort(_('at least one filename or pattern is required'))
244 raise util.Abort(_('at least one filename or pattern is required'))
245
245
246 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
246 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
247 ('number', ' ', lambda x: str(x[0].rev())),
247 ('number', ' ', lambda x: str(x[0].rev())),
248 ('changeset', ' ', lambda x: short(x[0].node())),
248 ('changeset', ' ', lambda x: short(x[0].node())),
249 ('date', ' ', getdate),
249 ('date', ' ', getdate),
250 ('file', ' ', lambda x: x[0].path()),
250 ('file', ' ', lambda x: x[0].path()),
251 ('line_number', ':', lambda x: str(x[1])),
251 ('line_number', ':', lambda x: str(x[1])),
252 ]
252 ]
253
253
254 if (not opts.get('user') and not opts.get('changeset')
254 if (not opts.get('user') and not opts.get('changeset')
255 and not opts.get('date') and not opts.get('file')):
255 and not opts.get('date') and not opts.get('file')):
256 opts['number'] = True
256 opts['number'] = True
257
257
258 linenumber = opts.get('line_number') is not None
258 linenumber = opts.get('line_number') is not None
259 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
259 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
260 raise util.Abort(_('at least one of -n/-c is required for -l'))
260 raise util.Abort(_('at least one of -n/-c is required for -l'))
261
261
262 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
262 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
263 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
263 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
264
264
265 def bad(x, y):
265 def bad(x, y):
266 raise util.Abort("%s: %s" % (x, y))
266 raise util.Abort("%s: %s" % (x, y))
267
267
268 ctx = scmutil.revsingle(repo, opts.get('rev'))
268 ctx = scmutil.revsingle(repo, opts.get('rev'))
269 m = scmutil.match(ctx, pats, opts)
269 m = scmutil.match(ctx, pats, opts)
270 m.bad = bad
270 m.bad = bad
271 follow = not opts.get('no_follow')
271 follow = not opts.get('no_follow')
272 for abs in ctx.walk(m):
272 for abs in ctx.walk(m):
273 fctx = ctx[abs]
273 fctx = ctx[abs]
274 if not opts.get('text') and util.binary(fctx.data()):
274 if not opts.get('text') and util.binary(fctx.data()):
275 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
275 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
276 continue
276 continue
277
277
278 lines = fctx.annotate(follow=follow, linenumber=linenumber)
278 lines = fctx.annotate(follow=follow, linenumber=linenumber)
279 pieces = []
279 pieces = []
280
280
281 for f, sep in funcmap:
281 for f, sep in funcmap:
282 l = [f(n) for n, dummy in lines]
282 l = [f(n) for n, dummy in lines]
283 if l:
283 if l:
284 sized = [(x, encoding.colwidth(x)) for x in l]
284 sized = [(x, encoding.colwidth(x)) for x in l]
285 ml = max([w for x, w in sized])
285 ml = max([w for x, w in sized])
286 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
286 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
287 for x, w in sized])
287 for x, w in sized])
288
288
289 if pieces:
289 if pieces:
290 for p, l in zip(zip(*pieces), lines):
290 for p, l in zip(zip(*pieces), lines):
291 ui.write("%s: %s" % ("".join(p), l[1]))
291 ui.write("%s: %s" % ("".join(p), l[1]))
292
292
293 @command('archive',
293 @command('archive',
294 [('', 'no-decode', None, _('do not pass files through decoders')),
294 [('', 'no-decode', None, _('do not pass files through decoders')),
295 ('p', 'prefix', '', _('directory prefix for files in archive'),
295 ('p', 'prefix', '', _('directory prefix for files in archive'),
296 _('PREFIX')),
296 _('PREFIX')),
297 ('r', 'rev', '', _('revision to distribute'), _('REV')),
297 ('r', 'rev', '', _('revision to distribute'), _('REV')),
298 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
298 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
299 ] + subrepoopts + walkopts,
299 ] + subrepoopts + walkopts,
300 _('[OPTION]... DEST'))
300 _('[OPTION]... DEST'))
301 def archive(ui, repo, dest, **opts):
301 def archive(ui, repo, dest, **opts):
302 '''create an unversioned archive of a repository revision
302 '''create an unversioned archive of a repository revision
303
303
304 By default, the revision used is the parent of the working
304 By default, the revision used is the parent of the working
305 directory; use -r/--rev to specify a different revision.
305 directory; use -r/--rev to specify a different revision.
306
306
307 The archive type is automatically detected based on file
307 The archive type is automatically detected based on file
308 extension (or override using -t/--type).
308 extension (or override using -t/--type).
309
309
310 .. container:: verbose
310 .. container:: verbose
311
311
312 Examples:
312 Examples:
313
313
314 - create a zip file containing the 1.0 release::
314 - create a zip file containing the 1.0 release::
315
315
316 hg archive -r 1.0 project-1.0.zip
316 hg archive -r 1.0 project-1.0.zip
317
317
318 - create a tarball excluding .hg files::
318 - create a tarball excluding .hg files::
319
319
320 hg archive project.tar.gz -X ".hg*"
320 hg archive project.tar.gz -X ".hg*"
321
321
322 Valid types are:
322 Valid types are:
323
323
324 :``files``: a directory full of files (default)
324 :``files``: a directory full of files (default)
325 :``tar``: tar archive, uncompressed
325 :``tar``: tar archive, uncompressed
326 :``tbz2``: tar archive, compressed using bzip2
326 :``tbz2``: tar archive, compressed using bzip2
327 :``tgz``: tar archive, compressed using gzip
327 :``tgz``: tar archive, compressed using gzip
328 :``uzip``: zip archive, uncompressed
328 :``uzip``: zip archive, uncompressed
329 :``zip``: zip archive, compressed using deflate
329 :``zip``: zip archive, compressed using deflate
330
330
331 The exact name of the destination archive or directory is given
331 The exact name of the destination archive or directory is given
332 using a format string; see :hg:`help export` for details.
332 using a format string; see :hg:`help export` for details.
333
333
334 Each member added to an archive file has a directory prefix
334 Each member added to an archive file has a directory prefix
335 prepended. Use -p/--prefix to specify a format string for the
335 prepended. Use -p/--prefix to specify a format string for the
336 prefix. The default is the basename of the archive, with suffixes
336 prefix. The default is the basename of the archive, with suffixes
337 removed.
337 removed.
338
338
339 Returns 0 on success.
339 Returns 0 on success.
340 '''
340 '''
341
341
342 ctx = scmutil.revsingle(repo, opts.get('rev'))
342 ctx = scmutil.revsingle(repo, opts.get('rev'))
343 if not ctx:
343 if not ctx:
344 raise util.Abort(_('no working directory: please specify a revision'))
344 raise util.Abort(_('no working directory: please specify a revision'))
345 node = ctx.node()
345 node = ctx.node()
346 dest = cmdutil.makefilename(repo, dest, node)
346 dest = cmdutil.makefilename(repo, dest, node)
347 if os.path.realpath(dest) == repo.root:
347 if os.path.realpath(dest) == repo.root:
348 raise util.Abort(_('repository root cannot be destination'))
348 raise util.Abort(_('repository root cannot be destination'))
349
349
350 kind = opts.get('type') or archival.guesskind(dest) or 'files'
350 kind = opts.get('type') or archival.guesskind(dest) or 'files'
351 prefix = opts.get('prefix')
351 prefix = opts.get('prefix')
352
352
353 if dest == '-':
353 if dest == '-':
354 if kind == 'files':
354 if kind == 'files':
355 raise util.Abort(_('cannot archive plain files to stdout'))
355 raise util.Abort(_('cannot archive plain files to stdout'))
356 dest = cmdutil.makefileobj(repo, dest)
356 dest = cmdutil.makefileobj(repo, dest)
357 if not prefix:
357 if not prefix:
358 prefix = os.path.basename(repo.root) + '-%h'
358 prefix = os.path.basename(repo.root) + '-%h'
359
359
360 prefix = cmdutil.makefilename(repo, prefix, node)
360 prefix = cmdutil.makefilename(repo, prefix, node)
361 matchfn = scmutil.match(ctx, [], opts)
361 matchfn = scmutil.match(ctx, [], opts)
362 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
362 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
363 matchfn, prefix, subrepos=opts.get('subrepos'))
363 matchfn, prefix, subrepos=opts.get('subrepos'))
364
364
365 @command('backout',
365 @command('backout',
366 [('', 'merge', None, _('merge with old dirstate parent after backout')),
366 [('', 'merge', None, _('merge with old dirstate parent after backout')),
367 ('', 'parent', '',
367 ('', 'parent', '',
368 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
368 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
369 ('r', 'rev', '', _('revision to backout'), _('REV')),
369 ('r', 'rev', '', _('revision to backout'), _('REV')),
370 ] + mergetoolopts + walkopts + commitopts + commitopts2,
370 ] + mergetoolopts + walkopts + commitopts + commitopts2,
371 _('[OPTION]... [-r] REV'))
371 _('[OPTION]... [-r] REV'))
372 def backout(ui, repo, node=None, rev=None, **opts):
372 def backout(ui, repo, node=None, rev=None, **opts):
373 '''reverse effect of earlier changeset
373 '''reverse effect of earlier changeset
374
374
375 Prepare a new changeset with the effect of REV undone in the
375 Prepare a new changeset with the effect of REV undone in the
376 current working directory.
376 current working directory.
377
377
378 If REV is the parent of the working directory, then this new changeset
378 If REV is the parent of the working directory, then this new changeset
379 is committed automatically. Otherwise, hg needs to merge the
379 is committed automatically. Otherwise, hg needs to merge the
380 changes and the merged result is left uncommitted.
380 changes and the merged result is left uncommitted.
381
381
382 .. note::
382 .. note::
383 backout cannot be used to fix either an unwanted or
383 backout cannot be used to fix either an unwanted or
384 incorrect merge.
384 incorrect merge.
385
385
386 .. container:: verbose
386 .. container:: verbose
387
387
388 By default, the pending changeset will have one parent,
388 By default, the pending changeset will have one parent,
389 maintaining a linear history. With --merge, the pending
389 maintaining a linear history. With --merge, the pending
390 changeset will instead have two parents: the old parent of the
390 changeset will instead have two parents: the old parent of the
391 working directory and a new child of REV that simply undoes REV.
391 working directory and a new child of REV that simply undoes REV.
392
392
393 Before version 1.7, the behavior without --merge was equivalent
393 Before version 1.7, the behavior without --merge was equivalent
394 to specifying --merge followed by :hg:`update --clean .` to
394 to specifying --merge followed by :hg:`update --clean .` to
395 cancel the merge and leave the child of REV as a head to be
395 cancel the merge and leave the child of REV as a head to be
396 merged separately.
396 merged separately.
397
397
398 See :hg:`help dates` for a list of formats valid for -d/--date.
398 See :hg:`help dates` for a list of formats valid for -d/--date.
399
399
400 Returns 0 on success.
400 Returns 0 on success.
401 '''
401 '''
402 if rev and node:
402 if rev and node:
403 raise util.Abort(_("please specify just one revision"))
403 raise util.Abort(_("please specify just one revision"))
404
404
405 if not rev:
405 if not rev:
406 rev = node
406 rev = node
407
407
408 if not rev:
408 if not rev:
409 raise util.Abort(_("please specify a revision to backout"))
409 raise util.Abort(_("please specify a revision to backout"))
410
410
411 date = opts.get('date')
411 date = opts.get('date')
412 if date:
412 if date:
413 opts['date'] = util.parsedate(date)
413 opts['date'] = util.parsedate(date)
414
414
415 cmdutil.bailifchanged(repo)
415 cmdutil.bailifchanged(repo)
416 node = scmutil.revsingle(repo, rev).node()
416 node = scmutil.revsingle(repo, rev).node()
417
417
418 op1, op2 = repo.dirstate.parents()
418 op1, op2 = repo.dirstate.parents()
419 a = repo.changelog.ancestor(op1, node)
419 a = repo.changelog.ancestor(op1, node)
420 if a != node:
420 if a != node:
421 raise util.Abort(_('cannot backout change on a different branch'))
421 raise util.Abort(_('cannot backout change on a different branch'))
422
422
423 p1, p2 = repo.changelog.parents(node)
423 p1, p2 = repo.changelog.parents(node)
424 if p1 == nullid:
424 if p1 == nullid:
425 raise util.Abort(_('cannot backout a change with no parents'))
425 raise util.Abort(_('cannot backout a change with no parents'))
426 if p2 != nullid:
426 if p2 != nullid:
427 if not opts.get('parent'):
427 if not opts.get('parent'):
428 raise util.Abort(_('cannot backout a merge changeset'))
428 raise util.Abort(_('cannot backout a merge changeset'))
429 p = repo.lookup(opts['parent'])
429 p = repo.lookup(opts['parent'])
430 if p not in (p1, p2):
430 if p not in (p1, p2):
431 raise util.Abort(_('%s is not a parent of %s') %
431 raise util.Abort(_('%s is not a parent of %s') %
432 (short(p), short(node)))
432 (short(p), short(node)))
433 parent = p
433 parent = p
434 else:
434 else:
435 if opts.get('parent'):
435 if opts.get('parent'):
436 raise util.Abort(_('cannot use --parent on non-merge changeset'))
436 raise util.Abort(_('cannot use --parent on non-merge changeset'))
437 parent = p1
437 parent = p1
438
438
439 # the backout should appear on the same branch
439 # the backout should appear on the same branch
440 branch = repo.dirstate.branch()
440 branch = repo.dirstate.branch()
441 hg.clean(repo, node, show_stats=False)
441 hg.clean(repo, node, show_stats=False)
442 repo.dirstate.setbranch(branch)
442 repo.dirstate.setbranch(branch)
443 revert_opts = opts.copy()
443 revert_opts = opts.copy()
444 revert_opts['date'] = None
444 revert_opts['date'] = None
445 revert_opts['all'] = True
445 revert_opts['all'] = True
446 revert_opts['rev'] = hex(parent)
446 revert_opts['rev'] = hex(parent)
447 revert_opts['no_backup'] = None
447 revert_opts['no_backup'] = None
448 revert(ui, repo, **revert_opts)
448 revert(ui, repo, **revert_opts)
449 if not opts.get('merge') and op1 != node:
449 if not opts.get('merge') and op1 != node:
450 try:
450 try:
451 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
452 return hg.update(repo, op1)
452 return hg.update(repo, op1)
453 finally:
453 finally:
454 ui.setconfig('ui', 'forcemerge', '')
454 ui.setconfig('ui', 'forcemerge', '')
455
455
456 commit_opts = opts.copy()
456 commit_opts = opts.copy()
457 commit_opts['addremove'] = False
457 commit_opts['addremove'] = False
458 if not commit_opts['message'] and not commit_opts['logfile']:
458 if not commit_opts['message'] and not commit_opts['logfile']:
459 # we don't translate commit messages
459 # we don't translate commit messages
460 commit_opts['message'] = "Backed out changeset %s" % short(node)
460 commit_opts['message'] = "Backed out changeset %s" % short(node)
461 commit_opts['force_editor'] = True
461 commit_opts['force_editor'] = True
462 commit(ui, repo, **commit_opts)
462 commit(ui, repo, **commit_opts)
463 def nice(node):
463 def nice(node):
464 return '%d:%s' % (repo.changelog.rev(node), short(node))
464 return '%d:%s' % (repo.changelog.rev(node), short(node))
465 ui.status(_('changeset %s backs out changeset %s\n') %
465 ui.status(_('changeset %s backs out changeset %s\n') %
466 (nice(repo.changelog.tip()), nice(node)))
466 (nice(repo.changelog.tip()), nice(node)))
467 if opts.get('merge') and op1 != node:
467 if opts.get('merge') and op1 != node:
468 hg.clean(repo, op1, show_stats=False)
468 hg.clean(repo, op1, show_stats=False)
469 ui.status(_('merging with changeset %s\n')
469 ui.status(_('merging with changeset %s\n')
470 % nice(repo.changelog.tip()))
470 % nice(repo.changelog.tip()))
471 try:
471 try:
472 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
472 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
473 return hg.merge(repo, hex(repo.changelog.tip()))
473 return hg.merge(repo, hex(repo.changelog.tip()))
474 finally:
474 finally:
475 ui.setconfig('ui', 'forcemerge', '')
475 ui.setconfig('ui', 'forcemerge', '')
476 return 0
476 return 0
477
477
478 @command('bisect',
478 @command('bisect',
479 [('r', 'reset', False, _('reset bisect state')),
479 [('r', 'reset', False, _('reset bisect state')),
480 ('g', 'good', False, _('mark changeset good')),
480 ('g', 'good', False, _('mark changeset good')),
481 ('b', 'bad', False, _('mark changeset bad')),
481 ('b', 'bad', False, _('mark changeset bad')),
482 ('s', 'skip', False, _('skip testing changeset')),
482 ('s', 'skip', False, _('skip testing changeset')),
483 ('e', 'extend', False, _('extend the bisect range')),
483 ('e', 'extend', False, _('extend the bisect range')),
484 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
484 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
485 ('U', 'noupdate', False, _('do not update to target'))],
485 ('U', 'noupdate', False, _('do not update to target'))],
486 _("[-gbsr] [-U] [-c CMD] [REV]"))
486 _("[-gbsr] [-U] [-c CMD] [REV]"))
487 def bisect(ui, repo, rev=None, extra=None, command=None,
487 def bisect(ui, repo, rev=None, extra=None, command=None,
488 reset=None, good=None, bad=None, skip=None, extend=None,
488 reset=None, good=None, bad=None, skip=None, extend=None,
489 noupdate=None):
489 noupdate=None):
490 """subdivision search of changesets
490 """subdivision search of changesets
491
491
492 This command helps to find changesets which introduce problems. To
492 This command helps to find changesets which introduce problems. To
493 use, mark the earliest changeset you know exhibits the problem as
493 use, mark the earliest changeset you know exhibits the problem as
494 bad, then mark the latest changeset which is free from the problem
494 bad, then mark the latest changeset which is free from the problem
495 as good. Bisect will update your working directory to a revision
495 as good. Bisect will update your working directory to a revision
496 for testing (unless the -U/--noupdate option is specified). Once
496 for testing (unless the -U/--noupdate option is specified). Once
497 you have performed tests, mark the working directory as good or
497 you have performed tests, mark the working directory as good or
498 bad, and bisect will either update to another candidate changeset
498 bad, and bisect will either update to another candidate changeset
499 or announce that it has found the bad revision.
499 or announce that it has found the bad revision.
500
500
501 As a shortcut, you can also use the revision argument to mark a
501 As a shortcut, you can also use the revision argument to mark a
502 revision as good or bad without checking it out first.
502 revision as good or bad without checking it out first.
503
503
504 If you supply a command, it will be used for automatic bisection.
504 If you supply a command, it will be used for automatic bisection.
505 Its exit status will be used to mark revisions as good or bad:
505 Its exit status will be used to mark revisions as good or bad:
506 status 0 means good, 125 means to skip the revision, 127
506 status 0 means good, 125 means to skip the revision, 127
507 (command not found) will abort the bisection, and any other
507 (command not found) will abort the bisection, and any other
508 non-zero exit status means the revision is bad.
508 non-zero exit status means the revision is bad.
509
509
510 .. container:: verbose
510 .. container:: verbose
511
511
512 Some examples:
512 Some examples:
513
513
514 - start a bisection with known bad revision 12, and good revision 34::
514 - start a bisection with known bad revision 12, and good revision 34::
515
515
516 hg bisect --bad 34
516 hg bisect --bad 34
517 hg bisect --good 12
517 hg bisect --good 12
518
518
519 - advance the current bisection by marking current revision as good or
519 - advance the current bisection by marking current revision as good or
520 bad::
520 bad::
521
521
522 hg bisect --good
522 hg bisect --good
523 hg bisect --bad
523 hg bisect --bad
524
524
525 - mark the current revision, or a known revision, to be skipped (eg. if
525 - mark the current revision, or a known revision, to be skipped (eg. if
526 that revision is not usable because of another issue)::
526 that revision is not usable because of another issue)::
527
527
528 hg bisect --skip
528 hg bisect --skip
529 hg bisect --skip 23
529 hg bisect --skip 23
530
530
531 - forget the current bisection::
531 - forget the current bisection::
532
532
533 hg bisect --reset
533 hg bisect --reset
534
534
535 - use 'make && make tests' to automatically find the first broken
535 - use 'make && make tests' to automatically find the first broken
536 revision::
536 revision::
537
537
538 hg bisect --reset
538 hg bisect --reset
539 hg bisect --bad 34
539 hg bisect --bad 34
540 hg bisect --good 12
540 hg bisect --good 12
541 hg bisect --command 'make && make tests'
541 hg bisect --command 'make && make tests'
542
542
543 - see all changesets whose states are already known in the current
543 - see all changesets whose states are already known in the current
544 bisection::
544 bisection::
545
545
546 hg log -r "bisect(pruned)"
546 hg log -r "bisect(pruned)"
547
547
548 - see all changesets that took part in the current bisection::
548 - see all changesets that took part in the current bisection::
549
549
550 hg log -r "bisect(range)"
550 hg log -r "bisect(range)"
551
551
552 - with the graphlog extension, you can even get a nice graph::
552 - with the graphlog extension, you can even get a nice graph::
553
553
554 hg log --graph -r "bisect(range)"
554 hg log --graph -r "bisect(range)"
555
555
556 See :hg:`help revsets` for more about the `bisect()` keyword.
556 See :hg:`help revsets` for more about the `bisect()` keyword.
557
557
558 Returns 0 on success.
558 Returns 0 on success.
559 """
559 """
560 def extendbisectrange(nodes, good):
560 def extendbisectrange(nodes, good):
561 # bisect is incomplete when it ends on a merge node and
561 # bisect is incomplete when it ends on a merge node and
562 # one of the parent was not checked.
562 # one of the parent was not checked.
563 parents = repo[nodes[0]].parents()
563 parents = repo[nodes[0]].parents()
564 if len(parents) > 1:
564 if len(parents) > 1:
565 side = good and state['bad'] or state['good']
565 side = good and state['bad'] or state['good']
566 num = len(set(i.node() for i in parents) & set(side))
566 num = len(set(i.node() for i in parents) & set(side))
567 if num == 1:
567 if num == 1:
568 return parents[0].ancestor(parents[1])
568 return parents[0].ancestor(parents[1])
569 return None
569 return None
570
570
571 def print_result(nodes, good):
571 def print_result(nodes, good):
572 displayer = cmdutil.show_changeset(ui, repo, {})
572 displayer = cmdutil.show_changeset(ui, repo, {})
573 if len(nodes) == 1:
573 if len(nodes) == 1:
574 # narrowed it down to a single revision
574 # narrowed it down to a single revision
575 if good:
575 if good:
576 ui.write(_("The first good revision is:\n"))
576 ui.write(_("The first good revision is:\n"))
577 else:
577 else:
578 ui.write(_("The first bad revision is:\n"))
578 ui.write(_("The first bad revision is:\n"))
579 displayer.show(repo[nodes[0]])
579 displayer.show(repo[nodes[0]])
580 extendnode = extendbisectrange(nodes, good)
580 extendnode = extendbisectrange(nodes, good)
581 if extendnode is not None:
581 if extendnode is not None:
582 ui.write(_('Not all ancestors of this changeset have been'
582 ui.write(_('Not all ancestors of this changeset have been'
583 ' checked.\nUse bisect --extend to continue the '
583 ' checked.\nUse bisect --extend to continue the '
584 'bisection from\nthe common ancestor, %s.\n')
584 'bisection from\nthe common ancestor, %s.\n')
585 % extendnode)
585 % extendnode)
586 else:
586 else:
587 # multiple possible revisions
587 # multiple possible revisions
588 if good:
588 if good:
589 ui.write(_("Due to skipped revisions, the first "
589 ui.write(_("Due to skipped revisions, the first "
590 "good revision could be any of:\n"))
590 "good revision could be any of:\n"))
591 else:
591 else:
592 ui.write(_("Due to skipped revisions, the first "
592 ui.write(_("Due to skipped revisions, the first "
593 "bad revision could be any of:\n"))
593 "bad revision could be any of:\n"))
594 for n in nodes:
594 for n in nodes:
595 displayer.show(repo[n])
595 displayer.show(repo[n])
596 displayer.close()
596 displayer.close()
597
597
598 def check_state(state, interactive=True):
598 def check_state(state, interactive=True):
599 if not state['good'] or not state['bad']:
599 if not state['good'] or not state['bad']:
600 if (good or bad or skip or reset) and interactive:
600 if (good or bad or skip or reset) and interactive:
601 return
601 return
602 if not state['good']:
602 if not state['good']:
603 raise util.Abort(_('cannot bisect (no known good revisions)'))
603 raise util.Abort(_('cannot bisect (no known good revisions)'))
604 else:
604 else:
605 raise util.Abort(_('cannot bisect (no known bad revisions)'))
605 raise util.Abort(_('cannot bisect (no known bad revisions)'))
606 return True
606 return True
607
607
608 # backward compatibility
608 # backward compatibility
609 if rev in "good bad reset init".split():
609 if rev in "good bad reset init".split():
610 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
610 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
611 cmd, rev, extra = rev, extra, None
611 cmd, rev, extra = rev, extra, None
612 if cmd == "good":
612 if cmd == "good":
613 good = True
613 good = True
614 elif cmd == "bad":
614 elif cmd == "bad":
615 bad = True
615 bad = True
616 else:
616 else:
617 reset = True
617 reset = True
618 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
618 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
619 raise util.Abort(_('incompatible arguments'))
619 raise util.Abort(_('incompatible arguments'))
620
620
621 if reset:
621 if reset:
622 p = repo.join("bisect.state")
622 p = repo.join("bisect.state")
623 if os.path.exists(p):
623 if os.path.exists(p):
624 os.unlink(p)
624 os.unlink(p)
625 return
625 return
626
626
627 state = hbisect.load_state(repo)
627 state = hbisect.load_state(repo)
628
628
629 if command:
629 if command:
630 changesets = 1
630 changesets = 1
631 try:
631 try:
632 while changesets:
632 while changesets:
633 # update state
633 # update state
634 status = util.system(command, out=ui.fout)
634 status = util.system(command, out=ui.fout)
635 if status == 125:
635 if status == 125:
636 transition = "skip"
636 transition = "skip"
637 elif status == 0:
637 elif status == 0:
638 transition = "good"
638 transition = "good"
639 # status < 0 means process was killed
639 # status < 0 means process was killed
640 elif status == 127:
640 elif status == 127:
641 raise util.Abort(_("failed to execute %s") % command)
641 raise util.Abort(_("failed to execute %s") % command)
642 elif status < 0:
642 elif status < 0:
643 raise util.Abort(_("%s killed") % command)
643 raise util.Abort(_("%s killed") % command)
644 else:
644 else:
645 transition = "bad"
645 transition = "bad"
646 ctx = scmutil.revsingle(repo, rev)
646 ctx = scmutil.revsingle(repo, rev)
647 rev = None # clear for future iterations
647 rev = None # clear for future iterations
648 state[transition].append(ctx.node())
648 state[transition].append(ctx.node())
649 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
649 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
650 check_state(state, interactive=False)
650 check_state(state, interactive=False)
651 # bisect
651 # bisect
652 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
652 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
653 # update to next check
653 # update to next check
654 cmdutil.bailifchanged(repo)
654 cmdutil.bailifchanged(repo)
655 hg.clean(repo, nodes[0], show_stats=False)
655 hg.clean(repo, nodes[0], show_stats=False)
656 finally:
656 finally:
657 hbisect.save_state(repo, state)
657 hbisect.save_state(repo, state)
658 print_result(nodes, good)
658 print_result(nodes, good)
659 return
659 return
660
660
661 # update state
661 # update state
662
662
663 if rev:
663 if rev:
664 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
664 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
665 else:
665 else:
666 nodes = [repo.lookup('.')]
666 nodes = [repo.lookup('.')]
667
667
668 if good or bad or skip:
668 if good or bad or skip:
669 if good:
669 if good:
670 state['good'] += nodes
670 state['good'] += nodes
671 elif bad:
671 elif bad:
672 state['bad'] += nodes
672 state['bad'] += nodes
673 elif skip:
673 elif skip:
674 state['skip'] += nodes
674 state['skip'] += nodes
675 hbisect.save_state(repo, state)
675 hbisect.save_state(repo, state)
676
676
677 if not check_state(state):
677 if not check_state(state):
678 return
678 return
679
679
680 # actually bisect
680 # actually bisect
681 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
681 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
682 if extend:
682 if extend:
683 if not changesets:
683 if not changesets:
684 extendnode = extendbisectrange(nodes, good)
684 extendnode = extendbisectrange(nodes, good)
685 if extendnode is not None:
685 if extendnode is not None:
686 ui.write(_("Extending search to changeset %d:%s\n"
686 ui.write(_("Extending search to changeset %d:%s\n"
687 % (extendnode.rev(), extendnode)))
687 % (extendnode.rev(), extendnode)))
688 if noupdate:
688 if noupdate:
689 return
689 return
690 cmdutil.bailifchanged(repo)
690 cmdutil.bailifchanged(repo)
691 return hg.clean(repo, extendnode.node())
691 return hg.clean(repo, extendnode.node())
692 raise util.Abort(_("nothing to extend"))
692 raise util.Abort(_("nothing to extend"))
693
693
694 if changesets == 0:
694 if changesets == 0:
695 print_result(nodes, good)
695 print_result(nodes, good)
696 else:
696 else:
697 assert len(nodes) == 1 # only a single node can be tested next
697 assert len(nodes) == 1 # only a single node can be tested next
698 node = nodes[0]
698 node = nodes[0]
699 # compute the approximate number of remaining tests
699 # compute the approximate number of remaining tests
700 tests, size = 0, 2
700 tests, size = 0, 2
701 while size <= changesets:
701 while size <= changesets:
702 tests, size = tests + 1, size * 2
702 tests, size = tests + 1, size * 2
703 rev = repo.changelog.rev(node)
703 rev = repo.changelog.rev(node)
704 ui.write(_("Testing changeset %d:%s "
704 ui.write(_("Testing changeset %d:%s "
705 "(%d changesets remaining, ~%d tests)\n")
705 "(%d changesets remaining, ~%d tests)\n")
706 % (rev, short(node), changesets, tests))
706 % (rev, short(node), changesets, tests))
707 if not noupdate:
707 if not noupdate:
708 cmdutil.bailifchanged(repo)
708 cmdutil.bailifchanged(repo)
709 return hg.clean(repo, node)
709 return hg.clean(repo, node)
710
710
711 @command('bookmarks',
711 @command('bookmarks',
712 [('f', 'force', False, _('force')),
712 [('f', 'force', False, _('force')),
713 ('r', 'rev', '', _('revision'), _('REV')),
713 ('r', 'rev', '', _('revision'), _('REV')),
714 ('d', 'delete', False, _('delete a given bookmark')),
714 ('d', 'delete', False, _('delete a given bookmark')),
715 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
715 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
716 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
716 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
717 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
717 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
718 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
718 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
719 rename=None, inactive=False):
719 rename=None, inactive=False):
720 '''track a line of development with movable markers
720 '''track a line of development with movable markers
721
721
722 Bookmarks are pointers to certain commits that move when
722 Bookmarks are pointers to certain commits that move when
723 committing. Bookmarks are local. They can be renamed, copied and
723 committing. Bookmarks are local. They can be renamed, copied and
724 deleted. It is possible to use bookmark names in :hg:`merge` and
724 deleted. It is possible to use bookmark names in :hg:`merge` and
725 :hg:`update` to merge and update respectively to a given bookmark.
725 :hg:`update` to merge and update respectively to a given bookmark.
726
726
727 You can use :hg:`bookmark NAME` to set a bookmark on the working
727 You can use :hg:`bookmark NAME` to set a bookmark on the working
728 directory's parent revision with the given name. If you specify
728 directory's parent revision with the given name. If you specify
729 a revision using -r REV (where REV may be an existing bookmark),
729 a revision using -r REV (where REV may be an existing bookmark),
730 the bookmark is assigned to that revision.
730 the bookmark is assigned to that revision.
731
731
732 Bookmarks can be pushed and pulled between repositories (see :hg:`help
732 Bookmarks can be pushed and pulled between repositories (see :hg:`help
733 push` and :hg:`help pull`). This requires both the local and remote
733 push` and :hg:`help pull`). This requires both the local and remote
734 repositories to support bookmarks. For versions prior to 1.8, this means
734 repositories to support bookmarks. For versions prior to 1.8, this means
735 the bookmarks extension must be enabled.
735 the bookmarks extension must be enabled.
736 '''
736 '''
737 hexfn = ui.debugflag and hex or short
737 hexfn = ui.debugflag and hex or short
738 marks = repo._bookmarks
738 marks = repo._bookmarks
739 cur = repo.changectx('.').node()
739 cur = repo.changectx('.').node()
740
740
741 if rename:
741 if rename:
742 if rename not in marks:
742 if rename not in marks:
743 raise util.Abort(_("bookmark '%s' does not exist") % rename)
743 raise util.Abort(_("bookmark '%s' does not exist") % rename)
744 if mark in marks and not force:
744 if mark in marks and not force:
745 raise util.Abort(_("bookmark '%s' already exists "
745 raise util.Abort(_("bookmark '%s' already exists "
746 "(use -f to force)") % mark)
746 "(use -f to force)") % mark)
747 if mark is None:
747 if mark is None:
748 raise util.Abort(_("new bookmark name required"))
748 raise util.Abort(_("new bookmark name required"))
749 marks[mark] = marks[rename]
749 marks[mark] = marks[rename]
750 if repo._bookmarkcurrent == rename and not inactive:
750 if repo._bookmarkcurrent == rename and not inactive:
751 bookmarks.setcurrent(repo, mark)
751 bookmarks.setcurrent(repo, mark)
752 del marks[rename]
752 del marks[rename]
753 bookmarks.write(repo)
753 bookmarks.write(repo)
754 return
754 return
755
755
756 if delete:
756 if delete:
757 if mark is None:
757 if mark is None:
758 raise util.Abort(_("bookmark name required"))
758 raise util.Abort(_("bookmark name required"))
759 if mark not in marks:
759 if mark not in marks:
760 raise util.Abort(_("bookmark '%s' does not exist") % mark)
760 raise util.Abort(_("bookmark '%s' does not exist") % mark)
761 if mark == repo._bookmarkcurrent:
761 if mark == repo._bookmarkcurrent:
762 bookmarks.setcurrent(repo, None)
762 bookmarks.setcurrent(repo, None)
763 del marks[mark]
763 del marks[mark]
764 bookmarks.write(repo)
764 bookmarks.write(repo)
765 return
765 return
766
766
767 if mark is not None:
767 if mark is not None:
768 if "\n" in mark:
768 if "\n" in mark:
769 raise util.Abort(_("bookmark name cannot contain newlines"))
769 raise util.Abort(_("bookmark name cannot contain newlines"))
770 mark = mark.strip()
770 mark = mark.strip()
771 if not mark:
771 if not mark:
772 raise util.Abort(_("bookmark names cannot consist entirely of "
772 raise util.Abort(_("bookmark names cannot consist entirely of "
773 "whitespace"))
773 "whitespace"))
774 if inactive and mark == repo._bookmarkcurrent:
774 if inactive and mark == repo._bookmarkcurrent:
775 bookmarks.setcurrent(repo, None)
775 bookmarks.setcurrent(repo, None)
776 return
776 return
777 if mark in marks and not force:
777 if mark in marks and not force:
778 raise util.Abort(_("bookmark '%s' already exists "
778 raise util.Abort(_("bookmark '%s' already exists "
779 "(use -f to force)") % mark)
779 "(use -f to force)") % mark)
780 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
780 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
781 and not force):
781 and not force):
782 raise util.Abort(
782 raise util.Abort(
783 _("a bookmark cannot have the name of an existing branch"))
783 _("a bookmark cannot have the name of an existing branch"))
784 if rev:
784 if rev:
785 marks[mark] = repo.lookup(rev)
785 marks[mark] = repo.lookup(rev)
786 else:
786 else:
787 marks[mark] = repo.changectx('.').node()
787 marks[mark] = repo.changectx('.').node()
788 if not inactive and repo.changectx('.').node() == marks[mark]:
788 if not inactive and repo.changectx('.').node() == marks[mark]:
789 bookmarks.setcurrent(repo, mark)
789 bookmarks.setcurrent(repo, mark)
790 bookmarks.write(repo)
790 bookmarks.write(repo)
791 return
791 return
792
792
793 if mark is None:
793 if mark is None:
794 if rev:
794 if rev:
795 raise util.Abort(_("bookmark name required"))
795 raise util.Abort(_("bookmark name required"))
796 if len(marks) == 0:
796 if len(marks) == 0:
797 ui.status(_("no bookmarks set\n"))
797 ui.status(_("no bookmarks set\n"))
798 else:
798 else:
799 for bmark, n in sorted(marks.iteritems()):
799 for bmark, n in sorted(marks.iteritems()):
800 current = repo._bookmarkcurrent
800 current = repo._bookmarkcurrent
801 if bmark == current and n == cur:
801 if bmark == current and n == cur:
802 prefix, label = '*', 'bookmarks.current'
802 prefix, label = '*', 'bookmarks.current'
803 else:
803 else:
804 prefix, label = ' ', ''
804 prefix, label = ' ', ''
805
805
806 if ui.quiet:
806 if ui.quiet:
807 ui.write("%s\n" % bmark, label=label)
807 ui.write("%s\n" % bmark, label=label)
808 else:
808 else:
809 ui.write(" %s %-25s %d:%s\n" % (
809 ui.write(" %s %-25s %d:%s\n" % (
810 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
810 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
811 label=label)
811 label=label)
812 return
812 return
813
813
814 @command('branch',
814 @command('branch',
815 [('f', 'force', None,
815 [('f', 'force', None,
816 _('set branch name even if it shadows an existing branch')),
816 _('set branch name even if it shadows an existing branch')),
817 ('C', 'clean', None, _('reset branch name to parent branch name'))],
817 ('C', 'clean', None, _('reset branch name to parent branch name'))],
818 _('[-fC] [NAME]'))
818 _('[-fC] [NAME]'))
819 def branch(ui, repo, label=None, **opts):
819 def branch(ui, repo, label=None, **opts):
820 """set or show the current branch name
820 """set or show the current branch name
821
821
822 With no argument, show the current branch name. With one argument,
822 With no argument, show the current branch name. With one argument,
823 set the working directory branch name (the branch will not exist
823 set the working directory branch name (the branch will not exist
824 in the repository until the next commit). Standard practice
824 in the repository until the next commit). Standard practice
825 recommends that primary development take place on the 'default'
825 recommends that primary development take place on the 'default'
826 branch.
826 branch.
827
827
828 Unless -f/--force is specified, branch will not let you set a
828 Unless -f/--force is specified, branch will not let you set a
829 branch name that already exists, even if it's inactive.
829 branch name that already exists, even if it's inactive.
830
830
831 Use -C/--clean to reset the working directory branch to that of
831 Use -C/--clean to reset the working directory branch to that of
832 the parent of the working directory, negating a previous branch
832 the parent of the working directory, negating a previous branch
833 change.
833 change.
834
834
835 Use the command :hg:`update` to switch to an existing branch. Use
835 Use the command :hg:`update` to switch to an existing branch. Use
836 :hg:`commit --close-branch` to mark this branch as closed.
836 :hg:`commit --close-branch` to mark this branch as closed.
837
837
838 .. note::
838 .. note::
839 Branch names are permanent. Use :hg:`bookmark` to create a
839 Branch names are permanent. Use :hg:`bookmark` to create a
840 light-weight bookmark instead. See :hg:`help glossary` for more
840 light-weight bookmark instead. See :hg:`help glossary` for more
841 information about named branches and bookmarks.
841 information about named branches and bookmarks.
842
842
843 Returns 0 on success.
843 Returns 0 on success.
844 """
844 """
845
845
846 if opts.get('clean'):
846 if opts.get('clean'):
847 label = repo[None].p1().branch()
847 label = repo[None].p1().branch()
848 repo.dirstate.setbranch(label)
848 repo.dirstate.setbranch(label)
849 ui.status(_('reset working directory to branch %s\n') % label)
849 ui.status(_('reset working directory to branch %s\n') % label)
850 elif label:
850 elif label:
851 if not opts.get('force') and label in repo.branchtags():
851 if not opts.get('force') and label in repo.branchtags():
852 if label not in [p.branch() for p in repo.parents()]:
852 if label not in [p.branch() for p in repo.parents()]:
853 raise util.Abort(_('a branch of the same name already exists'),
853 raise util.Abort(_('a branch of the same name already exists'),
854 # i18n: "it" refers to an existing branch
854 # i18n: "it" refers to an existing branch
855 hint=_("use 'hg update' to switch to it"))
855 hint=_("use 'hg update' to switch to it"))
856 repo.dirstate.setbranch(label)
856 repo.dirstate.setbranch(label)
857 ui.status(_('marked working directory as branch %s\n') % label)
857 ui.status(_('marked working directory as branch %s\n') % label)
858 else:
858 else:
859 ui.write("%s\n" % repo.dirstate.branch())
859 ui.write("%s\n" % repo.dirstate.branch())
860
860
861 @command('branches',
861 @command('branches',
862 [('a', 'active', False, _('show only branches that have unmerged heads')),
862 [('a', 'active', False, _('show only branches that have unmerged heads')),
863 ('c', 'closed', False, _('show normal and closed branches'))],
863 ('c', 'closed', False, _('show normal and closed branches'))],
864 _('[-ac]'))
864 _('[-ac]'))
865 def branches(ui, repo, active=False, closed=False):
865 def branches(ui, repo, active=False, closed=False):
866 """list repository named branches
866 """list repository named branches
867
867
868 List the repository's named branches, indicating which ones are
868 List the repository's named branches, indicating which ones are
869 inactive. If -c/--closed is specified, also list branches which have
869 inactive. If -c/--closed is specified, also list branches which have
870 been marked closed (see :hg:`commit --close-branch`).
870 been marked closed (see :hg:`commit --close-branch`).
871
871
872 If -a/--active is specified, only show active branches. A branch
872 If -a/--active is specified, only show active branches. A branch
873 is considered active if it contains repository heads.
873 is considered active if it contains repository heads.
874
874
875 Use the command :hg:`update` to switch to an existing branch.
875 Use the command :hg:`update` to switch to an existing branch.
876
876
877 Returns 0.
877 Returns 0.
878 """
878 """
879
879
880 hexfunc = ui.debugflag and hex or short
880 hexfunc = ui.debugflag and hex or short
881 activebranches = [repo[n].branch() for n in repo.heads()]
881 activebranches = [repo[n].branch() for n in repo.heads()]
882 def testactive(tag, node):
882 def testactive(tag, node):
883 realhead = tag in activebranches
883 realhead = tag in activebranches
884 open = node in repo.branchheads(tag, closed=False)
884 open = node in repo.branchheads(tag, closed=False)
885 return realhead and open
885 return realhead and open
886 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
886 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
887 for tag, node in repo.branchtags().items()],
887 for tag, node in repo.branchtags().items()],
888 reverse=True)
888 reverse=True)
889
889
890 for isactive, node, tag in branches:
890 for isactive, node, tag in branches:
891 if (not active) or isactive:
891 if (not active) or isactive:
892 if ui.quiet:
892 if ui.quiet:
893 ui.write("%s\n" % tag)
893 ui.write("%s\n" % tag)
894 else:
894 else:
895 hn = repo.lookup(node)
895 hn = repo.lookup(node)
896 if isactive:
896 if isactive:
897 label = 'branches.active'
897 label = 'branches.active'
898 notice = ''
898 notice = ''
899 elif hn not in repo.branchheads(tag, closed=False):
899 elif hn not in repo.branchheads(tag, closed=False):
900 if not closed:
900 if not closed:
901 continue
901 continue
902 label = 'branches.closed'
902 label = 'branches.closed'
903 notice = _(' (closed)')
903 notice = _(' (closed)')
904 else:
904 else:
905 label = 'branches.inactive'
905 label = 'branches.inactive'
906 notice = _(' (inactive)')
906 notice = _(' (inactive)')
907 if tag == repo.dirstate.branch():
907 if tag == repo.dirstate.branch():
908 label = 'branches.current'
908 label = 'branches.current'
909 rev = str(node).rjust(31 - encoding.colwidth(tag))
909 rev = str(node).rjust(31 - encoding.colwidth(tag))
910 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
910 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
911 tag = ui.label(tag, label)
911 tag = ui.label(tag, label)
912 ui.write("%s %s%s\n" % (tag, rev, notice))
912 ui.write("%s %s%s\n" % (tag, rev, notice))
913
913
914 @command('bundle',
914 @command('bundle',
915 [('f', 'force', None, _('run even when the destination is unrelated')),
915 [('f', 'force', None, _('run even when the destination is unrelated')),
916 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
916 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
917 _('REV')),
917 _('REV')),
918 ('b', 'branch', [], _('a specific branch you would like to bundle'),
918 ('b', 'branch', [], _('a specific branch you would like to bundle'),
919 _('BRANCH')),
919 _('BRANCH')),
920 ('', 'base', [],
920 ('', 'base', [],
921 _('a base changeset assumed to be available at the destination'),
921 _('a base changeset assumed to be available at the destination'),
922 _('REV')),
922 _('REV')),
923 ('a', 'all', None, _('bundle all changesets in the repository')),
923 ('a', 'all', None, _('bundle all changesets in the repository')),
924 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
924 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
925 ] + remoteopts,
925 ] + remoteopts,
926 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
926 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
927 def bundle(ui, repo, fname, dest=None, **opts):
927 def bundle(ui, repo, fname, dest=None, **opts):
928 """create a changegroup file
928 """create a changegroup file
929
929
930 Generate a compressed changegroup file collecting changesets not
930 Generate a compressed changegroup file collecting changesets not
931 known to be in another repository.
931 known to be in another repository.
932
932
933 If you omit the destination repository, then hg assumes the
933 If you omit the destination repository, then hg assumes the
934 destination will have all the nodes you specify with --base
934 destination will have all the nodes you specify with --base
935 parameters. To create a bundle containing all changesets, use
935 parameters. To create a bundle containing all changesets, use
936 -a/--all (or --base null).
936 -a/--all (or --base null).
937
937
938 You can change compression method with the -t/--type option.
938 You can change compression method with the -t/--type option.
939 The available compression methods are: none, bzip2, and
939 The available compression methods are: none, bzip2, and
940 gzip (by default, bundles are compressed using bzip2).
940 gzip (by default, bundles are compressed using bzip2).
941
941
942 The bundle file can then be transferred using conventional means
942 The bundle file can then be transferred using conventional means
943 and applied to another repository with the unbundle or pull
943 and applied to another repository with the unbundle or pull
944 command. This is useful when direct push and pull are not
944 command. This is useful when direct push and pull are not
945 available or when exporting an entire repository is undesirable.
945 available or when exporting an entire repository is undesirable.
946
946
947 Applying bundles preserves all changeset contents including
947 Applying bundles preserves all changeset contents including
948 permissions, copy/rename information, and revision history.
948 permissions, copy/rename information, and revision history.
949
949
950 Returns 0 on success, 1 if no changes found.
950 Returns 0 on success, 1 if no changes found.
951 """
951 """
952 revs = None
952 revs = None
953 if 'rev' in opts:
953 if 'rev' in opts:
954 revs = scmutil.revrange(repo, opts['rev'])
954 revs = scmutil.revrange(repo, opts['rev'])
955
955
956 if opts.get('all'):
956 if opts.get('all'):
957 base = ['null']
957 base = ['null']
958 else:
958 else:
959 base = scmutil.revrange(repo, opts.get('base'))
959 base = scmutil.revrange(repo, opts.get('base'))
960 if base:
960 if base:
961 if dest:
961 if dest:
962 raise util.Abort(_("--base is incompatible with specifying "
962 raise util.Abort(_("--base is incompatible with specifying "
963 "a destination"))
963 "a destination"))
964 common = [repo.lookup(rev) for rev in base]
964 common = [repo.lookup(rev) for rev in base]
965 heads = revs and map(repo.lookup, revs) or revs
965 heads = revs and map(repo.lookup, revs) or revs
966 else:
966 else:
967 dest = ui.expandpath(dest or 'default-push', dest or 'default')
967 dest = ui.expandpath(dest or 'default-push', dest or 'default')
968 dest, branches = hg.parseurl(dest, opts.get('branch'))
968 dest, branches = hg.parseurl(dest, opts.get('branch'))
969 other = hg.peer(repo, opts, dest)
969 other = hg.peer(repo, opts, dest)
970 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
970 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
971 heads = revs and map(repo.lookup, revs) or revs
971 heads = revs and map(repo.lookup, revs) or revs
972 common, outheads = discovery.findcommonoutgoing(repo, other,
972 common, outheads = discovery.findcommonoutgoing(repo, other,
973 onlyheads=heads,
973 onlyheads=heads,
974 force=opts.get('force'))
974 force=opts.get('force'))
975
975
976 cg = repo.getbundle('bundle', common=common, heads=heads)
976 cg = repo.getbundle('bundle', common=common, heads=heads)
977 if not cg:
977 if not cg:
978 ui.status(_("no changes found\n"))
978 ui.status(_("no changes found\n"))
979 return 1
979 return 1
980
980
981 bundletype = opts.get('type', 'bzip2').lower()
981 bundletype = opts.get('type', 'bzip2').lower()
982 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
982 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
983 bundletype = btypes.get(bundletype)
983 bundletype = btypes.get(bundletype)
984 if bundletype not in changegroup.bundletypes:
984 if bundletype not in changegroup.bundletypes:
985 raise util.Abort(_('unknown bundle type specified with --type'))
985 raise util.Abort(_('unknown bundle type specified with --type'))
986
986
987 changegroup.writebundle(cg, fname, bundletype)
987 changegroup.writebundle(cg, fname, bundletype)
988
988
989 @command('cat',
989 @command('cat',
990 [('o', 'output', '',
990 [('o', 'output', '',
991 _('print output to file with formatted name'), _('FORMAT')),
991 _('print output to file with formatted name'), _('FORMAT')),
992 ('r', 'rev', '', _('print the given revision'), _('REV')),
992 ('r', 'rev', '', _('print the given revision'), _('REV')),
993 ('', 'decode', None, _('apply any matching decode filter')),
993 ('', 'decode', None, _('apply any matching decode filter')),
994 ] + walkopts,
994 ] + walkopts,
995 _('[OPTION]... FILE...'))
995 _('[OPTION]... FILE...'))
996 def cat(ui, repo, file1, *pats, **opts):
996 def cat(ui, repo, file1, *pats, **opts):
997 """output the current or given revision of files
997 """output the current or given revision of files
998
998
999 Print the specified files as they were at the given revision. If
999 Print the specified files as they were at the given revision. If
1000 no revision is given, the parent of the working directory is used,
1000 no revision is given, the parent of the working directory is used,
1001 or tip if no revision is checked out.
1001 or tip if no revision is checked out.
1002
1002
1003 Output may be to a file, in which case the name of the file is
1003 Output may be to a file, in which case the name of the file is
1004 given using a format string. The formatting rules are the same as
1004 given using a format string. The formatting rules are the same as
1005 for the export command, with the following additions:
1005 for the export command, with the following additions:
1006
1006
1007 :``%s``: basename of file being printed
1007 :``%s``: basename of file being printed
1008 :``%d``: dirname of file being printed, or '.' if in repository root
1008 :``%d``: dirname of file being printed, or '.' if in repository root
1009 :``%p``: root-relative path name of file being printed
1009 :``%p``: root-relative path name of file being printed
1010
1010
1011 Returns 0 on success.
1011 Returns 0 on success.
1012 """
1012 """
1013 ctx = scmutil.revsingle(repo, opts.get('rev'))
1013 ctx = scmutil.revsingle(repo, opts.get('rev'))
1014 err = 1
1014 err = 1
1015 m = scmutil.match(ctx, (file1,) + pats, opts)
1015 m = scmutil.match(ctx, (file1,) + pats, opts)
1016 for abs in ctx.walk(m):
1016 for abs in ctx.walk(m):
1017 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1017 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1018 pathname=abs)
1018 pathname=abs)
1019 data = ctx[abs].data()
1019 data = ctx[abs].data()
1020 if opts.get('decode'):
1020 if opts.get('decode'):
1021 data = repo.wwritedata(abs, data)
1021 data = repo.wwritedata(abs, data)
1022 fp.write(data)
1022 fp.write(data)
1023 fp.close()
1023 fp.close()
1024 err = 0
1024 err = 0
1025 return err
1025 return err
1026
1026
1027 @command('^clone',
1027 @command('^clone',
1028 [('U', 'noupdate', None,
1028 [('U', 'noupdate', None,
1029 _('the clone will include an empty working copy (only a repository)')),
1029 _('the clone will include an empty working copy (only a repository)')),
1030 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1030 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1031 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1031 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1032 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1032 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1033 ('', 'pull', None, _('use pull protocol to copy metadata')),
1033 ('', 'pull', None, _('use pull protocol to copy metadata')),
1034 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1034 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1035 ] + remoteopts,
1035 ] + remoteopts,
1036 _('[OPTION]... SOURCE [DEST]'))
1036 _('[OPTION]... SOURCE [DEST]'))
1037 def clone(ui, source, dest=None, **opts):
1037 def clone(ui, source, dest=None, **opts):
1038 """make a copy of an existing repository
1038 """make a copy of an existing repository
1039
1039
1040 Create a copy of an existing repository in a new directory.
1040 Create a copy of an existing repository in a new directory.
1041
1041
1042 If no destination directory name is specified, it defaults to the
1042 If no destination directory name is specified, it defaults to the
1043 basename of the source.
1043 basename of the source.
1044
1044
1045 The location of the source is added to the new repository's
1045 The location of the source is added to the new repository's
1046 ``.hg/hgrc`` file, as the default to be used for future pulls.
1046 ``.hg/hgrc`` file, as the default to be used for future pulls.
1047
1047
1048 Only local paths and ``ssh://`` URLs are supported as
1048 Only local paths and ``ssh://`` URLs are supported as
1049 destinations. For ``ssh://`` destinations, no working directory or
1049 destinations. For ``ssh://`` destinations, no working directory or
1050 ``.hg/hgrc`` will be created on the remote side.
1050 ``.hg/hgrc`` will be created on the remote side.
1051
1051
1052 To pull only a subset of changesets, specify one or more revisions
1052 To pull only a subset of changesets, specify one or more revisions
1053 identifiers with -r/--rev or branches with -b/--branch. The
1053 identifiers with -r/--rev or branches with -b/--branch. The
1054 resulting clone will contain only the specified changesets and
1054 resulting clone will contain only the specified changesets and
1055 their ancestors. These options (or 'clone src#rev dest') imply
1055 their ancestors. These options (or 'clone src#rev dest') imply
1056 --pull, even for local source repositories. Note that specifying a
1056 --pull, even for local source repositories. Note that specifying a
1057 tag will include the tagged changeset but not the changeset
1057 tag will include the tagged changeset but not the changeset
1058 containing the tag.
1058 containing the tag.
1059
1059
1060 To check out a particular version, use -u/--update, or
1060 To check out a particular version, use -u/--update, or
1061 -U/--noupdate to create a clone with no working directory.
1061 -U/--noupdate to create a clone with no working directory.
1062
1062
1063 .. container:: verbose
1063 .. container:: verbose
1064
1064
1065 For efficiency, hardlinks are used for cloning whenever the
1065 For efficiency, hardlinks are used for cloning whenever the
1066 source and destination are on the same filesystem (note this
1066 source and destination are on the same filesystem (note this
1067 applies only to the repository data, not to the working
1067 applies only to the repository data, not to the working
1068 directory). Some filesystems, such as AFS, implement hardlinking
1068 directory). Some filesystems, such as AFS, implement hardlinking
1069 incorrectly, but do not report errors. In these cases, use the
1069 incorrectly, but do not report errors. In these cases, use the
1070 --pull option to avoid hardlinking.
1070 --pull option to avoid hardlinking.
1071
1071
1072 In some cases, you can clone repositories and the working
1072 In some cases, you can clone repositories and the working
1073 directory using full hardlinks with ::
1073 directory using full hardlinks with ::
1074
1074
1075 $ cp -al REPO REPOCLONE
1075 $ cp -al REPO REPOCLONE
1076
1076
1077 This is the fastest way to clone, but it is not always safe. The
1077 This is the fastest way to clone, but it is not always safe. The
1078 operation is not atomic (making sure REPO is not modified during
1078 operation is not atomic (making sure REPO is not modified during
1079 the operation is up to you) and you have to make sure your
1079 the operation is up to you) and you have to make sure your
1080 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1080 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1081 so). Also, this is not compatible with certain extensions that
1081 so). Also, this is not compatible with certain extensions that
1082 place their metadata under the .hg directory, such as mq.
1082 place their metadata under the .hg directory, such as mq.
1083
1083
1084 Mercurial will update the working directory to the first applicable
1084 Mercurial will update the working directory to the first applicable
1085 revision from this list:
1085 revision from this list:
1086
1086
1087 a) null if -U or the source repository has no changesets
1087 a) null if -U or the source repository has no changesets
1088 b) if -u . and the source repository is local, the first parent of
1088 b) if -u . and the source repository is local, the first parent of
1089 the source repository's working directory
1089 the source repository's working directory
1090 c) the changeset specified with -u (if a branch name, this means the
1090 c) the changeset specified with -u (if a branch name, this means the
1091 latest head of that branch)
1091 latest head of that branch)
1092 d) the changeset specified with -r
1092 d) the changeset specified with -r
1093 e) the tipmost head specified with -b
1093 e) the tipmost head specified with -b
1094 f) the tipmost head specified with the url#branch source syntax
1094 f) the tipmost head specified with the url#branch source syntax
1095 g) the tipmost head of the default branch
1095 g) the tipmost head of the default branch
1096 h) tip
1096 h) tip
1097
1097
1098 Examples:
1098 Examples:
1099
1099
1100 - clone a remote repository to a new directory named hg/::
1100 - clone a remote repository to a new directory named hg/::
1101
1101
1102 hg clone http://selenic.com/hg
1102 hg clone http://selenic.com/hg
1103
1103
1104 - create a lightweight local clone::
1104 - create a lightweight local clone::
1105
1105
1106 hg clone project/ project-feature/
1106 hg clone project/ project-feature/
1107
1107
1108 - clone from an absolute path on an ssh server (note double-slash)::
1108 - clone from an absolute path on an ssh server (note double-slash)::
1109
1109
1110 hg clone ssh://user@server//home/projects/alpha/
1110 hg clone ssh://user@server//home/projects/alpha/
1111
1111
1112 - do a high-speed clone over a LAN while checking out a
1112 - do a high-speed clone over a LAN while checking out a
1113 specified version::
1113 specified version::
1114
1114
1115 hg clone --uncompressed http://server/repo -u 1.5
1115 hg clone --uncompressed http://server/repo -u 1.5
1116
1116
1117 - create a repository without changesets after a particular revision::
1117 - create a repository without changesets after a particular revision::
1118
1118
1119 hg clone -r 04e544 experimental/ good/
1119 hg clone -r 04e544 experimental/ good/
1120
1120
1121 - clone (and track) a particular named branch::
1121 - clone (and track) a particular named branch::
1122
1122
1123 hg clone http://selenic.com/hg#stable
1123 hg clone http://selenic.com/hg#stable
1124
1124
1125 See :hg:`help urls` for details on specifying URLs.
1125 See :hg:`help urls` for details on specifying URLs.
1126
1126
1127 Returns 0 on success.
1127 Returns 0 on success.
1128 """
1128 """
1129 if opts.get('noupdate') and opts.get('updaterev'):
1129 if opts.get('noupdate') and opts.get('updaterev'):
1130 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1130 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1131
1131
1132 r = hg.clone(ui, opts, source, dest,
1132 r = hg.clone(ui, opts, source, dest,
1133 pull=opts.get('pull'),
1133 pull=opts.get('pull'),
1134 stream=opts.get('uncompressed'),
1134 stream=opts.get('uncompressed'),
1135 rev=opts.get('rev'),
1135 rev=opts.get('rev'),
1136 update=opts.get('updaterev') or not opts.get('noupdate'),
1136 update=opts.get('updaterev') or not opts.get('noupdate'),
1137 branch=opts.get('branch'))
1137 branch=opts.get('branch'))
1138
1138
1139 return r is None
1139 return r is None
1140
1140
1141 @command('^commit|ci',
1141 @command('^commit|ci',
1142 [('A', 'addremove', None,
1142 [('A', 'addremove', None,
1143 _('mark new/missing files as added/removed before committing')),
1143 _('mark new/missing files as added/removed before committing')),
1144 ('', 'close-branch', None,
1144 ('', 'close-branch', None,
1145 _('mark a branch as closed, hiding it from the branch list')),
1145 _('mark a branch as closed, hiding it from the branch list')),
1146 ] + walkopts + commitopts + commitopts2,
1146 ] + walkopts + commitopts + commitopts2,
1147 _('[OPTION]... [FILE]...'))
1147 _('[OPTION]... [FILE]...'))
1148 def commit(ui, repo, *pats, **opts):
1148 def commit(ui, repo, *pats, **opts):
1149 """commit the specified files or all outstanding changes
1149 """commit the specified files or all outstanding changes
1150
1150
1151 Commit changes to the given files into the repository. Unlike a
1151 Commit changes to the given files into the repository. Unlike a
1152 centralized SCM, this operation is a local operation. See
1152 centralized SCM, this operation is a local operation. See
1153 :hg:`push` for a way to actively distribute your changes.
1153 :hg:`push` for a way to actively distribute your changes.
1154
1154
1155 If a list of files is omitted, all changes reported by :hg:`status`
1155 If a list of files is omitted, all changes reported by :hg:`status`
1156 will be committed.
1156 will be committed.
1157
1157
1158 If you are committing the result of a merge, do not provide any
1158 If you are committing the result of a merge, do not provide any
1159 filenames or -I/-X filters.
1159 filenames or -I/-X filters.
1160
1160
1161 If no commit message is specified, Mercurial starts your
1161 If no commit message is specified, Mercurial starts your
1162 configured editor where you can enter a message. In case your
1162 configured editor where you can enter a message. In case your
1163 commit fails, you will find a backup of your message in
1163 commit fails, you will find a backup of your message in
1164 ``.hg/last-message.txt``.
1164 ``.hg/last-message.txt``.
1165
1165
1166 See :hg:`help dates` for a list of formats valid for -d/--date.
1166 See :hg:`help dates` for a list of formats valid for -d/--date.
1167
1167
1168 Returns 0 on success, 1 if nothing changed.
1168 Returns 0 on success, 1 if nothing changed.
1169 """
1169 """
1170 extra = {}
1170 extra = {}
1171 if opts.get('close_branch'):
1171 if opts.get('close_branch'):
1172 if repo['.'].node() not in repo.branchheads():
1172 if repo['.'].node() not in repo.branchheads():
1173 # The topo heads set is included in the branch heads set of the
1173 # The topo heads set is included in the branch heads set of the
1174 # current branch, so it's sufficient to test branchheads
1174 # current branch, so it's sufficient to test branchheads
1175 raise util.Abort(_('can only close branch heads'))
1175 raise util.Abort(_('can only close branch heads'))
1176 extra['close'] = 1
1176 extra['close'] = 1
1177 e = cmdutil.commiteditor
1177 e = cmdutil.commiteditor
1178 if opts.get('force_editor'):
1178 if opts.get('force_editor'):
1179 e = cmdutil.commitforceeditor
1179 e = cmdutil.commitforceeditor
1180
1180
1181 def commitfunc(ui, repo, message, match, opts):
1181 def commitfunc(ui, repo, message, match, opts):
1182 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1182 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1183 editor=e, extra=extra)
1183 editor=e, extra=extra)
1184
1184
1185 branch = repo[None].branch()
1185 branch = repo[None].branch()
1186 bheads = repo.branchheads(branch)
1186 bheads = repo.branchheads(branch)
1187
1187
1188 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1188 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1189 if not node:
1189 if not node:
1190 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1190 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1191 if stat[3]:
1191 if stat[3]:
1192 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1192 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1193 % len(stat[3]))
1193 % len(stat[3]))
1194 else:
1194 else:
1195 ui.status(_("nothing changed\n"))
1195 ui.status(_("nothing changed\n"))
1196 return 1
1196 return 1
1197
1197
1198 ctx = repo[node]
1198 ctx = repo[node]
1199 parents = ctx.parents()
1199 parents = ctx.parents()
1200
1200
1201 if (bheads and node not in bheads and not
1201 if (bheads and node not in bheads and not
1202 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1202 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1203 ui.status(_('created new head\n'))
1203 ui.status(_('created new head\n'))
1204 # The message is not printed for initial roots. For the other
1204 # The message is not printed for initial roots. For the other
1205 # changesets, it is printed in the following situations:
1205 # changesets, it is printed in the following situations:
1206 #
1206 #
1207 # Par column: for the 2 parents with ...
1207 # Par column: for the 2 parents with ...
1208 # N: null or no parent
1208 # N: null or no parent
1209 # B: parent is on another named branch
1209 # B: parent is on another named branch
1210 # C: parent is a regular non head changeset
1210 # C: parent is a regular non head changeset
1211 # H: parent was a branch head of the current branch
1211 # H: parent was a branch head of the current branch
1212 # Msg column: whether we print "created new head" message
1212 # Msg column: whether we print "created new head" message
1213 # In the following, it is assumed that there already exists some
1213 # In the following, it is assumed that there already exists some
1214 # initial branch heads of the current branch, otherwise nothing is
1214 # initial branch heads of the current branch, otherwise nothing is
1215 # printed anyway.
1215 # printed anyway.
1216 #
1216 #
1217 # Par Msg Comment
1217 # Par Msg Comment
1218 # NN y additional topo root
1218 # NN y additional topo root
1219 #
1219 #
1220 # BN y additional branch root
1220 # BN y additional branch root
1221 # CN y additional topo head
1221 # CN y additional topo head
1222 # HN n usual case
1222 # HN n usual case
1223 #
1223 #
1224 # BB y weird additional branch root
1224 # BB y weird additional branch root
1225 # CB y branch merge
1225 # CB y branch merge
1226 # HB n merge with named branch
1226 # HB n merge with named branch
1227 #
1227 #
1228 # CC y additional head from merge
1228 # CC y additional head from merge
1229 # CH n merge with a head
1229 # CH n merge with a head
1230 #
1230 #
1231 # HH n head merge: head count decreases
1231 # HH n head merge: head count decreases
1232
1232
1233 if not opts.get('close_branch'):
1233 if not opts.get('close_branch'):
1234 for r in parents:
1234 for r in parents:
1235 if r.extra().get('close') and r.branch() == branch:
1235 if r.extra().get('close') and r.branch() == branch:
1236 ui.status(_('reopening closed branch head %d\n') % r)
1236 ui.status(_('reopening closed branch head %d\n') % r)
1237
1237
1238 if ui.debugflag:
1238 if ui.debugflag:
1239 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1239 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1240 elif ui.verbose:
1240 elif ui.verbose:
1241 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1241 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1242
1242
1243 @command('copy|cp',
1243 @command('copy|cp',
1244 [('A', 'after', None, _('record a copy that has already occurred')),
1244 [('A', 'after', None, _('record a copy that has already occurred')),
1245 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1245 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1246 ] + walkopts + dryrunopts,
1246 ] + walkopts + dryrunopts,
1247 _('[OPTION]... [SOURCE]... DEST'))
1247 _('[OPTION]... [SOURCE]... DEST'))
1248 def copy(ui, repo, *pats, **opts):
1248 def copy(ui, repo, *pats, **opts):
1249 """mark files as copied for the next commit
1249 """mark files as copied for the next commit
1250
1250
1251 Mark dest as having copies of source files. If dest is a
1251 Mark dest as having copies of source files. If dest is a
1252 directory, copies are put in that directory. If dest is a file,
1252 directory, copies are put in that directory. If dest is a file,
1253 the source must be a single file.
1253 the source must be a single file.
1254
1254
1255 By default, this command copies the contents of files as they
1255 By default, this command copies the contents of files as they
1256 exist in the working directory. If invoked with -A/--after, the
1256 exist in the working directory. If invoked with -A/--after, the
1257 operation is recorded, but no copying is performed.
1257 operation is recorded, but no copying is performed.
1258
1258
1259 This command takes effect with the next commit. To undo a copy
1259 This command takes effect with the next commit. To undo a copy
1260 before that, see :hg:`revert`.
1260 before that, see :hg:`revert`.
1261
1261
1262 Returns 0 on success, 1 if errors are encountered.
1262 Returns 0 on success, 1 if errors are encountered.
1263 """
1263 """
1264 wlock = repo.wlock(False)
1264 wlock = repo.wlock(False)
1265 try:
1265 try:
1266 return cmdutil.copy(ui, repo, pats, opts)
1266 return cmdutil.copy(ui, repo, pats, opts)
1267 finally:
1267 finally:
1268 wlock.release()
1268 wlock.release()
1269
1269
1270 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1270 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1271 def debugancestor(ui, repo, *args):
1271 def debugancestor(ui, repo, *args):
1272 """find the ancestor revision of two revisions in a given index"""
1272 """find the ancestor revision of two revisions in a given index"""
1273 if len(args) == 3:
1273 if len(args) == 3:
1274 index, rev1, rev2 = args
1274 index, rev1, rev2 = args
1275 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1275 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1276 lookup = r.lookup
1276 lookup = r.lookup
1277 elif len(args) == 2:
1277 elif len(args) == 2:
1278 if not repo:
1278 if not repo:
1279 raise util.Abort(_("there is no Mercurial repository here "
1279 raise util.Abort(_("there is no Mercurial repository here "
1280 "(.hg not found)"))
1280 "(.hg not found)"))
1281 rev1, rev2 = args
1281 rev1, rev2 = args
1282 r = repo.changelog
1282 r = repo.changelog
1283 lookup = repo.lookup
1283 lookup = repo.lookup
1284 else:
1284 else:
1285 raise util.Abort(_('either two or three arguments required'))
1285 raise util.Abort(_('either two or three arguments required'))
1286 a = r.ancestor(lookup(rev1), lookup(rev2))
1286 a = r.ancestor(lookup(rev1), lookup(rev2))
1287 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1287 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1288
1288
1289 @command('debugbuilddag',
1289 @command('debugbuilddag',
1290 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1290 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1291 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1291 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1292 ('n', 'new-file', None, _('add new file at each rev'))],
1292 ('n', 'new-file', None, _('add new file at each rev'))],
1293 _('[OPTION]... [TEXT]'))
1293 _('[OPTION]... [TEXT]'))
1294 def debugbuilddag(ui, repo, text=None,
1294 def debugbuilddag(ui, repo, text=None,
1295 mergeable_file=False,
1295 mergeable_file=False,
1296 overwritten_file=False,
1296 overwritten_file=False,
1297 new_file=False):
1297 new_file=False):
1298 """builds a repo with a given DAG from scratch in the current empty repo
1298 """builds a repo with a given DAG from scratch in the current empty repo
1299
1299
1300 The description of the DAG is read from stdin if not given on the
1300 The description of the DAG is read from stdin if not given on the
1301 command line.
1301 command line.
1302
1302
1303 Elements:
1303 Elements:
1304
1304
1305 - "+n" is a linear run of n nodes based on the current default parent
1305 - "+n" is a linear run of n nodes based on the current default parent
1306 - "." is a single node based on the current default parent
1306 - "." is a single node based on the current default parent
1307 - "$" resets the default parent to null (implied at the start);
1307 - "$" resets the default parent to null (implied at the start);
1308 otherwise the default parent is always the last node created
1308 otherwise the default parent is always the last node created
1309 - "<p" sets the default parent to the backref p
1309 - "<p" sets the default parent to the backref p
1310 - "*p" is a fork at parent p, which is a backref
1310 - "*p" is a fork at parent p, which is a backref
1311 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1311 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1312 - "/p2" is a merge of the preceding node and p2
1312 - "/p2" is a merge of the preceding node and p2
1313 - ":tag" defines a local tag for the preceding node
1313 - ":tag" defines a local tag for the preceding node
1314 - "@branch" sets the named branch for subsequent nodes
1314 - "@branch" sets the named branch for subsequent nodes
1315 - "#...\\n" is a comment up to the end of the line
1315 - "#...\\n" is a comment up to the end of the line
1316
1316
1317 Whitespace between the above elements is ignored.
1317 Whitespace between the above elements is ignored.
1318
1318
1319 A backref is either
1319 A backref is either
1320
1320
1321 - a number n, which references the node curr-n, where curr is the current
1321 - a number n, which references the node curr-n, where curr is the current
1322 node, or
1322 node, or
1323 - the name of a local tag you placed earlier using ":tag", or
1323 - the name of a local tag you placed earlier using ":tag", or
1324 - empty to denote the default parent.
1324 - empty to denote the default parent.
1325
1325
1326 All string valued-elements are either strictly alphanumeric, or must
1326 All string valued-elements are either strictly alphanumeric, or must
1327 be enclosed in double quotes ("..."), with "\\" as escape character.
1327 be enclosed in double quotes ("..."), with "\\" as escape character.
1328 """
1328 """
1329
1329
1330 if text is None:
1330 if text is None:
1331 ui.status(_("reading DAG from stdin\n"))
1331 ui.status(_("reading DAG from stdin\n"))
1332 text = ui.fin.read()
1332 text = ui.fin.read()
1333
1333
1334 cl = repo.changelog
1334 cl = repo.changelog
1335 if len(cl) > 0:
1335 if len(cl) > 0:
1336 raise util.Abort(_('repository is not empty'))
1336 raise util.Abort(_('repository is not empty'))
1337
1337
1338 # determine number of revs in DAG
1338 # determine number of revs in DAG
1339 total = 0
1339 total = 0
1340 for type, data in dagparser.parsedag(text):
1340 for type, data in dagparser.parsedag(text):
1341 if type == 'n':
1341 if type == 'n':
1342 total += 1
1342 total += 1
1343
1343
1344 if mergeable_file:
1344 if mergeable_file:
1345 linesperrev = 2
1345 linesperrev = 2
1346 # make a file with k lines per rev
1346 # make a file with k lines per rev
1347 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1347 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1348 initialmergedlines.append("")
1348 initialmergedlines.append("")
1349
1349
1350 tags = []
1350 tags = []
1351
1351
1352 tr = repo.transaction("builddag")
1352 tr = repo.transaction("builddag")
1353 try:
1353 try:
1354
1354
1355 at = -1
1355 at = -1
1356 atbranch = 'default'
1356 atbranch = 'default'
1357 nodeids = []
1357 nodeids = []
1358 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1358 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1359 for type, data in dagparser.parsedag(text):
1359 for type, data in dagparser.parsedag(text):
1360 if type == 'n':
1360 if type == 'n':
1361 ui.note('node %s\n' % str(data))
1361 ui.note('node %s\n' % str(data))
1362 id, ps = data
1362 id, ps = data
1363
1363
1364 files = []
1364 files = []
1365 fctxs = {}
1365 fctxs = {}
1366
1366
1367 p2 = None
1367 p2 = None
1368 if mergeable_file:
1368 if mergeable_file:
1369 fn = "mf"
1369 fn = "mf"
1370 p1 = repo[ps[0]]
1370 p1 = repo[ps[0]]
1371 if len(ps) > 1:
1371 if len(ps) > 1:
1372 p2 = repo[ps[1]]
1372 p2 = repo[ps[1]]
1373 pa = p1.ancestor(p2)
1373 pa = p1.ancestor(p2)
1374 base, local, other = [x[fn].data() for x in pa, p1, p2]
1374 base, local, other = [x[fn].data() for x in pa, p1, p2]
1375 m3 = simplemerge.Merge3Text(base, local, other)
1375 m3 = simplemerge.Merge3Text(base, local, other)
1376 ml = [l.strip() for l in m3.merge_lines()]
1376 ml = [l.strip() for l in m3.merge_lines()]
1377 ml.append("")
1377 ml.append("")
1378 elif at > 0:
1378 elif at > 0:
1379 ml = p1[fn].data().split("\n")
1379 ml = p1[fn].data().split("\n")
1380 else:
1380 else:
1381 ml = initialmergedlines
1381 ml = initialmergedlines
1382 ml[id * linesperrev] += " r%i" % id
1382 ml[id * linesperrev] += " r%i" % id
1383 mergedtext = "\n".join(ml)
1383 mergedtext = "\n".join(ml)
1384 files.append(fn)
1384 files.append(fn)
1385 fctxs[fn] = context.memfilectx(fn, mergedtext)
1385 fctxs[fn] = context.memfilectx(fn, mergedtext)
1386
1386
1387 if overwritten_file:
1387 if overwritten_file:
1388 fn = "of"
1388 fn = "of"
1389 files.append(fn)
1389 files.append(fn)
1390 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1390 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1391
1391
1392 if new_file:
1392 if new_file:
1393 fn = "nf%i" % id
1393 fn = "nf%i" % id
1394 files.append(fn)
1394 files.append(fn)
1395 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1395 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1396 if len(ps) > 1:
1396 if len(ps) > 1:
1397 if not p2:
1397 if not p2:
1398 p2 = repo[ps[1]]
1398 p2 = repo[ps[1]]
1399 for fn in p2:
1399 for fn in p2:
1400 if fn.startswith("nf"):
1400 if fn.startswith("nf"):
1401 files.append(fn)
1401 files.append(fn)
1402 fctxs[fn] = p2[fn]
1402 fctxs[fn] = p2[fn]
1403
1403
1404 def fctxfn(repo, cx, path):
1404 def fctxfn(repo, cx, path):
1405 return fctxs.get(path)
1405 return fctxs.get(path)
1406
1406
1407 if len(ps) == 0 or ps[0] < 0:
1407 if len(ps) == 0 or ps[0] < 0:
1408 pars = [None, None]
1408 pars = [None, None]
1409 elif len(ps) == 1:
1409 elif len(ps) == 1:
1410 pars = [nodeids[ps[0]], None]
1410 pars = [nodeids[ps[0]], None]
1411 else:
1411 else:
1412 pars = [nodeids[p] for p in ps]
1412 pars = [nodeids[p] for p in ps]
1413 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1413 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1414 date=(id, 0),
1414 date=(id, 0),
1415 user="debugbuilddag",
1415 user="debugbuilddag",
1416 extra={'branch': atbranch})
1416 extra={'branch': atbranch})
1417 nodeid = repo.commitctx(cx)
1417 nodeid = repo.commitctx(cx)
1418 nodeids.append(nodeid)
1418 nodeids.append(nodeid)
1419 at = id
1419 at = id
1420 elif type == 'l':
1420 elif type == 'l':
1421 id, name = data
1421 id, name = data
1422 ui.note('tag %s\n' % name)
1422 ui.note('tag %s\n' % name)
1423 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1423 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1424 elif type == 'a':
1424 elif type == 'a':
1425 ui.note('branch %s\n' % data)
1425 ui.note('branch %s\n' % data)
1426 atbranch = data
1426 atbranch = data
1427 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1427 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1428 tr.close()
1428 tr.close()
1429 finally:
1429 finally:
1430 ui.progress(_('building'), None)
1430 ui.progress(_('building'), None)
1431 tr.release()
1431 tr.release()
1432
1432
1433 if tags:
1433 if tags:
1434 repo.opener.write("localtags", "".join(tags))
1434 repo.opener.write("localtags", "".join(tags))
1435
1435
1436 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1436 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1437 def debugbundle(ui, bundlepath, all=None, **opts):
1437 def debugbundle(ui, bundlepath, all=None, **opts):
1438 """lists the contents of a bundle"""
1438 """lists the contents of a bundle"""
1439 f = url.open(ui, bundlepath)
1439 f = url.open(ui, bundlepath)
1440 try:
1440 try:
1441 gen = changegroup.readbundle(f, bundlepath)
1441 gen = changegroup.readbundle(f, bundlepath)
1442 if all:
1442 if all:
1443 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1443 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1444
1444
1445 def showchunks(named):
1445 def showchunks(named):
1446 ui.write("\n%s\n" % named)
1446 ui.write("\n%s\n" % named)
1447 chain = None
1447 chain = None
1448 while True:
1448 while True:
1449 chunkdata = gen.deltachunk(chain)
1449 chunkdata = gen.deltachunk(chain)
1450 if not chunkdata:
1450 if not chunkdata:
1451 break
1451 break
1452 node = chunkdata['node']
1452 node = chunkdata['node']
1453 p1 = chunkdata['p1']
1453 p1 = chunkdata['p1']
1454 p2 = chunkdata['p2']
1454 p2 = chunkdata['p2']
1455 cs = chunkdata['cs']
1455 cs = chunkdata['cs']
1456 deltabase = chunkdata['deltabase']
1456 deltabase = chunkdata['deltabase']
1457 delta = chunkdata['delta']
1457 delta = chunkdata['delta']
1458 ui.write("%s %s %s %s %s %s\n" %
1458 ui.write("%s %s %s %s %s %s\n" %
1459 (hex(node), hex(p1), hex(p2),
1459 (hex(node), hex(p1), hex(p2),
1460 hex(cs), hex(deltabase), len(delta)))
1460 hex(cs), hex(deltabase), len(delta)))
1461 chain = node
1461 chain = node
1462
1462
1463 chunkdata = gen.changelogheader()
1463 chunkdata = gen.changelogheader()
1464 showchunks("changelog")
1464 showchunks("changelog")
1465 chunkdata = gen.manifestheader()
1465 chunkdata = gen.manifestheader()
1466 showchunks("manifest")
1466 showchunks("manifest")
1467 while True:
1467 while True:
1468 chunkdata = gen.filelogheader()
1468 chunkdata = gen.filelogheader()
1469 if not chunkdata:
1469 if not chunkdata:
1470 break
1470 break
1471 fname = chunkdata['filename']
1471 fname = chunkdata['filename']
1472 showchunks(fname)
1472 showchunks(fname)
1473 else:
1473 else:
1474 chunkdata = gen.changelogheader()
1474 chunkdata = gen.changelogheader()
1475 chain = None
1475 chain = None
1476 while True:
1476 while True:
1477 chunkdata = gen.deltachunk(chain)
1477 chunkdata = gen.deltachunk(chain)
1478 if not chunkdata:
1478 if not chunkdata:
1479 break
1479 break
1480 node = chunkdata['node']
1480 node = chunkdata['node']
1481 ui.write("%s\n" % hex(node))
1481 ui.write("%s\n" % hex(node))
1482 chain = node
1482 chain = node
1483 finally:
1483 finally:
1484 f.close()
1484 f.close()
1485
1485
1486 @command('debugcheckstate', [], '')
1486 @command('debugcheckstate', [], '')
1487 def debugcheckstate(ui, repo):
1487 def debugcheckstate(ui, repo):
1488 """validate the correctness of the current dirstate"""
1488 """validate the correctness of the current dirstate"""
1489 parent1, parent2 = repo.dirstate.parents()
1489 parent1, parent2 = repo.dirstate.parents()
1490 m1 = repo[parent1].manifest()
1490 m1 = repo[parent1].manifest()
1491 m2 = repo[parent2].manifest()
1491 m2 = repo[parent2].manifest()
1492 errors = 0
1492 errors = 0
1493 for f in repo.dirstate:
1493 for f in repo.dirstate:
1494 state = repo.dirstate[f]
1494 state = repo.dirstate[f]
1495 if state in "nr" and f not in m1:
1495 if state in "nr" and f not in m1:
1496 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1496 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1497 errors += 1
1497 errors += 1
1498 if state in "a" and f in m1:
1498 if state in "a" and f in m1:
1499 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1499 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1500 errors += 1
1500 errors += 1
1501 if state in "m" and f not in m1 and f not in m2:
1501 if state in "m" and f not in m1 and f not in m2:
1502 ui.warn(_("%s in state %s, but not in either manifest\n") %
1502 ui.warn(_("%s in state %s, but not in either manifest\n") %
1503 (f, state))
1503 (f, state))
1504 errors += 1
1504 errors += 1
1505 for f in m1:
1505 for f in m1:
1506 state = repo.dirstate[f]
1506 state = repo.dirstate[f]
1507 if state not in "nrm":
1507 if state not in "nrm":
1508 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1508 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1509 errors += 1
1509 errors += 1
1510 if errors:
1510 if errors:
1511 error = _(".hg/dirstate inconsistent with current parent's manifest")
1511 error = _(".hg/dirstate inconsistent with current parent's manifest")
1512 raise util.Abort(error)
1512 raise util.Abort(error)
1513
1513
1514 @command('debugcommands', [], _('[COMMAND]'))
1514 @command('debugcommands', [], _('[COMMAND]'))
1515 def debugcommands(ui, cmd='', *args):
1515 def debugcommands(ui, cmd='', *args):
1516 """list all available commands and options"""
1516 """list all available commands and options"""
1517 for cmd, vals in sorted(table.iteritems()):
1517 for cmd, vals in sorted(table.iteritems()):
1518 cmd = cmd.split('|')[0].strip('^')
1518 cmd = cmd.split('|')[0].strip('^')
1519 opts = ', '.join([i[1] for i in vals[1]])
1519 opts = ', '.join([i[1] for i in vals[1]])
1520 ui.write('%s: %s\n' % (cmd, opts))
1520 ui.write('%s: %s\n' % (cmd, opts))
1521
1521
1522 @command('debugcomplete',
1522 @command('debugcomplete',
1523 [('o', 'options', None, _('show the command options'))],
1523 [('o', 'options', None, _('show the command options'))],
1524 _('[-o] CMD'))
1524 _('[-o] CMD'))
1525 def debugcomplete(ui, cmd='', **opts):
1525 def debugcomplete(ui, cmd='', **opts):
1526 """returns the completion list associated with the given command"""
1526 """returns the completion list associated with the given command"""
1527
1527
1528 if opts.get('options'):
1528 if opts.get('options'):
1529 options = []
1529 options = []
1530 otables = [globalopts]
1530 otables = [globalopts]
1531 if cmd:
1531 if cmd:
1532 aliases, entry = cmdutil.findcmd(cmd, table, False)
1532 aliases, entry = cmdutil.findcmd(cmd, table, False)
1533 otables.append(entry[1])
1533 otables.append(entry[1])
1534 for t in otables:
1534 for t in otables:
1535 for o in t:
1535 for o in t:
1536 if "(DEPRECATED)" in o[3]:
1536 if "(DEPRECATED)" in o[3]:
1537 continue
1537 continue
1538 if o[0]:
1538 if o[0]:
1539 options.append('-%s' % o[0])
1539 options.append('-%s' % o[0])
1540 options.append('--%s' % o[1])
1540 options.append('--%s' % o[1])
1541 ui.write("%s\n" % "\n".join(options))
1541 ui.write("%s\n" % "\n".join(options))
1542 return
1542 return
1543
1543
1544 cmdlist = cmdutil.findpossible(cmd, table)
1544 cmdlist = cmdutil.findpossible(cmd, table)
1545 if ui.verbose:
1545 if ui.verbose:
1546 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1546 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1547 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1547 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1548
1548
1549 @command('debugdag',
1549 @command('debugdag',
1550 [('t', 'tags', None, _('use tags as labels')),
1550 [('t', 'tags', None, _('use tags as labels')),
1551 ('b', 'branches', None, _('annotate with branch names')),
1551 ('b', 'branches', None, _('annotate with branch names')),
1552 ('', 'dots', None, _('use dots for runs')),
1552 ('', 'dots', None, _('use dots for runs')),
1553 ('s', 'spaces', None, _('separate elements by spaces'))],
1553 ('s', 'spaces', None, _('separate elements by spaces'))],
1554 _('[OPTION]... [FILE [REV]...]'))
1554 _('[OPTION]... [FILE [REV]...]'))
1555 def debugdag(ui, repo, file_=None, *revs, **opts):
1555 def debugdag(ui, repo, file_=None, *revs, **opts):
1556 """format the changelog or an index DAG as a concise textual description
1556 """format the changelog or an index DAG as a concise textual description
1557
1557
1558 If you pass a revlog index, the revlog's DAG is emitted. If you list
1558 If you pass a revlog index, the revlog's DAG is emitted. If you list
1559 revision numbers, they get labelled in the output as rN.
1559 revision numbers, they get labelled in the output as rN.
1560
1560
1561 Otherwise, the changelog DAG of the current repo is emitted.
1561 Otherwise, the changelog DAG of the current repo is emitted.
1562 """
1562 """
1563 spaces = opts.get('spaces')
1563 spaces = opts.get('spaces')
1564 dots = opts.get('dots')
1564 dots = opts.get('dots')
1565 if file_:
1565 if file_:
1566 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1566 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1567 revs = set((int(r) for r in revs))
1567 revs = set((int(r) for r in revs))
1568 def events():
1568 def events():
1569 for r in rlog:
1569 for r in rlog:
1570 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1570 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1571 if r in revs:
1571 if r in revs:
1572 yield 'l', (r, "r%i" % r)
1572 yield 'l', (r, "r%i" % r)
1573 elif repo:
1573 elif repo:
1574 cl = repo.changelog
1574 cl = repo.changelog
1575 tags = opts.get('tags')
1575 tags = opts.get('tags')
1576 branches = opts.get('branches')
1576 branches = opts.get('branches')
1577 if tags:
1577 if tags:
1578 labels = {}
1578 labels = {}
1579 for l, n in repo.tags().items():
1579 for l, n in repo.tags().items():
1580 labels.setdefault(cl.rev(n), []).append(l)
1580 labels.setdefault(cl.rev(n), []).append(l)
1581 def events():
1581 def events():
1582 b = "default"
1582 b = "default"
1583 for r in cl:
1583 for r in cl:
1584 if branches:
1584 if branches:
1585 newb = cl.read(cl.node(r))[5]['branch']
1585 newb = cl.read(cl.node(r))[5]['branch']
1586 if newb != b:
1586 if newb != b:
1587 yield 'a', newb
1587 yield 'a', newb
1588 b = newb
1588 b = newb
1589 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1589 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1590 if tags:
1590 if tags:
1591 ls = labels.get(r)
1591 ls = labels.get(r)
1592 if ls:
1592 if ls:
1593 for l in ls:
1593 for l in ls:
1594 yield 'l', (r, l)
1594 yield 'l', (r, l)
1595 else:
1595 else:
1596 raise util.Abort(_('need repo for changelog dag'))
1596 raise util.Abort(_('need repo for changelog dag'))
1597
1597
1598 for line in dagparser.dagtextlines(events(),
1598 for line in dagparser.dagtextlines(events(),
1599 addspaces=spaces,
1599 addspaces=spaces,
1600 wraplabels=True,
1600 wraplabels=True,
1601 wrapannotations=True,
1601 wrapannotations=True,
1602 wrapnonlinear=dots,
1602 wrapnonlinear=dots,
1603 usedots=dots,
1603 usedots=dots,
1604 maxlinewidth=70):
1604 maxlinewidth=70):
1605 ui.write(line)
1605 ui.write(line)
1606 ui.write("\n")
1606 ui.write("\n")
1607
1607
1608 @command('debugdata',
1608 @command('debugdata',
1609 [('c', 'changelog', False, _('open changelog')),
1609 [('c', 'changelog', False, _('open changelog')),
1610 ('m', 'manifest', False, _('open manifest'))],
1610 ('m', 'manifest', False, _('open manifest'))],
1611 _('-c|-m|FILE REV'))
1611 _('-c|-m|FILE REV'))
1612 def debugdata(ui, repo, file_, rev = None, **opts):
1612 def debugdata(ui, repo, file_, rev = None, **opts):
1613 """dump the contents of a data file revision"""
1613 """dump the contents of a data file revision"""
1614 if opts.get('changelog') or opts.get('manifest'):
1614 if opts.get('changelog') or opts.get('manifest'):
1615 file_, rev = None, file_
1615 file_, rev = None, file_
1616 elif rev is None:
1616 elif rev is None:
1617 raise error.CommandError('debugdata', _('invalid arguments'))
1617 raise error.CommandError('debugdata', _('invalid arguments'))
1618 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1618 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1619 try:
1619 try:
1620 ui.write(r.revision(r.lookup(rev)))
1620 ui.write(r.revision(r.lookup(rev)))
1621 except KeyError:
1621 except KeyError:
1622 raise util.Abort(_('invalid revision identifier %s') % rev)
1622 raise util.Abort(_('invalid revision identifier %s') % rev)
1623
1623
1624 @command('debugdate',
1624 @command('debugdate',
1625 [('e', 'extended', None, _('try extended date formats'))],
1625 [('e', 'extended', None, _('try extended date formats'))],
1626 _('[-e] DATE [RANGE]'))
1626 _('[-e] DATE [RANGE]'))
1627 def debugdate(ui, date, range=None, **opts):
1627 def debugdate(ui, date, range=None, **opts):
1628 """parse and display a date"""
1628 """parse and display a date"""
1629 if opts["extended"]:
1629 if opts["extended"]:
1630 d = util.parsedate(date, util.extendeddateformats)
1630 d = util.parsedate(date, util.extendeddateformats)
1631 else:
1631 else:
1632 d = util.parsedate(date)
1632 d = util.parsedate(date)
1633 ui.write("internal: %s %s\n" % d)
1633 ui.write("internal: %s %s\n" % d)
1634 ui.write("standard: %s\n" % util.datestr(d))
1634 ui.write("standard: %s\n" % util.datestr(d))
1635 if range:
1635 if range:
1636 m = util.matchdate(range)
1636 m = util.matchdate(range)
1637 ui.write("match: %s\n" % m(d[0]))
1637 ui.write("match: %s\n" % m(d[0]))
1638
1638
1639 @command('debugdiscovery',
1639 @command('debugdiscovery',
1640 [('', 'old', None, _('use old-style discovery')),
1640 [('', 'old', None, _('use old-style discovery')),
1641 ('', 'nonheads', None,
1641 ('', 'nonheads', None,
1642 _('use old-style discovery with non-heads included')),
1642 _('use old-style discovery with non-heads included')),
1643 ] + remoteopts,
1643 ] + remoteopts,
1644 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1644 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1645 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1645 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1646 """runs the changeset discovery protocol in isolation"""
1646 """runs the changeset discovery protocol in isolation"""
1647 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1647 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1648 remote = hg.peer(repo, opts, remoteurl)
1648 remote = hg.peer(repo, opts, remoteurl)
1649 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1649 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1650
1650
1651 # make sure tests are repeatable
1651 # make sure tests are repeatable
1652 random.seed(12323)
1652 random.seed(12323)
1653
1653
1654 def doit(localheads, remoteheads):
1654 def doit(localheads, remoteheads):
1655 if opts.get('old'):
1655 if opts.get('old'):
1656 if localheads:
1656 if localheads:
1657 raise util.Abort('cannot use localheads with old style discovery')
1657 raise util.Abort('cannot use localheads with old style discovery')
1658 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1658 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1659 force=True)
1659 force=True)
1660 common = set(common)
1660 common = set(common)
1661 if not opts.get('nonheads'):
1661 if not opts.get('nonheads'):
1662 ui.write("unpruned common: %s\n" % " ".join([short(n)
1662 ui.write("unpruned common: %s\n" % " ".join([short(n)
1663 for n in common]))
1663 for n in common]))
1664 dag = dagutil.revlogdag(repo.changelog)
1664 dag = dagutil.revlogdag(repo.changelog)
1665 all = dag.ancestorset(dag.internalizeall(common))
1665 all = dag.ancestorset(dag.internalizeall(common))
1666 common = dag.externalizeall(dag.headsetofconnecteds(all))
1666 common = dag.externalizeall(dag.headsetofconnecteds(all))
1667 else:
1667 else:
1668 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1668 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1669 common = set(common)
1669 common = set(common)
1670 rheads = set(hds)
1670 rheads = set(hds)
1671 lheads = set(repo.heads())
1671 lheads = set(repo.heads())
1672 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1672 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1673 if lheads <= common:
1673 if lheads <= common:
1674 ui.write("local is subset\n")
1674 ui.write("local is subset\n")
1675 elif rheads <= common:
1675 elif rheads <= common:
1676 ui.write("remote is subset\n")
1676 ui.write("remote is subset\n")
1677
1677
1678 serverlogs = opts.get('serverlog')
1678 serverlogs = opts.get('serverlog')
1679 if serverlogs:
1679 if serverlogs:
1680 for filename in serverlogs:
1680 for filename in serverlogs:
1681 logfile = open(filename, 'r')
1681 logfile = open(filename, 'r')
1682 try:
1682 try:
1683 line = logfile.readline()
1683 line = logfile.readline()
1684 while line:
1684 while line:
1685 parts = line.strip().split(';')
1685 parts = line.strip().split(';')
1686 op = parts[1]
1686 op = parts[1]
1687 if op == 'cg':
1687 if op == 'cg':
1688 pass
1688 pass
1689 elif op == 'cgss':
1689 elif op == 'cgss':
1690 doit(parts[2].split(' '), parts[3].split(' '))
1690 doit(parts[2].split(' '), parts[3].split(' '))
1691 elif op == 'unb':
1691 elif op == 'unb':
1692 doit(parts[3].split(' '), parts[2].split(' '))
1692 doit(parts[3].split(' '), parts[2].split(' '))
1693 line = logfile.readline()
1693 line = logfile.readline()
1694 finally:
1694 finally:
1695 logfile.close()
1695 logfile.close()
1696
1696
1697 else:
1697 else:
1698 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1698 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1699 opts.get('remote_head'))
1699 opts.get('remote_head'))
1700 localrevs = opts.get('local_head')
1700 localrevs = opts.get('local_head')
1701 doit(localrevs, remoterevs)
1701 doit(localrevs, remoterevs)
1702
1702
1703 @command('debugfileset', [], ('REVSPEC'))
1703 @command('debugfileset', [], ('REVSPEC'))
1704 def debugfileset(ui, repo, expr):
1704 def debugfileset(ui, repo, expr):
1705 '''parse and apply a fileset specification'''
1705 '''parse and apply a fileset specification'''
1706 if ui.verbose:
1706 if ui.verbose:
1707 tree = fileset.parse(expr)[0]
1707 tree = fileset.parse(expr)[0]
1708 ui.note(tree, "\n")
1708 ui.note(tree, "\n")
1709
1709
1710 for f in fileset.getfileset(repo[None], expr):
1710 for f in fileset.getfileset(repo[None], expr):
1711 ui.write("%s\n" % f)
1711 ui.write("%s\n" % f)
1712
1712
1713 @command('debugfsinfo', [], _('[PATH]'))
1713 @command('debugfsinfo', [], _('[PATH]'))
1714 def debugfsinfo(ui, path = "."):
1714 def debugfsinfo(ui, path = "."):
1715 """show information detected about current filesystem"""
1715 """show information detected about current filesystem"""
1716 util.writefile('.debugfsinfo', '')
1716 util.writefile('.debugfsinfo', '')
1717 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1717 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1718 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1718 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1719 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1719 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1720 and 'yes' or 'no'))
1720 and 'yes' or 'no'))
1721 os.unlink('.debugfsinfo')
1721 os.unlink('.debugfsinfo')
1722
1722
1723 @command('debuggetbundle',
1723 @command('debuggetbundle',
1724 [('H', 'head', [], _('id of head node'), _('ID')),
1724 [('H', 'head', [], _('id of head node'), _('ID')),
1725 ('C', 'common', [], _('id of common node'), _('ID')),
1725 ('C', 'common', [], _('id of common node'), _('ID')),
1726 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1726 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1727 _('REPO FILE [-H|-C ID]...'))
1727 _('REPO FILE [-H|-C ID]...'))
1728 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1728 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1729 """retrieves a bundle from a repo
1729 """retrieves a bundle from a repo
1730
1730
1731 Every ID must be a full-length hex node id string. Saves the bundle to the
1731 Every ID must be a full-length hex node id string. Saves the bundle to the
1732 given file.
1732 given file.
1733 """
1733 """
1734 repo = hg.peer(ui, opts, repopath)
1734 repo = hg.peer(ui, opts, repopath)
1735 if not repo.capable('getbundle'):
1735 if not repo.capable('getbundle'):
1736 raise util.Abort("getbundle() not supported by target repository")
1736 raise util.Abort("getbundle() not supported by target repository")
1737 args = {}
1737 args = {}
1738 if common:
1738 if common:
1739 args['common'] = [bin(s) for s in common]
1739 args['common'] = [bin(s) for s in common]
1740 if head:
1740 if head:
1741 args['heads'] = [bin(s) for s in head]
1741 args['heads'] = [bin(s) for s in head]
1742 bundle = repo.getbundle('debug', **args)
1742 bundle = repo.getbundle('debug', **args)
1743
1743
1744 bundletype = opts.get('type', 'bzip2').lower()
1744 bundletype = opts.get('type', 'bzip2').lower()
1745 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1745 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1746 bundletype = btypes.get(bundletype)
1746 bundletype = btypes.get(bundletype)
1747 if bundletype not in changegroup.bundletypes:
1747 if bundletype not in changegroup.bundletypes:
1748 raise util.Abort(_('unknown bundle type specified with --type'))
1748 raise util.Abort(_('unknown bundle type specified with --type'))
1749 changegroup.writebundle(bundle, bundlepath, bundletype)
1749 changegroup.writebundle(bundle, bundlepath, bundletype)
1750
1750
1751 @command('debugignore', [], '')
1751 @command('debugignore', [], '')
1752 def debugignore(ui, repo, *values, **opts):
1752 def debugignore(ui, repo, *values, **opts):
1753 """display the combined ignore pattern"""
1753 """display the combined ignore pattern"""
1754 ignore = repo.dirstate._ignore
1754 ignore = repo.dirstate._ignore
1755 includepat = getattr(ignore, 'includepat', None)
1755 includepat = getattr(ignore, 'includepat', None)
1756 if includepat is not None:
1756 if includepat is not None:
1757 ui.write("%s\n" % includepat)
1757 ui.write("%s\n" % includepat)
1758 else:
1758 else:
1759 raise util.Abort(_("no ignore patterns found"))
1759 raise util.Abort(_("no ignore patterns found"))
1760
1760
1761 @command('debugindex',
1761 @command('debugindex',
1762 [('c', 'changelog', False, _('open changelog')),
1762 [('c', 'changelog', False, _('open changelog')),
1763 ('m', 'manifest', False, _('open manifest')),
1763 ('m', 'manifest', False, _('open manifest')),
1764 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1764 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1765 _('[-f FORMAT] -c|-m|FILE'))
1765 _('[-f FORMAT] -c|-m|FILE'))
1766 def debugindex(ui, repo, file_ = None, **opts):
1766 def debugindex(ui, repo, file_ = None, **opts):
1767 """dump the contents of an index file"""
1767 """dump the contents of an index file"""
1768 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1768 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1769 format = opts.get('format', 0)
1769 format = opts.get('format', 0)
1770 if format not in (0, 1):
1770 if format not in (0, 1):
1771 raise util.Abort(_("unknown format %d") % format)
1771 raise util.Abort(_("unknown format %d") % format)
1772
1772
1773 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1773 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1774 if generaldelta:
1774 if generaldelta:
1775 basehdr = ' delta'
1775 basehdr = ' delta'
1776 else:
1776 else:
1777 basehdr = ' base'
1777 basehdr = ' base'
1778
1778
1779 if format == 0:
1779 if format == 0:
1780 ui.write(" rev offset length " + basehdr + " linkrev"
1780 ui.write(" rev offset length " + basehdr + " linkrev"
1781 " nodeid p1 p2\n")
1781 " nodeid p1 p2\n")
1782 elif format == 1:
1782 elif format == 1:
1783 ui.write(" rev flag offset length"
1783 ui.write(" rev flag offset length"
1784 " size " + basehdr + " link p1 p2 nodeid\n")
1784 " size " + basehdr + " link p1 p2 nodeid\n")
1785
1785
1786 for i in r:
1786 for i in r:
1787 node = r.node(i)
1787 node = r.node(i)
1788 if generaldelta:
1788 if generaldelta:
1789 base = r.deltaparent(i)
1789 base = r.deltaparent(i)
1790 else:
1790 else:
1791 base = r.chainbase(i)
1791 base = r.chainbase(i)
1792 if format == 0:
1792 if format == 0:
1793 try:
1793 try:
1794 pp = r.parents(node)
1794 pp = r.parents(node)
1795 except:
1795 except:
1796 pp = [nullid, nullid]
1796 pp = [nullid, nullid]
1797 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1797 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1798 i, r.start(i), r.length(i), base, r.linkrev(i),
1798 i, r.start(i), r.length(i), base, r.linkrev(i),
1799 short(node), short(pp[0]), short(pp[1])))
1799 short(node), short(pp[0]), short(pp[1])))
1800 elif format == 1:
1800 elif format == 1:
1801 pr = r.parentrevs(i)
1801 pr = r.parentrevs(i)
1802 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1802 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1803 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1803 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1804 base, r.linkrev(i), pr[0], pr[1], short(node)))
1804 base, r.linkrev(i), pr[0], pr[1], short(node)))
1805
1805
1806 @command('debugindexdot', [], _('FILE'))
1806 @command('debugindexdot', [], _('FILE'))
1807 def debugindexdot(ui, repo, file_):
1807 def debugindexdot(ui, repo, file_):
1808 """dump an index DAG as a graphviz dot file"""
1808 """dump an index DAG as a graphviz dot file"""
1809 r = None
1809 r = None
1810 if repo:
1810 if repo:
1811 filelog = repo.file(file_)
1811 filelog = repo.file(file_)
1812 if len(filelog):
1812 if len(filelog):
1813 r = filelog
1813 r = filelog
1814 if not r:
1814 if not r:
1815 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1815 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1816 ui.write("digraph G {\n")
1816 ui.write("digraph G {\n")
1817 for i in r:
1817 for i in r:
1818 node = r.node(i)
1818 node = r.node(i)
1819 pp = r.parents(node)
1819 pp = r.parents(node)
1820 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1820 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1821 if pp[1] != nullid:
1821 if pp[1] != nullid:
1822 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1822 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1823 ui.write("}\n")
1823 ui.write("}\n")
1824
1824
1825 @command('debuginstall', [], '')
1825 @command('debuginstall', [], '')
1826 def debuginstall(ui):
1826 def debuginstall(ui):
1827 '''test Mercurial installation
1827 '''test Mercurial installation
1828
1828
1829 Returns 0 on success.
1829 Returns 0 on success.
1830 '''
1830 '''
1831
1831
1832 def writetemp(contents):
1832 def writetemp(contents):
1833 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1833 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1834 f = os.fdopen(fd, "wb")
1834 f = os.fdopen(fd, "wb")
1835 f.write(contents)
1835 f.write(contents)
1836 f.close()
1836 f.close()
1837 return name
1837 return name
1838
1838
1839 problems = 0
1839 problems = 0
1840
1840
1841 # encoding
1841 # encoding
1842 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1842 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1843 try:
1843 try:
1844 encoding.fromlocal("test")
1844 encoding.fromlocal("test")
1845 except util.Abort, inst:
1845 except util.Abort, inst:
1846 ui.write(" %s\n" % inst)
1846 ui.write(" %s\n" % inst)
1847 ui.write(_(" (check that your locale is properly set)\n"))
1847 ui.write(_(" (check that your locale is properly set)\n"))
1848 problems += 1
1848 problems += 1
1849
1849
1850 # compiled modules
1850 # compiled modules
1851 ui.status(_("Checking installed modules (%s)...\n")
1851 ui.status(_("Checking installed modules (%s)...\n")
1852 % os.path.dirname(__file__))
1852 % os.path.dirname(__file__))
1853 try:
1853 try:
1854 import bdiff, mpatch, base85, osutil
1854 import bdiff, mpatch, base85, osutil
1855 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1855 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1856 except Exception, inst:
1856 except Exception, inst:
1857 ui.write(" %s\n" % inst)
1857 ui.write(" %s\n" % inst)
1858 ui.write(_(" One or more extensions could not be found"))
1858 ui.write(_(" One or more extensions could not be found"))
1859 ui.write(_(" (check that you compiled the extensions)\n"))
1859 ui.write(_(" (check that you compiled the extensions)\n"))
1860 problems += 1
1860 problems += 1
1861
1861
1862 # templates
1862 # templates
1863 import templater
1863 import templater
1864 p = templater.templatepath()
1864 p = templater.templatepath()
1865 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1865 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1866 try:
1866 try:
1867 templater.templater(templater.templatepath("map-cmdline.default"))
1867 templater.templater(templater.templatepath("map-cmdline.default"))
1868 except Exception, inst:
1868 except Exception, inst:
1869 ui.write(" %s\n" % inst)
1869 ui.write(" %s\n" % inst)
1870 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1870 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1871 problems += 1
1871 problems += 1
1872
1872
1873 # editor
1873 # editor
1874 ui.status(_("Checking commit editor...\n"))
1874 ui.status(_("Checking commit editor...\n"))
1875 editor = ui.geteditor()
1875 editor = ui.geteditor()
1876 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1876 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1877 if not cmdpath:
1877 if not cmdpath:
1878 if editor == 'vi':
1878 if editor == 'vi':
1879 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1879 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1880 ui.write(_(" (specify a commit editor in your configuration"
1880 ui.write(_(" (specify a commit editor in your configuration"
1881 " file)\n"))
1881 " file)\n"))
1882 else:
1882 else:
1883 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1883 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1884 ui.write(_(" (specify a commit editor in your configuration"
1884 ui.write(_(" (specify a commit editor in your configuration"
1885 " file)\n"))
1885 " file)\n"))
1886 problems += 1
1886 problems += 1
1887
1887
1888 # check username
1888 # check username
1889 ui.status(_("Checking username...\n"))
1889 ui.status(_("Checking username...\n"))
1890 try:
1890 try:
1891 ui.username()
1891 ui.username()
1892 except util.Abort, e:
1892 except util.Abort, e:
1893 ui.write(" %s\n" % e)
1893 ui.write(" %s\n" % e)
1894 ui.write(_(" (specify a username in your configuration file)\n"))
1894 ui.write(_(" (specify a username in your configuration file)\n"))
1895 problems += 1
1895 problems += 1
1896
1896
1897 if not problems:
1897 if not problems:
1898 ui.status(_("No problems detected\n"))
1898 ui.status(_("No problems detected\n"))
1899 else:
1899 else:
1900 ui.write(_("%s problems detected,"
1900 ui.write(_("%s problems detected,"
1901 " please check your install!\n") % problems)
1901 " please check your install!\n") % problems)
1902
1902
1903 return problems
1903 return problems
1904
1904
1905 @command('debugknown', [], _('REPO ID...'))
1905 @command('debugknown', [], _('REPO ID...'))
1906 def debugknown(ui, repopath, *ids, **opts):
1906 def debugknown(ui, repopath, *ids, **opts):
1907 """test whether node ids are known to a repo
1907 """test whether node ids are known to a repo
1908
1908
1909 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1909 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1910 indicating unknown/known.
1910 indicating unknown/known.
1911 """
1911 """
1912 repo = hg.peer(ui, opts, repopath)
1912 repo = hg.peer(ui, opts, repopath)
1913 if not repo.capable('known'):
1913 if not repo.capable('known'):
1914 raise util.Abort("known() not supported by target repository")
1914 raise util.Abort("known() not supported by target repository")
1915 flags = repo.known([bin(s) for s in ids])
1915 flags = repo.known([bin(s) for s in ids])
1916 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1916 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1917
1917
1918 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1918 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1919 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1919 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1920 '''access the pushkey key/value protocol
1920 '''access the pushkey key/value protocol
1921
1921
1922 With two args, list the keys in the given namespace.
1922 With two args, list the keys in the given namespace.
1923
1923
1924 With five args, set a key to new if it currently is set to old.
1924 With five args, set a key to new if it currently is set to old.
1925 Reports success or failure.
1925 Reports success or failure.
1926 '''
1926 '''
1927
1927
1928 target = hg.peer(ui, {}, repopath)
1928 target = hg.peer(ui, {}, repopath)
1929 if keyinfo:
1929 if keyinfo:
1930 key, old, new = keyinfo
1930 key, old, new = keyinfo
1931 r = target.pushkey(namespace, key, old, new)
1931 r = target.pushkey(namespace, key, old, new)
1932 ui.status(str(r) + '\n')
1932 ui.status(str(r) + '\n')
1933 return not r
1933 return not r
1934 else:
1934 else:
1935 for k, v in target.listkeys(namespace).iteritems():
1935 for k, v in target.listkeys(namespace).iteritems():
1936 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1936 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1937 v.encode('string-escape')))
1937 v.encode('string-escape')))
1938
1938
1939 @command('debugrebuildstate',
1939 @command('debugrebuildstate',
1940 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1940 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1941 _('[-r REV] [REV]'))
1941 _('[-r REV] [REV]'))
1942 def debugrebuildstate(ui, repo, rev="tip"):
1942 def debugrebuildstate(ui, repo, rev="tip"):
1943 """rebuild the dirstate as it would look like for the given revision"""
1943 """rebuild the dirstate as it would look like for the given revision"""
1944 ctx = scmutil.revsingle(repo, rev)
1944 ctx = scmutil.revsingle(repo, rev)
1945 wlock = repo.wlock()
1945 wlock = repo.wlock()
1946 try:
1946 try:
1947 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1947 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1948 finally:
1948 finally:
1949 wlock.release()
1949 wlock.release()
1950
1950
1951 @command('debugrename',
1951 @command('debugrename',
1952 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1952 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1953 _('[-r REV] FILE'))
1953 _('[-r REV] FILE'))
1954 def debugrename(ui, repo, file1, *pats, **opts):
1954 def debugrename(ui, repo, file1, *pats, **opts):
1955 """dump rename information"""
1955 """dump rename information"""
1956
1956
1957 ctx = scmutil.revsingle(repo, opts.get('rev'))
1957 ctx = scmutil.revsingle(repo, opts.get('rev'))
1958 m = scmutil.match(ctx, (file1,) + pats, opts)
1958 m = scmutil.match(ctx, (file1,) + pats, opts)
1959 for abs in ctx.walk(m):
1959 for abs in ctx.walk(m):
1960 fctx = ctx[abs]
1960 fctx = ctx[abs]
1961 o = fctx.filelog().renamed(fctx.filenode())
1961 o = fctx.filelog().renamed(fctx.filenode())
1962 rel = m.rel(abs)
1962 rel = m.rel(abs)
1963 if o:
1963 if o:
1964 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1964 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1965 else:
1965 else:
1966 ui.write(_("%s not renamed\n") % rel)
1966 ui.write(_("%s not renamed\n") % rel)
1967
1967
1968 @command('debugrevlog',
1968 @command('debugrevlog',
1969 [('c', 'changelog', False, _('open changelog')),
1969 [('c', 'changelog', False, _('open changelog')),
1970 ('m', 'manifest', False, _('open manifest')),
1970 ('m', 'manifest', False, _('open manifest')),
1971 ('d', 'dump', False, _('dump index data'))],
1971 ('d', 'dump', False, _('dump index data'))],
1972 _('-c|-m|FILE'))
1972 _('-c|-m|FILE'))
1973 def debugrevlog(ui, repo, file_ = None, **opts):
1973 def debugrevlog(ui, repo, file_ = None, **opts):
1974 """show data and statistics about a revlog"""
1974 """show data and statistics about a revlog"""
1975 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1975 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1976
1976
1977 if opts.get("dump"):
1977 if opts.get("dump"):
1978 numrevs = len(r)
1978 numrevs = len(r)
1979 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1979 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1980 " rawsize totalsize compression heads\n")
1980 " rawsize totalsize compression heads\n")
1981 ts = 0
1981 ts = 0
1982 heads = set()
1982 heads = set()
1983 for rev in xrange(numrevs):
1983 for rev in xrange(numrevs):
1984 dbase = r.deltaparent(rev)
1984 dbase = r.deltaparent(rev)
1985 if dbase == -1:
1985 if dbase == -1:
1986 dbase = rev
1986 dbase = rev
1987 cbase = r.chainbase(rev)
1987 cbase = r.chainbase(rev)
1988 p1, p2 = r.parentrevs(rev)
1988 p1, p2 = r.parentrevs(rev)
1989 rs = r.rawsize(rev)
1989 rs = r.rawsize(rev)
1990 ts = ts + rs
1990 ts = ts + rs
1991 heads -= set(r.parentrevs(rev))
1991 heads -= set(r.parentrevs(rev))
1992 heads.add(rev)
1992 heads.add(rev)
1993 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1993 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1994 (rev, p1, p2, r.start(rev), r.end(rev),
1994 (rev, p1, p2, r.start(rev), r.end(rev),
1995 r.start(dbase), r.start(cbase),
1995 r.start(dbase), r.start(cbase),
1996 r.start(p1), r.start(p2),
1996 r.start(p1), r.start(p2),
1997 rs, ts, ts / r.end(rev), len(heads)))
1997 rs, ts, ts / r.end(rev), len(heads)))
1998 return 0
1998 return 0
1999
1999
2000 v = r.version
2000 v = r.version
2001 format = v & 0xFFFF
2001 format = v & 0xFFFF
2002 flags = []
2002 flags = []
2003 gdelta = False
2003 gdelta = False
2004 if v & revlog.REVLOGNGINLINEDATA:
2004 if v & revlog.REVLOGNGINLINEDATA:
2005 flags.append('inline')
2005 flags.append('inline')
2006 if v & revlog.REVLOGGENERALDELTA:
2006 if v & revlog.REVLOGGENERALDELTA:
2007 gdelta = True
2007 gdelta = True
2008 flags.append('generaldelta')
2008 flags.append('generaldelta')
2009 if not flags:
2009 if not flags:
2010 flags = ['(none)']
2010 flags = ['(none)']
2011
2011
2012 nummerges = 0
2012 nummerges = 0
2013 numfull = 0
2013 numfull = 0
2014 numprev = 0
2014 numprev = 0
2015 nump1 = 0
2015 nump1 = 0
2016 nump2 = 0
2016 nump2 = 0
2017 numother = 0
2017 numother = 0
2018 nump1prev = 0
2018 nump1prev = 0
2019 nump2prev = 0
2019 nump2prev = 0
2020 chainlengths = []
2020 chainlengths = []
2021
2021
2022 datasize = [None, 0, 0L]
2022 datasize = [None, 0, 0L]
2023 fullsize = [None, 0, 0L]
2023 fullsize = [None, 0, 0L]
2024 deltasize = [None, 0, 0L]
2024 deltasize = [None, 0, 0L]
2025
2025
2026 def addsize(size, l):
2026 def addsize(size, l):
2027 if l[0] is None or size < l[0]:
2027 if l[0] is None or size < l[0]:
2028 l[0] = size
2028 l[0] = size
2029 if size > l[1]:
2029 if size > l[1]:
2030 l[1] = size
2030 l[1] = size
2031 l[2] += size
2031 l[2] += size
2032
2032
2033 numrevs = len(r)
2033 numrevs = len(r)
2034 for rev in xrange(numrevs):
2034 for rev in xrange(numrevs):
2035 p1, p2 = r.parentrevs(rev)
2035 p1, p2 = r.parentrevs(rev)
2036 delta = r.deltaparent(rev)
2036 delta = r.deltaparent(rev)
2037 if format > 0:
2037 if format > 0:
2038 addsize(r.rawsize(rev), datasize)
2038 addsize(r.rawsize(rev), datasize)
2039 if p2 != nullrev:
2039 if p2 != nullrev:
2040 nummerges += 1
2040 nummerges += 1
2041 size = r.length(rev)
2041 size = r.length(rev)
2042 if delta == nullrev:
2042 if delta == nullrev:
2043 chainlengths.append(0)
2043 chainlengths.append(0)
2044 numfull += 1
2044 numfull += 1
2045 addsize(size, fullsize)
2045 addsize(size, fullsize)
2046 else:
2046 else:
2047 chainlengths.append(chainlengths[delta] + 1)
2047 chainlengths.append(chainlengths[delta] + 1)
2048 addsize(size, deltasize)
2048 addsize(size, deltasize)
2049 if delta == rev - 1:
2049 if delta == rev - 1:
2050 numprev += 1
2050 numprev += 1
2051 if delta == p1:
2051 if delta == p1:
2052 nump1prev += 1
2052 nump1prev += 1
2053 elif delta == p2:
2053 elif delta == p2:
2054 nump2prev += 1
2054 nump2prev += 1
2055 elif delta == p1:
2055 elif delta == p1:
2056 nump1 += 1
2056 nump1 += 1
2057 elif delta == p2:
2057 elif delta == p2:
2058 nump2 += 1
2058 nump2 += 1
2059 elif delta != nullrev:
2059 elif delta != nullrev:
2060 numother += 1
2060 numother += 1
2061
2061
2062 numdeltas = numrevs - numfull
2062 numdeltas = numrevs - numfull
2063 numoprev = numprev - nump1prev - nump2prev
2063 numoprev = numprev - nump1prev - nump2prev
2064 totalrawsize = datasize[2]
2064 totalrawsize = datasize[2]
2065 datasize[2] /= numrevs
2065 datasize[2] /= numrevs
2066 fulltotal = fullsize[2]
2066 fulltotal = fullsize[2]
2067 fullsize[2] /= numfull
2067 fullsize[2] /= numfull
2068 deltatotal = deltasize[2]
2068 deltatotal = deltasize[2]
2069 deltasize[2] /= numrevs - numfull
2069 deltasize[2] /= numrevs - numfull
2070 totalsize = fulltotal + deltatotal
2070 totalsize = fulltotal + deltatotal
2071 avgchainlen = sum(chainlengths) / numrevs
2071 avgchainlen = sum(chainlengths) / numrevs
2072 compratio = totalrawsize / totalsize
2072 compratio = totalrawsize / totalsize
2073
2073
2074 basedfmtstr = '%%%dd\n'
2074 basedfmtstr = '%%%dd\n'
2075 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2075 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2076
2076
2077 def dfmtstr(max):
2077 def dfmtstr(max):
2078 return basedfmtstr % len(str(max))
2078 return basedfmtstr % len(str(max))
2079 def pcfmtstr(max, padding=0):
2079 def pcfmtstr(max, padding=0):
2080 return basepcfmtstr % (len(str(max)), ' ' * padding)
2080 return basepcfmtstr % (len(str(max)), ' ' * padding)
2081
2081
2082 def pcfmt(value, total):
2082 def pcfmt(value, total):
2083 return (value, 100 * float(value) / total)
2083 return (value, 100 * float(value) / total)
2084
2084
2085 ui.write('format : %d\n' % format)
2085 ui.write('format : %d\n' % format)
2086 ui.write('flags : %s\n' % ', '.join(flags))
2086 ui.write('flags : %s\n' % ', '.join(flags))
2087
2087
2088 ui.write('\n')
2088 ui.write('\n')
2089 fmt = pcfmtstr(totalsize)
2089 fmt = pcfmtstr(totalsize)
2090 fmt2 = dfmtstr(totalsize)
2090 fmt2 = dfmtstr(totalsize)
2091 ui.write('revisions : ' + fmt2 % numrevs)
2091 ui.write('revisions : ' + fmt2 % numrevs)
2092 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2092 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2093 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2093 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2094 ui.write('revisions : ' + fmt2 % numrevs)
2094 ui.write('revisions : ' + fmt2 % numrevs)
2095 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2095 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2096 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2096 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2097 ui.write('revision size : ' + fmt2 % totalsize)
2097 ui.write('revision size : ' + fmt2 % totalsize)
2098 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2098 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2099 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2099 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2100
2100
2101 ui.write('\n')
2101 ui.write('\n')
2102 fmt = dfmtstr(max(avgchainlen, compratio))
2102 fmt = dfmtstr(max(avgchainlen, compratio))
2103 ui.write('avg chain length : ' + fmt % avgchainlen)
2103 ui.write('avg chain length : ' + fmt % avgchainlen)
2104 ui.write('compression ratio : ' + fmt % compratio)
2104 ui.write('compression ratio : ' + fmt % compratio)
2105
2105
2106 if format > 0:
2106 if format > 0:
2107 ui.write('\n')
2107 ui.write('\n')
2108 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2108 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2109 % tuple(datasize))
2109 % tuple(datasize))
2110 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2110 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2111 % tuple(fullsize))
2111 % tuple(fullsize))
2112 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2112 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2113 % tuple(deltasize))
2113 % tuple(deltasize))
2114
2114
2115 if numdeltas > 0:
2115 if numdeltas > 0:
2116 ui.write('\n')
2116 ui.write('\n')
2117 fmt = pcfmtstr(numdeltas)
2117 fmt = pcfmtstr(numdeltas)
2118 fmt2 = pcfmtstr(numdeltas, 4)
2118 fmt2 = pcfmtstr(numdeltas, 4)
2119 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2119 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2120 if numprev > 0:
2120 if numprev > 0:
2121 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2121 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2122 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2122 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2123 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2123 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2124 if gdelta:
2124 if gdelta:
2125 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2125 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2126 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2126 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2127 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2127 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2128
2128
2129 @command('debugrevspec', [], ('REVSPEC'))
2129 @command('debugrevspec', [], ('REVSPEC'))
2130 def debugrevspec(ui, repo, expr):
2130 def debugrevspec(ui, repo, expr):
2131 '''parse and apply a revision specification'''
2131 '''parse and apply a revision specification'''
2132 if ui.verbose:
2132 if ui.verbose:
2133 tree = revset.parse(expr)[0]
2133 tree = revset.parse(expr)[0]
2134 ui.note(tree, "\n")
2134 ui.note(tree, "\n")
2135 newtree = revset.findaliases(ui, tree)
2135 newtree = revset.findaliases(ui, tree)
2136 if newtree != tree:
2136 if newtree != tree:
2137 ui.note(newtree, "\n")
2137 ui.note(newtree, "\n")
2138 func = revset.match(ui, expr)
2138 func = revset.match(ui, expr)
2139 for c in func(repo, range(len(repo))):
2139 for c in func(repo, range(len(repo))):
2140 ui.write("%s\n" % c)
2140 ui.write("%s\n" % c)
2141
2141
2142 @command('debugsetparents', [], _('REV1 [REV2]'))
2142 @command('debugsetparents', [], _('REV1 [REV2]'))
2143 def debugsetparents(ui, repo, rev1, rev2=None):
2143 def debugsetparents(ui, repo, rev1, rev2=None):
2144 """manually set the parents of the current working directory
2144 """manually set the parents of the current working directory
2145
2145
2146 This is useful for writing repository conversion tools, but should
2146 This is useful for writing repository conversion tools, but should
2147 be used with care.
2147 be used with care.
2148
2148
2149 Returns 0 on success.
2149 Returns 0 on success.
2150 """
2150 """
2151
2151
2152 r1 = scmutil.revsingle(repo, rev1).node()
2152 r1 = scmutil.revsingle(repo, rev1).node()
2153 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2153 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2154
2154
2155 wlock = repo.wlock()
2155 wlock = repo.wlock()
2156 try:
2156 try:
2157 repo.dirstate.setparents(r1, r2)
2157 repo.dirstate.setparents(r1, r2)
2158 finally:
2158 finally:
2159 wlock.release()
2159 wlock.release()
2160
2160
2161 @command('debugstate',
2161 @command('debugstate',
2162 [('', 'nodates', None, _('do not display the saved mtime')),
2162 [('', 'nodates', None, _('do not display the saved mtime')),
2163 ('', 'datesort', None, _('sort by saved mtime'))],
2163 ('', 'datesort', None, _('sort by saved mtime'))],
2164 _('[OPTION]...'))
2164 _('[OPTION]...'))
2165 def debugstate(ui, repo, nodates=None, datesort=None):
2165 def debugstate(ui, repo, nodates=None, datesort=None):
2166 """show the contents of the current dirstate"""
2166 """show the contents of the current dirstate"""
2167 timestr = ""
2167 timestr = ""
2168 showdate = not nodates
2168 showdate = not nodates
2169 if datesort:
2169 if datesort:
2170 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2170 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2171 else:
2171 else:
2172 keyfunc = None # sort by filename
2172 keyfunc = None # sort by filename
2173 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2173 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2174 if showdate:
2174 if showdate:
2175 if ent[3] == -1:
2175 if ent[3] == -1:
2176 # Pad or slice to locale representation
2176 # Pad or slice to locale representation
2177 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2177 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2178 time.localtime(0)))
2178 time.localtime(0)))
2179 timestr = 'unset'
2179 timestr = 'unset'
2180 timestr = (timestr[:locale_len] +
2180 timestr = (timestr[:locale_len] +
2181 ' ' * (locale_len - len(timestr)))
2181 ' ' * (locale_len - len(timestr)))
2182 else:
2182 else:
2183 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2183 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2184 time.localtime(ent[3]))
2184 time.localtime(ent[3]))
2185 if ent[1] & 020000:
2185 if ent[1] & 020000:
2186 mode = 'lnk'
2186 mode = 'lnk'
2187 else:
2187 else:
2188 mode = '%3o' % (ent[1] & 0777)
2188 mode = '%3o' % (ent[1] & 0777)
2189 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2189 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2190 for f in repo.dirstate.copies():
2190 for f in repo.dirstate.copies():
2191 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2191 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2192
2192
2193 @command('debugsub',
2193 @command('debugsub',
2194 [('r', 'rev', '',
2194 [('r', 'rev', '',
2195 _('revision to check'), _('REV'))],
2195 _('revision to check'), _('REV'))],
2196 _('[-r REV] [REV]'))
2196 _('[-r REV] [REV]'))
2197 def debugsub(ui, repo, rev=None):
2197 def debugsub(ui, repo, rev=None):
2198 ctx = scmutil.revsingle(repo, rev, None)
2198 ctx = scmutil.revsingle(repo, rev, None)
2199 for k, v in sorted(ctx.substate.items()):
2199 for k, v in sorted(ctx.substate.items()):
2200 ui.write('path %s\n' % k)
2200 ui.write('path %s\n' % k)
2201 ui.write(' source %s\n' % v[0])
2201 ui.write(' source %s\n' % v[0])
2202 ui.write(' revision %s\n' % v[1])
2202 ui.write(' revision %s\n' % v[1])
2203
2203
2204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2205 def debugwalk(ui, repo, *pats, **opts):
2205 def debugwalk(ui, repo, *pats, **opts):
2206 """show how files match on given patterns"""
2206 """show how files match on given patterns"""
2207 m = scmutil.match(repo[None], pats, opts)
2207 m = scmutil.match(repo[None], pats, opts)
2208 items = list(repo.walk(m))
2208 items = list(repo.walk(m))
2209 if not items:
2209 if not items:
2210 return
2210 return
2211 fmt = 'f %%-%ds %%-%ds %%s' % (
2211 fmt = 'f %%-%ds %%-%ds %%s' % (
2212 max([len(abs) for abs in items]),
2212 max([len(abs) for abs in items]),
2213 max([len(m.rel(abs)) for abs in items]))
2213 max([len(m.rel(abs)) for abs in items]))
2214 for abs in items:
2214 for abs in items:
2215 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2215 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2216 ui.write("%s\n" % line.rstrip())
2216 ui.write("%s\n" % line.rstrip())
2217
2217
2218 @command('debugwireargs',
2218 @command('debugwireargs',
2219 [('', 'three', '', 'three'),
2219 [('', 'three', '', 'three'),
2220 ('', 'four', '', 'four'),
2220 ('', 'four', '', 'four'),
2221 ('', 'five', '', 'five'),
2221 ('', 'five', '', 'five'),
2222 ] + remoteopts,
2222 ] + remoteopts,
2223 _('REPO [OPTIONS]... [ONE [TWO]]'))
2223 _('REPO [OPTIONS]... [ONE [TWO]]'))
2224 def debugwireargs(ui, repopath, *vals, **opts):
2224 def debugwireargs(ui, repopath, *vals, **opts):
2225 repo = hg.peer(ui, opts, repopath)
2225 repo = hg.peer(ui, opts, repopath)
2226 for opt in remoteopts:
2226 for opt in remoteopts:
2227 del opts[opt[1]]
2227 del opts[opt[1]]
2228 args = {}
2228 args = {}
2229 for k, v in opts.iteritems():
2229 for k, v in opts.iteritems():
2230 if v:
2230 if v:
2231 args[k] = v
2231 args[k] = v
2232 # run twice to check that we don't mess up the stream for the next command
2232 # run twice to check that we don't mess up the stream for the next command
2233 res1 = repo.debugwireargs(*vals, **args)
2233 res1 = repo.debugwireargs(*vals, **args)
2234 res2 = repo.debugwireargs(*vals, **args)
2234 res2 = repo.debugwireargs(*vals, **args)
2235 ui.write("%s\n" % res1)
2235 ui.write("%s\n" % res1)
2236 if res1 != res2:
2236 if res1 != res2:
2237 ui.warn("%s\n" % res2)
2237 ui.warn("%s\n" % res2)
2238
2238
2239 @command('^diff',
2239 @command('^diff',
2240 [('r', 'rev', [], _('revision'), _('REV')),
2240 [('r', 'rev', [], _('revision'), _('REV')),
2241 ('c', 'change', '', _('change made by revision'), _('REV'))
2241 ('c', 'change', '', _('change made by revision'), _('REV'))
2242 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2242 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2243 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2243 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2244 def diff(ui, repo, *pats, **opts):
2244 def diff(ui, repo, *pats, **opts):
2245 """diff repository (or selected files)
2245 """diff repository (or selected files)
2246
2246
2247 Show differences between revisions for the specified files.
2247 Show differences between revisions for the specified files.
2248
2248
2249 Differences between files are shown using the unified diff format.
2249 Differences between files are shown using the unified diff format.
2250
2250
2251 .. note::
2251 .. note::
2252 diff may generate unexpected results for merges, as it will
2252 diff may generate unexpected results for merges, as it will
2253 default to comparing against the working directory's first
2253 default to comparing against the working directory's first
2254 parent changeset if no revisions are specified.
2254 parent changeset if no revisions are specified.
2255
2255
2256 When two revision arguments are given, then changes are shown
2256 When two revision arguments are given, then changes are shown
2257 between those revisions. If only one revision is specified then
2257 between those revisions. If only one revision is specified then
2258 that revision is compared to the working directory, and, when no
2258 that revision is compared to the working directory, and, when no
2259 revisions are specified, the working directory files are compared
2259 revisions are specified, the working directory files are compared
2260 to its parent.
2260 to its parent.
2261
2261
2262 Alternatively you can specify -c/--change with a revision to see
2262 Alternatively you can specify -c/--change with a revision to see
2263 the changes in that changeset relative to its first parent.
2263 the changes in that changeset relative to its first parent.
2264
2264
2265 Without the -a/--text option, diff will avoid generating diffs of
2265 Without the -a/--text option, diff will avoid generating diffs of
2266 files it detects as binary. With -a, diff will generate a diff
2266 files it detects as binary. With -a, diff will generate a diff
2267 anyway, probably with undesirable results.
2267 anyway, probably with undesirable results.
2268
2268
2269 Use the -g/--git option to generate diffs in the git extended diff
2269 Use the -g/--git option to generate diffs in the git extended diff
2270 format. For more information, read :hg:`help diffs`.
2270 format. For more information, read :hg:`help diffs`.
2271
2271
2272 .. container:: verbose
2272 .. container:: verbose
2273
2273
2274 Examples:
2274 Examples:
2275
2275
2276 - compare a file in the current working directory to its parent::
2276 - compare a file in the current working directory to its parent::
2277
2277
2278 hg diff foo.c
2278 hg diff foo.c
2279
2279
2280 - compare two historical versions of a directory, with rename info::
2280 - compare two historical versions of a directory, with rename info::
2281
2281
2282 hg diff --git -r 1.0:1.2 lib/
2282 hg diff --git -r 1.0:1.2 lib/
2283
2283
2284 - get change stats relative to the last change on some date::
2284 - get change stats relative to the last change on some date::
2285
2285
2286 hg diff --stat -r "date('may 2')"
2286 hg diff --stat -r "date('may 2')"
2287
2287
2288 - diff all newly-added files that contain a keyword::
2288 - diff all newly-added files that contain a keyword::
2289
2289
2290 hg diff "set:added() and grep(GNU)"
2290 hg diff "set:added() and grep(GNU)"
2291
2291
2292 - compare a revision and its parents::
2292 - compare a revision and its parents::
2293
2293
2294 hg diff -c 9353 # compare against first parent
2294 hg diff -c 9353 # compare against first parent
2295 hg diff -r 9353^:9353 # same using revset syntax
2295 hg diff -r 9353^:9353 # same using revset syntax
2296 hg diff -r 9353^2:9353 # compare against the second parent
2296 hg diff -r 9353^2:9353 # compare against the second parent
2297
2297
2298 Returns 0 on success.
2298 Returns 0 on success.
2299 """
2299 """
2300
2300
2301 revs = opts.get('rev')
2301 revs = opts.get('rev')
2302 change = opts.get('change')
2302 change = opts.get('change')
2303 stat = opts.get('stat')
2303 stat = opts.get('stat')
2304 reverse = opts.get('reverse')
2304 reverse = opts.get('reverse')
2305
2305
2306 if revs and change:
2306 if revs and change:
2307 msg = _('cannot specify --rev and --change at the same time')
2307 msg = _('cannot specify --rev and --change at the same time')
2308 raise util.Abort(msg)
2308 raise util.Abort(msg)
2309 elif change:
2309 elif change:
2310 node2 = scmutil.revsingle(repo, change, None).node()
2310 node2 = scmutil.revsingle(repo, change, None).node()
2311 node1 = repo[node2].p1().node()
2311 node1 = repo[node2].p1().node()
2312 else:
2312 else:
2313 node1, node2 = scmutil.revpair(repo, revs)
2313 node1, node2 = scmutil.revpair(repo, revs)
2314
2314
2315 if reverse:
2315 if reverse:
2316 node1, node2 = node2, node1
2316 node1, node2 = node2, node1
2317
2317
2318 diffopts = patch.diffopts(ui, opts)
2318 diffopts = patch.diffopts(ui, opts)
2319 m = scmutil.match(repo[node2], pats, opts)
2319 m = scmutil.match(repo[node2], pats, opts)
2320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2321 listsubrepos=opts.get('subrepos'))
2321 listsubrepos=opts.get('subrepos'))
2322
2322
2323 @command('^export',
2323 @command('^export',
2324 [('o', 'output', '',
2324 [('o', 'output', '',
2325 _('print output to file with formatted name'), _('FORMAT')),
2325 _('print output to file with formatted name'), _('FORMAT')),
2326 ('', 'switch-parent', None, _('diff against the second parent')),
2326 ('', 'switch-parent', None, _('diff against the second parent')),
2327 ('r', 'rev', [], _('revisions to export'), _('REV')),
2327 ('r', 'rev', [], _('revisions to export'), _('REV')),
2328 ] + diffopts,
2328 ] + diffopts,
2329 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2329 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2330 def export(ui, repo, *changesets, **opts):
2330 def export(ui, repo, *changesets, **opts):
2331 """dump the header and diffs for one or more changesets
2331 """dump the header and diffs for one or more changesets
2332
2332
2333 Print the changeset header and diffs for one or more revisions.
2333 Print the changeset header and diffs for one or more revisions.
2334
2334
2335 The information shown in the changeset header is: author, date,
2335 The information shown in the changeset header is: author, date,
2336 branch name (if non-default), changeset hash, parent(s) and commit
2336 branch name (if non-default), changeset hash, parent(s) and commit
2337 comment.
2337 comment.
2338
2338
2339 .. note::
2339 .. note::
2340 export may generate unexpected diff output for merge
2340 export may generate unexpected diff output for merge
2341 changesets, as it will compare the merge changeset against its
2341 changesets, as it will compare the merge changeset against its
2342 first parent only.
2342 first parent only.
2343
2343
2344 Output may be to a file, in which case the name of the file is
2344 Output may be to a file, in which case the name of the file is
2345 given using a format string. The formatting rules are as follows:
2345 given using a format string. The formatting rules are as follows:
2346
2346
2347 :``%%``: literal "%" character
2347 :``%%``: literal "%" character
2348 :``%H``: changeset hash (40 hexadecimal digits)
2348 :``%H``: changeset hash (40 hexadecimal digits)
2349 :``%N``: number of patches being generated
2349 :``%N``: number of patches being generated
2350 :``%R``: changeset revision number
2350 :``%R``: changeset revision number
2351 :``%b``: basename of the exporting repository
2351 :``%b``: basename of the exporting repository
2352 :``%h``: short-form changeset hash (12 hexadecimal digits)
2352 :``%h``: short-form changeset hash (12 hexadecimal digits)
2353 :``%m``: first line of the commit message (only alphanumeric characters)
2353 :``%m``: first line of the commit message (only alphanumeric characters)
2354 :``%n``: zero-padded sequence number, starting at 1
2354 :``%n``: zero-padded sequence number, starting at 1
2355 :``%r``: zero-padded changeset revision number
2355 :``%r``: zero-padded changeset revision number
2356
2356
2357 Without the -a/--text option, export will avoid generating diffs
2357 Without the -a/--text option, export will avoid generating diffs
2358 of files it detects as binary. With -a, export will generate a
2358 of files it detects as binary. With -a, export will generate a
2359 diff anyway, probably with undesirable results.
2359 diff anyway, probably with undesirable results.
2360
2360
2361 Use the -g/--git option to generate diffs in the git extended diff
2361 Use the -g/--git option to generate diffs in the git extended diff
2362 format. See :hg:`help diffs` for more information.
2362 format. See :hg:`help diffs` for more information.
2363
2363
2364 With the --switch-parent option, the diff will be against the
2364 With the --switch-parent option, the diff will be against the
2365 second parent. It can be useful to review a merge.
2365 second parent. It can be useful to review a merge.
2366
2366
2367 .. container:: verbose
2367 .. container:: verbose
2368
2368
2369 Examples:
2369 Examples:
2370
2370
2371 - use export and import to transplant a bugfix to the current
2371 - use export and import to transplant a bugfix to the current
2372 branch::
2372 branch::
2373
2373
2374 hg export -r 9353 | hg import -
2374 hg export -r 9353 | hg import -
2375
2375
2376 - export all the changesets between two revisions to a file with
2376 - export all the changesets between two revisions to a file with
2377 rename information::
2377 rename information::
2378
2378
2379 hg export --git -r 123:150 > changes.txt
2379 hg export --git -r 123:150 > changes.txt
2380
2380
2381 - split outgoing changes into a series of patches with
2381 - split outgoing changes into a series of patches with
2382 descriptive names::
2382 descriptive names::
2383
2383
2384 hg export -r "outgoing()" -o "%n-%m.patch"
2384 hg export -r "outgoing()" -o "%n-%m.patch"
2385
2385
2386 Returns 0 on success.
2386 Returns 0 on success.
2387 """
2387 """
2388 changesets += tuple(opts.get('rev', []))
2388 changesets += tuple(opts.get('rev', []))
2389 if not changesets:
2389 if not changesets:
2390 raise util.Abort(_("export requires at least one changeset"))
2390 raise util.Abort(_("export requires at least one changeset"))
2391 revs = scmutil.revrange(repo, changesets)
2391 revs = scmutil.revrange(repo, changesets)
2392 if len(revs) > 1:
2392 if len(revs) > 1:
2393 ui.note(_('exporting patches:\n'))
2393 ui.note(_('exporting patches:\n'))
2394 else:
2394 else:
2395 ui.note(_('exporting patch:\n'))
2395 ui.note(_('exporting patch:\n'))
2396 cmdutil.export(repo, revs, template=opts.get('output'),
2396 cmdutil.export(repo, revs, template=opts.get('output'),
2397 switch_parent=opts.get('switch_parent'),
2397 switch_parent=opts.get('switch_parent'),
2398 opts=patch.diffopts(ui, opts))
2398 opts=patch.diffopts(ui, opts))
2399
2399
2400 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2400 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2401 def forget(ui, repo, *pats, **opts):
2401 def forget(ui, repo, *pats, **opts):
2402 """forget the specified files on the next commit
2402 """forget the specified files on the next commit
2403
2403
2404 Mark the specified files so they will no longer be tracked
2404 Mark the specified files so they will no longer be tracked
2405 after the next commit.
2405 after the next commit.
2406
2406
2407 This only removes files from the current branch, not from the
2407 This only removes files from the current branch, not from the
2408 entire project history, and it does not delete them from the
2408 entire project history, and it does not delete them from the
2409 working directory.
2409 working directory.
2410
2410
2411 To undo a forget before the next commit, see :hg:`add`.
2411 To undo a forget before the next commit, see :hg:`add`.
2412
2412
2413 .. container:: verbose
2413 .. container:: verbose
2414
2414
2415 Examples:
2415 Examples:
2416
2416
2417 - forget newly-added binary files::
2417 - forget newly-added binary files::
2418
2418
2419 hg forget "set:added() and binary()"
2419 hg forget "set:added() and binary()"
2420
2420
2421 - forget files that would be excluded by .hgignore::
2421 - forget files that would be excluded by .hgignore::
2422
2422
2423 hg forget "set:hgignore()"
2423 hg forget "set:hgignore()"
2424
2424
2425 Returns 0 on success.
2425 Returns 0 on success.
2426 """
2426 """
2427
2427
2428 if not pats:
2428 if not pats:
2429 raise util.Abort(_('no files specified'))
2429 raise util.Abort(_('no files specified'))
2430
2430
2431 m = scmutil.match(repo[None], pats, opts)
2431 m = scmutil.match(repo[None], pats, opts)
2432 s = repo.status(match=m, clean=True)
2432 s = repo.status(match=m, clean=True)
2433 forget = sorted(s[0] + s[1] + s[3] + s[6])
2433 forget = sorted(s[0] + s[1] + s[3] + s[6])
2434 errs = 0
2434 errs = 0
2435
2435
2436 for f in m.files():
2436 for f in m.files():
2437 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2437 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2438 if os.path.exists(m.rel(f)):
2438 if os.path.exists(m.rel(f)):
2439 ui.warn(_('not removing %s: file is already untracked\n')
2439 ui.warn(_('not removing %s: file is already untracked\n')
2440 % m.rel(f))
2440 % m.rel(f))
2441 errs = 1
2441 errs = 1
2442
2442
2443 for f in forget:
2443 for f in forget:
2444 if ui.verbose or not m.exact(f):
2444 if ui.verbose or not m.exact(f):
2445 ui.status(_('removing %s\n') % m.rel(f))
2445 ui.status(_('removing %s\n') % m.rel(f))
2446
2446
2447 repo[None].forget(forget)
2447 repo[None].forget(forget)
2448 return errs
2448 return errs
2449
2449
2450 @command('graft',
2451 [],
2452 _('[OPTION]... REVISION...'))
2453 def graft(ui, repo, rev, *revs, **opts):
2454 '''copy changes from other branches onto the current branch
2455
2456 This command uses Mercurial's merge logic to copy individual
2457 changes from other branches without merging branches in the
2458 history graph. This is sometimes known as 'backporting' or
2459 'cherry-picking'.
2460
2461 Changesets that are ancestors of the current revision, that have
2462 already been grafted, or that are merges will be skipped.
2463
2464 Returns 0 on successful completion.
2465 '''
2466
2467 cmdutil.bailifchanged(repo)
2468
2469 revs = [rev] + list(revs)
2470 revs = scmutil.revrange(repo, revs)
2471
2472 # check for merges
2473 for ctx in repo.set('%ld and merge()', revs):
2474 ui.warn(_('skipping ungraftable merge revision %s\n') % ctx.rev())
2475 revs.remove(ctx.rev())
2476 if not revs:
2477 return -1
2478
2479 # check for ancestors of dest branch
2480 for ctx in repo.set('::. and %ld', revs):
2481 ui.warn(_('skipping ancestor revision %s\n') % ctx.rev())
2482 revs.remove(ctx.rev())
2483 if not revs:
2484 return -1
2485
2486 # check ancestors for earlier grafts
2487 ui.debug('scanning for existing transplants')
2488 for ctx in repo.set("::. - ::%ld", revs):
2489 n = ctx.extra().get('source')
2490 if n and n in repo:
2491 r = repo[n].rev()
2492 ui.warn(_('skipping already grafted revision %s\n') % r)
2493 revs.remove(r)
2494 if not revs:
2495 return -1
2496
2497 for ctx in repo.set("%ld", revs):
2498 current = repo['.']
2499 ui.debug('grafting revision %s', ctx.rev())
2500 # perform the graft merge with p1(rev) as 'ancestor'
2501 stats = mergemod.update(repo, ctx.node(), True, True, False,
2502 ctx.p1().node())
2503 # drop the second merge parent
2504 repo.dirstate.setparents(current.node(), nullid)
2505 repo.dirstate.write()
2506 # fix up dirstate for copies and renames
2507 cmdutil.duplicatecopies(repo, ctx.rev(), current.node(), nullid)
2508 # report any conflicts
2509 if stats and stats[3] > 0:
2510 raise util.Abort(_("unresolved conflicts, can't continue"),
2511 hint=_('use hg resolve and hg graft --continue'))
2512 # commit
2513 extra = {'source': ctx.hex()}
2514 repo.commit(text=ctx.description(), user=ctx.user(),
2515 date=ctx.date(), extra=extra)
2516
2517 return 0
2518
2450 @command('grep',
2519 @command('grep',
2451 [('0', 'print0', None, _('end fields with NUL')),
2520 [('0', 'print0', None, _('end fields with NUL')),
2452 ('', 'all', None, _('print all revisions that match')),
2521 ('', 'all', None, _('print all revisions that match')),
2453 ('a', 'text', None, _('treat all files as text')),
2522 ('a', 'text', None, _('treat all files as text')),
2454 ('f', 'follow', None,
2523 ('f', 'follow', None,
2455 _('follow changeset history,'
2524 _('follow changeset history,'
2456 ' or file history across copies and renames')),
2525 ' or file history across copies and renames')),
2457 ('i', 'ignore-case', None, _('ignore case when matching')),
2526 ('i', 'ignore-case', None, _('ignore case when matching')),
2458 ('l', 'files-with-matches', None,
2527 ('l', 'files-with-matches', None,
2459 _('print only filenames and revisions that match')),
2528 _('print only filenames and revisions that match')),
2460 ('n', 'line-number', None, _('print matching line numbers')),
2529 ('n', 'line-number', None, _('print matching line numbers')),
2461 ('r', 'rev', [],
2530 ('r', 'rev', [],
2462 _('only search files changed within revision range'), _('REV')),
2531 _('only search files changed within revision range'), _('REV')),
2463 ('u', 'user', None, _('list the author (long with -v)')),
2532 ('u', 'user', None, _('list the author (long with -v)')),
2464 ('d', 'date', None, _('list the date (short with -q)')),
2533 ('d', 'date', None, _('list the date (short with -q)')),
2465 ] + walkopts,
2534 ] + walkopts,
2466 _('[OPTION]... PATTERN [FILE]...'))
2535 _('[OPTION]... PATTERN [FILE]...'))
2467 def grep(ui, repo, pattern, *pats, **opts):
2536 def grep(ui, repo, pattern, *pats, **opts):
2468 """search for a pattern in specified files and revisions
2537 """search for a pattern in specified files and revisions
2469
2538
2470 Search revisions of files for a regular expression.
2539 Search revisions of files for a regular expression.
2471
2540
2472 This command behaves differently than Unix grep. It only accepts
2541 This command behaves differently than Unix grep. It only accepts
2473 Python/Perl regexps. It searches repository history, not the
2542 Python/Perl regexps. It searches repository history, not the
2474 working directory. It always prints the revision number in which a
2543 working directory. It always prints the revision number in which a
2475 match appears.
2544 match appears.
2476
2545
2477 By default, grep only prints output for the first revision of a
2546 By default, grep only prints output for the first revision of a
2478 file in which it finds a match. To get it to print every revision
2547 file in which it finds a match. To get it to print every revision
2479 that contains a change in match status ("-" for a match that
2548 that contains a change in match status ("-" for a match that
2480 becomes a non-match, or "+" for a non-match that becomes a match),
2549 becomes a non-match, or "+" for a non-match that becomes a match),
2481 use the --all flag.
2550 use the --all flag.
2482
2551
2483 Returns 0 if a match is found, 1 otherwise.
2552 Returns 0 if a match is found, 1 otherwise.
2484 """
2553 """
2485 reflags = 0
2554 reflags = 0
2486 if opts.get('ignore_case'):
2555 if opts.get('ignore_case'):
2487 reflags |= re.I
2556 reflags |= re.I
2488 try:
2557 try:
2489 regexp = re.compile(pattern, reflags)
2558 regexp = re.compile(pattern, reflags)
2490 except re.error, inst:
2559 except re.error, inst:
2491 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2560 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2492 return 1
2561 return 1
2493 sep, eol = ':', '\n'
2562 sep, eol = ':', '\n'
2494 if opts.get('print0'):
2563 if opts.get('print0'):
2495 sep = eol = '\0'
2564 sep = eol = '\0'
2496
2565
2497 getfile = util.lrucachefunc(repo.file)
2566 getfile = util.lrucachefunc(repo.file)
2498
2567
2499 def matchlines(body):
2568 def matchlines(body):
2500 begin = 0
2569 begin = 0
2501 linenum = 0
2570 linenum = 0
2502 while True:
2571 while True:
2503 match = regexp.search(body, begin)
2572 match = regexp.search(body, begin)
2504 if not match:
2573 if not match:
2505 break
2574 break
2506 mstart, mend = match.span()
2575 mstart, mend = match.span()
2507 linenum += body.count('\n', begin, mstart) + 1
2576 linenum += body.count('\n', begin, mstart) + 1
2508 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2577 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2509 begin = body.find('\n', mend) + 1 or len(body)
2578 begin = body.find('\n', mend) + 1 or len(body)
2510 lend = begin - 1
2579 lend = begin - 1
2511 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2580 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2512
2581
2513 class linestate(object):
2582 class linestate(object):
2514 def __init__(self, line, linenum, colstart, colend):
2583 def __init__(self, line, linenum, colstart, colend):
2515 self.line = line
2584 self.line = line
2516 self.linenum = linenum
2585 self.linenum = linenum
2517 self.colstart = colstart
2586 self.colstart = colstart
2518 self.colend = colend
2587 self.colend = colend
2519
2588
2520 def __hash__(self):
2589 def __hash__(self):
2521 return hash((self.linenum, self.line))
2590 return hash((self.linenum, self.line))
2522
2591
2523 def __eq__(self, other):
2592 def __eq__(self, other):
2524 return self.line == other.line
2593 return self.line == other.line
2525
2594
2526 matches = {}
2595 matches = {}
2527 copies = {}
2596 copies = {}
2528 def grepbody(fn, rev, body):
2597 def grepbody(fn, rev, body):
2529 matches[rev].setdefault(fn, [])
2598 matches[rev].setdefault(fn, [])
2530 m = matches[rev][fn]
2599 m = matches[rev][fn]
2531 for lnum, cstart, cend, line in matchlines(body):
2600 for lnum, cstart, cend, line in matchlines(body):
2532 s = linestate(line, lnum, cstart, cend)
2601 s = linestate(line, lnum, cstart, cend)
2533 m.append(s)
2602 m.append(s)
2534
2603
2535 def difflinestates(a, b):
2604 def difflinestates(a, b):
2536 sm = difflib.SequenceMatcher(None, a, b)
2605 sm = difflib.SequenceMatcher(None, a, b)
2537 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2606 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2538 if tag == 'insert':
2607 if tag == 'insert':
2539 for i in xrange(blo, bhi):
2608 for i in xrange(blo, bhi):
2540 yield ('+', b[i])
2609 yield ('+', b[i])
2541 elif tag == 'delete':
2610 elif tag == 'delete':
2542 for i in xrange(alo, ahi):
2611 for i in xrange(alo, ahi):
2543 yield ('-', a[i])
2612 yield ('-', a[i])
2544 elif tag == 'replace':
2613 elif tag == 'replace':
2545 for i in xrange(alo, ahi):
2614 for i in xrange(alo, ahi):
2546 yield ('-', a[i])
2615 yield ('-', a[i])
2547 for i in xrange(blo, bhi):
2616 for i in xrange(blo, bhi):
2548 yield ('+', b[i])
2617 yield ('+', b[i])
2549
2618
2550 def display(fn, ctx, pstates, states):
2619 def display(fn, ctx, pstates, states):
2551 rev = ctx.rev()
2620 rev = ctx.rev()
2552 datefunc = ui.quiet and util.shortdate or util.datestr
2621 datefunc = ui.quiet and util.shortdate or util.datestr
2553 found = False
2622 found = False
2554 filerevmatches = {}
2623 filerevmatches = {}
2555 def binary():
2624 def binary():
2556 flog = getfile(fn)
2625 flog = getfile(fn)
2557 return util.binary(flog.read(ctx.filenode(fn)))
2626 return util.binary(flog.read(ctx.filenode(fn)))
2558
2627
2559 if opts.get('all'):
2628 if opts.get('all'):
2560 iter = difflinestates(pstates, states)
2629 iter = difflinestates(pstates, states)
2561 else:
2630 else:
2562 iter = [('', l) for l in states]
2631 iter = [('', l) for l in states]
2563 for change, l in iter:
2632 for change, l in iter:
2564 cols = [fn, str(rev)]
2633 cols = [fn, str(rev)]
2565 before, match, after = None, None, None
2634 before, match, after = None, None, None
2566 if opts.get('line_number'):
2635 if opts.get('line_number'):
2567 cols.append(str(l.linenum))
2636 cols.append(str(l.linenum))
2568 if opts.get('all'):
2637 if opts.get('all'):
2569 cols.append(change)
2638 cols.append(change)
2570 if opts.get('user'):
2639 if opts.get('user'):
2571 cols.append(ui.shortuser(ctx.user()))
2640 cols.append(ui.shortuser(ctx.user()))
2572 if opts.get('date'):
2641 if opts.get('date'):
2573 cols.append(datefunc(ctx.date()))
2642 cols.append(datefunc(ctx.date()))
2574 if opts.get('files_with_matches'):
2643 if opts.get('files_with_matches'):
2575 c = (fn, rev)
2644 c = (fn, rev)
2576 if c in filerevmatches:
2645 if c in filerevmatches:
2577 continue
2646 continue
2578 filerevmatches[c] = 1
2647 filerevmatches[c] = 1
2579 else:
2648 else:
2580 before = l.line[:l.colstart]
2649 before = l.line[:l.colstart]
2581 match = l.line[l.colstart:l.colend]
2650 match = l.line[l.colstart:l.colend]
2582 after = l.line[l.colend:]
2651 after = l.line[l.colend:]
2583 ui.write(sep.join(cols))
2652 ui.write(sep.join(cols))
2584 if before is not None:
2653 if before is not None:
2585 if not opts.get('text') and binary():
2654 if not opts.get('text') and binary():
2586 ui.write(sep + " Binary file matches")
2655 ui.write(sep + " Binary file matches")
2587 else:
2656 else:
2588 ui.write(sep + before)
2657 ui.write(sep + before)
2589 ui.write(match, label='grep.match')
2658 ui.write(match, label='grep.match')
2590 ui.write(after)
2659 ui.write(after)
2591 ui.write(eol)
2660 ui.write(eol)
2592 found = True
2661 found = True
2593 return found
2662 return found
2594
2663
2595 skip = {}
2664 skip = {}
2596 revfiles = {}
2665 revfiles = {}
2597 matchfn = scmutil.match(repo[None], pats, opts)
2666 matchfn = scmutil.match(repo[None], pats, opts)
2598 found = False
2667 found = False
2599 follow = opts.get('follow')
2668 follow = opts.get('follow')
2600
2669
2601 def prep(ctx, fns):
2670 def prep(ctx, fns):
2602 rev = ctx.rev()
2671 rev = ctx.rev()
2603 pctx = ctx.p1()
2672 pctx = ctx.p1()
2604 parent = pctx.rev()
2673 parent = pctx.rev()
2605 matches.setdefault(rev, {})
2674 matches.setdefault(rev, {})
2606 matches.setdefault(parent, {})
2675 matches.setdefault(parent, {})
2607 files = revfiles.setdefault(rev, [])
2676 files = revfiles.setdefault(rev, [])
2608 for fn in fns:
2677 for fn in fns:
2609 flog = getfile(fn)
2678 flog = getfile(fn)
2610 try:
2679 try:
2611 fnode = ctx.filenode(fn)
2680 fnode = ctx.filenode(fn)
2612 except error.LookupError:
2681 except error.LookupError:
2613 continue
2682 continue
2614
2683
2615 copied = flog.renamed(fnode)
2684 copied = flog.renamed(fnode)
2616 copy = follow and copied and copied[0]
2685 copy = follow and copied and copied[0]
2617 if copy:
2686 if copy:
2618 copies.setdefault(rev, {})[fn] = copy
2687 copies.setdefault(rev, {})[fn] = copy
2619 if fn in skip:
2688 if fn in skip:
2620 if copy:
2689 if copy:
2621 skip[copy] = True
2690 skip[copy] = True
2622 continue
2691 continue
2623 files.append(fn)
2692 files.append(fn)
2624
2693
2625 if fn not in matches[rev]:
2694 if fn not in matches[rev]:
2626 grepbody(fn, rev, flog.read(fnode))
2695 grepbody(fn, rev, flog.read(fnode))
2627
2696
2628 pfn = copy or fn
2697 pfn = copy or fn
2629 if pfn not in matches[parent]:
2698 if pfn not in matches[parent]:
2630 try:
2699 try:
2631 fnode = pctx.filenode(pfn)
2700 fnode = pctx.filenode(pfn)
2632 grepbody(pfn, parent, flog.read(fnode))
2701 grepbody(pfn, parent, flog.read(fnode))
2633 except error.LookupError:
2702 except error.LookupError:
2634 pass
2703 pass
2635
2704
2636 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2705 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2637 rev = ctx.rev()
2706 rev = ctx.rev()
2638 parent = ctx.p1().rev()
2707 parent = ctx.p1().rev()
2639 for fn in sorted(revfiles.get(rev, [])):
2708 for fn in sorted(revfiles.get(rev, [])):
2640 states = matches[rev][fn]
2709 states = matches[rev][fn]
2641 copy = copies.get(rev, {}).get(fn)
2710 copy = copies.get(rev, {}).get(fn)
2642 if fn in skip:
2711 if fn in skip:
2643 if copy:
2712 if copy:
2644 skip[copy] = True
2713 skip[copy] = True
2645 continue
2714 continue
2646 pstates = matches.get(parent, {}).get(copy or fn, [])
2715 pstates = matches.get(parent, {}).get(copy or fn, [])
2647 if pstates or states:
2716 if pstates or states:
2648 r = display(fn, ctx, pstates, states)
2717 r = display(fn, ctx, pstates, states)
2649 found = found or r
2718 found = found or r
2650 if r and not opts.get('all'):
2719 if r and not opts.get('all'):
2651 skip[fn] = True
2720 skip[fn] = True
2652 if copy:
2721 if copy:
2653 skip[copy] = True
2722 skip[copy] = True
2654 del matches[rev]
2723 del matches[rev]
2655 del revfiles[rev]
2724 del revfiles[rev]
2656
2725
2657 return not found
2726 return not found
2658
2727
2659 @command('heads',
2728 @command('heads',
2660 [('r', 'rev', '',
2729 [('r', 'rev', '',
2661 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2730 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2662 ('t', 'topo', False, _('show topological heads only')),
2731 ('t', 'topo', False, _('show topological heads only')),
2663 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2732 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2664 ('c', 'closed', False, _('show normal and closed branch heads')),
2733 ('c', 'closed', False, _('show normal and closed branch heads')),
2665 ] + templateopts,
2734 ] + templateopts,
2666 _('[-ac] [-r STARTREV] [REV]...'))
2735 _('[-ac] [-r STARTREV] [REV]...'))
2667 def heads(ui, repo, *branchrevs, **opts):
2736 def heads(ui, repo, *branchrevs, **opts):
2668 """show current repository heads or show branch heads
2737 """show current repository heads or show branch heads
2669
2738
2670 With no arguments, show all repository branch heads.
2739 With no arguments, show all repository branch heads.
2671
2740
2672 Repository "heads" are changesets with no child changesets. They are
2741 Repository "heads" are changesets with no child changesets. They are
2673 where development generally takes place and are the usual targets
2742 where development generally takes place and are the usual targets
2674 for update and merge operations. Branch heads are changesets that have
2743 for update and merge operations. Branch heads are changesets that have
2675 no child changeset on the same branch.
2744 no child changeset on the same branch.
2676
2745
2677 If one or more REVs are given, only branch heads on the branches
2746 If one or more REVs are given, only branch heads on the branches
2678 associated with the specified changesets are shown. This means
2747 associated with the specified changesets are shown. This means
2679 that you can use :hg:`heads foo` to see the heads on a branch
2748 that you can use :hg:`heads foo` to see the heads on a branch
2680 named ``foo``.
2749 named ``foo``.
2681
2750
2682 If -c/--closed is specified, also show branch heads marked closed
2751 If -c/--closed is specified, also show branch heads marked closed
2683 (see :hg:`commit --close-branch`).
2752 (see :hg:`commit --close-branch`).
2684
2753
2685 If STARTREV is specified, only those heads that are descendants of
2754 If STARTREV is specified, only those heads that are descendants of
2686 STARTREV will be displayed.
2755 STARTREV will be displayed.
2687
2756
2688 If -t/--topo is specified, named branch mechanics will be ignored and only
2757 If -t/--topo is specified, named branch mechanics will be ignored and only
2689 changesets without children will be shown.
2758 changesets without children will be shown.
2690
2759
2691 Returns 0 if matching heads are found, 1 if not.
2760 Returns 0 if matching heads are found, 1 if not.
2692 """
2761 """
2693
2762
2694 start = None
2763 start = None
2695 if 'rev' in opts:
2764 if 'rev' in opts:
2696 start = scmutil.revsingle(repo, opts['rev'], None).node()
2765 start = scmutil.revsingle(repo, opts['rev'], None).node()
2697
2766
2698 if opts.get('topo'):
2767 if opts.get('topo'):
2699 heads = [repo[h] for h in repo.heads(start)]
2768 heads = [repo[h] for h in repo.heads(start)]
2700 else:
2769 else:
2701 heads = []
2770 heads = []
2702 for branch in repo.branchmap():
2771 for branch in repo.branchmap():
2703 heads += repo.branchheads(branch, start, opts.get('closed'))
2772 heads += repo.branchheads(branch, start, opts.get('closed'))
2704 heads = [repo[h] for h in heads]
2773 heads = [repo[h] for h in heads]
2705
2774
2706 if branchrevs:
2775 if branchrevs:
2707 branches = set(repo[br].branch() for br in branchrevs)
2776 branches = set(repo[br].branch() for br in branchrevs)
2708 heads = [h for h in heads if h.branch() in branches]
2777 heads = [h for h in heads if h.branch() in branches]
2709
2778
2710 if opts.get('active') and branchrevs:
2779 if opts.get('active') and branchrevs:
2711 dagheads = repo.heads(start)
2780 dagheads = repo.heads(start)
2712 heads = [h for h in heads if h.node() in dagheads]
2781 heads = [h for h in heads if h.node() in dagheads]
2713
2782
2714 if branchrevs:
2783 if branchrevs:
2715 haveheads = set(h.branch() for h in heads)
2784 haveheads = set(h.branch() for h in heads)
2716 if branches - haveheads:
2785 if branches - haveheads:
2717 headless = ', '.join(b for b in branches - haveheads)
2786 headless = ', '.join(b for b in branches - haveheads)
2718 msg = _('no open branch heads found on branches %s')
2787 msg = _('no open branch heads found on branches %s')
2719 if opts.get('rev'):
2788 if opts.get('rev'):
2720 msg += _(' (started at %s)' % opts['rev'])
2789 msg += _(' (started at %s)' % opts['rev'])
2721 ui.warn((msg + '\n') % headless)
2790 ui.warn((msg + '\n') % headless)
2722
2791
2723 if not heads:
2792 if not heads:
2724 return 1
2793 return 1
2725
2794
2726 heads = sorted(heads, key=lambda x: -x.rev())
2795 heads = sorted(heads, key=lambda x: -x.rev())
2727 displayer = cmdutil.show_changeset(ui, repo, opts)
2796 displayer = cmdutil.show_changeset(ui, repo, opts)
2728 for ctx in heads:
2797 for ctx in heads:
2729 displayer.show(ctx)
2798 displayer.show(ctx)
2730 displayer.close()
2799 displayer.close()
2731
2800
2732 @command('help',
2801 @command('help',
2733 [('e', 'extension', None, _('show only help for extensions')),
2802 [('e', 'extension', None, _('show only help for extensions')),
2734 ('c', 'command', None, _('show only help for commands'))],
2803 ('c', 'command', None, _('show only help for commands'))],
2735 _('[-ec] [TOPIC]'))
2804 _('[-ec] [TOPIC]'))
2736 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2805 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2737 """show help for a given topic or a help overview
2806 """show help for a given topic or a help overview
2738
2807
2739 With no arguments, print a list of commands with short help messages.
2808 With no arguments, print a list of commands with short help messages.
2740
2809
2741 Given a topic, extension, or command name, print help for that
2810 Given a topic, extension, or command name, print help for that
2742 topic.
2811 topic.
2743
2812
2744 Returns 0 if successful.
2813 Returns 0 if successful.
2745 """
2814 """
2746
2815
2747 textwidth = min(ui.termwidth(), 80) - 2
2816 textwidth = min(ui.termwidth(), 80) - 2
2748
2817
2749 def optrst(options):
2818 def optrst(options):
2750 data = []
2819 data = []
2751 multioccur = False
2820 multioccur = False
2752 for option in options:
2821 for option in options:
2753 if len(option) == 5:
2822 if len(option) == 5:
2754 shortopt, longopt, default, desc, optlabel = option
2823 shortopt, longopt, default, desc, optlabel = option
2755 else:
2824 else:
2756 shortopt, longopt, default, desc = option
2825 shortopt, longopt, default, desc = option
2757 optlabel = _("VALUE") # default label
2826 optlabel = _("VALUE") # default label
2758
2827
2759 if _("DEPRECATED") in desc and not ui.verbose:
2828 if _("DEPRECATED") in desc and not ui.verbose:
2760 continue
2829 continue
2761
2830
2762 so = ''
2831 so = ''
2763 if shortopt:
2832 if shortopt:
2764 so = '-' + shortopt
2833 so = '-' + shortopt
2765 lo = '--' + longopt
2834 lo = '--' + longopt
2766 if default:
2835 if default:
2767 desc += _(" (default: %s)") % default
2836 desc += _(" (default: %s)") % default
2768
2837
2769 if isinstance(default, list):
2838 if isinstance(default, list):
2770 lo += " %s [+]" % optlabel
2839 lo += " %s [+]" % optlabel
2771 multioccur = True
2840 multioccur = True
2772 elif (default is not None) and not isinstance(default, bool):
2841 elif (default is not None) and not isinstance(default, bool):
2773 lo += " %s" % optlabel
2842 lo += " %s" % optlabel
2774
2843
2775 data.append((so, lo, desc))
2844 data.append((so, lo, desc))
2776
2845
2777 rst = minirst.maketable(data, 1)
2846 rst = minirst.maketable(data, 1)
2778
2847
2779 if multioccur:
2848 if multioccur:
2780 rst += _("\n[+] marked option can be specified multiple times\n")
2849 rst += _("\n[+] marked option can be specified multiple times\n")
2781
2850
2782 return rst
2851 return rst
2783
2852
2784 # list all option lists
2853 # list all option lists
2785 def opttext(optlist, width):
2854 def opttext(optlist, width):
2786 rst = ''
2855 rst = ''
2787 if not optlist:
2856 if not optlist:
2788 return ''
2857 return ''
2789
2858
2790 for title, options in optlist:
2859 for title, options in optlist:
2791 rst += '\n%s\n' % title
2860 rst += '\n%s\n' % title
2792 if options:
2861 if options:
2793 rst += "\n"
2862 rst += "\n"
2794 rst += optrst(options)
2863 rst += optrst(options)
2795 rst += '\n'
2864 rst += '\n'
2796
2865
2797 return '\n' + minirst.format(rst, width)
2866 return '\n' + minirst.format(rst, width)
2798
2867
2799 def addglobalopts(optlist, aliases):
2868 def addglobalopts(optlist, aliases):
2800 if ui.quiet:
2869 if ui.quiet:
2801 return []
2870 return []
2802
2871
2803 if ui.verbose:
2872 if ui.verbose:
2804 optlist.append((_("global options:"), globalopts))
2873 optlist.append((_("global options:"), globalopts))
2805 if name == 'shortlist':
2874 if name == 'shortlist':
2806 optlist.append((_('use "hg help" for the full list '
2875 optlist.append((_('use "hg help" for the full list '
2807 'of commands'), ()))
2876 'of commands'), ()))
2808 else:
2877 else:
2809 if name == 'shortlist':
2878 if name == 'shortlist':
2810 msg = _('use "hg help" for the full list of commands '
2879 msg = _('use "hg help" for the full list of commands '
2811 'or "hg -v" for details')
2880 'or "hg -v" for details')
2812 elif name and not full:
2881 elif name and not full:
2813 msg = _('use "hg help %s" to show the full help text' % name)
2882 msg = _('use "hg help %s" to show the full help text' % name)
2814 elif aliases:
2883 elif aliases:
2815 msg = _('use "hg -v help%s" to show builtin aliases and '
2884 msg = _('use "hg -v help%s" to show builtin aliases and '
2816 'global options') % (name and " " + name or "")
2885 'global options') % (name and " " + name or "")
2817 else:
2886 else:
2818 msg = _('use "hg -v help %s" to show more info') % name
2887 msg = _('use "hg -v help %s" to show more info') % name
2819 optlist.append((msg, ()))
2888 optlist.append((msg, ()))
2820
2889
2821 def helpcmd(name):
2890 def helpcmd(name):
2822 try:
2891 try:
2823 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2892 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2824 except error.AmbiguousCommand, inst:
2893 except error.AmbiguousCommand, inst:
2825 # py3k fix: except vars can't be used outside the scope of the
2894 # py3k fix: except vars can't be used outside the scope of the
2826 # except block, nor can be used inside a lambda. python issue4617
2895 # except block, nor can be used inside a lambda. python issue4617
2827 prefix = inst.args[0]
2896 prefix = inst.args[0]
2828 select = lambda c: c.lstrip('^').startswith(prefix)
2897 select = lambda c: c.lstrip('^').startswith(prefix)
2829 helplist(select)
2898 helplist(select)
2830 return
2899 return
2831
2900
2832 # check if it's an invalid alias and display its error if it is
2901 # check if it's an invalid alias and display its error if it is
2833 if getattr(entry[0], 'badalias', False):
2902 if getattr(entry[0], 'badalias', False):
2834 if not unknowncmd:
2903 if not unknowncmd:
2835 entry[0](ui)
2904 entry[0](ui)
2836 return
2905 return
2837
2906
2838 rst = ""
2907 rst = ""
2839
2908
2840 # synopsis
2909 # synopsis
2841 if len(entry) > 2:
2910 if len(entry) > 2:
2842 if entry[2].startswith('hg'):
2911 if entry[2].startswith('hg'):
2843 rst += "%s\n" % entry[2]
2912 rst += "%s\n" % entry[2]
2844 else:
2913 else:
2845 rst += 'hg %s %s\n' % (aliases[0], entry[2])
2914 rst += 'hg %s %s\n' % (aliases[0], entry[2])
2846 else:
2915 else:
2847 rst += 'hg %s\n' % aliases[0]
2916 rst += 'hg %s\n' % aliases[0]
2848
2917
2849 # aliases
2918 # aliases
2850 if full and not ui.quiet and len(aliases) > 1:
2919 if full and not ui.quiet and len(aliases) > 1:
2851 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
2920 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
2852
2921
2853 # description
2922 # description
2854 doc = gettext(entry[0].__doc__)
2923 doc = gettext(entry[0].__doc__)
2855 if not doc:
2924 if not doc:
2856 doc = _("(no help text available)")
2925 doc = _("(no help text available)")
2857 if util.safehasattr(entry[0], 'definition'): # aliased command
2926 if util.safehasattr(entry[0], 'definition'): # aliased command
2858 if entry[0].definition.startswith('!'): # shell alias
2927 if entry[0].definition.startswith('!'): # shell alias
2859 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2928 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2860 else:
2929 else:
2861 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2930 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2862 if ui.quiet or not full:
2931 if ui.quiet or not full:
2863 doc = doc.splitlines()[0]
2932 doc = doc.splitlines()[0]
2864 rst += "\n" + doc + "\n"
2933 rst += "\n" + doc + "\n"
2865
2934
2866 # check if this command shadows a non-trivial (multi-line)
2935 # check if this command shadows a non-trivial (multi-line)
2867 # extension help text
2936 # extension help text
2868 try:
2937 try:
2869 mod = extensions.find(name)
2938 mod = extensions.find(name)
2870 doc = gettext(mod.__doc__) or ''
2939 doc = gettext(mod.__doc__) or ''
2871 if '\n' in doc.strip():
2940 if '\n' in doc.strip():
2872 msg = _('use "hg help -e %s" to show help for '
2941 msg = _('use "hg help -e %s" to show help for '
2873 'the %s extension') % (name, name)
2942 'the %s extension') % (name, name)
2874 rst += '\n%s\n' % msg
2943 rst += '\n%s\n' % msg
2875 except KeyError:
2944 except KeyError:
2876 pass
2945 pass
2877
2946
2878 # options
2947 # options
2879 if not ui.quiet and entry[1]:
2948 if not ui.quiet and entry[1]:
2880 rst += '\noptions:\n\n'
2949 rst += '\noptions:\n\n'
2881 rst += optrst(entry[1])
2950 rst += optrst(entry[1])
2882
2951
2883 if ui.verbose:
2952 if ui.verbose:
2884 rst += '\nglobal options:\n\n'
2953 rst += '\nglobal options:\n\n'
2885 rst += optrst(globalopts)
2954 rst += optrst(globalopts)
2886
2955
2887 keep = ui.verbose and ['verbose'] or []
2956 keep = ui.verbose and ['verbose'] or []
2888 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
2957 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
2889 ui.write(formatted)
2958 ui.write(formatted)
2890
2959
2891 if not ui.verbose:
2960 if not ui.verbose:
2892 if not full:
2961 if not full:
2893 ui.write(_('\nuse "hg help %s" to show the full help text\n')
2962 ui.write(_('\nuse "hg help %s" to show the full help text\n')
2894 % name)
2963 % name)
2895 elif not ui.quiet:
2964 elif not ui.quiet:
2896 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
2965 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
2897
2966
2898
2967
2899 def helplist(select=None):
2968 def helplist(select=None):
2900 # list of commands
2969 # list of commands
2901 if name == "shortlist":
2970 if name == "shortlist":
2902 header = _('basic commands:\n\n')
2971 header = _('basic commands:\n\n')
2903 else:
2972 else:
2904 header = _('list of commands:\n\n')
2973 header = _('list of commands:\n\n')
2905
2974
2906 h = {}
2975 h = {}
2907 cmds = {}
2976 cmds = {}
2908 for c, e in table.iteritems():
2977 for c, e in table.iteritems():
2909 f = c.split("|", 1)[0]
2978 f = c.split("|", 1)[0]
2910 if select and not select(f):
2979 if select and not select(f):
2911 continue
2980 continue
2912 if (not select and name != 'shortlist' and
2981 if (not select and name != 'shortlist' and
2913 e[0].__module__ != __name__):
2982 e[0].__module__ != __name__):
2914 continue
2983 continue
2915 if name == "shortlist" and not f.startswith("^"):
2984 if name == "shortlist" and not f.startswith("^"):
2916 continue
2985 continue
2917 f = f.lstrip("^")
2986 f = f.lstrip("^")
2918 if not ui.debugflag and f.startswith("debug"):
2987 if not ui.debugflag and f.startswith("debug"):
2919 continue
2988 continue
2920 doc = e[0].__doc__
2989 doc = e[0].__doc__
2921 if doc and 'DEPRECATED' in doc and not ui.verbose:
2990 if doc and 'DEPRECATED' in doc and not ui.verbose:
2922 continue
2991 continue
2923 doc = gettext(doc)
2992 doc = gettext(doc)
2924 if not doc:
2993 if not doc:
2925 doc = _("(no help text available)")
2994 doc = _("(no help text available)")
2926 h[f] = doc.splitlines()[0].rstrip()
2995 h[f] = doc.splitlines()[0].rstrip()
2927 cmds[f] = c.lstrip("^")
2996 cmds[f] = c.lstrip("^")
2928
2997
2929 if not h:
2998 if not h:
2930 ui.status(_('no commands defined\n'))
2999 ui.status(_('no commands defined\n'))
2931 return
3000 return
2932
3001
2933 ui.status(header)
3002 ui.status(header)
2934 fns = sorted(h)
3003 fns = sorted(h)
2935 m = max(map(len, fns))
3004 m = max(map(len, fns))
2936 for f in fns:
3005 for f in fns:
2937 if ui.verbose:
3006 if ui.verbose:
2938 commands = cmds[f].replace("|",", ")
3007 commands = cmds[f].replace("|",", ")
2939 ui.write(" %s:\n %s\n"%(commands, h[f]))
3008 ui.write(" %s:\n %s\n"%(commands, h[f]))
2940 else:
3009 else:
2941 ui.write('%s\n' % (util.wrap(h[f], textwidth,
3010 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2942 initindent=' %-*s ' % (m, f),
3011 initindent=' %-*s ' % (m, f),
2943 hangindent=' ' * (m + 4))))
3012 hangindent=' ' * (m + 4))))
2944
3013
2945 if not name:
3014 if not name:
2946 text = help.listexts(_('enabled extensions:'), extensions.enabled())
3015 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2947 if text:
3016 if text:
2948 ui.write("\n%s" % minirst.format(text, textwidth))
3017 ui.write("\n%s" % minirst.format(text, textwidth))
2949
3018
2950 ui.write(_("\nadditional help topics:\n\n"))
3019 ui.write(_("\nadditional help topics:\n\n"))
2951 topics = []
3020 topics = []
2952 for names, header, doc in help.helptable:
3021 for names, header, doc in help.helptable:
2953 topics.append((sorted(names, key=len, reverse=True)[0], header))
3022 topics.append((sorted(names, key=len, reverse=True)[0], header))
2954 topics_len = max([len(s[0]) for s in topics])
3023 topics_len = max([len(s[0]) for s in topics])
2955 for t, desc in topics:
3024 for t, desc in topics:
2956 ui.write(" %-*s %s\n" % (topics_len, t, desc))
3025 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2957
3026
2958 optlist = []
3027 optlist = []
2959 addglobalopts(optlist, True)
3028 addglobalopts(optlist, True)
2960 ui.write(opttext(optlist, textwidth))
3029 ui.write(opttext(optlist, textwidth))
2961
3030
2962 def helptopic(name):
3031 def helptopic(name):
2963 for names, header, doc in help.helptable:
3032 for names, header, doc in help.helptable:
2964 if name in names:
3033 if name in names:
2965 break
3034 break
2966 else:
3035 else:
2967 raise error.UnknownCommand(name)
3036 raise error.UnknownCommand(name)
2968
3037
2969 # description
3038 # description
2970 if not doc:
3039 if not doc:
2971 doc = _("(no help text available)")
3040 doc = _("(no help text available)")
2972 if util.safehasattr(doc, '__call__'):
3041 if util.safehasattr(doc, '__call__'):
2973 doc = doc()
3042 doc = doc()
2974
3043
2975 ui.write("%s\n\n" % header)
3044 ui.write("%s\n\n" % header)
2976 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
3045 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
2977 try:
3046 try:
2978 cmdutil.findcmd(name, table)
3047 cmdutil.findcmd(name, table)
2979 ui.write(_('\nuse "hg help -c %s" to see help for '
3048 ui.write(_('\nuse "hg help -c %s" to see help for '
2980 'the %s command\n') % (name, name))
3049 'the %s command\n') % (name, name))
2981 except error.UnknownCommand:
3050 except error.UnknownCommand:
2982 pass
3051 pass
2983
3052
2984 def helpext(name):
3053 def helpext(name):
2985 try:
3054 try:
2986 mod = extensions.find(name)
3055 mod = extensions.find(name)
2987 doc = gettext(mod.__doc__) or _('no help text available')
3056 doc = gettext(mod.__doc__) or _('no help text available')
2988 except KeyError:
3057 except KeyError:
2989 mod = None
3058 mod = None
2990 doc = extensions.disabledext(name)
3059 doc = extensions.disabledext(name)
2991 if not doc:
3060 if not doc:
2992 raise error.UnknownCommand(name)
3061 raise error.UnknownCommand(name)
2993
3062
2994 if '\n' not in doc:
3063 if '\n' not in doc:
2995 head, tail = doc, ""
3064 head, tail = doc, ""
2996 else:
3065 else:
2997 head, tail = doc.split('\n', 1)
3066 head, tail = doc.split('\n', 1)
2998 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
3067 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2999 if tail:
3068 if tail:
3000 ui.write(minirst.format(tail, textwidth))
3069 ui.write(minirst.format(tail, textwidth))
3001 ui.status('\n')
3070 ui.status('\n')
3002
3071
3003 if mod:
3072 if mod:
3004 try:
3073 try:
3005 ct = mod.cmdtable
3074 ct = mod.cmdtable
3006 except AttributeError:
3075 except AttributeError:
3007 ct = {}
3076 ct = {}
3008 modcmds = set([c.split('|', 1)[0] for c in ct])
3077 modcmds = set([c.split('|', 1)[0] for c in ct])
3009 helplist(modcmds.__contains__)
3078 helplist(modcmds.__contains__)
3010 else:
3079 else:
3011 ui.write(_('use "hg help extensions" for information on enabling '
3080 ui.write(_('use "hg help extensions" for information on enabling '
3012 'extensions\n'))
3081 'extensions\n'))
3013
3082
3014 def helpextcmd(name):
3083 def helpextcmd(name):
3015 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3084 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3016 doc = gettext(mod.__doc__).splitlines()[0]
3085 doc = gettext(mod.__doc__).splitlines()[0]
3017
3086
3018 msg = help.listexts(_("'%s' is provided by the following "
3087 msg = help.listexts(_("'%s' is provided by the following "
3019 "extension:") % cmd, {ext: doc}, indent=4)
3088 "extension:") % cmd, {ext: doc}, indent=4)
3020 ui.write(minirst.format(msg, textwidth))
3089 ui.write(minirst.format(msg, textwidth))
3021 ui.write('\n')
3090 ui.write('\n')
3022 ui.write(_('use "hg help extensions" for information on enabling '
3091 ui.write(_('use "hg help extensions" for information on enabling '
3023 'extensions\n'))
3092 'extensions\n'))
3024
3093
3025 if name and name != 'shortlist':
3094 if name and name != 'shortlist':
3026 i = None
3095 i = None
3027 if unknowncmd:
3096 if unknowncmd:
3028 queries = (helpextcmd,)
3097 queries = (helpextcmd,)
3029 elif opts.get('extension'):
3098 elif opts.get('extension'):
3030 queries = (helpext,)
3099 queries = (helpext,)
3031 elif opts.get('command'):
3100 elif opts.get('command'):
3032 queries = (helpcmd,)
3101 queries = (helpcmd,)
3033 else:
3102 else:
3034 queries = (helptopic, helpcmd, helpext, helpextcmd)
3103 queries = (helptopic, helpcmd, helpext, helpextcmd)
3035 for f in queries:
3104 for f in queries:
3036 try:
3105 try:
3037 f(name)
3106 f(name)
3038 i = None
3107 i = None
3039 break
3108 break
3040 except error.UnknownCommand, inst:
3109 except error.UnknownCommand, inst:
3041 i = inst
3110 i = inst
3042 if i:
3111 if i:
3043 raise i
3112 raise i
3044 else:
3113 else:
3045 # program name
3114 # program name
3046 ui.status(_("Mercurial Distributed SCM\n"))
3115 ui.status(_("Mercurial Distributed SCM\n"))
3047 ui.status('\n')
3116 ui.status('\n')
3048 helplist()
3117 helplist()
3049
3118
3050
3119
3051 @command('identify|id',
3120 @command('identify|id',
3052 [('r', 'rev', '',
3121 [('r', 'rev', '',
3053 _('identify the specified revision'), _('REV')),
3122 _('identify the specified revision'), _('REV')),
3054 ('n', 'num', None, _('show local revision number')),
3123 ('n', 'num', None, _('show local revision number')),
3055 ('i', 'id', None, _('show global revision id')),
3124 ('i', 'id', None, _('show global revision id')),
3056 ('b', 'branch', None, _('show branch')),
3125 ('b', 'branch', None, _('show branch')),
3057 ('t', 'tags', None, _('show tags')),
3126 ('t', 'tags', None, _('show tags')),
3058 ('B', 'bookmarks', None, _('show bookmarks'))],
3127 ('B', 'bookmarks', None, _('show bookmarks'))],
3059 _('[-nibtB] [-r REV] [SOURCE]'))
3128 _('[-nibtB] [-r REV] [SOURCE]'))
3060 def identify(ui, repo, source=None, rev=None,
3129 def identify(ui, repo, source=None, rev=None,
3061 num=None, id=None, branch=None, tags=None, bookmarks=None):
3130 num=None, id=None, branch=None, tags=None, bookmarks=None):
3062 """identify the working copy or specified revision
3131 """identify the working copy or specified revision
3063
3132
3064 Print a summary identifying the repository state at REV using one or
3133 Print a summary identifying the repository state at REV using one or
3065 two parent hash identifiers, followed by a "+" if the working
3134 two parent hash identifiers, followed by a "+" if the working
3066 directory has uncommitted changes, the branch name (if not default),
3135 directory has uncommitted changes, the branch name (if not default),
3067 a list of tags, and a list of bookmarks.
3136 a list of tags, and a list of bookmarks.
3068
3137
3069 When REV is not given, print a summary of the current state of the
3138 When REV is not given, print a summary of the current state of the
3070 repository.
3139 repository.
3071
3140
3072 Specifying a path to a repository root or Mercurial bundle will
3141 Specifying a path to a repository root or Mercurial bundle will
3073 cause lookup to operate on that repository/bundle.
3142 cause lookup to operate on that repository/bundle.
3074
3143
3075 .. container:: verbose
3144 .. container:: verbose
3076
3145
3077 Examples:
3146 Examples:
3078
3147
3079 - generate a build identifier for the working directory::
3148 - generate a build identifier for the working directory::
3080
3149
3081 hg id --id > build-id.dat
3150 hg id --id > build-id.dat
3082
3151
3083 - find the revision corresponding to a tag::
3152 - find the revision corresponding to a tag::
3084
3153
3085 hg id -n -r 1.3
3154 hg id -n -r 1.3
3086
3155
3087 - check the most recent revision of a remote repository::
3156 - check the most recent revision of a remote repository::
3088
3157
3089 hg id -r tip http://selenic.com/hg/
3158 hg id -r tip http://selenic.com/hg/
3090
3159
3091 Returns 0 if successful.
3160 Returns 0 if successful.
3092 """
3161 """
3093
3162
3094 if not repo and not source:
3163 if not repo and not source:
3095 raise util.Abort(_("there is no Mercurial repository here "
3164 raise util.Abort(_("there is no Mercurial repository here "
3096 "(.hg not found)"))
3165 "(.hg not found)"))
3097
3166
3098 hexfunc = ui.debugflag and hex or short
3167 hexfunc = ui.debugflag and hex or short
3099 default = not (num or id or branch or tags or bookmarks)
3168 default = not (num or id or branch or tags or bookmarks)
3100 output = []
3169 output = []
3101 revs = []
3170 revs = []
3102
3171
3103 if source:
3172 if source:
3104 source, branches = hg.parseurl(ui.expandpath(source))
3173 source, branches = hg.parseurl(ui.expandpath(source))
3105 repo = hg.peer(ui, {}, source)
3174 repo = hg.peer(ui, {}, source)
3106 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3175 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3107
3176
3108 if not repo.local():
3177 if not repo.local():
3109 if num or branch or tags:
3178 if num or branch or tags:
3110 raise util.Abort(
3179 raise util.Abort(
3111 _("can't query remote revision number, branch, or tags"))
3180 _("can't query remote revision number, branch, or tags"))
3112 if not rev and revs:
3181 if not rev and revs:
3113 rev = revs[0]
3182 rev = revs[0]
3114 if not rev:
3183 if not rev:
3115 rev = "tip"
3184 rev = "tip"
3116
3185
3117 remoterev = repo.lookup(rev)
3186 remoterev = repo.lookup(rev)
3118 if default or id:
3187 if default or id:
3119 output = [hexfunc(remoterev)]
3188 output = [hexfunc(remoterev)]
3120
3189
3121 def getbms():
3190 def getbms():
3122 bms = []
3191 bms = []
3123
3192
3124 if 'bookmarks' in repo.listkeys('namespaces'):
3193 if 'bookmarks' in repo.listkeys('namespaces'):
3125 hexremoterev = hex(remoterev)
3194 hexremoterev = hex(remoterev)
3126 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3195 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3127 if bmr == hexremoterev]
3196 if bmr == hexremoterev]
3128
3197
3129 return bms
3198 return bms
3130
3199
3131 if bookmarks:
3200 if bookmarks:
3132 output.extend(getbms())
3201 output.extend(getbms())
3133 elif default and not ui.quiet:
3202 elif default and not ui.quiet:
3134 # multiple bookmarks for a single parent separated by '/'
3203 # multiple bookmarks for a single parent separated by '/'
3135 bm = '/'.join(getbms())
3204 bm = '/'.join(getbms())
3136 if bm:
3205 if bm:
3137 output.append(bm)
3206 output.append(bm)
3138 else:
3207 else:
3139 if not rev:
3208 if not rev:
3140 ctx = repo[None]
3209 ctx = repo[None]
3141 parents = ctx.parents()
3210 parents = ctx.parents()
3142 changed = ""
3211 changed = ""
3143 if default or id or num:
3212 if default or id or num:
3144 changed = util.any(repo.status()) and "+" or ""
3213 changed = util.any(repo.status()) and "+" or ""
3145 if default or id:
3214 if default or id:
3146 output = ["%s%s" %
3215 output = ["%s%s" %
3147 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3216 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3148 if num:
3217 if num:
3149 output.append("%s%s" %
3218 output.append("%s%s" %
3150 ('+'.join([str(p.rev()) for p in parents]), changed))
3219 ('+'.join([str(p.rev()) for p in parents]), changed))
3151 else:
3220 else:
3152 ctx = scmutil.revsingle(repo, rev)
3221 ctx = scmutil.revsingle(repo, rev)
3153 if default or id:
3222 if default or id:
3154 output = [hexfunc(ctx.node())]
3223 output = [hexfunc(ctx.node())]
3155 if num:
3224 if num:
3156 output.append(str(ctx.rev()))
3225 output.append(str(ctx.rev()))
3157
3226
3158 if default and not ui.quiet:
3227 if default and not ui.quiet:
3159 b = ctx.branch()
3228 b = ctx.branch()
3160 if b != 'default':
3229 if b != 'default':
3161 output.append("(%s)" % b)
3230 output.append("(%s)" % b)
3162
3231
3163 # multiple tags for a single parent separated by '/'
3232 # multiple tags for a single parent separated by '/'
3164 t = '/'.join(ctx.tags())
3233 t = '/'.join(ctx.tags())
3165 if t:
3234 if t:
3166 output.append(t)
3235 output.append(t)
3167
3236
3168 # multiple bookmarks for a single parent separated by '/'
3237 # multiple bookmarks for a single parent separated by '/'
3169 bm = '/'.join(ctx.bookmarks())
3238 bm = '/'.join(ctx.bookmarks())
3170 if bm:
3239 if bm:
3171 output.append(bm)
3240 output.append(bm)
3172 else:
3241 else:
3173 if branch:
3242 if branch:
3174 output.append(ctx.branch())
3243 output.append(ctx.branch())
3175
3244
3176 if tags:
3245 if tags:
3177 output.extend(ctx.tags())
3246 output.extend(ctx.tags())
3178
3247
3179 if bookmarks:
3248 if bookmarks:
3180 output.extend(ctx.bookmarks())
3249 output.extend(ctx.bookmarks())
3181
3250
3182 ui.write("%s\n" % ' '.join(output))
3251 ui.write("%s\n" % ' '.join(output))
3183
3252
3184 @command('import|patch',
3253 @command('import|patch',
3185 [('p', 'strip', 1,
3254 [('p', 'strip', 1,
3186 _('directory strip option for patch. This has the same '
3255 _('directory strip option for patch. This has the same '
3187 'meaning as the corresponding patch option'), _('NUM')),
3256 'meaning as the corresponding patch option'), _('NUM')),
3188 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3257 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3189 ('e', 'edit', False, _('invoke editor on commit messages')),
3258 ('e', 'edit', False, _('invoke editor on commit messages')),
3190 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3259 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3191 ('', 'no-commit', None,
3260 ('', 'no-commit', None,
3192 _("don't commit, just update the working directory")),
3261 _("don't commit, just update the working directory")),
3193 ('', 'bypass', None,
3262 ('', 'bypass', None,
3194 _("apply patch without touching the working directory")),
3263 _("apply patch without touching the working directory")),
3195 ('', 'exact', None,
3264 ('', 'exact', None,
3196 _('apply patch to the nodes from which it was generated')),
3265 _('apply patch to the nodes from which it was generated')),
3197 ('', 'import-branch', None,
3266 ('', 'import-branch', None,
3198 _('use any branch information in patch (implied by --exact)'))] +
3267 _('use any branch information in patch (implied by --exact)'))] +
3199 commitopts + commitopts2 + similarityopts,
3268 commitopts + commitopts2 + similarityopts,
3200 _('[OPTION]... PATCH...'))
3269 _('[OPTION]... PATCH...'))
3201 def import_(ui, repo, patch1, *patches, **opts):
3270 def import_(ui, repo, patch1, *patches, **opts):
3202 """import an ordered set of patches
3271 """import an ordered set of patches
3203
3272
3204 Import a list of patches and commit them individually (unless
3273 Import a list of patches and commit them individually (unless
3205 --no-commit is specified).
3274 --no-commit is specified).
3206
3275
3207 If there are outstanding changes in the working directory, import
3276 If there are outstanding changes in the working directory, import
3208 will abort unless given the -f/--force flag.
3277 will abort unless given the -f/--force flag.
3209
3278
3210 You can import a patch straight from a mail message. Even patches
3279 You can import a patch straight from a mail message. Even patches
3211 as attachments work (to use the body part, it must have type
3280 as attachments work (to use the body part, it must have type
3212 text/plain or text/x-patch). From and Subject headers of email
3281 text/plain or text/x-patch). From and Subject headers of email
3213 message are used as default committer and commit message. All
3282 message are used as default committer and commit message. All
3214 text/plain body parts before first diff are added to commit
3283 text/plain body parts before first diff are added to commit
3215 message.
3284 message.
3216
3285
3217 If the imported patch was generated by :hg:`export`, user and
3286 If the imported patch was generated by :hg:`export`, user and
3218 description from patch override values from message headers and
3287 description from patch override values from message headers and
3219 body. Values given on command line with -m/--message and -u/--user
3288 body. Values given on command line with -m/--message and -u/--user
3220 override these.
3289 override these.
3221
3290
3222 If --exact is specified, import will set the working directory to
3291 If --exact is specified, import will set the working directory to
3223 the parent of each patch before applying it, and will abort if the
3292 the parent of each patch before applying it, and will abort if the
3224 resulting changeset has a different ID than the one recorded in
3293 resulting changeset has a different ID than the one recorded in
3225 the patch. This may happen due to character set problems or other
3294 the patch. This may happen due to character set problems or other
3226 deficiencies in the text patch format.
3295 deficiencies in the text patch format.
3227
3296
3228 Use --bypass to apply and commit patches directly to the
3297 Use --bypass to apply and commit patches directly to the
3229 repository, not touching the working directory. Without --exact,
3298 repository, not touching the working directory. Without --exact,
3230 patches will be applied on top of the working directory parent
3299 patches will be applied on top of the working directory parent
3231 revision.
3300 revision.
3232
3301
3233 With -s/--similarity, hg will attempt to discover renames and
3302 With -s/--similarity, hg will attempt to discover renames and
3234 copies in the patch in the same way as 'addremove'.
3303 copies in the patch in the same way as 'addremove'.
3235
3304
3236 To read a patch from standard input, use "-" as the patch name. If
3305 To read a patch from standard input, use "-" as the patch name. If
3237 a URL is specified, the patch will be downloaded from it.
3306 a URL is specified, the patch will be downloaded from it.
3238 See :hg:`help dates` for a list of formats valid for -d/--date.
3307 See :hg:`help dates` for a list of formats valid for -d/--date.
3239
3308
3240 .. container:: verbose
3309 .. container:: verbose
3241
3310
3242 Examples:
3311 Examples:
3243
3312
3244 - import a traditional patch from a website and detect renames::
3313 - import a traditional patch from a website and detect renames::
3245
3314
3246 hg import -s 80 http://example.com/bugfix.patch
3315 hg import -s 80 http://example.com/bugfix.patch
3247
3316
3248 - import a changeset from an hgweb server::
3317 - import a changeset from an hgweb server::
3249
3318
3250 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3319 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3251
3320
3252 - import all the patches in an Unix-style mbox::
3321 - import all the patches in an Unix-style mbox::
3253
3322
3254 hg import incoming-patches.mbox
3323 hg import incoming-patches.mbox
3255
3324
3256 - attempt to exactly restore an exported changeset (not always
3325 - attempt to exactly restore an exported changeset (not always
3257 possible)::
3326 possible)::
3258
3327
3259 hg import --exact proposed-fix.patch
3328 hg import --exact proposed-fix.patch
3260
3329
3261 Returns 0 on success.
3330 Returns 0 on success.
3262 """
3331 """
3263 patches = (patch1,) + patches
3332 patches = (patch1,) + patches
3264
3333
3265 date = opts.get('date')
3334 date = opts.get('date')
3266 if date:
3335 if date:
3267 opts['date'] = util.parsedate(date)
3336 opts['date'] = util.parsedate(date)
3268
3337
3269 editor = cmdutil.commiteditor
3338 editor = cmdutil.commiteditor
3270 if opts.get('edit'):
3339 if opts.get('edit'):
3271 editor = cmdutil.commitforceeditor
3340 editor = cmdutil.commitforceeditor
3272
3341
3273 update = not opts.get('bypass')
3342 update = not opts.get('bypass')
3274 if not update and opts.get('no_commit'):
3343 if not update and opts.get('no_commit'):
3275 raise util.Abort(_('cannot use --no-commit with --bypass'))
3344 raise util.Abort(_('cannot use --no-commit with --bypass'))
3276 try:
3345 try:
3277 sim = float(opts.get('similarity') or 0)
3346 sim = float(opts.get('similarity') or 0)
3278 except ValueError:
3347 except ValueError:
3279 raise util.Abort(_('similarity must be a number'))
3348 raise util.Abort(_('similarity must be a number'))
3280 if sim < 0 or sim > 100:
3349 if sim < 0 or sim > 100:
3281 raise util.Abort(_('similarity must be between 0 and 100'))
3350 raise util.Abort(_('similarity must be between 0 and 100'))
3282 if sim and not update:
3351 if sim and not update:
3283 raise util.Abort(_('cannot use --similarity with --bypass'))
3352 raise util.Abort(_('cannot use --similarity with --bypass'))
3284
3353
3285 if (opts.get('exact') or not opts.get('force')) and update:
3354 if (opts.get('exact') or not opts.get('force')) and update:
3286 cmdutil.bailifchanged(repo)
3355 cmdutil.bailifchanged(repo)
3287
3356
3288 base = opts["base"]
3357 base = opts["base"]
3289 strip = opts["strip"]
3358 strip = opts["strip"]
3290 wlock = lock = tr = None
3359 wlock = lock = tr = None
3291 msgs = []
3360 msgs = []
3292
3361
3293 def checkexact(repo, n, nodeid):
3362 def checkexact(repo, n, nodeid):
3294 if opts.get('exact') and hex(n) != nodeid:
3363 if opts.get('exact') and hex(n) != nodeid:
3295 repo.rollback()
3364 repo.rollback()
3296 raise util.Abort(_('patch is damaged or loses information'))
3365 raise util.Abort(_('patch is damaged or loses information'))
3297
3366
3298 def tryone(ui, hunk, parents):
3367 def tryone(ui, hunk, parents):
3299 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3368 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3300 patch.extract(ui, hunk)
3369 patch.extract(ui, hunk)
3301
3370
3302 if not tmpname:
3371 if not tmpname:
3303 return (None, None)
3372 return (None, None)
3304 msg = _('applied to working directory')
3373 msg = _('applied to working directory')
3305
3374
3306 try:
3375 try:
3307 cmdline_message = cmdutil.logmessage(ui, opts)
3376 cmdline_message = cmdutil.logmessage(ui, opts)
3308 if cmdline_message:
3377 if cmdline_message:
3309 # pickup the cmdline msg
3378 # pickup the cmdline msg
3310 message = cmdline_message
3379 message = cmdline_message
3311 elif message:
3380 elif message:
3312 # pickup the patch msg
3381 # pickup the patch msg
3313 message = message.strip()
3382 message = message.strip()
3314 else:
3383 else:
3315 # launch the editor
3384 # launch the editor
3316 message = None
3385 message = None
3317 ui.debug('message:\n%s\n' % message)
3386 ui.debug('message:\n%s\n' % message)
3318
3387
3319 if len(parents) == 1:
3388 if len(parents) == 1:
3320 parents.append(repo[nullid])
3389 parents.append(repo[nullid])
3321 if opts.get('exact'):
3390 if opts.get('exact'):
3322 if not nodeid or not p1:
3391 if not nodeid or not p1:
3323 raise util.Abort(_('not a Mercurial patch'))
3392 raise util.Abort(_('not a Mercurial patch'))
3324 p1 = repo[p1]
3393 p1 = repo[p1]
3325 p2 = repo[p2 or nullid]
3394 p2 = repo[p2 or nullid]
3326 elif p2:
3395 elif p2:
3327 try:
3396 try:
3328 p1 = repo[p1]
3397 p1 = repo[p1]
3329 p2 = repo[p2]
3398 p2 = repo[p2]
3330 except error.RepoError:
3399 except error.RepoError:
3331 p1, p2 = parents
3400 p1, p2 = parents
3332 else:
3401 else:
3333 p1, p2 = parents
3402 p1, p2 = parents
3334
3403
3335 n = None
3404 n = None
3336 if update:
3405 if update:
3337 if opts.get('exact') and p1 != parents[0]:
3406 if opts.get('exact') and p1 != parents[0]:
3338 hg.clean(repo, p1.node())
3407 hg.clean(repo, p1.node())
3339 if p1 != parents[0] and p2 != parents[1]:
3408 if p1 != parents[0] and p2 != parents[1]:
3340 repo.dirstate.setparents(p1.node(), p2.node())
3409 repo.dirstate.setparents(p1.node(), p2.node())
3341
3410
3342 if opts.get('exact') or opts.get('import_branch'):
3411 if opts.get('exact') or opts.get('import_branch'):
3343 repo.dirstate.setbranch(branch or 'default')
3412 repo.dirstate.setbranch(branch or 'default')
3344
3413
3345 files = set()
3414 files = set()
3346 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3415 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3347 eolmode=None, similarity=sim / 100.0)
3416 eolmode=None, similarity=sim / 100.0)
3348 files = list(files)
3417 files = list(files)
3349 if opts.get('no_commit'):
3418 if opts.get('no_commit'):
3350 if message:
3419 if message:
3351 msgs.append(message)
3420 msgs.append(message)
3352 else:
3421 else:
3353 if opts.get('exact'):
3422 if opts.get('exact'):
3354 m = None
3423 m = None
3355 else:
3424 else:
3356 m = scmutil.matchfiles(repo, files or [])
3425 m = scmutil.matchfiles(repo, files or [])
3357 n = repo.commit(message, opts.get('user') or user,
3426 n = repo.commit(message, opts.get('user') or user,
3358 opts.get('date') or date, match=m,
3427 opts.get('date') or date, match=m,
3359 editor=editor)
3428 editor=editor)
3360 checkexact(repo, n, nodeid)
3429 checkexact(repo, n, nodeid)
3361 else:
3430 else:
3362 if opts.get('exact') or opts.get('import_branch'):
3431 if opts.get('exact') or opts.get('import_branch'):
3363 branch = branch or 'default'
3432 branch = branch or 'default'
3364 else:
3433 else:
3365 branch = p1.branch()
3434 branch = p1.branch()
3366 store = patch.filestore()
3435 store = patch.filestore()
3367 try:
3436 try:
3368 files = set()
3437 files = set()
3369 try:
3438 try:
3370 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3439 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3371 files, eolmode=None)
3440 files, eolmode=None)
3372 except patch.PatchError, e:
3441 except patch.PatchError, e:
3373 raise util.Abort(str(e))
3442 raise util.Abort(str(e))
3374 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3443 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3375 message,
3444 message,
3376 opts.get('user') or user,
3445 opts.get('user') or user,
3377 opts.get('date') or date,
3446 opts.get('date') or date,
3378 branch, files, store,
3447 branch, files, store,
3379 editor=cmdutil.commiteditor)
3448 editor=cmdutil.commiteditor)
3380 repo.savecommitmessage(memctx.description())
3449 repo.savecommitmessage(memctx.description())
3381 n = memctx.commit()
3450 n = memctx.commit()
3382 checkexact(repo, n, nodeid)
3451 checkexact(repo, n, nodeid)
3383 finally:
3452 finally:
3384 store.close()
3453 store.close()
3385 if n:
3454 if n:
3386 msg = _('created %s') % short(n)
3455 msg = _('created %s') % short(n)
3387 return (msg, n)
3456 return (msg, n)
3388 finally:
3457 finally:
3389 os.unlink(tmpname)
3458 os.unlink(tmpname)
3390
3459
3391 try:
3460 try:
3392 wlock = repo.wlock()
3461 wlock = repo.wlock()
3393 lock = repo.lock()
3462 lock = repo.lock()
3394 tr = repo.transaction('import')
3463 tr = repo.transaction('import')
3395 parents = repo.parents()
3464 parents = repo.parents()
3396 for patchurl in patches:
3465 for patchurl in patches:
3397 if patchurl == '-':
3466 if patchurl == '-':
3398 ui.status(_('applying patch from stdin\n'))
3467 ui.status(_('applying patch from stdin\n'))
3399 patchfile = ui.fin
3468 patchfile = ui.fin
3400 patchurl = 'stdin' # for error message
3469 patchurl = 'stdin' # for error message
3401 else:
3470 else:
3402 patchurl = os.path.join(base, patchurl)
3471 patchurl = os.path.join(base, patchurl)
3403 ui.status(_('applying %s\n') % patchurl)
3472 ui.status(_('applying %s\n') % patchurl)
3404 patchfile = url.open(ui, patchurl)
3473 patchfile = url.open(ui, patchurl)
3405
3474
3406 haspatch = False
3475 haspatch = False
3407 for hunk in patch.split(patchfile):
3476 for hunk in patch.split(patchfile):
3408 (msg, node) = tryone(ui, hunk, parents)
3477 (msg, node) = tryone(ui, hunk, parents)
3409 if msg:
3478 if msg:
3410 haspatch = True
3479 haspatch = True
3411 ui.note(msg + '\n')
3480 ui.note(msg + '\n')
3412 if update or opts.get('exact'):
3481 if update or opts.get('exact'):
3413 parents = repo.parents()
3482 parents = repo.parents()
3414 else:
3483 else:
3415 parents = [repo[node]]
3484 parents = [repo[node]]
3416
3485
3417 if not haspatch:
3486 if not haspatch:
3418 raise util.Abort(_('%s: no diffs found') % patchurl)
3487 raise util.Abort(_('%s: no diffs found') % patchurl)
3419
3488
3420 tr.close()
3489 tr.close()
3421 if msgs:
3490 if msgs:
3422 repo.savecommitmessage('\n* * *\n'.join(msgs))
3491 repo.savecommitmessage('\n* * *\n'.join(msgs))
3423 except:
3492 except:
3424 # wlock.release() indirectly calls dirstate.write(): since
3493 # wlock.release() indirectly calls dirstate.write(): since
3425 # we're crashing, we do not want to change the working dir
3494 # we're crashing, we do not want to change the working dir
3426 # parent after all, so make sure it writes nothing
3495 # parent after all, so make sure it writes nothing
3427 repo.dirstate.invalidate()
3496 repo.dirstate.invalidate()
3428 raise
3497 raise
3429 finally:
3498 finally:
3430 if tr:
3499 if tr:
3431 tr.release()
3500 tr.release()
3432 release(lock, wlock)
3501 release(lock, wlock)
3433
3502
3434 @command('incoming|in',
3503 @command('incoming|in',
3435 [('f', 'force', None,
3504 [('f', 'force', None,
3436 _('run even if remote repository is unrelated')),
3505 _('run even if remote repository is unrelated')),
3437 ('n', 'newest-first', None, _('show newest record first')),
3506 ('n', 'newest-first', None, _('show newest record first')),
3438 ('', 'bundle', '',
3507 ('', 'bundle', '',
3439 _('file to store the bundles into'), _('FILE')),
3508 _('file to store the bundles into'), _('FILE')),
3440 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3509 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3441 ('B', 'bookmarks', False, _("compare bookmarks")),
3510 ('B', 'bookmarks', False, _("compare bookmarks")),
3442 ('b', 'branch', [],
3511 ('b', 'branch', [],
3443 _('a specific branch you would like to pull'), _('BRANCH')),
3512 _('a specific branch you would like to pull'), _('BRANCH')),
3444 ] + logopts + remoteopts + subrepoopts,
3513 ] + logopts + remoteopts + subrepoopts,
3445 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3514 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3446 def incoming(ui, repo, source="default", **opts):
3515 def incoming(ui, repo, source="default", **opts):
3447 """show new changesets found in source
3516 """show new changesets found in source
3448
3517
3449 Show new changesets found in the specified path/URL or the default
3518 Show new changesets found in the specified path/URL or the default
3450 pull location. These are the changesets that would have been pulled
3519 pull location. These are the changesets that would have been pulled
3451 if a pull at the time you issued this command.
3520 if a pull at the time you issued this command.
3452
3521
3453 For remote repository, using --bundle avoids downloading the
3522 For remote repository, using --bundle avoids downloading the
3454 changesets twice if the incoming is followed by a pull.
3523 changesets twice if the incoming is followed by a pull.
3455
3524
3456 See pull for valid source format details.
3525 See pull for valid source format details.
3457
3526
3458 Returns 0 if there are incoming changes, 1 otherwise.
3527 Returns 0 if there are incoming changes, 1 otherwise.
3459 """
3528 """
3460 if opts.get('bundle') and opts.get('subrepos'):
3529 if opts.get('bundle') and opts.get('subrepos'):
3461 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3530 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3462
3531
3463 if opts.get('bookmarks'):
3532 if opts.get('bookmarks'):
3464 source, branches = hg.parseurl(ui.expandpath(source),
3533 source, branches = hg.parseurl(ui.expandpath(source),
3465 opts.get('branch'))
3534 opts.get('branch'))
3466 other = hg.peer(repo, opts, source)
3535 other = hg.peer(repo, opts, source)
3467 if 'bookmarks' not in other.listkeys('namespaces'):
3536 if 'bookmarks' not in other.listkeys('namespaces'):
3468 ui.warn(_("remote doesn't support bookmarks\n"))
3537 ui.warn(_("remote doesn't support bookmarks\n"))
3469 return 0
3538 return 0
3470 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3539 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3471 return bookmarks.diff(ui, repo, other)
3540 return bookmarks.diff(ui, repo, other)
3472
3541
3473 repo._subtoppath = ui.expandpath(source)
3542 repo._subtoppath = ui.expandpath(source)
3474 try:
3543 try:
3475 return hg.incoming(ui, repo, source, opts)
3544 return hg.incoming(ui, repo, source, opts)
3476 finally:
3545 finally:
3477 del repo._subtoppath
3546 del repo._subtoppath
3478
3547
3479
3548
3480 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3549 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3481 def init(ui, dest=".", **opts):
3550 def init(ui, dest=".", **opts):
3482 """create a new repository in the given directory
3551 """create a new repository in the given directory
3483
3552
3484 Initialize a new repository in the given directory. If the given
3553 Initialize a new repository in the given directory. If the given
3485 directory does not exist, it will be created.
3554 directory does not exist, it will be created.
3486
3555
3487 If no directory is given, the current directory is used.
3556 If no directory is given, the current directory is used.
3488
3557
3489 It is possible to specify an ``ssh://`` URL as the destination.
3558 It is possible to specify an ``ssh://`` URL as the destination.
3490 See :hg:`help urls` for more information.
3559 See :hg:`help urls` for more information.
3491
3560
3492 Returns 0 on success.
3561 Returns 0 on success.
3493 """
3562 """
3494 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3563 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3495
3564
3496 @command('locate',
3565 @command('locate',
3497 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3566 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3498 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3567 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3499 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3568 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3500 ] + walkopts,
3569 ] + walkopts,
3501 _('[OPTION]... [PATTERN]...'))
3570 _('[OPTION]... [PATTERN]...'))
3502 def locate(ui, repo, *pats, **opts):
3571 def locate(ui, repo, *pats, **opts):
3503 """locate files matching specific patterns
3572 """locate files matching specific patterns
3504
3573
3505 Print files under Mercurial control in the working directory whose
3574 Print files under Mercurial control in the working directory whose
3506 names match the given patterns.
3575 names match the given patterns.
3507
3576
3508 By default, this command searches all directories in the working
3577 By default, this command searches all directories in the working
3509 directory. To search just the current directory and its
3578 directory. To search just the current directory and its
3510 subdirectories, use "--include .".
3579 subdirectories, use "--include .".
3511
3580
3512 If no patterns are given to match, this command prints the names
3581 If no patterns are given to match, this command prints the names
3513 of all files under Mercurial control in the working directory.
3582 of all files under Mercurial control in the working directory.
3514
3583
3515 If you want to feed the output of this command into the "xargs"
3584 If you want to feed the output of this command into the "xargs"
3516 command, use the -0 option to both this command and "xargs". This
3585 command, use the -0 option to both this command and "xargs". This
3517 will avoid the problem of "xargs" treating single filenames that
3586 will avoid the problem of "xargs" treating single filenames that
3518 contain whitespace as multiple filenames.
3587 contain whitespace as multiple filenames.
3519
3588
3520 Returns 0 if a match is found, 1 otherwise.
3589 Returns 0 if a match is found, 1 otherwise.
3521 """
3590 """
3522 end = opts.get('print0') and '\0' or '\n'
3591 end = opts.get('print0') and '\0' or '\n'
3523 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3592 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3524
3593
3525 ret = 1
3594 ret = 1
3526 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3595 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3527 m.bad = lambda x, y: False
3596 m.bad = lambda x, y: False
3528 for abs in repo[rev].walk(m):
3597 for abs in repo[rev].walk(m):
3529 if not rev and abs not in repo.dirstate:
3598 if not rev and abs not in repo.dirstate:
3530 continue
3599 continue
3531 if opts.get('fullpath'):
3600 if opts.get('fullpath'):
3532 ui.write(repo.wjoin(abs), end)
3601 ui.write(repo.wjoin(abs), end)
3533 else:
3602 else:
3534 ui.write(((pats and m.rel(abs)) or abs), end)
3603 ui.write(((pats and m.rel(abs)) or abs), end)
3535 ret = 0
3604 ret = 0
3536
3605
3537 return ret
3606 return ret
3538
3607
3539 @command('^log|history',
3608 @command('^log|history',
3540 [('f', 'follow', None,
3609 [('f', 'follow', None,
3541 _('follow changeset history, or file history across copies and renames')),
3610 _('follow changeset history, or file history across copies and renames')),
3542 ('', 'follow-first', None,
3611 ('', 'follow-first', None,
3543 _('only follow the first parent of merge changesets')),
3612 _('only follow the first parent of merge changesets')),
3544 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3613 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3545 ('C', 'copies', None, _('show copied files')),
3614 ('C', 'copies', None, _('show copied files')),
3546 ('k', 'keyword', [],
3615 ('k', 'keyword', [],
3547 _('do case-insensitive search for a given text'), _('TEXT')),
3616 _('do case-insensitive search for a given text'), _('TEXT')),
3548 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3617 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3549 ('', 'removed', None, _('include revisions where files were removed')),
3618 ('', 'removed', None, _('include revisions where files were removed')),
3550 ('m', 'only-merges', None, _('show only merges')),
3619 ('m', 'only-merges', None, _('show only merges')),
3551 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3620 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3552 ('', 'only-branch', [],
3621 ('', 'only-branch', [],
3553 _('show only changesets within the given named branch (DEPRECATED)'),
3622 _('show only changesets within the given named branch (DEPRECATED)'),
3554 _('BRANCH')),
3623 _('BRANCH')),
3555 ('b', 'branch', [],
3624 ('b', 'branch', [],
3556 _('show changesets within the given named branch'), _('BRANCH')),
3625 _('show changesets within the given named branch'), _('BRANCH')),
3557 ('P', 'prune', [],
3626 ('P', 'prune', [],
3558 _('do not display revision or any of its ancestors'), _('REV')),
3627 _('do not display revision or any of its ancestors'), _('REV')),
3559 ('', 'hidden', False, _('show hidden changesets')),
3628 ('', 'hidden', False, _('show hidden changesets')),
3560 ] + logopts + walkopts,
3629 ] + logopts + walkopts,
3561 _('[OPTION]... [FILE]'))
3630 _('[OPTION]... [FILE]'))
3562 def log(ui, repo, *pats, **opts):
3631 def log(ui, repo, *pats, **opts):
3563 """show revision history of entire repository or files
3632 """show revision history of entire repository or files
3564
3633
3565 Print the revision history of the specified files or the entire
3634 Print the revision history of the specified files or the entire
3566 project.
3635 project.
3567
3636
3568 If no revision range is specified, the default is ``tip:0`` unless
3637 If no revision range is specified, the default is ``tip:0`` unless
3569 --follow is set, in which case the working directory parent is
3638 --follow is set, in which case the working directory parent is
3570 used as the starting revision.
3639 used as the starting revision.
3571
3640
3572 File history is shown without following rename or copy history of
3641 File history is shown without following rename or copy history of
3573 files. Use -f/--follow with a filename to follow history across
3642 files. Use -f/--follow with a filename to follow history across
3574 renames and copies. --follow without a filename will only show
3643 renames and copies. --follow without a filename will only show
3575 ancestors or descendants of the starting revision.
3644 ancestors or descendants of the starting revision.
3576
3645
3577 By default this command prints revision number and changeset id,
3646 By default this command prints revision number and changeset id,
3578 tags, non-trivial parents, user, date and time, and a summary for
3647 tags, non-trivial parents, user, date and time, and a summary for
3579 each commit. When the -v/--verbose switch is used, the list of
3648 each commit. When the -v/--verbose switch is used, the list of
3580 changed files and full commit message are shown.
3649 changed files and full commit message are shown.
3581
3650
3582 .. note::
3651 .. note::
3583 log -p/--patch may generate unexpected diff output for merge
3652 log -p/--patch may generate unexpected diff output for merge
3584 changesets, as it will only compare the merge changeset against
3653 changesets, as it will only compare the merge changeset against
3585 its first parent. Also, only files different from BOTH parents
3654 its first parent. Also, only files different from BOTH parents
3586 will appear in files:.
3655 will appear in files:.
3587
3656
3588 .. note::
3657 .. note::
3589 for performance reasons, log FILE may omit duplicate changes
3658 for performance reasons, log FILE may omit duplicate changes
3590 made on branches and will not show deletions. To see all
3659 made on branches and will not show deletions. To see all
3591 changes including duplicates and deletions, use the --removed
3660 changes including duplicates and deletions, use the --removed
3592 switch.
3661 switch.
3593
3662
3594 .. container:: verbose
3663 .. container:: verbose
3595
3664
3596 Some examples:
3665 Some examples:
3597
3666
3598 - changesets with full descriptions and file lists::
3667 - changesets with full descriptions and file lists::
3599
3668
3600 hg log -v
3669 hg log -v
3601
3670
3602 - changesets ancestral to the working directory::
3671 - changesets ancestral to the working directory::
3603
3672
3604 hg log -f
3673 hg log -f
3605
3674
3606 - last 10 commits on the current branch::
3675 - last 10 commits on the current branch::
3607
3676
3608 hg log -l 10 -b .
3677 hg log -l 10 -b .
3609
3678
3610 - changesets showing all modifications of a file, including removals::
3679 - changesets showing all modifications of a file, including removals::
3611
3680
3612 hg log --removed file.c
3681 hg log --removed file.c
3613
3682
3614 - all changesets that touch a directory, with diffs, excluding merges::
3683 - all changesets that touch a directory, with diffs, excluding merges::
3615
3684
3616 hg log -Mp lib/
3685 hg log -Mp lib/
3617
3686
3618 - all revision numbers that match a keyword::
3687 - all revision numbers that match a keyword::
3619
3688
3620 hg log -k bug --template "{rev}\\n"
3689 hg log -k bug --template "{rev}\\n"
3621
3690
3622 - check if a given changeset is included is a tagged release::
3691 - check if a given changeset is included is a tagged release::
3623
3692
3624 hg log -r "a21ccf and ancestor(1.9)"
3693 hg log -r "a21ccf and ancestor(1.9)"
3625
3694
3626 - find all changesets by some user in a date range::
3695 - find all changesets by some user in a date range::
3627
3696
3628 hg log -k alice -d "may 2008 to jul 2008"
3697 hg log -k alice -d "may 2008 to jul 2008"
3629
3698
3630 - summary of all changesets after the last tag::
3699 - summary of all changesets after the last tag::
3631
3700
3632 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3701 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3633
3702
3634 See :hg:`help dates` for a list of formats valid for -d/--date.
3703 See :hg:`help dates` for a list of formats valid for -d/--date.
3635
3704
3636 See :hg:`help revisions` and :hg:`help revsets` for more about
3705 See :hg:`help revisions` and :hg:`help revsets` for more about
3637 specifying revisions.
3706 specifying revisions.
3638
3707
3639 Returns 0 on success.
3708 Returns 0 on success.
3640 """
3709 """
3641
3710
3642 matchfn = scmutil.match(repo[None], pats, opts)
3711 matchfn = scmutil.match(repo[None], pats, opts)
3643 limit = cmdutil.loglimit(opts)
3712 limit = cmdutil.loglimit(opts)
3644 count = 0
3713 count = 0
3645
3714
3646 endrev = None
3715 endrev = None
3647 if opts.get('copies') and opts.get('rev'):
3716 if opts.get('copies') and opts.get('rev'):
3648 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3717 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3649
3718
3650 df = False
3719 df = False
3651 if opts["date"]:
3720 if opts["date"]:
3652 df = util.matchdate(opts["date"])
3721 df = util.matchdate(opts["date"])
3653
3722
3654 branches = opts.get('branch', []) + opts.get('only_branch', [])
3723 branches = opts.get('branch', []) + opts.get('only_branch', [])
3655 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3724 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3656
3725
3657 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3726 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3658 def prep(ctx, fns):
3727 def prep(ctx, fns):
3659 rev = ctx.rev()
3728 rev = ctx.rev()
3660 parents = [p for p in repo.changelog.parentrevs(rev)
3729 parents = [p for p in repo.changelog.parentrevs(rev)
3661 if p != nullrev]
3730 if p != nullrev]
3662 if opts.get('no_merges') and len(parents) == 2:
3731 if opts.get('no_merges') and len(parents) == 2:
3663 return
3732 return
3664 if opts.get('only_merges') and len(parents) != 2:
3733 if opts.get('only_merges') and len(parents) != 2:
3665 return
3734 return
3666 if opts.get('branch') and ctx.branch() not in opts['branch']:
3735 if opts.get('branch') and ctx.branch() not in opts['branch']:
3667 return
3736 return
3668 if not opts.get('hidden') and ctx.hidden():
3737 if not opts.get('hidden') and ctx.hidden():
3669 return
3738 return
3670 if df and not df(ctx.date()[0]):
3739 if df and not df(ctx.date()[0]):
3671 return
3740 return
3672 if opts['user'] and not [k for k in opts['user']
3741 if opts['user'] and not [k for k in opts['user']
3673 if k.lower() in ctx.user().lower()]:
3742 if k.lower() in ctx.user().lower()]:
3674 return
3743 return
3675 if opts.get('keyword'):
3744 if opts.get('keyword'):
3676 for k in [kw.lower() for kw in opts['keyword']]:
3745 for k in [kw.lower() for kw in opts['keyword']]:
3677 if (k in ctx.user().lower() or
3746 if (k in ctx.user().lower() or
3678 k in ctx.description().lower() or
3747 k in ctx.description().lower() or
3679 k in " ".join(ctx.files()).lower()):
3748 k in " ".join(ctx.files()).lower()):
3680 break
3749 break
3681 else:
3750 else:
3682 return
3751 return
3683
3752
3684 copies = None
3753 copies = None
3685 if opts.get('copies') and rev:
3754 if opts.get('copies') and rev:
3686 copies = []
3755 copies = []
3687 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3756 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3688 for fn in ctx.files():
3757 for fn in ctx.files():
3689 rename = getrenamed(fn, rev)
3758 rename = getrenamed(fn, rev)
3690 if rename:
3759 if rename:
3691 copies.append((fn, rename[0]))
3760 copies.append((fn, rename[0]))
3692
3761
3693 revmatchfn = None
3762 revmatchfn = None
3694 if opts.get('patch') or opts.get('stat'):
3763 if opts.get('patch') or opts.get('stat'):
3695 if opts.get('follow') or opts.get('follow_first'):
3764 if opts.get('follow') or opts.get('follow_first'):
3696 # note: this might be wrong when following through merges
3765 # note: this might be wrong when following through merges
3697 revmatchfn = scmutil.match(repo[None], fns, default='path')
3766 revmatchfn = scmutil.match(repo[None], fns, default='path')
3698 else:
3767 else:
3699 revmatchfn = matchfn
3768 revmatchfn = matchfn
3700
3769
3701 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3770 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3702
3771
3703 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3772 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3704 if count == limit:
3773 if count == limit:
3705 break
3774 break
3706 if displayer.flush(ctx.rev()):
3775 if displayer.flush(ctx.rev()):
3707 count += 1
3776 count += 1
3708 displayer.close()
3777 displayer.close()
3709
3778
3710 @command('manifest',
3779 @command('manifest',
3711 [('r', 'rev', '', _('revision to display'), _('REV')),
3780 [('r', 'rev', '', _('revision to display'), _('REV')),
3712 ('', 'all', False, _("list files from all revisions"))],
3781 ('', 'all', False, _("list files from all revisions"))],
3713 _('[-r REV]'))
3782 _('[-r REV]'))
3714 def manifest(ui, repo, node=None, rev=None, **opts):
3783 def manifest(ui, repo, node=None, rev=None, **opts):
3715 """output the current or given revision of the project manifest
3784 """output the current or given revision of the project manifest
3716
3785
3717 Print a list of version controlled files for the given revision.
3786 Print a list of version controlled files for the given revision.
3718 If no revision is given, the first parent of the working directory
3787 If no revision is given, the first parent of the working directory
3719 is used, or the null revision if no revision is checked out.
3788 is used, or the null revision if no revision is checked out.
3720
3789
3721 With -v, print file permissions, symlink and executable bits.
3790 With -v, print file permissions, symlink and executable bits.
3722 With --debug, print file revision hashes.
3791 With --debug, print file revision hashes.
3723
3792
3724 If option --all is specified, the list of all files from all revisions
3793 If option --all is specified, the list of all files from all revisions
3725 is printed. This includes deleted and renamed files.
3794 is printed. This includes deleted and renamed files.
3726
3795
3727 Returns 0 on success.
3796 Returns 0 on success.
3728 """
3797 """
3729 if opts.get('all'):
3798 if opts.get('all'):
3730 if rev or node:
3799 if rev or node:
3731 raise util.Abort(_("can't specify a revision with --all"))
3800 raise util.Abort(_("can't specify a revision with --all"))
3732
3801
3733 res = []
3802 res = []
3734 prefix = "data/"
3803 prefix = "data/"
3735 suffix = ".i"
3804 suffix = ".i"
3736 plen = len(prefix)
3805 plen = len(prefix)
3737 slen = len(suffix)
3806 slen = len(suffix)
3738 lock = repo.lock()
3807 lock = repo.lock()
3739 try:
3808 try:
3740 for fn, b, size in repo.store.datafiles():
3809 for fn, b, size in repo.store.datafiles():
3741 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3810 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3742 res.append(fn[plen:-slen])
3811 res.append(fn[plen:-slen])
3743 finally:
3812 finally:
3744 lock.release()
3813 lock.release()
3745 for f in sorted(res):
3814 for f in sorted(res):
3746 ui.write("%s\n" % f)
3815 ui.write("%s\n" % f)
3747 return
3816 return
3748
3817
3749 if rev and node:
3818 if rev and node:
3750 raise util.Abort(_("please specify just one revision"))
3819 raise util.Abort(_("please specify just one revision"))
3751
3820
3752 if not node:
3821 if not node:
3753 node = rev
3822 node = rev
3754
3823
3755 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3824 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3756 ctx = scmutil.revsingle(repo, node)
3825 ctx = scmutil.revsingle(repo, node)
3757 for f in ctx:
3826 for f in ctx:
3758 if ui.debugflag:
3827 if ui.debugflag:
3759 ui.write("%40s " % hex(ctx.manifest()[f]))
3828 ui.write("%40s " % hex(ctx.manifest()[f]))
3760 if ui.verbose:
3829 if ui.verbose:
3761 ui.write(decor[ctx.flags(f)])
3830 ui.write(decor[ctx.flags(f)])
3762 ui.write("%s\n" % f)
3831 ui.write("%s\n" % f)
3763
3832
3764 @command('^merge',
3833 @command('^merge',
3765 [('f', 'force', None, _('force a merge with outstanding changes')),
3834 [('f', 'force', None, _('force a merge with outstanding changes')),
3766 ('r', 'rev', '', _('revision to merge'), _('REV')),
3835 ('r', 'rev', '', _('revision to merge'), _('REV')),
3767 ('P', 'preview', None,
3836 ('P', 'preview', None,
3768 _('review revisions to merge (no merge is performed)'))
3837 _('review revisions to merge (no merge is performed)'))
3769 ] + mergetoolopts,
3838 ] + mergetoolopts,
3770 _('[-P] [-f] [[-r] REV]'))
3839 _('[-P] [-f] [[-r] REV]'))
3771 def merge(ui, repo, node=None, **opts):
3840 def merge(ui, repo, node=None, **opts):
3772 """merge working directory with another revision
3841 """merge working directory with another revision
3773
3842
3774 The current working directory is updated with all changes made in
3843 The current working directory is updated with all changes made in
3775 the requested revision since the last common predecessor revision.
3844 the requested revision since the last common predecessor revision.
3776
3845
3777 Files that changed between either parent are marked as changed for
3846 Files that changed between either parent are marked as changed for
3778 the next commit and a commit must be performed before any further
3847 the next commit and a commit must be performed before any further
3779 updates to the repository are allowed. The next commit will have
3848 updates to the repository are allowed. The next commit will have
3780 two parents.
3849 two parents.
3781
3850
3782 ``--tool`` can be used to specify the merge tool used for file
3851 ``--tool`` can be used to specify the merge tool used for file
3783 merges. It overrides the HGMERGE environment variable and your
3852 merges. It overrides the HGMERGE environment variable and your
3784 configuration files. See :hg:`help merge-tools` for options.
3853 configuration files. See :hg:`help merge-tools` for options.
3785
3854
3786 If no revision is specified, the working directory's parent is a
3855 If no revision is specified, the working directory's parent is a
3787 head revision, and the current branch contains exactly one other
3856 head revision, and the current branch contains exactly one other
3788 head, the other head is merged with by default. Otherwise, an
3857 head, the other head is merged with by default. Otherwise, an
3789 explicit revision with which to merge with must be provided.
3858 explicit revision with which to merge with must be provided.
3790
3859
3791 :hg:`resolve` must be used to resolve unresolved files.
3860 :hg:`resolve` must be used to resolve unresolved files.
3792
3861
3793 To undo an uncommitted merge, use :hg:`update --clean .` which
3862 To undo an uncommitted merge, use :hg:`update --clean .` which
3794 will check out a clean copy of the original merge parent, losing
3863 will check out a clean copy of the original merge parent, losing
3795 all changes.
3864 all changes.
3796
3865
3797 Returns 0 on success, 1 if there are unresolved files.
3866 Returns 0 on success, 1 if there are unresolved files.
3798 """
3867 """
3799
3868
3800 if opts.get('rev') and node:
3869 if opts.get('rev') and node:
3801 raise util.Abort(_("please specify just one revision"))
3870 raise util.Abort(_("please specify just one revision"))
3802 if not node:
3871 if not node:
3803 node = opts.get('rev')
3872 node = opts.get('rev')
3804
3873
3805 if not node:
3874 if not node:
3806 branch = repo[None].branch()
3875 branch = repo[None].branch()
3807 bheads = repo.branchheads(branch)
3876 bheads = repo.branchheads(branch)
3808 if len(bheads) > 2:
3877 if len(bheads) > 2:
3809 raise util.Abort(_("branch '%s' has %d heads - "
3878 raise util.Abort(_("branch '%s' has %d heads - "
3810 "please merge with an explicit rev")
3879 "please merge with an explicit rev")
3811 % (branch, len(bheads)),
3880 % (branch, len(bheads)),
3812 hint=_("run 'hg heads .' to see heads"))
3881 hint=_("run 'hg heads .' to see heads"))
3813
3882
3814 parent = repo.dirstate.p1()
3883 parent = repo.dirstate.p1()
3815 if len(bheads) == 1:
3884 if len(bheads) == 1:
3816 if len(repo.heads()) > 1:
3885 if len(repo.heads()) > 1:
3817 raise util.Abort(_("branch '%s' has one head - "
3886 raise util.Abort(_("branch '%s' has one head - "
3818 "please merge with an explicit rev")
3887 "please merge with an explicit rev")
3819 % branch,
3888 % branch,
3820 hint=_("run 'hg heads' to see all heads"))
3889 hint=_("run 'hg heads' to see all heads"))
3821 msg = _('there is nothing to merge')
3890 msg = _('there is nothing to merge')
3822 if parent != repo.lookup(repo[None].branch()):
3891 if parent != repo.lookup(repo[None].branch()):
3823 msg = _('%s - use "hg update" instead') % msg
3892 msg = _('%s - use "hg update" instead') % msg
3824 raise util.Abort(msg)
3893 raise util.Abort(msg)
3825
3894
3826 if parent not in bheads:
3895 if parent not in bheads:
3827 raise util.Abort(_('working directory not at a head revision'),
3896 raise util.Abort(_('working directory not at a head revision'),
3828 hint=_("use 'hg update' or merge with an "
3897 hint=_("use 'hg update' or merge with an "
3829 "explicit revision"))
3898 "explicit revision"))
3830 node = parent == bheads[0] and bheads[-1] or bheads[0]
3899 node = parent == bheads[0] and bheads[-1] or bheads[0]
3831 else:
3900 else:
3832 node = scmutil.revsingle(repo, node).node()
3901 node = scmutil.revsingle(repo, node).node()
3833
3902
3834 if opts.get('preview'):
3903 if opts.get('preview'):
3835 # find nodes that are ancestors of p2 but not of p1
3904 # find nodes that are ancestors of p2 but not of p1
3836 p1 = repo.lookup('.')
3905 p1 = repo.lookup('.')
3837 p2 = repo.lookup(node)
3906 p2 = repo.lookup(node)
3838 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3907 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3839
3908
3840 displayer = cmdutil.show_changeset(ui, repo, opts)
3909 displayer = cmdutil.show_changeset(ui, repo, opts)
3841 for node in nodes:
3910 for node in nodes:
3842 displayer.show(repo[node])
3911 displayer.show(repo[node])
3843 displayer.close()
3912 displayer.close()
3844 return 0
3913 return 0
3845
3914
3846 try:
3915 try:
3847 # ui.forcemerge is an internal variable, do not document
3916 # ui.forcemerge is an internal variable, do not document
3848 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3917 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3849 return hg.merge(repo, node, force=opts.get('force'))
3918 return hg.merge(repo, node, force=opts.get('force'))
3850 finally:
3919 finally:
3851 ui.setconfig('ui', 'forcemerge', '')
3920 ui.setconfig('ui', 'forcemerge', '')
3852
3921
3853 @command('outgoing|out',
3922 @command('outgoing|out',
3854 [('f', 'force', None, _('run even when the destination is unrelated')),
3923 [('f', 'force', None, _('run even when the destination is unrelated')),
3855 ('r', 'rev', [],
3924 ('r', 'rev', [],
3856 _('a changeset intended to be included in the destination'), _('REV')),
3925 _('a changeset intended to be included in the destination'), _('REV')),
3857 ('n', 'newest-first', None, _('show newest record first')),
3926 ('n', 'newest-first', None, _('show newest record first')),
3858 ('B', 'bookmarks', False, _('compare bookmarks')),
3927 ('B', 'bookmarks', False, _('compare bookmarks')),
3859 ('b', 'branch', [], _('a specific branch you would like to push'),
3928 ('b', 'branch', [], _('a specific branch you would like to push'),
3860 _('BRANCH')),
3929 _('BRANCH')),
3861 ] + logopts + remoteopts + subrepoopts,
3930 ] + logopts + remoteopts + subrepoopts,
3862 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3931 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3863 def outgoing(ui, repo, dest=None, **opts):
3932 def outgoing(ui, repo, dest=None, **opts):
3864 """show changesets not found in the destination
3933 """show changesets not found in the destination
3865
3934
3866 Show changesets not found in the specified destination repository
3935 Show changesets not found in the specified destination repository
3867 or the default push location. These are the changesets that would
3936 or the default push location. These are the changesets that would
3868 be pushed if a push was requested.
3937 be pushed if a push was requested.
3869
3938
3870 See pull for details of valid destination formats.
3939 See pull for details of valid destination formats.
3871
3940
3872 Returns 0 if there are outgoing changes, 1 otherwise.
3941 Returns 0 if there are outgoing changes, 1 otherwise.
3873 """
3942 """
3874
3943
3875 if opts.get('bookmarks'):
3944 if opts.get('bookmarks'):
3876 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3945 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3877 dest, branches = hg.parseurl(dest, opts.get('branch'))
3946 dest, branches = hg.parseurl(dest, opts.get('branch'))
3878 other = hg.peer(repo, opts, dest)
3947 other = hg.peer(repo, opts, dest)
3879 if 'bookmarks' not in other.listkeys('namespaces'):
3948 if 'bookmarks' not in other.listkeys('namespaces'):
3880 ui.warn(_("remote doesn't support bookmarks\n"))
3949 ui.warn(_("remote doesn't support bookmarks\n"))
3881 return 0
3950 return 0
3882 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3951 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3883 return bookmarks.diff(ui, other, repo)
3952 return bookmarks.diff(ui, other, repo)
3884
3953
3885 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3954 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3886 try:
3955 try:
3887 return hg.outgoing(ui, repo, dest, opts)
3956 return hg.outgoing(ui, repo, dest, opts)
3888 finally:
3957 finally:
3889 del repo._subtoppath
3958 del repo._subtoppath
3890
3959
3891 @command('parents',
3960 @command('parents',
3892 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3961 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3893 ] + templateopts,
3962 ] + templateopts,
3894 _('[-r REV] [FILE]'))
3963 _('[-r REV] [FILE]'))
3895 def parents(ui, repo, file_=None, **opts):
3964 def parents(ui, repo, file_=None, **opts):
3896 """show the parents of the working directory or revision
3965 """show the parents of the working directory or revision
3897
3966
3898 Print the working directory's parent revisions. If a revision is
3967 Print the working directory's parent revisions. If a revision is
3899 given via -r/--rev, the parent of that revision will be printed.
3968 given via -r/--rev, the parent of that revision will be printed.
3900 If a file argument is given, the revision in which the file was
3969 If a file argument is given, the revision in which the file was
3901 last changed (before the working directory revision or the
3970 last changed (before the working directory revision or the
3902 argument to --rev if given) is printed.
3971 argument to --rev if given) is printed.
3903
3972
3904 Returns 0 on success.
3973 Returns 0 on success.
3905 """
3974 """
3906
3975
3907 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3976 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3908
3977
3909 if file_:
3978 if file_:
3910 m = scmutil.match(ctx, (file_,), opts)
3979 m = scmutil.match(ctx, (file_,), opts)
3911 if m.anypats() or len(m.files()) != 1:
3980 if m.anypats() or len(m.files()) != 1:
3912 raise util.Abort(_('can only specify an explicit filename'))
3981 raise util.Abort(_('can only specify an explicit filename'))
3913 file_ = m.files()[0]
3982 file_ = m.files()[0]
3914 filenodes = []
3983 filenodes = []
3915 for cp in ctx.parents():
3984 for cp in ctx.parents():
3916 if not cp:
3985 if not cp:
3917 continue
3986 continue
3918 try:
3987 try:
3919 filenodes.append(cp.filenode(file_))
3988 filenodes.append(cp.filenode(file_))
3920 except error.LookupError:
3989 except error.LookupError:
3921 pass
3990 pass
3922 if not filenodes:
3991 if not filenodes:
3923 raise util.Abort(_("'%s' not found in manifest!") % file_)
3992 raise util.Abort(_("'%s' not found in manifest!") % file_)
3924 fl = repo.file(file_)
3993 fl = repo.file(file_)
3925 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3994 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3926 else:
3995 else:
3927 p = [cp.node() for cp in ctx.parents()]
3996 p = [cp.node() for cp in ctx.parents()]
3928
3997
3929 displayer = cmdutil.show_changeset(ui, repo, opts)
3998 displayer = cmdutil.show_changeset(ui, repo, opts)
3930 for n in p:
3999 for n in p:
3931 if n != nullid:
4000 if n != nullid:
3932 displayer.show(repo[n])
4001 displayer.show(repo[n])
3933 displayer.close()
4002 displayer.close()
3934
4003
3935 @command('paths', [], _('[NAME]'))
4004 @command('paths', [], _('[NAME]'))
3936 def paths(ui, repo, search=None):
4005 def paths(ui, repo, search=None):
3937 """show aliases for remote repositories
4006 """show aliases for remote repositories
3938
4007
3939 Show definition of symbolic path name NAME. If no name is given,
4008 Show definition of symbolic path name NAME. If no name is given,
3940 show definition of all available names.
4009 show definition of all available names.
3941
4010
3942 Option -q/--quiet suppresses all output when searching for NAME
4011 Option -q/--quiet suppresses all output when searching for NAME
3943 and shows only the path names when listing all definitions.
4012 and shows only the path names when listing all definitions.
3944
4013
3945 Path names are defined in the [paths] section of your
4014 Path names are defined in the [paths] section of your
3946 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4015 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3947 repository, ``.hg/hgrc`` is used, too.
4016 repository, ``.hg/hgrc`` is used, too.
3948
4017
3949 The path names ``default`` and ``default-push`` have a special
4018 The path names ``default`` and ``default-push`` have a special
3950 meaning. When performing a push or pull operation, they are used
4019 meaning. When performing a push or pull operation, they are used
3951 as fallbacks if no location is specified on the command-line.
4020 as fallbacks if no location is specified on the command-line.
3952 When ``default-push`` is set, it will be used for push and
4021 When ``default-push`` is set, it will be used for push and
3953 ``default`` will be used for pull; otherwise ``default`` is used
4022 ``default`` will be used for pull; otherwise ``default`` is used
3954 as the fallback for both. When cloning a repository, the clone
4023 as the fallback for both. When cloning a repository, the clone
3955 source is written as ``default`` in ``.hg/hgrc``. Note that
4024 source is written as ``default`` in ``.hg/hgrc``. Note that
3956 ``default`` and ``default-push`` apply to all inbound (e.g.
4025 ``default`` and ``default-push`` apply to all inbound (e.g.
3957 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4026 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3958 :hg:`bundle`) operations.
4027 :hg:`bundle`) operations.
3959
4028
3960 See :hg:`help urls` for more information.
4029 See :hg:`help urls` for more information.
3961
4030
3962 Returns 0 on success.
4031 Returns 0 on success.
3963 """
4032 """
3964 if search:
4033 if search:
3965 for name, path in ui.configitems("paths"):
4034 for name, path in ui.configitems("paths"):
3966 if name == search:
4035 if name == search:
3967 ui.status("%s\n" % util.hidepassword(path))
4036 ui.status("%s\n" % util.hidepassword(path))
3968 return
4037 return
3969 if not ui.quiet:
4038 if not ui.quiet:
3970 ui.warn(_("not found!\n"))
4039 ui.warn(_("not found!\n"))
3971 return 1
4040 return 1
3972 else:
4041 else:
3973 for name, path in ui.configitems("paths"):
4042 for name, path in ui.configitems("paths"):
3974 if ui.quiet:
4043 if ui.quiet:
3975 ui.write("%s\n" % name)
4044 ui.write("%s\n" % name)
3976 else:
4045 else:
3977 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4046 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3978
4047
3979 def postincoming(ui, repo, modheads, optupdate, checkout):
4048 def postincoming(ui, repo, modheads, optupdate, checkout):
3980 if modheads == 0:
4049 if modheads == 0:
3981 return
4050 return
3982 if optupdate:
4051 if optupdate:
3983 try:
4052 try:
3984 return hg.update(repo, checkout)
4053 return hg.update(repo, checkout)
3985 except util.Abort, inst:
4054 except util.Abort, inst:
3986 ui.warn(_("not updating: %s\n" % str(inst)))
4055 ui.warn(_("not updating: %s\n" % str(inst)))
3987 return 0
4056 return 0
3988 if modheads > 1:
4057 if modheads > 1:
3989 currentbranchheads = len(repo.branchheads())
4058 currentbranchheads = len(repo.branchheads())
3990 if currentbranchheads == modheads:
4059 if currentbranchheads == modheads:
3991 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4060 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3992 elif currentbranchheads > 1:
4061 elif currentbranchheads > 1:
3993 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
4062 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3994 else:
4063 else:
3995 ui.status(_("(run 'hg heads' to see heads)\n"))
4064 ui.status(_("(run 'hg heads' to see heads)\n"))
3996 else:
4065 else:
3997 ui.status(_("(run 'hg update' to get a working copy)\n"))
4066 ui.status(_("(run 'hg update' to get a working copy)\n"))
3998
4067
3999 @command('^pull',
4068 @command('^pull',
4000 [('u', 'update', None,
4069 [('u', 'update', None,
4001 _('update to new branch head if changesets were pulled')),
4070 _('update to new branch head if changesets were pulled')),
4002 ('f', 'force', None, _('run even when remote repository is unrelated')),
4071 ('f', 'force', None, _('run even when remote repository is unrelated')),
4003 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4072 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4004 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4073 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4005 ('b', 'branch', [], _('a specific branch you would like to pull'),
4074 ('b', 'branch', [], _('a specific branch you would like to pull'),
4006 _('BRANCH')),
4075 _('BRANCH')),
4007 ] + remoteopts,
4076 ] + remoteopts,
4008 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4077 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4009 def pull(ui, repo, source="default", **opts):
4078 def pull(ui, repo, source="default", **opts):
4010 """pull changes from the specified source
4079 """pull changes from the specified source
4011
4080
4012 Pull changes from a remote repository to a local one.
4081 Pull changes from a remote repository to a local one.
4013
4082
4014 This finds all changes from the repository at the specified path
4083 This finds all changes from the repository at the specified path
4015 or URL and adds them to a local repository (the current one unless
4084 or URL and adds them to a local repository (the current one unless
4016 -R is specified). By default, this does not update the copy of the
4085 -R is specified). By default, this does not update the copy of the
4017 project in the working directory.
4086 project in the working directory.
4018
4087
4019 Use :hg:`incoming` if you want to see what would have been added
4088 Use :hg:`incoming` if you want to see what would have been added
4020 by a pull at the time you issued this command. If you then decide
4089 by a pull at the time you issued this command. If you then decide
4021 to add those changes to the repository, you should use :hg:`pull
4090 to add those changes to the repository, you should use :hg:`pull
4022 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4091 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4023
4092
4024 If SOURCE is omitted, the 'default' path will be used.
4093 If SOURCE is omitted, the 'default' path will be used.
4025 See :hg:`help urls` for more information.
4094 See :hg:`help urls` for more information.
4026
4095
4027 Returns 0 on success, 1 if an update had unresolved files.
4096 Returns 0 on success, 1 if an update had unresolved files.
4028 """
4097 """
4029 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4098 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4030 other = hg.peer(repo, opts, source)
4099 other = hg.peer(repo, opts, source)
4031 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4100 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4032 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4101 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4033
4102
4034 if opts.get('bookmark'):
4103 if opts.get('bookmark'):
4035 if not revs:
4104 if not revs:
4036 revs = []
4105 revs = []
4037 rb = other.listkeys('bookmarks')
4106 rb = other.listkeys('bookmarks')
4038 for b in opts['bookmark']:
4107 for b in opts['bookmark']:
4039 if b not in rb:
4108 if b not in rb:
4040 raise util.Abort(_('remote bookmark %s not found!') % b)
4109 raise util.Abort(_('remote bookmark %s not found!') % b)
4041 revs.append(rb[b])
4110 revs.append(rb[b])
4042
4111
4043 if revs:
4112 if revs:
4044 try:
4113 try:
4045 revs = [other.lookup(rev) for rev in revs]
4114 revs = [other.lookup(rev) for rev in revs]
4046 except error.CapabilityError:
4115 except error.CapabilityError:
4047 err = _("other repository doesn't support revision lookup, "
4116 err = _("other repository doesn't support revision lookup, "
4048 "so a rev cannot be specified.")
4117 "so a rev cannot be specified.")
4049 raise util.Abort(err)
4118 raise util.Abort(err)
4050
4119
4051 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4120 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4052 bookmarks.updatefromremote(ui, repo, other)
4121 bookmarks.updatefromremote(ui, repo, other)
4053 if checkout:
4122 if checkout:
4054 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4123 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4055 repo._subtoppath = source
4124 repo._subtoppath = source
4056 try:
4125 try:
4057 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4126 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4058
4127
4059 finally:
4128 finally:
4060 del repo._subtoppath
4129 del repo._subtoppath
4061
4130
4062 # update specified bookmarks
4131 # update specified bookmarks
4063 if opts.get('bookmark'):
4132 if opts.get('bookmark'):
4064 for b in opts['bookmark']:
4133 for b in opts['bookmark']:
4065 # explicit pull overrides local bookmark if any
4134 # explicit pull overrides local bookmark if any
4066 ui.status(_("importing bookmark %s\n") % b)
4135 ui.status(_("importing bookmark %s\n") % b)
4067 repo._bookmarks[b] = repo[rb[b]].node()
4136 repo._bookmarks[b] = repo[rb[b]].node()
4068 bookmarks.write(repo)
4137 bookmarks.write(repo)
4069
4138
4070 return ret
4139 return ret
4071
4140
4072 @command('^push',
4141 @command('^push',
4073 [('f', 'force', None, _('force push')),
4142 [('f', 'force', None, _('force push')),
4074 ('r', 'rev', [],
4143 ('r', 'rev', [],
4075 _('a changeset intended to be included in the destination'),
4144 _('a changeset intended to be included in the destination'),
4076 _('REV')),
4145 _('REV')),
4077 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4146 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4078 ('b', 'branch', [],
4147 ('b', 'branch', [],
4079 _('a specific branch you would like to push'), _('BRANCH')),
4148 _('a specific branch you would like to push'), _('BRANCH')),
4080 ('', 'new-branch', False, _('allow pushing a new branch')),
4149 ('', 'new-branch', False, _('allow pushing a new branch')),
4081 ] + remoteopts,
4150 ] + remoteopts,
4082 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4151 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4083 def push(ui, repo, dest=None, **opts):
4152 def push(ui, repo, dest=None, **opts):
4084 """push changes to the specified destination
4153 """push changes to the specified destination
4085
4154
4086 Push changesets from the local repository to the specified
4155 Push changesets from the local repository to the specified
4087 destination.
4156 destination.
4088
4157
4089 This operation is symmetrical to pull: it is identical to a pull
4158 This operation is symmetrical to pull: it is identical to a pull
4090 in the destination repository from the current one.
4159 in the destination repository from the current one.
4091
4160
4092 By default, push will not allow creation of new heads at the
4161 By default, push will not allow creation of new heads at the
4093 destination, since multiple heads would make it unclear which head
4162 destination, since multiple heads would make it unclear which head
4094 to use. In this situation, it is recommended to pull and merge
4163 to use. In this situation, it is recommended to pull and merge
4095 before pushing.
4164 before pushing.
4096
4165
4097 Use --new-branch if you want to allow push to create a new named
4166 Use --new-branch if you want to allow push to create a new named
4098 branch that is not present at the destination. This allows you to
4167 branch that is not present at the destination. This allows you to
4099 only create a new branch without forcing other changes.
4168 only create a new branch without forcing other changes.
4100
4169
4101 Use -f/--force to override the default behavior and push all
4170 Use -f/--force to override the default behavior and push all
4102 changesets on all branches.
4171 changesets on all branches.
4103
4172
4104 If -r/--rev is used, the specified revision and all its ancestors
4173 If -r/--rev is used, the specified revision and all its ancestors
4105 will be pushed to the remote repository.
4174 will be pushed to the remote repository.
4106
4175
4107 Please see :hg:`help urls` for important details about ``ssh://``
4176 Please see :hg:`help urls` for important details about ``ssh://``
4108 URLs. If DESTINATION is omitted, a default path will be used.
4177 URLs. If DESTINATION is omitted, a default path will be used.
4109
4178
4110 Returns 0 if push was successful, 1 if nothing to push.
4179 Returns 0 if push was successful, 1 if nothing to push.
4111 """
4180 """
4112
4181
4113 if opts.get('bookmark'):
4182 if opts.get('bookmark'):
4114 for b in opts['bookmark']:
4183 for b in opts['bookmark']:
4115 # translate -B options to -r so changesets get pushed
4184 # translate -B options to -r so changesets get pushed
4116 if b in repo._bookmarks:
4185 if b in repo._bookmarks:
4117 opts.setdefault('rev', []).append(b)
4186 opts.setdefault('rev', []).append(b)
4118 else:
4187 else:
4119 # if we try to push a deleted bookmark, translate it to null
4188 # if we try to push a deleted bookmark, translate it to null
4120 # this lets simultaneous -r, -b options continue working
4189 # this lets simultaneous -r, -b options continue working
4121 opts.setdefault('rev', []).append("null")
4190 opts.setdefault('rev', []).append("null")
4122
4191
4123 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4192 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4124 dest, branches = hg.parseurl(dest, opts.get('branch'))
4193 dest, branches = hg.parseurl(dest, opts.get('branch'))
4125 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4194 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4126 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4195 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4127 other = hg.peer(repo, opts, dest)
4196 other = hg.peer(repo, opts, dest)
4128 if revs:
4197 if revs:
4129 revs = [repo.lookup(rev) for rev in revs]
4198 revs = [repo.lookup(rev) for rev in revs]
4130
4199
4131 repo._subtoppath = dest
4200 repo._subtoppath = dest
4132 try:
4201 try:
4133 # push subrepos depth-first for coherent ordering
4202 # push subrepos depth-first for coherent ordering
4134 c = repo['']
4203 c = repo['']
4135 subs = c.substate # only repos that are committed
4204 subs = c.substate # only repos that are committed
4136 for s in sorted(subs):
4205 for s in sorted(subs):
4137 if not c.sub(s).push(opts.get('force')):
4206 if not c.sub(s).push(opts.get('force')):
4138 return False
4207 return False
4139 finally:
4208 finally:
4140 del repo._subtoppath
4209 del repo._subtoppath
4141 result = repo.push(other, opts.get('force'), revs=revs,
4210 result = repo.push(other, opts.get('force'), revs=revs,
4142 newbranch=opts.get('new_branch'))
4211 newbranch=opts.get('new_branch'))
4143
4212
4144 result = (result == 0)
4213 result = (result == 0)
4145
4214
4146 if opts.get('bookmark'):
4215 if opts.get('bookmark'):
4147 rb = other.listkeys('bookmarks')
4216 rb = other.listkeys('bookmarks')
4148 for b in opts['bookmark']:
4217 for b in opts['bookmark']:
4149 # explicit push overrides remote bookmark if any
4218 # explicit push overrides remote bookmark if any
4150 if b in repo._bookmarks:
4219 if b in repo._bookmarks:
4151 ui.status(_("exporting bookmark %s\n") % b)
4220 ui.status(_("exporting bookmark %s\n") % b)
4152 new = repo[b].hex()
4221 new = repo[b].hex()
4153 elif b in rb:
4222 elif b in rb:
4154 ui.status(_("deleting remote bookmark %s\n") % b)
4223 ui.status(_("deleting remote bookmark %s\n") % b)
4155 new = '' # delete
4224 new = '' # delete
4156 else:
4225 else:
4157 ui.warn(_('bookmark %s does not exist on the local '
4226 ui.warn(_('bookmark %s does not exist on the local '
4158 'or remote repository!\n') % b)
4227 'or remote repository!\n') % b)
4159 return 2
4228 return 2
4160 old = rb.get(b, '')
4229 old = rb.get(b, '')
4161 r = other.pushkey('bookmarks', b, old, new)
4230 r = other.pushkey('bookmarks', b, old, new)
4162 if not r:
4231 if not r:
4163 ui.warn(_('updating bookmark %s failed!\n') % b)
4232 ui.warn(_('updating bookmark %s failed!\n') % b)
4164 if not result:
4233 if not result:
4165 result = 2
4234 result = 2
4166
4235
4167 return result
4236 return result
4168
4237
4169 @command('recover', [])
4238 @command('recover', [])
4170 def recover(ui, repo):
4239 def recover(ui, repo):
4171 """roll back an interrupted transaction
4240 """roll back an interrupted transaction
4172
4241
4173 Recover from an interrupted commit or pull.
4242 Recover from an interrupted commit or pull.
4174
4243
4175 This command tries to fix the repository status after an
4244 This command tries to fix the repository status after an
4176 interrupted operation. It should only be necessary when Mercurial
4245 interrupted operation. It should only be necessary when Mercurial
4177 suggests it.
4246 suggests it.
4178
4247
4179 Returns 0 if successful, 1 if nothing to recover or verify fails.
4248 Returns 0 if successful, 1 if nothing to recover or verify fails.
4180 """
4249 """
4181 if repo.recover():
4250 if repo.recover():
4182 return hg.verify(repo)
4251 return hg.verify(repo)
4183 return 1
4252 return 1
4184
4253
4185 @command('^remove|rm',
4254 @command('^remove|rm',
4186 [('A', 'after', None, _('record delete for missing files')),
4255 [('A', 'after', None, _('record delete for missing files')),
4187 ('f', 'force', None,
4256 ('f', 'force', None,
4188 _('remove (and delete) file even if added or modified')),
4257 _('remove (and delete) file even if added or modified')),
4189 ] + walkopts,
4258 ] + walkopts,
4190 _('[OPTION]... FILE...'))
4259 _('[OPTION]... FILE...'))
4191 def remove(ui, repo, *pats, **opts):
4260 def remove(ui, repo, *pats, **opts):
4192 """remove the specified files on the next commit
4261 """remove the specified files on the next commit
4193
4262
4194 Schedule the indicated files for removal from the current branch.
4263 Schedule the indicated files for removal from the current branch.
4195
4264
4196 This command schedules the files to be removed at the next commit.
4265 This command schedules the files to be removed at the next commit.
4197 To undo a remove before that, see :hg:`revert`. To undo added
4266 To undo a remove before that, see :hg:`revert`. To undo added
4198 files, see :hg:`forget`.
4267 files, see :hg:`forget`.
4199
4268
4200 .. container:: verbose
4269 .. container:: verbose
4201
4270
4202 -A/--after can be used to remove only files that have already
4271 -A/--after can be used to remove only files that have already
4203 been deleted, -f/--force can be used to force deletion, and -Af
4272 been deleted, -f/--force can be used to force deletion, and -Af
4204 can be used to remove files from the next revision without
4273 can be used to remove files from the next revision without
4205 deleting them from the working directory.
4274 deleting them from the working directory.
4206
4275
4207 The following table details the behavior of remove for different
4276 The following table details the behavior of remove for different
4208 file states (columns) and option combinations (rows). The file
4277 file states (columns) and option combinations (rows). The file
4209 states are Added [A], Clean [C], Modified [M] and Missing [!]
4278 states are Added [A], Clean [C], Modified [M] and Missing [!]
4210 (as reported by :hg:`status`). The actions are Warn, Remove
4279 (as reported by :hg:`status`). The actions are Warn, Remove
4211 (from branch) and Delete (from disk):
4280 (from branch) and Delete (from disk):
4212
4281
4213 ======= == == == ==
4282 ======= == == == ==
4214 A C M !
4283 A C M !
4215 ======= == == == ==
4284 ======= == == == ==
4216 none W RD W R
4285 none W RD W R
4217 -f R RD RD R
4286 -f R RD RD R
4218 -A W W W R
4287 -A W W W R
4219 -Af R R R R
4288 -Af R R R R
4220 ======= == == == ==
4289 ======= == == == ==
4221
4290
4222 Note that remove never deletes files in Added [A] state from the
4291 Note that remove never deletes files in Added [A] state from the
4223 working directory, not even if option --force is specified.
4292 working directory, not even if option --force is specified.
4224
4293
4225 Returns 0 on success, 1 if any warnings encountered.
4294 Returns 0 on success, 1 if any warnings encountered.
4226 """
4295 """
4227
4296
4228 ret = 0
4297 ret = 0
4229 after, force = opts.get('after'), opts.get('force')
4298 after, force = opts.get('after'), opts.get('force')
4230 if not pats and not after:
4299 if not pats and not after:
4231 raise util.Abort(_('no files specified'))
4300 raise util.Abort(_('no files specified'))
4232
4301
4233 m = scmutil.match(repo[None], pats, opts)
4302 m = scmutil.match(repo[None], pats, opts)
4234 s = repo.status(match=m, clean=True)
4303 s = repo.status(match=m, clean=True)
4235 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4304 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4236
4305
4237 for f in m.files():
4306 for f in m.files():
4238 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4307 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4239 if os.path.exists(m.rel(f)):
4308 if os.path.exists(m.rel(f)):
4240 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4309 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4241 ret = 1
4310 ret = 1
4242
4311
4243 if force:
4312 if force:
4244 list = modified + deleted + clean + added
4313 list = modified + deleted + clean + added
4245 elif after:
4314 elif after:
4246 list = deleted
4315 list = deleted
4247 for f in modified + added + clean:
4316 for f in modified + added + clean:
4248 ui.warn(_('not removing %s: file still exists (use -f'
4317 ui.warn(_('not removing %s: file still exists (use -f'
4249 ' to force removal)\n') % m.rel(f))
4318 ' to force removal)\n') % m.rel(f))
4250 ret = 1
4319 ret = 1
4251 else:
4320 else:
4252 list = deleted + clean
4321 list = deleted + clean
4253 for f in modified:
4322 for f in modified:
4254 ui.warn(_('not removing %s: file is modified (use -f'
4323 ui.warn(_('not removing %s: file is modified (use -f'
4255 ' to force removal)\n') % m.rel(f))
4324 ' to force removal)\n') % m.rel(f))
4256 ret = 1
4325 ret = 1
4257 for f in added:
4326 for f in added:
4258 ui.warn(_('not removing %s: file has been marked for add'
4327 ui.warn(_('not removing %s: file has been marked for add'
4259 ' (use forget to undo)\n') % m.rel(f))
4328 ' (use forget to undo)\n') % m.rel(f))
4260 ret = 1
4329 ret = 1
4261
4330
4262 for f in sorted(list):
4331 for f in sorted(list):
4263 if ui.verbose or not m.exact(f):
4332 if ui.verbose or not m.exact(f):
4264 ui.status(_('removing %s\n') % m.rel(f))
4333 ui.status(_('removing %s\n') % m.rel(f))
4265
4334
4266 wlock = repo.wlock()
4335 wlock = repo.wlock()
4267 try:
4336 try:
4268 if not after:
4337 if not after:
4269 for f in list:
4338 for f in list:
4270 if f in added:
4339 if f in added:
4271 continue # we never unlink added files on remove
4340 continue # we never unlink added files on remove
4272 try:
4341 try:
4273 util.unlinkpath(repo.wjoin(f))
4342 util.unlinkpath(repo.wjoin(f))
4274 except OSError, inst:
4343 except OSError, inst:
4275 if inst.errno != errno.ENOENT:
4344 if inst.errno != errno.ENOENT:
4276 raise
4345 raise
4277 repo[None].forget(list)
4346 repo[None].forget(list)
4278 finally:
4347 finally:
4279 wlock.release()
4348 wlock.release()
4280
4349
4281 return ret
4350 return ret
4282
4351
4283 @command('rename|move|mv',
4352 @command('rename|move|mv',
4284 [('A', 'after', None, _('record a rename that has already occurred')),
4353 [('A', 'after', None, _('record a rename that has already occurred')),
4285 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4354 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4286 ] + walkopts + dryrunopts,
4355 ] + walkopts + dryrunopts,
4287 _('[OPTION]... SOURCE... DEST'))
4356 _('[OPTION]... SOURCE... DEST'))
4288 def rename(ui, repo, *pats, **opts):
4357 def rename(ui, repo, *pats, **opts):
4289 """rename files; equivalent of copy + remove
4358 """rename files; equivalent of copy + remove
4290
4359
4291 Mark dest as copies of sources; mark sources for deletion. If dest
4360 Mark dest as copies of sources; mark sources for deletion. If dest
4292 is a directory, copies are put in that directory. If dest is a
4361 is a directory, copies are put in that directory. If dest is a
4293 file, there can only be one source.
4362 file, there can only be one source.
4294
4363
4295 By default, this command copies the contents of files as they
4364 By default, this command copies the contents of files as they
4296 exist in the working directory. If invoked with -A/--after, the
4365 exist in the working directory. If invoked with -A/--after, the
4297 operation is recorded, but no copying is performed.
4366 operation is recorded, but no copying is performed.
4298
4367
4299 This command takes effect at the next commit. To undo a rename
4368 This command takes effect at the next commit. To undo a rename
4300 before that, see :hg:`revert`.
4369 before that, see :hg:`revert`.
4301
4370
4302 Returns 0 on success, 1 if errors are encountered.
4371 Returns 0 on success, 1 if errors are encountered.
4303 """
4372 """
4304 wlock = repo.wlock(False)
4373 wlock = repo.wlock(False)
4305 try:
4374 try:
4306 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4375 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4307 finally:
4376 finally:
4308 wlock.release()
4377 wlock.release()
4309
4378
4310 @command('resolve',
4379 @command('resolve',
4311 [('a', 'all', None, _('select all unresolved files')),
4380 [('a', 'all', None, _('select all unresolved files')),
4312 ('l', 'list', None, _('list state of files needing merge')),
4381 ('l', 'list', None, _('list state of files needing merge')),
4313 ('m', 'mark', None, _('mark files as resolved')),
4382 ('m', 'mark', None, _('mark files as resolved')),
4314 ('u', 'unmark', None, _('mark files as unresolved')),
4383 ('u', 'unmark', None, _('mark files as unresolved')),
4315 ('n', 'no-status', None, _('hide status prefix'))]
4384 ('n', 'no-status', None, _('hide status prefix'))]
4316 + mergetoolopts + walkopts,
4385 + mergetoolopts + walkopts,
4317 _('[OPTION]... [FILE]...'))
4386 _('[OPTION]... [FILE]...'))
4318 def resolve(ui, repo, *pats, **opts):
4387 def resolve(ui, repo, *pats, **opts):
4319 """redo merges or set/view the merge status of files
4388 """redo merges or set/view the merge status of files
4320
4389
4321 Merges with unresolved conflicts are often the result of
4390 Merges with unresolved conflicts are often the result of
4322 non-interactive merging using the ``internal:merge`` configuration
4391 non-interactive merging using the ``internal:merge`` configuration
4323 setting, or a command-line merge tool like ``diff3``. The resolve
4392 setting, or a command-line merge tool like ``diff3``. The resolve
4324 command is used to manage the files involved in a merge, after
4393 command is used to manage the files involved in a merge, after
4325 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4394 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4326 working directory must have two parents).
4395 working directory must have two parents).
4327
4396
4328 The resolve command can be used in the following ways:
4397 The resolve command can be used in the following ways:
4329
4398
4330 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4399 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4331 files, discarding any previous merge attempts. Re-merging is not
4400 files, discarding any previous merge attempts. Re-merging is not
4332 performed for files already marked as resolved. Use ``--all/-a``
4401 performed for files already marked as resolved. Use ``--all/-a``
4333 to select all unresolved files. ``--tool`` can be used to specify
4402 to select all unresolved files. ``--tool`` can be used to specify
4334 the merge tool used for the given files. It overrides the HGMERGE
4403 the merge tool used for the given files. It overrides the HGMERGE
4335 environment variable and your configuration files. Previous file
4404 environment variable and your configuration files. Previous file
4336 contents are saved with a ``.orig`` suffix.
4405 contents are saved with a ``.orig`` suffix.
4337
4406
4338 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4407 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4339 (e.g. after having manually fixed-up the files). The default is
4408 (e.g. after having manually fixed-up the files). The default is
4340 to mark all unresolved files.
4409 to mark all unresolved files.
4341
4410
4342 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4411 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4343 default is to mark all resolved files.
4412 default is to mark all resolved files.
4344
4413
4345 - :hg:`resolve -l`: list files which had or still have conflicts.
4414 - :hg:`resolve -l`: list files which had or still have conflicts.
4346 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4415 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4347
4416
4348 Note that Mercurial will not let you commit files with unresolved
4417 Note that Mercurial will not let you commit files with unresolved
4349 merge conflicts. You must use :hg:`resolve -m ...` before you can
4418 merge conflicts. You must use :hg:`resolve -m ...` before you can
4350 commit after a conflicting merge.
4419 commit after a conflicting merge.
4351
4420
4352 Returns 0 on success, 1 if any files fail a resolve attempt.
4421 Returns 0 on success, 1 if any files fail a resolve attempt.
4353 """
4422 """
4354
4423
4355 all, mark, unmark, show, nostatus = \
4424 all, mark, unmark, show, nostatus = \
4356 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4425 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4357
4426
4358 if (show and (mark or unmark)) or (mark and unmark):
4427 if (show and (mark or unmark)) or (mark and unmark):
4359 raise util.Abort(_("too many options specified"))
4428 raise util.Abort(_("too many options specified"))
4360 if pats and all:
4429 if pats and all:
4361 raise util.Abort(_("can't specify --all and patterns"))
4430 raise util.Abort(_("can't specify --all and patterns"))
4362 if not (all or pats or show or mark or unmark):
4431 if not (all or pats or show or mark or unmark):
4363 raise util.Abort(_('no files or directories specified; '
4432 raise util.Abort(_('no files or directories specified; '
4364 'use --all to remerge all files'))
4433 'use --all to remerge all files'))
4365
4434
4366 ms = mergemod.mergestate(repo)
4435 ms = mergemod.mergestate(repo)
4367 m = scmutil.match(repo[None], pats, opts)
4436 m = scmutil.match(repo[None], pats, opts)
4368 ret = 0
4437 ret = 0
4369
4438
4370 for f in ms:
4439 for f in ms:
4371 if m(f):
4440 if m(f):
4372 if show:
4441 if show:
4373 if nostatus:
4442 if nostatus:
4374 ui.write("%s\n" % f)
4443 ui.write("%s\n" % f)
4375 else:
4444 else:
4376 ui.write("%s %s\n" % (ms[f].upper(), f),
4445 ui.write("%s %s\n" % (ms[f].upper(), f),
4377 label='resolve.' +
4446 label='resolve.' +
4378 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4447 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4379 elif mark:
4448 elif mark:
4380 ms.mark(f, "r")
4449 ms.mark(f, "r")
4381 elif unmark:
4450 elif unmark:
4382 ms.mark(f, "u")
4451 ms.mark(f, "u")
4383 else:
4452 else:
4384 wctx = repo[None]
4453 wctx = repo[None]
4385 mctx = wctx.parents()[-1]
4454 mctx = wctx.parents()[-1]
4386
4455
4387 # backup pre-resolve (merge uses .orig for its own purposes)
4456 # backup pre-resolve (merge uses .orig for its own purposes)
4388 a = repo.wjoin(f)
4457 a = repo.wjoin(f)
4389 util.copyfile(a, a + ".resolve")
4458 util.copyfile(a, a + ".resolve")
4390
4459
4391 try:
4460 try:
4392 # resolve file
4461 # resolve file
4393 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4462 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4394 if ms.resolve(f, wctx, mctx):
4463 if ms.resolve(f, wctx, mctx):
4395 ret = 1
4464 ret = 1
4396 finally:
4465 finally:
4397 ui.setconfig('ui', 'forcemerge', '')
4466 ui.setconfig('ui', 'forcemerge', '')
4398
4467
4399 # replace filemerge's .orig file with our resolve file
4468 # replace filemerge's .orig file with our resolve file
4400 util.rename(a + ".resolve", a + ".orig")
4469 util.rename(a + ".resolve", a + ".orig")
4401
4470
4402 ms.commit()
4471 ms.commit()
4403 return ret
4472 return ret
4404
4473
4405 @command('revert',
4474 @command('revert',
4406 [('a', 'all', None, _('revert all changes when no arguments given')),
4475 [('a', 'all', None, _('revert all changes when no arguments given')),
4407 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4476 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4408 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4477 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4409 ('C', 'no-backup', None, _('do not save backup copies of files')),
4478 ('C', 'no-backup', None, _('do not save backup copies of files')),
4410 ] + walkopts + dryrunopts,
4479 ] + walkopts + dryrunopts,
4411 _('[OPTION]... [-r REV] [NAME]...'))
4480 _('[OPTION]... [-r REV] [NAME]...'))
4412 def revert(ui, repo, *pats, **opts):
4481 def revert(ui, repo, *pats, **opts):
4413 """restore files to their checkout state
4482 """restore files to their checkout state
4414
4483
4415 .. note::
4484 .. note::
4416 To check out earlier revisions, you should use :hg:`update REV`.
4485 To check out earlier revisions, you should use :hg:`update REV`.
4417 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4486 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4418
4487
4419 With no revision specified, revert the specified files or directories
4488 With no revision specified, revert the specified files or directories
4420 to the contents they had in the parent of the working directory.
4489 to the contents they had in the parent of the working directory.
4421 This restores the contents of files to an unmodified
4490 This restores the contents of files to an unmodified
4422 state and unschedules adds, removes, copies, and renames. If the
4491 state and unschedules adds, removes, copies, and renames. If the
4423 working directory has two parents, you must explicitly specify a
4492 working directory has two parents, you must explicitly specify a
4424 revision.
4493 revision.
4425
4494
4426 Using the -r/--rev or -d/--date options, revert the given files or
4495 Using the -r/--rev or -d/--date options, revert the given files or
4427 directories to their states as of a specific revision. Because
4496 directories to their states as of a specific revision. Because
4428 revert does not change the working directory parents, this will
4497 revert does not change the working directory parents, this will
4429 cause these files to appear modified. This can be helpful to "back
4498 cause these files to appear modified. This can be helpful to "back
4430 out" some or all of an earlier change. See :hg:`backout` for a
4499 out" some or all of an earlier change. See :hg:`backout` for a
4431 related method.
4500 related method.
4432
4501
4433 Modified files are saved with a .orig suffix before reverting.
4502 Modified files are saved with a .orig suffix before reverting.
4434 To disable these backups, use --no-backup.
4503 To disable these backups, use --no-backup.
4435
4504
4436 See :hg:`help dates` for a list of formats valid for -d/--date.
4505 See :hg:`help dates` for a list of formats valid for -d/--date.
4437
4506
4438 Returns 0 on success.
4507 Returns 0 on success.
4439 """
4508 """
4440
4509
4441 if opts.get("date"):
4510 if opts.get("date"):
4442 if opts.get("rev"):
4511 if opts.get("rev"):
4443 raise util.Abort(_("you can't specify a revision and a date"))
4512 raise util.Abort(_("you can't specify a revision and a date"))
4444 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4513 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4445
4514
4446 parent, p2 = repo.dirstate.parents()
4515 parent, p2 = repo.dirstate.parents()
4447 if not opts.get('rev') and p2 != nullid:
4516 if not opts.get('rev') and p2 != nullid:
4448 # revert after merge is a trap for new users (issue2915)
4517 # revert after merge is a trap for new users (issue2915)
4449 raise util.Abort(_('uncommitted merge with no revision specified'),
4518 raise util.Abort(_('uncommitted merge with no revision specified'),
4450 hint=_('use "hg update" or see "hg help revert"'))
4519 hint=_('use "hg update" or see "hg help revert"'))
4451
4520
4452 ctx = scmutil.revsingle(repo, opts.get('rev'))
4521 ctx = scmutil.revsingle(repo, opts.get('rev'))
4453 node = ctx.node()
4522 node = ctx.node()
4454
4523
4455 if not pats and not opts.get('all'):
4524 if not pats and not opts.get('all'):
4456 msg = _("no files or directories specified")
4525 msg = _("no files or directories specified")
4457 if p2 != nullid:
4526 if p2 != nullid:
4458 hint = _("uncommitted merge, use --all to discard all changes,"
4527 hint = _("uncommitted merge, use --all to discard all changes,"
4459 " or 'hg update -C .' to abort the merge")
4528 " or 'hg update -C .' to abort the merge")
4460 raise util.Abort(msg, hint=hint)
4529 raise util.Abort(msg, hint=hint)
4461 dirty = util.any(repo.status())
4530 dirty = util.any(repo.status())
4462 if node != parent:
4531 if node != parent:
4463 if dirty:
4532 if dirty:
4464 hint = _("uncommitted changes, use --all to discard all"
4533 hint = _("uncommitted changes, use --all to discard all"
4465 " changes, or 'hg update %s' to update") % ctx.rev()
4534 " changes, or 'hg update %s' to update") % ctx.rev()
4466 else:
4535 else:
4467 hint = _("use --all to revert all files,"
4536 hint = _("use --all to revert all files,"
4468 " or 'hg update %s' to update") % ctx.rev()
4537 " or 'hg update %s' to update") % ctx.rev()
4469 elif dirty:
4538 elif dirty:
4470 hint = _("uncommitted changes, use --all to discard all changes")
4539 hint = _("uncommitted changes, use --all to discard all changes")
4471 else:
4540 else:
4472 hint = _("use --all to revert all files")
4541 hint = _("use --all to revert all files")
4473 raise util.Abort(msg, hint=hint)
4542 raise util.Abort(msg, hint=hint)
4474
4543
4475 mf = ctx.manifest()
4544 mf = ctx.manifest()
4476 if node == parent:
4545 if node == parent:
4477 pmf = mf
4546 pmf = mf
4478 else:
4547 else:
4479 pmf = None
4548 pmf = None
4480
4549
4481 # need all matching names in dirstate and manifest of target rev,
4550 # need all matching names in dirstate and manifest of target rev,
4482 # so have to walk both. do not print errors if files exist in one
4551 # so have to walk both. do not print errors if files exist in one
4483 # but not other.
4552 # but not other.
4484
4553
4485 names = {}
4554 names = {}
4486
4555
4487 wlock = repo.wlock()
4556 wlock = repo.wlock()
4488 try:
4557 try:
4489 # walk dirstate.
4558 # walk dirstate.
4490
4559
4491 m = scmutil.match(repo[None], pats, opts)
4560 m = scmutil.match(repo[None], pats, opts)
4492 m.bad = lambda x, y: False
4561 m.bad = lambda x, y: False
4493 for abs in repo.walk(m):
4562 for abs in repo.walk(m):
4494 names[abs] = m.rel(abs), m.exact(abs)
4563 names[abs] = m.rel(abs), m.exact(abs)
4495
4564
4496 # walk target manifest.
4565 # walk target manifest.
4497
4566
4498 def badfn(path, msg):
4567 def badfn(path, msg):
4499 if path in names:
4568 if path in names:
4500 return
4569 return
4501 path_ = path + '/'
4570 path_ = path + '/'
4502 for f in names:
4571 for f in names:
4503 if f.startswith(path_):
4572 if f.startswith(path_):
4504 return
4573 return
4505 ui.warn("%s: %s\n" % (m.rel(path), msg))
4574 ui.warn("%s: %s\n" % (m.rel(path), msg))
4506
4575
4507 m = scmutil.match(repo[node], pats, opts)
4576 m = scmutil.match(repo[node], pats, opts)
4508 m.bad = badfn
4577 m.bad = badfn
4509 for abs in repo[node].walk(m):
4578 for abs in repo[node].walk(m):
4510 if abs not in names:
4579 if abs not in names:
4511 names[abs] = m.rel(abs), m.exact(abs)
4580 names[abs] = m.rel(abs), m.exact(abs)
4512
4581
4513 m = scmutil.matchfiles(repo, names)
4582 m = scmutil.matchfiles(repo, names)
4514 changes = repo.status(match=m)[:4]
4583 changes = repo.status(match=m)[:4]
4515 modified, added, removed, deleted = map(set, changes)
4584 modified, added, removed, deleted = map(set, changes)
4516
4585
4517 # if f is a rename, also revert the source
4586 # if f is a rename, also revert the source
4518 cwd = repo.getcwd()
4587 cwd = repo.getcwd()
4519 for f in added:
4588 for f in added:
4520 src = repo.dirstate.copied(f)
4589 src = repo.dirstate.copied(f)
4521 if src and src not in names and repo.dirstate[src] == 'r':
4590 if src and src not in names and repo.dirstate[src] == 'r':
4522 removed.add(src)
4591 removed.add(src)
4523 names[src] = (repo.pathto(src, cwd), True)
4592 names[src] = (repo.pathto(src, cwd), True)
4524
4593
4525 def removeforget(abs):
4594 def removeforget(abs):
4526 if repo.dirstate[abs] == 'a':
4595 if repo.dirstate[abs] == 'a':
4527 return _('forgetting %s\n')
4596 return _('forgetting %s\n')
4528 return _('removing %s\n')
4597 return _('removing %s\n')
4529
4598
4530 revert = ([], _('reverting %s\n'))
4599 revert = ([], _('reverting %s\n'))
4531 add = ([], _('adding %s\n'))
4600 add = ([], _('adding %s\n'))
4532 remove = ([], removeforget)
4601 remove = ([], removeforget)
4533 undelete = ([], _('undeleting %s\n'))
4602 undelete = ([], _('undeleting %s\n'))
4534
4603
4535 disptable = (
4604 disptable = (
4536 # dispatch table:
4605 # dispatch table:
4537 # file state
4606 # file state
4538 # action if in target manifest
4607 # action if in target manifest
4539 # action if not in target manifest
4608 # action if not in target manifest
4540 # make backup if in target manifest
4609 # make backup if in target manifest
4541 # make backup if not in target manifest
4610 # make backup if not in target manifest
4542 (modified, revert, remove, True, True),
4611 (modified, revert, remove, True, True),
4543 (added, revert, remove, True, False),
4612 (added, revert, remove, True, False),
4544 (removed, undelete, None, False, False),
4613 (removed, undelete, None, False, False),
4545 (deleted, revert, remove, False, False),
4614 (deleted, revert, remove, False, False),
4546 )
4615 )
4547
4616
4548 for abs, (rel, exact) in sorted(names.items()):
4617 for abs, (rel, exact) in sorted(names.items()):
4549 mfentry = mf.get(abs)
4618 mfentry = mf.get(abs)
4550 target = repo.wjoin(abs)
4619 target = repo.wjoin(abs)
4551 def handle(xlist, dobackup):
4620 def handle(xlist, dobackup):
4552 xlist[0].append(abs)
4621 xlist[0].append(abs)
4553 if (dobackup and not opts.get('no_backup') and
4622 if (dobackup and not opts.get('no_backup') and
4554 os.path.lexists(target)):
4623 os.path.lexists(target)):
4555 bakname = "%s.orig" % rel
4624 bakname = "%s.orig" % rel
4556 ui.note(_('saving current version of %s as %s\n') %
4625 ui.note(_('saving current version of %s as %s\n') %
4557 (rel, bakname))
4626 (rel, bakname))
4558 if not opts.get('dry_run'):
4627 if not opts.get('dry_run'):
4559 util.rename(target, bakname)
4628 util.rename(target, bakname)
4560 if ui.verbose or not exact:
4629 if ui.verbose or not exact:
4561 msg = xlist[1]
4630 msg = xlist[1]
4562 if not isinstance(msg, basestring):
4631 if not isinstance(msg, basestring):
4563 msg = msg(abs)
4632 msg = msg(abs)
4564 ui.status(msg % rel)
4633 ui.status(msg % rel)
4565 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4634 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4566 if abs not in table:
4635 if abs not in table:
4567 continue
4636 continue
4568 # file has changed in dirstate
4637 # file has changed in dirstate
4569 if mfentry:
4638 if mfentry:
4570 handle(hitlist, backuphit)
4639 handle(hitlist, backuphit)
4571 elif misslist is not None:
4640 elif misslist is not None:
4572 handle(misslist, backupmiss)
4641 handle(misslist, backupmiss)
4573 break
4642 break
4574 else:
4643 else:
4575 if abs not in repo.dirstate:
4644 if abs not in repo.dirstate:
4576 if mfentry:
4645 if mfentry:
4577 handle(add, True)
4646 handle(add, True)
4578 elif exact:
4647 elif exact:
4579 ui.warn(_('file not managed: %s\n') % rel)
4648 ui.warn(_('file not managed: %s\n') % rel)
4580 continue
4649 continue
4581 # file has not changed in dirstate
4650 # file has not changed in dirstate
4582 if node == parent:
4651 if node == parent:
4583 if exact:
4652 if exact:
4584 ui.warn(_('no changes needed to %s\n') % rel)
4653 ui.warn(_('no changes needed to %s\n') % rel)
4585 continue
4654 continue
4586 if pmf is None:
4655 if pmf is None:
4587 # only need parent manifest in this unlikely case,
4656 # only need parent manifest in this unlikely case,
4588 # so do not read by default
4657 # so do not read by default
4589 pmf = repo[parent].manifest()
4658 pmf = repo[parent].manifest()
4590 if abs in pmf:
4659 if abs in pmf:
4591 if mfentry:
4660 if mfentry:
4592 # if version of file is same in parent and target
4661 # if version of file is same in parent and target
4593 # manifests, do nothing
4662 # manifests, do nothing
4594 if (pmf[abs] != mfentry or
4663 if (pmf[abs] != mfentry or
4595 pmf.flags(abs) != mf.flags(abs)):
4664 pmf.flags(abs) != mf.flags(abs)):
4596 handle(revert, False)
4665 handle(revert, False)
4597 else:
4666 else:
4598 handle(remove, False)
4667 handle(remove, False)
4599
4668
4600 if not opts.get('dry_run'):
4669 if not opts.get('dry_run'):
4601 def checkout(f):
4670 def checkout(f):
4602 fc = ctx[f]
4671 fc = ctx[f]
4603 repo.wwrite(f, fc.data(), fc.flags())
4672 repo.wwrite(f, fc.data(), fc.flags())
4604
4673
4605 audit_path = scmutil.pathauditor(repo.root)
4674 audit_path = scmutil.pathauditor(repo.root)
4606 for f in remove[0]:
4675 for f in remove[0]:
4607 if repo.dirstate[f] == 'a':
4676 if repo.dirstate[f] == 'a':
4608 repo.dirstate.drop(f)
4677 repo.dirstate.drop(f)
4609 continue
4678 continue
4610 audit_path(f)
4679 audit_path(f)
4611 try:
4680 try:
4612 util.unlinkpath(repo.wjoin(f))
4681 util.unlinkpath(repo.wjoin(f))
4613 except OSError:
4682 except OSError:
4614 pass
4683 pass
4615 repo.dirstate.remove(f)
4684 repo.dirstate.remove(f)
4616
4685
4617 normal = None
4686 normal = None
4618 if node == parent:
4687 if node == parent:
4619 # We're reverting to our parent. If possible, we'd like status
4688 # We're reverting to our parent. If possible, we'd like status
4620 # to report the file as clean. We have to use normallookup for
4689 # to report the file as clean. We have to use normallookup for
4621 # merges to avoid losing information about merged/dirty files.
4690 # merges to avoid losing information about merged/dirty files.
4622 if p2 != nullid:
4691 if p2 != nullid:
4623 normal = repo.dirstate.normallookup
4692 normal = repo.dirstate.normallookup
4624 else:
4693 else:
4625 normal = repo.dirstate.normal
4694 normal = repo.dirstate.normal
4626 for f in revert[0]:
4695 for f in revert[0]:
4627 checkout(f)
4696 checkout(f)
4628 if normal:
4697 if normal:
4629 normal(f)
4698 normal(f)
4630
4699
4631 for f in add[0]:
4700 for f in add[0]:
4632 checkout(f)
4701 checkout(f)
4633 repo.dirstate.add(f)
4702 repo.dirstate.add(f)
4634
4703
4635 normal = repo.dirstate.normallookup
4704 normal = repo.dirstate.normallookup
4636 if node == parent and p2 == nullid:
4705 if node == parent and p2 == nullid:
4637 normal = repo.dirstate.normal
4706 normal = repo.dirstate.normal
4638 for f in undelete[0]:
4707 for f in undelete[0]:
4639 checkout(f)
4708 checkout(f)
4640 normal(f)
4709 normal(f)
4641
4710
4642 finally:
4711 finally:
4643 wlock.release()
4712 wlock.release()
4644
4713
4645 @command('rollback', dryrunopts +
4714 @command('rollback', dryrunopts +
4646 [('f', 'force', False, _('ignore safety measures'))])
4715 [('f', 'force', False, _('ignore safety measures'))])
4647 def rollback(ui, repo, **opts):
4716 def rollback(ui, repo, **opts):
4648 """roll back the last transaction (dangerous)
4717 """roll back the last transaction (dangerous)
4649
4718
4650 This command should be used with care. There is only one level of
4719 This command should be used with care. There is only one level of
4651 rollback, and there is no way to undo a rollback. It will also
4720 rollback, and there is no way to undo a rollback. It will also
4652 restore the dirstate at the time of the last transaction, losing
4721 restore the dirstate at the time of the last transaction, losing
4653 any dirstate changes since that time. This command does not alter
4722 any dirstate changes since that time. This command does not alter
4654 the working directory.
4723 the working directory.
4655
4724
4656 Transactions are used to encapsulate the effects of all commands
4725 Transactions are used to encapsulate the effects of all commands
4657 that create new changesets or propagate existing changesets into a
4726 that create new changesets or propagate existing changesets into a
4658 repository. For example, the following commands are transactional,
4727 repository. For example, the following commands are transactional,
4659 and their effects can be rolled back:
4728 and their effects can be rolled back:
4660
4729
4661 - commit
4730 - commit
4662 - import
4731 - import
4663 - pull
4732 - pull
4664 - push (with this repository as the destination)
4733 - push (with this repository as the destination)
4665 - unbundle
4734 - unbundle
4666
4735
4667 It's possible to lose data with rollback: commit, update back to
4736 It's possible to lose data with rollback: commit, update back to
4668 an older changeset, and then rollback. The update removes the
4737 an older changeset, and then rollback. The update removes the
4669 changes you committed from the working directory, and rollback
4738 changes you committed from the working directory, and rollback
4670 removes them from history. To avoid data loss, you must pass
4739 removes them from history. To avoid data loss, you must pass
4671 --force in this case.
4740 --force in this case.
4672
4741
4673 This command is not intended for use on public repositories. Once
4742 This command is not intended for use on public repositories. Once
4674 changes are visible for pull by other users, rolling a transaction
4743 changes are visible for pull by other users, rolling a transaction
4675 back locally is ineffective (someone else may already have pulled
4744 back locally is ineffective (someone else may already have pulled
4676 the changes). Furthermore, a race is possible with readers of the
4745 the changes). Furthermore, a race is possible with readers of the
4677 repository; for example an in-progress pull from the repository
4746 repository; for example an in-progress pull from the repository
4678 may fail if a rollback is performed.
4747 may fail if a rollback is performed.
4679
4748
4680 Returns 0 on success, 1 if no rollback data is available.
4749 Returns 0 on success, 1 if no rollback data is available.
4681 """
4750 """
4682 return repo.rollback(dryrun=opts.get('dry_run'),
4751 return repo.rollback(dryrun=opts.get('dry_run'),
4683 force=opts.get('force'))
4752 force=opts.get('force'))
4684
4753
4685 @command('root', [])
4754 @command('root', [])
4686 def root(ui, repo):
4755 def root(ui, repo):
4687 """print the root (top) of the current working directory
4756 """print the root (top) of the current working directory
4688
4757
4689 Print the root directory of the current repository.
4758 Print the root directory of the current repository.
4690
4759
4691 Returns 0 on success.
4760 Returns 0 on success.
4692 """
4761 """
4693 ui.write(repo.root + "\n")
4762 ui.write(repo.root + "\n")
4694
4763
4695 @command('^serve',
4764 @command('^serve',
4696 [('A', 'accesslog', '', _('name of access log file to write to'),
4765 [('A', 'accesslog', '', _('name of access log file to write to'),
4697 _('FILE')),
4766 _('FILE')),
4698 ('d', 'daemon', None, _('run server in background')),
4767 ('d', 'daemon', None, _('run server in background')),
4699 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4768 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4700 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4769 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4701 # use string type, then we can check if something was passed
4770 # use string type, then we can check if something was passed
4702 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4771 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4703 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4772 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4704 _('ADDR')),
4773 _('ADDR')),
4705 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4774 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4706 _('PREFIX')),
4775 _('PREFIX')),
4707 ('n', 'name', '',
4776 ('n', 'name', '',
4708 _('name to show in web pages (default: working directory)'), _('NAME')),
4777 _('name to show in web pages (default: working directory)'), _('NAME')),
4709 ('', 'web-conf', '',
4778 ('', 'web-conf', '',
4710 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4779 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4711 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4780 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4712 _('FILE')),
4781 _('FILE')),
4713 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4782 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4714 ('', 'stdio', None, _('for remote clients')),
4783 ('', 'stdio', None, _('for remote clients')),
4715 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4784 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4716 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4785 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4717 ('', 'style', '', _('template style to use'), _('STYLE')),
4786 ('', 'style', '', _('template style to use'), _('STYLE')),
4718 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4787 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4719 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4788 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4720 _('[OPTION]...'))
4789 _('[OPTION]...'))
4721 def serve(ui, repo, **opts):
4790 def serve(ui, repo, **opts):
4722 """start stand-alone webserver
4791 """start stand-alone webserver
4723
4792
4724 Start a local HTTP repository browser and pull server. You can use
4793 Start a local HTTP repository browser and pull server. You can use
4725 this for ad-hoc sharing and browsing of repositories. It is
4794 this for ad-hoc sharing and browsing of repositories. It is
4726 recommended to use a real web server to serve a repository for
4795 recommended to use a real web server to serve a repository for
4727 longer periods of time.
4796 longer periods of time.
4728
4797
4729 Please note that the server does not implement access control.
4798 Please note that the server does not implement access control.
4730 This means that, by default, anybody can read from the server and
4799 This means that, by default, anybody can read from the server and
4731 nobody can write to it by default. Set the ``web.allow_push``
4800 nobody can write to it by default. Set the ``web.allow_push``
4732 option to ``*`` to allow everybody to push to the server. You
4801 option to ``*`` to allow everybody to push to the server. You
4733 should use a real web server if you need to authenticate users.
4802 should use a real web server if you need to authenticate users.
4734
4803
4735 By default, the server logs accesses to stdout and errors to
4804 By default, the server logs accesses to stdout and errors to
4736 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4805 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4737 files.
4806 files.
4738
4807
4739 To have the server choose a free port number to listen on, specify
4808 To have the server choose a free port number to listen on, specify
4740 a port number of 0; in this case, the server will print the port
4809 a port number of 0; in this case, the server will print the port
4741 number it uses.
4810 number it uses.
4742
4811
4743 Returns 0 on success.
4812 Returns 0 on success.
4744 """
4813 """
4745
4814
4746 if opts["stdio"] and opts["cmdserver"]:
4815 if opts["stdio"] and opts["cmdserver"]:
4747 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4816 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4748
4817
4749 def checkrepo():
4818 def checkrepo():
4750 if repo is None:
4819 if repo is None:
4751 raise error.RepoError(_("There is no Mercurial repository here"
4820 raise error.RepoError(_("There is no Mercurial repository here"
4752 " (.hg not found)"))
4821 " (.hg not found)"))
4753
4822
4754 if opts["stdio"]:
4823 if opts["stdio"]:
4755 checkrepo()
4824 checkrepo()
4756 s = sshserver.sshserver(ui, repo)
4825 s = sshserver.sshserver(ui, repo)
4757 s.serve_forever()
4826 s.serve_forever()
4758
4827
4759 if opts["cmdserver"]:
4828 if opts["cmdserver"]:
4760 checkrepo()
4829 checkrepo()
4761 s = commandserver.server(ui, repo, opts["cmdserver"])
4830 s = commandserver.server(ui, repo, opts["cmdserver"])
4762 return s.serve()
4831 return s.serve()
4763
4832
4764 # this way we can check if something was given in the command-line
4833 # this way we can check if something was given in the command-line
4765 if opts.get('port'):
4834 if opts.get('port'):
4766 opts['port'] = util.getport(opts.get('port'))
4835 opts['port'] = util.getport(opts.get('port'))
4767
4836
4768 baseui = repo and repo.baseui or ui
4837 baseui = repo and repo.baseui or ui
4769 optlist = ("name templates style address port prefix ipv6"
4838 optlist = ("name templates style address port prefix ipv6"
4770 " accesslog errorlog certificate encoding")
4839 " accesslog errorlog certificate encoding")
4771 for o in optlist.split():
4840 for o in optlist.split():
4772 val = opts.get(o, '')
4841 val = opts.get(o, '')
4773 if val in (None, ''): # should check against default options instead
4842 if val in (None, ''): # should check against default options instead
4774 continue
4843 continue
4775 baseui.setconfig("web", o, val)
4844 baseui.setconfig("web", o, val)
4776 if repo and repo.ui != baseui:
4845 if repo and repo.ui != baseui:
4777 repo.ui.setconfig("web", o, val)
4846 repo.ui.setconfig("web", o, val)
4778
4847
4779 o = opts.get('web_conf') or opts.get('webdir_conf')
4848 o = opts.get('web_conf') or opts.get('webdir_conf')
4780 if not o:
4849 if not o:
4781 if not repo:
4850 if not repo:
4782 raise error.RepoError(_("There is no Mercurial repository"
4851 raise error.RepoError(_("There is no Mercurial repository"
4783 " here (.hg not found)"))
4852 " here (.hg not found)"))
4784 o = repo.root
4853 o = repo.root
4785
4854
4786 app = hgweb.hgweb(o, baseui=ui)
4855 app = hgweb.hgweb(o, baseui=ui)
4787
4856
4788 class service(object):
4857 class service(object):
4789 def init(self):
4858 def init(self):
4790 util.setsignalhandler()
4859 util.setsignalhandler()
4791 self.httpd = hgweb.server.create_server(ui, app)
4860 self.httpd = hgweb.server.create_server(ui, app)
4792
4861
4793 if opts['port'] and not ui.verbose:
4862 if opts['port'] and not ui.verbose:
4794 return
4863 return
4795
4864
4796 if self.httpd.prefix:
4865 if self.httpd.prefix:
4797 prefix = self.httpd.prefix.strip('/') + '/'
4866 prefix = self.httpd.prefix.strip('/') + '/'
4798 else:
4867 else:
4799 prefix = ''
4868 prefix = ''
4800
4869
4801 port = ':%d' % self.httpd.port
4870 port = ':%d' % self.httpd.port
4802 if port == ':80':
4871 if port == ':80':
4803 port = ''
4872 port = ''
4804
4873
4805 bindaddr = self.httpd.addr
4874 bindaddr = self.httpd.addr
4806 if bindaddr == '0.0.0.0':
4875 if bindaddr == '0.0.0.0':
4807 bindaddr = '*'
4876 bindaddr = '*'
4808 elif ':' in bindaddr: # IPv6
4877 elif ':' in bindaddr: # IPv6
4809 bindaddr = '[%s]' % bindaddr
4878 bindaddr = '[%s]' % bindaddr
4810
4879
4811 fqaddr = self.httpd.fqaddr
4880 fqaddr = self.httpd.fqaddr
4812 if ':' in fqaddr:
4881 if ':' in fqaddr:
4813 fqaddr = '[%s]' % fqaddr
4882 fqaddr = '[%s]' % fqaddr
4814 if opts['port']:
4883 if opts['port']:
4815 write = ui.status
4884 write = ui.status
4816 else:
4885 else:
4817 write = ui.write
4886 write = ui.write
4818 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4887 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4819 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4888 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4820
4889
4821 def run(self):
4890 def run(self):
4822 self.httpd.serve_forever()
4891 self.httpd.serve_forever()
4823
4892
4824 service = service()
4893 service = service()
4825
4894
4826 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4895 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4827
4896
4828 @command('showconfig|debugconfig',
4897 @command('showconfig|debugconfig',
4829 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4898 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4830 _('[-u] [NAME]...'))
4899 _('[-u] [NAME]...'))
4831 def showconfig(ui, repo, *values, **opts):
4900 def showconfig(ui, repo, *values, **opts):
4832 """show combined config settings from all hgrc files
4901 """show combined config settings from all hgrc files
4833
4902
4834 With no arguments, print names and values of all config items.
4903 With no arguments, print names and values of all config items.
4835
4904
4836 With one argument of the form section.name, print just the value
4905 With one argument of the form section.name, print just the value
4837 of that config item.
4906 of that config item.
4838
4907
4839 With multiple arguments, print names and values of all config
4908 With multiple arguments, print names and values of all config
4840 items with matching section names.
4909 items with matching section names.
4841
4910
4842 With --debug, the source (filename and line number) is printed
4911 With --debug, the source (filename and line number) is printed
4843 for each config item.
4912 for each config item.
4844
4913
4845 Returns 0 on success.
4914 Returns 0 on success.
4846 """
4915 """
4847
4916
4848 for f in scmutil.rcpath():
4917 for f in scmutil.rcpath():
4849 ui.debug('read config from: %s\n' % f)
4918 ui.debug('read config from: %s\n' % f)
4850 untrusted = bool(opts.get('untrusted'))
4919 untrusted = bool(opts.get('untrusted'))
4851 if values:
4920 if values:
4852 sections = [v for v in values if '.' not in v]
4921 sections = [v for v in values if '.' not in v]
4853 items = [v for v in values if '.' in v]
4922 items = [v for v in values if '.' in v]
4854 if len(items) > 1 or items and sections:
4923 if len(items) > 1 or items and sections:
4855 raise util.Abort(_('only one config item permitted'))
4924 raise util.Abort(_('only one config item permitted'))
4856 for section, name, value in ui.walkconfig(untrusted=untrusted):
4925 for section, name, value in ui.walkconfig(untrusted=untrusted):
4857 value = str(value).replace('\n', '\\n')
4926 value = str(value).replace('\n', '\\n')
4858 sectname = section + '.' + name
4927 sectname = section + '.' + name
4859 if values:
4928 if values:
4860 for v in values:
4929 for v in values:
4861 if v == section:
4930 if v == section:
4862 ui.debug('%s: ' %
4931 ui.debug('%s: ' %
4863 ui.configsource(section, name, untrusted))
4932 ui.configsource(section, name, untrusted))
4864 ui.write('%s=%s\n' % (sectname, value))
4933 ui.write('%s=%s\n' % (sectname, value))
4865 elif v == sectname:
4934 elif v == sectname:
4866 ui.debug('%s: ' %
4935 ui.debug('%s: ' %
4867 ui.configsource(section, name, untrusted))
4936 ui.configsource(section, name, untrusted))
4868 ui.write(value, '\n')
4937 ui.write(value, '\n')
4869 else:
4938 else:
4870 ui.debug('%s: ' %
4939 ui.debug('%s: ' %
4871 ui.configsource(section, name, untrusted))
4940 ui.configsource(section, name, untrusted))
4872 ui.write('%s=%s\n' % (sectname, value))
4941 ui.write('%s=%s\n' % (sectname, value))
4873
4942
4874 @command('^status|st',
4943 @command('^status|st',
4875 [('A', 'all', None, _('show status of all files')),
4944 [('A', 'all', None, _('show status of all files')),
4876 ('m', 'modified', None, _('show only modified files')),
4945 ('m', 'modified', None, _('show only modified files')),
4877 ('a', 'added', None, _('show only added files')),
4946 ('a', 'added', None, _('show only added files')),
4878 ('r', 'removed', None, _('show only removed files')),
4947 ('r', 'removed', None, _('show only removed files')),
4879 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4948 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4880 ('c', 'clean', None, _('show only files without changes')),
4949 ('c', 'clean', None, _('show only files without changes')),
4881 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4950 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4882 ('i', 'ignored', None, _('show only ignored files')),
4951 ('i', 'ignored', None, _('show only ignored files')),
4883 ('n', 'no-status', None, _('hide status prefix')),
4952 ('n', 'no-status', None, _('hide status prefix')),
4884 ('C', 'copies', None, _('show source of copied files')),
4953 ('C', 'copies', None, _('show source of copied files')),
4885 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4954 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4886 ('', 'rev', [], _('show difference from revision'), _('REV')),
4955 ('', 'rev', [], _('show difference from revision'), _('REV')),
4887 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4956 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4888 ] + walkopts + subrepoopts,
4957 ] + walkopts + subrepoopts,
4889 _('[OPTION]... [FILE]...'))
4958 _('[OPTION]... [FILE]...'))
4890 def status(ui, repo, *pats, **opts):
4959 def status(ui, repo, *pats, **opts):
4891 """show changed files in the working directory
4960 """show changed files in the working directory
4892
4961
4893 Show status of files in the repository. If names are given, only
4962 Show status of files in the repository. If names are given, only
4894 files that match are shown. Files that are clean or ignored or
4963 files that match are shown. Files that are clean or ignored or
4895 the source of a copy/move operation, are not listed unless
4964 the source of a copy/move operation, are not listed unless
4896 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4965 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4897 Unless options described with "show only ..." are given, the
4966 Unless options described with "show only ..." are given, the
4898 options -mardu are used.
4967 options -mardu are used.
4899
4968
4900 Option -q/--quiet hides untracked (unknown and ignored) files
4969 Option -q/--quiet hides untracked (unknown and ignored) files
4901 unless explicitly requested with -u/--unknown or -i/--ignored.
4970 unless explicitly requested with -u/--unknown or -i/--ignored.
4902
4971
4903 .. note::
4972 .. note::
4904 status may appear to disagree with diff if permissions have
4973 status may appear to disagree with diff if permissions have
4905 changed or a merge has occurred. The standard diff format does
4974 changed or a merge has occurred. The standard diff format does
4906 not report permission changes and diff only reports changes
4975 not report permission changes and diff only reports changes
4907 relative to one merge parent.
4976 relative to one merge parent.
4908
4977
4909 If one revision is given, it is used as the base revision.
4978 If one revision is given, it is used as the base revision.
4910 If two revisions are given, the differences between them are
4979 If two revisions are given, the differences between them are
4911 shown. The --change option can also be used as a shortcut to list
4980 shown. The --change option can also be used as a shortcut to list
4912 the changed files of a revision from its first parent.
4981 the changed files of a revision from its first parent.
4913
4982
4914 The codes used to show the status of files are::
4983 The codes used to show the status of files are::
4915
4984
4916 M = modified
4985 M = modified
4917 A = added
4986 A = added
4918 R = removed
4987 R = removed
4919 C = clean
4988 C = clean
4920 ! = missing (deleted by non-hg command, but still tracked)
4989 ! = missing (deleted by non-hg command, but still tracked)
4921 ? = not tracked
4990 ? = not tracked
4922 I = ignored
4991 I = ignored
4923 = origin of the previous file listed as A (added)
4992 = origin of the previous file listed as A (added)
4924
4993
4925 .. container:: verbose
4994 .. container:: verbose
4926
4995
4927 Examples:
4996 Examples:
4928
4997
4929 - show changes in the working directory relative to a changeset:
4998 - show changes in the working directory relative to a changeset:
4930
4999
4931 hg status --rev 9353
5000 hg status --rev 9353
4932
5001
4933 - show all changes including copies in an existing changeset::
5002 - show all changes including copies in an existing changeset::
4934
5003
4935 hg status --copies --change 9353
5004 hg status --copies --change 9353
4936
5005
4937 - get a NUL separated list of added files, suitable for xargs::
5006 - get a NUL separated list of added files, suitable for xargs::
4938
5007
4939 hg status -an0
5008 hg status -an0
4940
5009
4941 Returns 0 on success.
5010 Returns 0 on success.
4942 """
5011 """
4943
5012
4944 revs = opts.get('rev')
5013 revs = opts.get('rev')
4945 change = opts.get('change')
5014 change = opts.get('change')
4946
5015
4947 if revs and change:
5016 if revs and change:
4948 msg = _('cannot specify --rev and --change at the same time')
5017 msg = _('cannot specify --rev and --change at the same time')
4949 raise util.Abort(msg)
5018 raise util.Abort(msg)
4950 elif change:
5019 elif change:
4951 node2 = repo.lookup(change)
5020 node2 = repo.lookup(change)
4952 node1 = repo[node2].p1().node()
5021 node1 = repo[node2].p1().node()
4953 else:
5022 else:
4954 node1, node2 = scmutil.revpair(repo, revs)
5023 node1, node2 = scmutil.revpair(repo, revs)
4955
5024
4956 cwd = (pats and repo.getcwd()) or ''
5025 cwd = (pats and repo.getcwd()) or ''
4957 end = opts.get('print0') and '\0' or '\n'
5026 end = opts.get('print0') and '\0' or '\n'
4958 copy = {}
5027 copy = {}
4959 states = 'modified added removed deleted unknown ignored clean'.split()
5028 states = 'modified added removed deleted unknown ignored clean'.split()
4960 show = [k for k in states if opts.get(k)]
5029 show = [k for k in states if opts.get(k)]
4961 if opts.get('all'):
5030 if opts.get('all'):
4962 show += ui.quiet and (states[:4] + ['clean']) or states
5031 show += ui.quiet and (states[:4] + ['clean']) or states
4963 if not show:
5032 if not show:
4964 show = ui.quiet and states[:4] or states[:5]
5033 show = ui.quiet and states[:4] or states[:5]
4965
5034
4966 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5035 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
4967 'ignored' in show, 'clean' in show, 'unknown' in show,
5036 'ignored' in show, 'clean' in show, 'unknown' in show,
4968 opts.get('subrepos'))
5037 opts.get('subrepos'))
4969 changestates = zip(states, 'MAR!?IC', stat)
5038 changestates = zip(states, 'MAR!?IC', stat)
4970
5039
4971 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5040 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4972 ctxn = repo[nullid]
5041 ctxn = repo[nullid]
4973 ctx1 = repo[node1]
5042 ctx1 = repo[node1]
4974 ctx2 = repo[node2]
5043 ctx2 = repo[node2]
4975 added = stat[1]
5044 added = stat[1]
4976 if node2 is None:
5045 if node2 is None:
4977 added = stat[0] + stat[1] # merged?
5046 added = stat[0] + stat[1] # merged?
4978
5047
4979 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
5048 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4980 if k in added:
5049 if k in added:
4981 copy[k] = v
5050 copy[k] = v
4982 elif v in added:
5051 elif v in added:
4983 copy[v] = k
5052 copy[v] = k
4984
5053
4985 for state, char, files in changestates:
5054 for state, char, files in changestates:
4986 if state in show:
5055 if state in show:
4987 format = "%s %%s%s" % (char, end)
5056 format = "%s %%s%s" % (char, end)
4988 if opts.get('no_status'):
5057 if opts.get('no_status'):
4989 format = "%%s%s" % end
5058 format = "%%s%s" % end
4990
5059
4991 for f in files:
5060 for f in files:
4992 ui.write(format % repo.pathto(f, cwd),
5061 ui.write(format % repo.pathto(f, cwd),
4993 label='status.' + state)
5062 label='status.' + state)
4994 if f in copy:
5063 if f in copy:
4995 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
5064 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4996 label='status.copied')
5065 label='status.copied')
4997
5066
4998 @command('^summary|sum',
5067 @command('^summary|sum',
4999 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5068 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5000 def summary(ui, repo, **opts):
5069 def summary(ui, repo, **opts):
5001 """summarize working directory state
5070 """summarize working directory state
5002
5071
5003 This generates a brief summary of the working directory state,
5072 This generates a brief summary of the working directory state,
5004 including parents, branch, commit status, and available updates.
5073 including parents, branch, commit status, and available updates.
5005
5074
5006 With the --remote option, this will check the default paths for
5075 With the --remote option, this will check the default paths for
5007 incoming and outgoing changes. This can be time-consuming.
5076 incoming and outgoing changes. This can be time-consuming.
5008
5077
5009 Returns 0 on success.
5078 Returns 0 on success.
5010 """
5079 """
5011
5080
5012 ctx = repo[None]
5081 ctx = repo[None]
5013 parents = ctx.parents()
5082 parents = ctx.parents()
5014 pnode = parents[0].node()
5083 pnode = parents[0].node()
5015 marks = []
5084 marks = []
5016
5085
5017 for p in parents:
5086 for p in parents:
5018 # label with log.changeset (instead of log.parent) since this
5087 # label with log.changeset (instead of log.parent) since this
5019 # shows a working directory parent *changeset*:
5088 # shows a working directory parent *changeset*:
5020 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5089 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5021 label='log.changeset')
5090 label='log.changeset')
5022 ui.write(' '.join(p.tags()), label='log.tag')
5091 ui.write(' '.join(p.tags()), label='log.tag')
5023 if p.bookmarks():
5092 if p.bookmarks():
5024 marks.extend(p.bookmarks())
5093 marks.extend(p.bookmarks())
5025 if p.rev() == -1:
5094 if p.rev() == -1:
5026 if not len(repo):
5095 if not len(repo):
5027 ui.write(_(' (empty repository)'))
5096 ui.write(_(' (empty repository)'))
5028 else:
5097 else:
5029 ui.write(_(' (no revision checked out)'))
5098 ui.write(_(' (no revision checked out)'))
5030 ui.write('\n')
5099 ui.write('\n')
5031 if p.description():
5100 if p.description():
5032 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5101 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5033 label='log.summary')
5102 label='log.summary')
5034
5103
5035 branch = ctx.branch()
5104 branch = ctx.branch()
5036 bheads = repo.branchheads(branch)
5105 bheads = repo.branchheads(branch)
5037 m = _('branch: %s\n') % branch
5106 m = _('branch: %s\n') % branch
5038 if branch != 'default':
5107 if branch != 'default':
5039 ui.write(m, label='log.branch')
5108 ui.write(m, label='log.branch')
5040 else:
5109 else:
5041 ui.status(m, label='log.branch')
5110 ui.status(m, label='log.branch')
5042
5111
5043 if marks:
5112 if marks:
5044 current = repo._bookmarkcurrent
5113 current = repo._bookmarkcurrent
5045 ui.write(_('bookmarks:'), label='log.bookmark')
5114 ui.write(_('bookmarks:'), label='log.bookmark')
5046 if current is not None:
5115 if current is not None:
5047 try:
5116 try:
5048 marks.remove(current)
5117 marks.remove(current)
5049 ui.write(' *' + current, label='bookmarks.current')
5118 ui.write(' *' + current, label='bookmarks.current')
5050 except ValueError:
5119 except ValueError:
5051 # current bookmark not in parent ctx marks
5120 # current bookmark not in parent ctx marks
5052 pass
5121 pass
5053 for m in marks:
5122 for m in marks:
5054 ui.write(' ' + m, label='log.bookmark')
5123 ui.write(' ' + m, label='log.bookmark')
5055 ui.write('\n', label='log.bookmark')
5124 ui.write('\n', label='log.bookmark')
5056
5125
5057 st = list(repo.status(unknown=True))[:6]
5126 st = list(repo.status(unknown=True))[:6]
5058
5127
5059 c = repo.dirstate.copies()
5128 c = repo.dirstate.copies()
5060 copied, renamed = [], []
5129 copied, renamed = [], []
5061 for d, s in c.iteritems():
5130 for d, s in c.iteritems():
5062 if s in st[2]:
5131 if s in st[2]:
5063 st[2].remove(s)
5132 st[2].remove(s)
5064 renamed.append(d)
5133 renamed.append(d)
5065 else:
5134 else:
5066 copied.append(d)
5135 copied.append(d)
5067 if d in st[1]:
5136 if d in st[1]:
5068 st[1].remove(d)
5137 st[1].remove(d)
5069 st.insert(3, renamed)
5138 st.insert(3, renamed)
5070 st.insert(4, copied)
5139 st.insert(4, copied)
5071
5140
5072 ms = mergemod.mergestate(repo)
5141 ms = mergemod.mergestate(repo)
5073 st.append([f for f in ms if ms[f] == 'u'])
5142 st.append([f for f in ms if ms[f] == 'u'])
5074
5143
5075 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5144 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5076 st.append(subs)
5145 st.append(subs)
5077
5146
5078 labels = [ui.label(_('%d modified'), 'status.modified'),
5147 labels = [ui.label(_('%d modified'), 'status.modified'),
5079 ui.label(_('%d added'), 'status.added'),
5148 ui.label(_('%d added'), 'status.added'),
5080 ui.label(_('%d removed'), 'status.removed'),
5149 ui.label(_('%d removed'), 'status.removed'),
5081 ui.label(_('%d renamed'), 'status.copied'),
5150 ui.label(_('%d renamed'), 'status.copied'),
5082 ui.label(_('%d copied'), 'status.copied'),
5151 ui.label(_('%d copied'), 'status.copied'),
5083 ui.label(_('%d deleted'), 'status.deleted'),
5152 ui.label(_('%d deleted'), 'status.deleted'),
5084 ui.label(_('%d unknown'), 'status.unknown'),
5153 ui.label(_('%d unknown'), 'status.unknown'),
5085 ui.label(_('%d ignored'), 'status.ignored'),
5154 ui.label(_('%d ignored'), 'status.ignored'),
5086 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5155 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5087 ui.label(_('%d subrepos'), 'status.modified')]
5156 ui.label(_('%d subrepos'), 'status.modified')]
5088 t = []
5157 t = []
5089 for s, l in zip(st, labels):
5158 for s, l in zip(st, labels):
5090 if s:
5159 if s:
5091 t.append(l % len(s))
5160 t.append(l % len(s))
5092
5161
5093 t = ', '.join(t)
5162 t = ', '.join(t)
5094 cleanworkdir = False
5163 cleanworkdir = False
5095
5164
5096 if len(parents) > 1:
5165 if len(parents) > 1:
5097 t += _(' (merge)')
5166 t += _(' (merge)')
5098 elif branch != parents[0].branch():
5167 elif branch != parents[0].branch():
5099 t += _(' (new branch)')
5168 t += _(' (new branch)')
5100 elif (parents[0].extra().get('close') and
5169 elif (parents[0].extra().get('close') and
5101 pnode in repo.branchheads(branch, closed=True)):
5170 pnode in repo.branchheads(branch, closed=True)):
5102 t += _(' (head closed)')
5171 t += _(' (head closed)')
5103 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5172 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5104 t += _(' (clean)')
5173 t += _(' (clean)')
5105 cleanworkdir = True
5174 cleanworkdir = True
5106 elif pnode not in bheads:
5175 elif pnode not in bheads:
5107 t += _(' (new branch head)')
5176 t += _(' (new branch head)')
5108
5177
5109 if cleanworkdir:
5178 if cleanworkdir:
5110 ui.status(_('commit: %s\n') % t.strip())
5179 ui.status(_('commit: %s\n') % t.strip())
5111 else:
5180 else:
5112 ui.write(_('commit: %s\n') % t.strip())
5181 ui.write(_('commit: %s\n') % t.strip())
5113
5182
5114 # all ancestors of branch heads - all ancestors of parent = new csets
5183 # all ancestors of branch heads - all ancestors of parent = new csets
5115 new = [0] * len(repo)
5184 new = [0] * len(repo)
5116 cl = repo.changelog
5185 cl = repo.changelog
5117 for a in [cl.rev(n) for n in bheads]:
5186 for a in [cl.rev(n) for n in bheads]:
5118 new[a] = 1
5187 new[a] = 1
5119 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5188 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5120 new[a] = 1
5189 new[a] = 1
5121 for a in [p.rev() for p in parents]:
5190 for a in [p.rev() for p in parents]:
5122 if a >= 0:
5191 if a >= 0:
5123 new[a] = 0
5192 new[a] = 0
5124 for a in cl.ancestors(*[p.rev() for p in parents]):
5193 for a in cl.ancestors(*[p.rev() for p in parents]):
5125 new[a] = 0
5194 new[a] = 0
5126 new = sum(new)
5195 new = sum(new)
5127
5196
5128 if new == 0:
5197 if new == 0:
5129 ui.status(_('update: (current)\n'))
5198 ui.status(_('update: (current)\n'))
5130 elif pnode not in bheads:
5199 elif pnode not in bheads:
5131 ui.write(_('update: %d new changesets (update)\n') % new)
5200 ui.write(_('update: %d new changesets (update)\n') % new)
5132 else:
5201 else:
5133 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5202 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5134 (new, len(bheads)))
5203 (new, len(bheads)))
5135
5204
5136 if opts.get('remote'):
5205 if opts.get('remote'):
5137 t = []
5206 t = []
5138 source, branches = hg.parseurl(ui.expandpath('default'))
5207 source, branches = hg.parseurl(ui.expandpath('default'))
5139 other = hg.peer(repo, {}, source)
5208 other = hg.peer(repo, {}, source)
5140 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5209 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5141 ui.debug('comparing with %s\n' % util.hidepassword(source))
5210 ui.debug('comparing with %s\n' % util.hidepassword(source))
5142 repo.ui.pushbuffer()
5211 repo.ui.pushbuffer()
5143 commoninc = discovery.findcommonincoming(repo, other)
5212 commoninc = discovery.findcommonincoming(repo, other)
5144 _common, incoming, _rheads = commoninc
5213 _common, incoming, _rheads = commoninc
5145 repo.ui.popbuffer()
5214 repo.ui.popbuffer()
5146 if incoming:
5215 if incoming:
5147 t.append(_('1 or more incoming'))
5216 t.append(_('1 or more incoming'))
5148
5217
5149 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5218 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5150 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5219 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5151 if source != dest:
5220 if source != dest:
5152 other = hg.peer(repo, {}, dest)
5221 other = hg.peer(repo, {}, dest)
5153 commoninc = None
5222 commoninc = None
5154 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5223 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5155 repo.ui.pushbuffer()
5224 repo.ui.pushbuffer()
5156 common, outheads = discovery.findcommonoutgoing(repo, other,
5225 common, outheads = discovery.findcommonoutgoing(repo, other,
5157 commoninc=commoninc)
5226 commoninc=commoninc)
5158 repo.ui.popbuffer()
5227 repo.ui.popbuffer()
5159 o = repo.changelog.findmissing(common=common, heads=outheads)
5228 o = repo.changelog.findmissing(common=common, heads=outheads)
5160 if o:
5229 if o:
5161 t.append(_('%d outgoing') % len(o))
5230 t.append(_('%d outgoing') % len(o))
5162 if 'bookmarks' in other.listkeys('namespaces'):
5231 if 'bookmarks' in other.listkeys('namespaces'):
5163 lmarks = repo.listkeys('bookmarks')
5232 lmarks = repo.listkeys('bookmarks')
5164 rmarks = other.listkeys('bookmarks')
5233 rmarks = other.listkeys('bookmarks')
5165 diff = set(rmarks) - set(lmarks)
5234 diff = set(rmarks) - set(lmarks)
5166 if len(diff) > 0:
5235 if len(diff) > 0:
5167 t.append(_('%d incoming bookmarks') % len(diff))
5236 t.append(_('%d incoming bookmarks') % len(diff))
5168 diff = set(lmarks) - set(rmarks)
5237 diff = set(lmarks) - set(rmarks)
5169 if len(diff) > 0:
5238 if len(diff) > 0:
5170 t.append(_('%d outgoing bookmarks') % len(diff))
5239 t.append(_('%d outgoing bookmarks') % len(diff))
5171
5240
5172 if t:
5241 if t:
5173 ui.write(_('remote: %s\n') % (', '.join(t)))
5242 ui.write(_('remote: %s\n') % (', '.join(t)))
5174 else:
5243 else:
5175 ui.status(_('remote: (synced)\n'))
5244 ui.status(_('remote: (synced)\n'))
5176
5245
5177 @command('tag',
5246 @command('tag',
5178 [('f', 'force', None, _('force tag')),
5247 [('f', 'force', None, _('force tag')),
5179 ('l', 'local', None, _('make the tag local')),
5248 ('l', 'local', None, _('make the tag local')),
5180 ('r', 'rev', '', _('revision to tag'), _('REV')),
5249 ('r', 'rev', '', _('revision to tag'), _('REV')),
5181 ('', 'remove', None, _('remove a tag')),
5250 ('', 'remove', None, _('remove a tag')),
5182 # -l/--local is already there, commitopts cannot be used
5251 # -l/--local is already there, commitopts cannot be used
5183 ('e', 'edit', None, _('edit commit message')),
5252 ('e', 'edit', None, _('edit commit message')),
5184 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5253 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5185 ] + commitopts2,
5254 ] + commitopts2,
5186 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5255 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5187 def tag(ui, repo, name1, *names, **opts):
5256 def tag(ui, repo, name1, *names, **opts):
5188 """add one or more tags for the current or given revision
5257 """add one or more tags for the current or given revision
5189
5258
5190 Name a particular revision using <name>.
5259 Name a particular revision using <name>.
5191
5260
5192 Tags are used to name particular revisions of the repository and are
5261 Tags are used to name particular revisions of the repository and are
5193 very useful to compare different revisions, to go back to significant
5262 very useful to compare different revisions, to go back to significant
5194 earlier versions or to mark branch points as releases, etc. Changing
5263 earlier versions or to mark branch points as releases, etc. Changing
5195 an existing tag is normally disallowed; use -f/--force to override.
5264 an existing tag is normally disallowed; use -f/--force to override.
5196
5265
5197 If no revision is given, the parent of the working directory is
5266 If no revision is given, the parent of the working directory is
5198 used, or tip if no revision is checked out.
5267 used, or tip if no revision is checked out.
5199
5268
5200 To facilitate version control, distribution, and merging of tags,
5269 To facilitate version control, distribution, and merging of tags,
5201 they are stored as a file named ".hgtags" which is managed similarly
5270 they are stored as a file named ".hgtags" which is managed similarly
5202 to other project files and can be hand-edited if necessary. This
5271 to other project files and can be hand-edited if necessary. This
5203 also means that tagging creates a new commit. The file
5272 also means that tagging creates a new commit. The file
5204 ".hg/localtags" is used for local tags (not shared among
5273 ".hg/localtags" is used for local tags (not shared among
5205 repositories).
5274 repositories).
5206
5275
5207 Tag commits are usually made at the head of a branch. If the parent
5276 Tag commits are usually made at the head of a branch. If the parent
5208 of the working directory is not a branch head, :hg:`tag` aborts; use
5277 of the working directory is not a branch head, :hg:`tag` aborts; use
5209 -f/--force to force the tag commit to be based on a non-head
5278 -f/--force to force the tag commit to be based on a non-head
5210 changeset.
5279 changeset.
5211
5280
5212 See :hg:`help dates` for a list of formats valid for -d/--date.
5281 See :hg:`help dates` for a list of formats valid for -d/--date.
5213
5282
5214 Since tag names have priority over branch names during revision
5283 Since tag names have priority over branch names during revision
5215 lookup, using an existing branch name as a tag name is discouraged.
5284 lookup, using an existing branch name as a tag name is discouraged.
5216
5285
5217 Returns 0 on success.
5286 Returns 0 on success.
5218 """
5287 """
5219
5288
5220 rev_ = "."
5289 rev_ = "."
5221 names = [t.strip() for t in (name1,) + names]
5290 names = [t.strip() for t in (name1,) + names]
5222 if len(names) != len(set(names)):
5291 if len(names) != len(set(names)):
5223 raise util.Abort(_('tag names must be unique'))
5292 raise util.Abort(_('tag names must be unique'))
5224 for n in names:
5293 for n in names:
5225 if n in ['tip', '.', 'null']:
5294 if n in ['tip', '.', 'null']:
5226 raise util.Abort(_("the name '%s' is reserved") % n)
5295 raise util.Abort(_("the name '%s' is reserved") % n)
5227 if not n:
5296 if not n:
5228 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
5297 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
5229 if opts.get('rev') and opts.get('remove'):
5298 if opts.get('rev') and opts.get('remove'):
5230 raise util.Abort(_("--rev and --remove are incompatible"))
5299 raise util.Abort(_("--rev and --remove are incompatible"))
5231 if opts.get('rev'):
5300 if opts.get('rev'):
5232 rev_ = opts['rev']
5301 rev_ = opts['rev']
5233 message = opts.get('message')
5302 message = opts.get('message')
5234 if opts.get('remove'):
5303 if opts.get('remove'):
5235 expectedtype = opts.get('local') and 'local' or 'global'
5304 expectedtype = opts.get('local') and 'local' or 'global'
5236 for n in names:
5305 for n in names:
5237 if not repo.tagtype(n):
5306 if not repo.tagtype(n):
5238 raise util.Abort(_("tag '%s' does not exist") % n)
5307 raise util.Abort(_("tag '%s' does not exist") % n)
5239 if repo.tagtype(n) != expectedtype:
5308 if repo.tagtype(n) != expectedtype:
5240 if expectedtype == 'global':
5309 if expectedtype == 'global':
5241 raise util.Abort(_("tag '%s' is not a global tag") % n)
5310 raise util.Abort(_("tag '%s' is not a global tag") % n)
5242 else:
5311 else:
5243 raise util.Abort(_("tag '%s' is not a local tag") % n)
5312 raise util.Abort(_("tag '%s' is not a local tag") % n)
5244 rev_ = nullid
5313 rev_ = nullid
5245 if not message:
5314 if not message:
5246 # we don't translate commit messages
5315 # we don't translate commit messages
5247 message = 'Removed tag %s' % ', '.join(names)
5316 message = 'Removed tag %s' % ', '.join(names)
5248 elif not opts.get('force'):
5317 elif not opts.get('force'):
5249 for n in names:
5318 for n in names:
5250 if n in repo.tags():
5319 if n in repo.tags():
5251 raise util.Abort(_("tag '%s' already exists "
5320 raise util.Abort(_("tag '%s' already exists "
5252 "(use -f to force)") % n)
5321 "(use -f to force)") % n)
5253 if not opts.get('local'):
5322 if not opts.get('local'):
5254 p1, p2 = repo.dirstate.parents()
5323 p1, p2 = repo.dirstate.parents()
5255 if p2 != nullid:
5324 if p2 != nullid:
5256 raise util.Abort(_('uncommitted merge'))
5325 raise util.Abort(_('uncommitted merge'))
5257 bheads = repo.branchheads()
5326 bheads = repo.branchheads()
5258 if not opts.get('force') and bheads and p1 not in bheads:
5327 if not opts.get('force') and bheads and p1 not in bheads:
5259 raise util.Abort(_('not at a branch head (use -f to force)'))
5328 raise util.Abort(_('not at a branch head (use -f to force)'))
5260 r = scmutil.revsingle(repo, rev_).node()
5329 r = scmutil.revsingle(repo, rev_).node()
5261
5330
5262 if not message:
5331 if not message:
5263 # we don't translate commit messages
5332 # we don't translate commit messages
5264 message = ('Added tag %s for changeset %s' %
5333 message = ('Added tag %s for changeset %s' %
5265 (', '.join(names), short(r)))
5334 (', '.join(names), short(r)))
5266
5335
5267 date = opts.get('date')
5336 date = opts.get('date')
5268 if date:
5337 if date:
5269 date = util.parsedate(date)
5338 date = util.parsedate(date)
5270
5339
5271 if opts.get('edit'):
5340 if opts.get('edit'):
5272 message = ui.edit(message, ui.username())
5341 message = ui.edit(message, ui.username())
5273
5342
5274 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5343 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5275
5344
5276 @command('tags', [], '')
5345 @command('tags', [], '')
5277 def tags(ui, repo):
5346 def tags(ui, repo):
5278 """list repository tags
5347 """list repository tags
5279
5348
5280 This lists both regular and local tags. When the -v/--verbose
5349 This lists both regular and local tags. When the -v/--verbose
5281 switch is used, a third column "local" is printed for local tags.
5350 switch is used, a third column "local" is printed for local tags.
5282
5351
5283 Returns 0 on success.
5352 Returns 0 on success.
5284 """
5353 """
5285
5354
5286 hexfunc = ui.debugflag and hex or short
5355 hexfunc = ui.debugflag and hex or short
5287 tagtype = ""
5356 tagtype = ""
5288
5357
5289 for t, n in reversed(repo.tagslist()):
5358 for t, n in reversed(repo.tagslist()):
5290 if ui.quiet:
5359 if ui.quiet:
5291 ui.write("%s\n" % t, label='tags.normal')
5360 ui.write("%s\n" % t, label='tags.normal')
5292 continue
5361 continue
5293
5362
5294 hn = hexfunc(n)
5363 hn = hexfunc(n)
5295 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5364 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5296 rev = ui.label(r, 'log.changeset')
5365 rev = ui.label(r, 'log.changeset')
5297 spaces = " " * (30 - encoding.colwidth(t))
5366 spaces = " " * (30 - encoding.colwidth(t))
5298
5367
5299 tag = ui.label(t, 'tags.normal')
5368 tag = ui.label(t, 'tags.normal')
5300 if ui.verbose:
5369 if ui.verbose:
5301 if repo.tagtype(t) == 'local':
5370 if repo.tagtype(t) == 'local':
5302 tagtype = " local"
5371 tagtype = " local"
5303 tag = ui.label(t, 'tags.local')
5372 tag = ui.label(t, 'tags.local')
5304 else:
5373 else:
5305 tagtype = ""
5374 tagtype = ""
5306 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5375 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5307
5376
5308 @command('tip',
5377 @command('tip',
5309 [('p', 'patch', None, _('show patch')),
5378 [('p', 'patch', None, _('show patch')),
5310 ('g', 'git', None, _('use git extended diff format')),
5379 ('g', 'git', None, _('use git extended diff format')),
5311 ] + templateopts,
5380 ] + templateopts,
5312 _('[-p] [-g]'))
5381 _('[-p] [-g]'))
5313 def tip(ui, repo, **opts):
5382 def tip(ui, repo, **opts):
5314 """show the tip revision
5383 """show the tip revision
5315
5384
5316 The tip revision (usually just called the tip) is the changeset
5385 The tip revision (usually just called the tip) is the changeset
5317 most recently added to the repository (and therefore the most
5386 most recently added to the repository (and therefore the most
5318 recently changed head).
5387 recently changed head).
5319
5388
5320 If you have just made a commit, that commit will be the tip. If
5389 If you have just made a commit, that commit will be the tip. If
5321 you have just pulled changes from another repository, the tip of
5390 you have just pulled changes from another repository, the tip of
5322 that repository becomes the current tip. The "tip" tag is special
5391 that repository becomes the current tip. The "tip" tag is special
5323 and cannot be renamed or assigned to a different changeset.
5392 and cannot be renamed or assigned to a different changeset.
5324
5393
5325 Returns 0 on success.
5394 Returns 0 on success.
5326 """
5395 """
5327 displayer = cmdutil.show_changeset(ui, repo, opts)
5396 displayer = cmdutil.show_changeset(ui, repo, opts)
5328 displayer.show(repo[len(repo) - 1])
5397 displayer.show(repo[len(repo) - 1])
5329 displayer.close()
5398 displayer.close()
5330
5399
5331 @command('unbundle',
5400 @command('unbundle',
5332 [('u', 'update', None,
5401 [('u', 'update', None,
5333 _('update to new branch head if changesets were unbundled'))],
5402 _('update to new branch head if changesets were unbundled'))],
5334 _('[-u] FILE...'))
5403 _('[-u] FILE...'))
5335 def unbundle(ui, repo, fname1, *fnames, **opts):
5404 def unbundle(ui, repo, fname1, *fnames, **opts):
5336 """apply one or more changegroup files
5405 """apply one or more changegroup files
5337
5406
5338 Apply one or more compressed changegroup files generated by the
5407 Apply one or more compressed changegroup files generated by the
5339 bundle command.
5408 bundle command.
5340
5409
5341 Returns 0 on success, 1 if an update has unresolved files.
5410 Returns 0 on success, 1 if an update has unresolved files.
5342 """
5411 """
5343 fnames = (fname1,) + fnames
5412 fnames = (fname1,) + fnames
5344
5413
5345 lock = repo.lock()
5414 lock = repo.lock()
5346 wc = repo['.']
5415 wc = repo['.']
5347 try:
5416 try:
5348 for fname in fnames:
5417 for fname in fnames:
5349 f = url.open(ui, fname)
5418 f = url.open(ui, fname)
5350 gen = changegroup.readbundle(f, fname)
5419 gen = changegroup.readbundle(f, fname)
5351 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5420 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5352 lock=lock)
5421 lock=lock)
5353 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5422 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5354 finally:
5423 finally:
5355 lock.release()
5424 lock.release()
5356 return postincoming(ui, repo, modheads, opts.get('update'), None)
5425 return postincoming(ui, repo, modheads, opts.get('update'), None)
5357
5426
5358 @command('^update|up|checkout|co',
5427 @command('^update|up|checkout|co',
5359 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5428 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5360 ('c', 'check', None,
5429 ('c', 'check', None,
5361 _('update across branches if no uncommitted changes')),
5430 _('update across branches if no uncommitted changes')),
5362 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5431 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5363 ('r', 'rev', '', _('revision'), _('REV'))],
5432 ('r', 'rev', '', _('revision'), _('REV'))],
5364 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5433 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5365 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5434 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5366 """update working directory (or switch revisions)
5435 """update working directory (or switch revisions)
5367
5436
5368 Update the repository's working directory to the specified
5437 Update the repository's working directory to the specified
5369 changeset. If no changeset is specified, update to the tip of the
5438 changeset. If no changeset is specified, update to the tip of the
5370 current named branch.
5439 current named branch.
5371
5440
5372 If the changeset is not a descendant of the working directory's
5441 If the changeset is not a descendant of the working directory's
5373 parent, the update is aborted. With the -c/--check option, the
5442 parent, the update is aborted. With the -c/--check option, the
5374 working directory is checked for uncommitted changes; if none are
5443 working directory is checked for uncommitted changes; if none are
5375 found, the working directory is updated to the specified
5444 found, the working directory is updated to the specified
5376 changeset.
5445 changeset.
5377
5446
5378 Update sets the working directory's parent revison to the specified
5447 Update sets the working directory's parent revison to the specified
5379 changeset (see :hg:`help parents`).
5448 changeset (see :hg:`help parents`).
5380
5449
5381 The following rules apply when the working directory contains
5450 The following rules apply when the working directory contains
5382 uncommitted changes:
5451 uncommitted changes:
5383
5452
5384 1. If neither -c/--check nor -C/--clean is specified, and if
5453 1. If neither -c/--check nor -C/--clean is specified, and if
5385 the requested changeset is an ancestor or descendant of
5454 the requested changeset is an ancestor or descendant of
5386 the working directory's parent, the uncommitted changes
5455 the working directory's parent, the uncommitted changes
5387 are merged into the requested changeset and the merged
5456 are merged into the requested changeset and the merged
5388 result is left uncommitted. If the requested changeset is
5457 result is left uncommitted. If the requested changeset is
5389 not an ancestor or descendant (that is, it is on another
5458 not an ancestor or descendant (that is, it is on another
5390 branch), the update is aborted and the uncommitted changes
5459 branch), the update is aborted and the uncommitted changes
5391 are preserved.
5460 are preserved.
5392
5461
5393 2. With the -c/--check option, the update is aborted and the
5462 2. With the -c/--check option, the update is aborted and the
5394 uncommitted changes are preserved.
5463 uncommitted changes are preserved.
5395
5464
5396 3. With the -C/--clean option, uncommitted changes are discarded and
5465 3. With the -C/--clean option, uncommitted changes are discarded and
5397 the working directory is updated to the requested changeset.
5466 the working directory is updated to the requested changeset.
5398
5467
5399 Use null as the changeset to remove the working directory (like
5468 Use null as the changeset to remove the working directory (like
5400 :hg:`clone -U`).
5469 :hg:`clone -U`).
5401
5470
5402 If you want to revert just one file to an older revision, use
5471 If you want to revert just one file to an older revision, use
5403 :hg:`revert [-r REV] NAME`.
5472 :hg:`revert [-r REV] NAME`.
5404
5473
5405 See :hg:`help dates` for a list of formats valid for -d/--date.
5474 See :hg:`help dates` for a list of formats valid for -d/--date.
5406
5475
5407 Returns 0 on success, 1 if there are unresolved files.
5476 Returns 0 on success, 1 if there are unresolved files.
5408 """
5477 """
5409 if rev and node:
5478 if rev and node:
5410 raise util.Abort(_("please specify just one revision"))
5479 raise util.Abort(_("please specify just one revision"))
5411
5480
5412 if rev is None or rev == '':
5481 if rev is None or rev == '':
5413 rev = node
5482 rev = node
5414
5483
5415 # if we defined a bookmark, we have to remember the original bookmark name
5484 # if we defined a bookmark, we have to remember the original bookmark name
5416 brev = rev
5485 brev = rev
5417 rev = scmutil.revsingle(repo, rev, rev).rev()
5486 rev = scmutil.revsingle(repo, rev, rev).rev()
5418
5487
5419 if check and clean:
5488 if check and clean:
5420 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5489 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5421
5490
5422 if check:
5491 if check:
5423 # we could use dirty() but we can ignore merge and branch trivia
5492 # we could use dirty() but we can ignore merge and branch trivia
5424 c = repo[None]
5493 c = repo[None]
5425 if c.modified() or c.added() or c.removed():
5494 if c.modified() or c.added() or c.removed():
5426 raise util.Abort(_("uncommitted local changes"))
5495 raise util.Abort(_("uncommitted local changes"))
5427
5496
5428 if date:
5497 if date:
5429 if rev is not None:
5498 if rev is not None:
5430 raise util.Abort(_("you can't specify a revision and a date"))
5499 raise util.Abort(_("you can't specify a revision and a date"))
5431 rev = cmdutil.finddate(ui, repo, date)
5500 rev = cmdutil.finddate(ui, repo, date)
5432
5501
5433 if clean or check:
5502 if clean or check:
5434 ret = hg.clean(repo, rev)
5503 ret = hg.clean(repo, rev)
5435 else:
5504 else:
5436 ret = hg.update(repo, rev)
5505 ret = hg.update(repo, rev)
5437
5506
5438 if brev in repo._bookmarks:
5507 if brev in repo._bookmarks:
5439 bookmarks.setcurrent(repo, brev)
5508 bookmarks.setcurrent(repo, brev)
5440
5509
5441 return ret
5510 return ret
5442
5511
5443 @command('verify', [])
5512 @command('verify', [])
5444 def verify(ui, repo):
5513 def verify(ui, repo):
5445 """verify the integrity of the repository
5514 """verify the integrity of the repository
5446
5515
5447 Verify the integrity of the current repository.
5516 Verify the integrity of the current repository.
5448
5517
5449 This will perform an extensive check of the repository's
5518 This will perform an extensive check of the repository's
5450 integrity, validating the hashes and checksums of each entry in
5519 integrity, validating the hashes and checksums of each entry in
5451 the changelog, manifest, and tracked files, as well as the
5520 the changelog, manifest, and tracked files, as well as the
5452 integrity of their crosslinks and indices.
5521 integrity of their crosslinks and indices.
5453
5522
5454 Returns 0 on success, 1 if errors are encountered.
5523 Returns 0 on success, 1 if errors are encountered.
5455 """
5524 """
5456 return hg.verify(repo)
5525 return hg.verify(repo)
5457
5526
5458 @command('version', [])
5527 @command('version', [])
5459 def version_(ui):
5528 def version_(ui):
5460 """output version and copyright information"""
5529 """output version and copyright information"""
5461 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5530 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5462 % util.version())
5531 % util.version())
5463 ui.status(_(
5532 ui.status(_(
5464 "(see http://mercurial.selenic.com for more information)\n"
5533 "(see http://mercurial.selenic.com for more information)\n"
5465 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5534 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5466 "This is free software; see the source for copying conditions. "
5535 "This is free software; see the source for copying conditions. "
5467 "There is NO\nwarranty; "
5536 "There is NO\nwarranty; "
5468 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5537 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5469 ))
5538 ))
5470
5539
5471 norepo = ("clone init version help debugcommands debugcomplete"
5540 norepo = ("clone init version help debugcommands debugcomplete"
5472 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5541 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5473 " debugknown debuggetbundle debugbundle")
5542 " debugknown debuggetbundle debugbundle")
5474 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5543 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5475 " debugdata debugindex debugindexdot debugrevlog")
5544 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,268 +1,270 b''
1 Show all commands except debug commands
1 Show all commands except debug commands
2 $ hg debugcomplete
2 $ hg debugcomplete
3 add
3 add
4 addremove
4 addremove
5 annotate
5 annotate
6 archive
6 archive
7 backout
7 backout
8 bisect
8 bisect
9 bookmarks
9 bookmarks
10 branch
10 branch
11 branches
11 branches
12 bundle
12 bundle
13 cat
13 cat
14 clone
14 clone
15 commit
15 commit
16 copy
16 copy
17 diff
17 diff
18 export
18 export
19 forget
19 forget
20 graft
20 grep
21 grep
21 heads
22 heads
22 help
23 help
23 identify
24 identify
24 import
25 import
25 incoming
26 incoming
26 init
27 init
27 locate
28 locate
28 log
29 log
29 manifest
30 manifest
30 merge
31 merge
31 outgoing
32 outgoing
32 parents
33 parents
33 paths
34 paths
34 pull
35 pull
35 push
36 push
36 recover
37 recover
37 remove
38 remove
38 rename
39 rename
39 resolve
40 resolve
40 revert
41 revert
41 rollback
42 rollback
42 root
43 root
43 serve
44 serve
44 showconfig
45 showconfig
45 status
46 status
46 summary
47 summary
47 tag
48 tag
48 tags
49 tags
49 tip
50 tip
50 unbundle
51 unbundle
51 update
52 update
52 verify
53 verify
53 version
54 version
54
55
55 Show all commands that start with "a"
56 Show all commands that start with "a"
56 $ hg debugcomplete a
57 $ hg debugcomplete a
57 add
58 add
58 addremove
59 addremove
59 annotate
60 annotate
60 archive
61 archive
61
62
62 Do not show debug commands if there are other candidates
63 Do not show debug commands if there are other candidates
63 $ hg debugcomplete d
64 $ hg debugcomplete d
64 diff
65 diff
65
66
66 Show debug commands if there are no other candidates
67 Show debug commands if there are no other candidates
67 $ hg debugcomplete debug
68 $ hg debugcomplete debug
68 debugancestor
69 debugancestor
69 debugbuilddag
70 debugbuilddag
70 debugbundle
71 debugbundle
71 debugcheckstate
72 debugcheckstate
72 debugcommands
73 debugcommands
73 debugcomplete
74 debugcomplete
74 debugconfig
75 debugconfig
75 debugdag
76 debugdag
76 debugdata
77 debugdata
77 debugdate
78 debugdate
78 debugdiscovery
79 debugdiscovery
79 debugfileset
80 debugfileset
80 debugfsinfo
81 debugfsinfo
81 debuggetbundle
82 debuggetbundle
82 debugignore
83 debugignore
83 debugindex
84 debugindex
84 debugindexdot
85 debugindexdot
85 debuginstall
86 debuginstall
86 debugknown
87 debugknown
87 debugpushkey
88 debugpushkey
88 debugrebuildstate
89 debugrebuildstate
89 debugrename
90 debugrename
90 debugrevlog
91 debugrevlog
91 debugrevspec
92 debugrevspec
92 debugsetparents
93 debugsetparents
93 debugstate
94 debugstate
94 debugsub
95 debugsub
95 debugwalk
96 debugwalk
96 debugwireargs
97 debugwireargs
97
98
98 Do not show the alias of a debug command if there are other candidates
99 Do not show the alias of a debug command if there are other candidates
99 (this should hide rawcommit)
100 (this should hide rawcommit)
100 $ hg debugcomplete r
101 $ hg debugcomplete r
101 recover
102 recover
102 remove
103 remove
103 rename
104 rename
104 resolve
105 resolve
105 revert
106 revert
106 rollback
107 rollback
107 root
108 root
108 Show the alias of a debug command if there are no other candidates
109 Show the alias of a debug command if there are no other candidates
109 $ hg debugcomplete rawc
110 $ hg debugcomplete rawc
110
111
111
112
112 Show the global options
113 Show the global options
113 $ hg debugcomplete --options | sort
114 $ hg debugcomplete --options | sort
114 --config
115 --config
115 --cwd
116 --cwd
116 --debug
117 --debug
117 --debugger
118 --debugger
118 --encoding
119 --encoding
119 --encodingmode
120 --encodingmode
120 --help
121 --help
121 --noninteractive
122 --noninteractive
122 --profile
123 --profile
123 --quiet
124 --quiet
124 --repository
125 --repository
125 --time
126 --time
126 --traceback
127 --traceback
127 --verbose
128 --verbose
128 --version
129 --version
129 -R
130 -R
130 -h
131 -h
131 -q
132 -q
132 -v
133 -v
133 -y
134 -y
134
135
135 Show the options for the "serve" command
136 Show the options for the "serve" command
136 $ hg debugcomplete --options serve | sort
137 $ hg debugcomplete --options serve | sort
137 --accesslog
138 --accesslog
138 --address
139 --address
139 --certificate
140 --certificate
140 --cmdserver
141 --cmdserver
141 --config
142 --config
142 --cwd
143 --cwd
143 --daemon
144 --daemon
144 --daemon-pipefds
145 --daemon-pipefds
145 --debug
146 --debug
146 --debugger
147 --debugger
147 --encoding
148 --encoding
148 --encodingmode
149 --encodingmode
149 --errorlog
150 --errorlog
150 --help
151 --help
151 --ipv6
152 --ipv6
152 --name
153 --name
153 --noninteractive
154 --noninteractive
154 --pid-file
155 --pid-file
155 --port
156 --port
156 --prefix
157 --prefix
157 --profile
158 --profile
158 --quiet
159 --quiet
159 --repository
160 --repository
160 --stdio
161 --stdio
161 --style
162 --style
162 --templates
163 --templates
163 --time
164 --time
164 --traceback
165 --traceback
165 --verbose
166 --verbose
166 --version
167 --version
167 --web-conf
168 --web-conf
168 -6
169 -6
169 -A
170 -A
170 -E
171 -E
171 -R
172 -R
172 -a
173 -a
173 -d
174 -d
174 -h
175 -h
175 -n
176 -n
176 -p
177 -p
177 -q
178 -q
178 -t
179 -t
179 -v
180 -v
180 -y
181 -y
181
182
182 Show an error if we use --options with an ambiguous abbreviation
183 Show an error if we use --options with an ambiguous abbreviation
183 $ hg debugcomplete --options s
184 $ hg debugcomplete --options s
184 hg: command 's' is ambiguous:
185 hg: command 's' is ambiguous:
185 serve showconfig status summary
186 serve showconfig status summary
186 [255]
187 [255]
187
188
188 Show all commands + options
189 Show all commands + options
189 $ hg debugcommands
190 $ hg debugcommands
190 add: include, exclude, subrepos, dry-run
191 add: include, exclude, subrepos, dry-run
191 annotate: rev, follow, no-follow, text, user, file, date, number, changeset, line-number, include, exclude
192 annotate: rev, follow, no-follow, text, user, file, date, number, changeset, line-number, include, exclude
192 clone: noupdate, updaterev, rev, branch, pull, uncompressed, ssh, remotecmd, insecure
193 clone: noupdate, updaterev, rev, branch, pull, uncompressed, ssh, remotecmd, insecure
193 commit: addremove, close-branch, include, exclude, message, logfile, date, user
194 commit: addremove, close-branch, include, exclude, message, logfile, date, user
194 diff: rev, change, text, git, nodates, show-function, reverse, ignore-all-space, ignore-space-change, ignore-blank-lines, unified, stat, include, exclude, subrepos
195 diff: rev, change, text, git, nodates, show-function, reverse, ignore-all-space, ignore-space-change, ignore-blank-lines, unified, stat, include, exclude, subrepos
195 export: output, switch-parent, rev, text, git, nodates
196 export: output, switch-parent, rev, text, git, nodates
196 forget: include, exclude
197 forget: include, exclude
197 init: ssh, remotecmd, insecure
198 init: ssh, remotecmd, insecure
198 log: follow, follow-first, date, copies, keyword, rev, removed, only-merges, user, only-branch, branch, prune, hidden, patch, git, limit, no-merges, stat, style, template, include, exclude
199 log: follow, follow-first, date, copies, keyword, rev, removed, only-merges, user, only-branch, branch, prune, hidden, patch, git, limit, no-merges, stat, style, template, include, exclude
199 merge: force, rev, preview, tool
200 merge: force, rev, preview, tool
200 pull: update, force, rev, bookmark, branch, ssh, remotecmd, insecure
201 pull: update, force, rev, bookmark, branch, ssh, remotecmd, insecure
201 push: force, rev, bookmark, branch, new-branch, ssh, remotecmd, insecure
202 push: force, rev, bookmark, branch, new-branch, ssh, remotecmd, insecure
202 remove: after, force, include, exclude
203 remove: after, force, include, exclude
203 serve: accesslog, daemon, daemon-pipefds, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate
204 serve: accesslog, daemon, daemon-pipefds, errorlog, port, address, prefix, name, web-conf, webdir-conf, pid-file, stdio, cmdserver, templates, style, ipv6, certificate
204 status: all, modified, added, removed, deleted, clean, unknown, ignored, no-status, copies, print0, rev, change, include, exclude, subrepos
205 status: all, modified, added, removed, deleted, clean, unknown, ignored, no-status, copies, print0, rev, change, include, exclude, subrepos
205 summary: remote
206 summary: remote
206 update: clean, check, date, rev
207 update: clean, check, date, rev
207 addremove: similarity, include, exclude, dry-run
208 addremove: similarity, include, exclude, dry-run
208 archive: no-decode, prefix, rev, type, subrepos, include, exclude
209 archive: no-decode, prefix, rev, type, subrepos, include, exclude
209 backout: merge, parent, rev, tool, include, exclude, message, logfile, date, user
210 backout: merge, parent, rev, tool, include, exclude, message, logfile, date, user
210 bisect: reset, good, bad, skip, extend, command, noupdate
211 bisect: reset, good, bad, skip, extend, command, noupdate
211 bookmarks: force, rev, delete, rename, inactive
212 bookmarks: force, rev, delete, rename, inactive
212 branch: force, clean
213 branch: force, clean
213 branches: active, closed
214 branches: active, closed
214 bundle: force, rev, branch, base, all, type, ssh, remotecmd, insecure
215 bundle: force, rev, branch, base, all, type, ssh, remotecmd, insecure
215 cat: output, rev, decode, include, exclude
216 cat: output, rev, decode, include, exclude
216 copy: after, force, include, exclude, dry-run
217 copy: after, force, include, exclude, dry-run
217 debugancestor:
218 debugancestor:
218 debugbuilddag: mergeable-file, overwritten-file, new-file
219 debugbuilddag: mergeable-file, overwritten-file, new-file
219 debugbundle: all
220 debugbundle: all
220 debugcheckstate:
221 debugcheckstate:
221 debugcommands:
222 debugcommands:
222 debugcomplete: options
223 debugcomplete: options
223 debugdag: tags, branches, dots, spaces
224 debugdag: tags, branches, dots, spaces
224 debugdata: changelog, manifest
225 debugdata: changelog, manifest
225 debugdate: extended
226 debugdate: extended
226 debugdiscovery: old, nonheads, ssh, remotecmd, insecure
227 debugdiscovery: old, nonheads, ssh, remotecmd, insecure
227 debugfileset:
228 debugfileset:
228 debugfsinfo:
229 debugfsinfo:
229 debuggetbundle: head, common, type
230 debuggetbundle: head, common, type
230 debugignore:
231 debugignore:
231 debugindex: changelog, manifest, format
232 debugindex: changelog, manifest, format
232 debugindexdot:
233 debugindexdot:
233 debuginstall:
234 debuginstall:
234 debugknown:
235 debugknown:
235 debugpushkey:
236 debugpushkey:
236 debugrebuildstate: rev
237 debugrebuildstate: rev
237 debugrename: rev
238 debugrename: rev
238 debugrevlog: changelog, manifest, dump
239 debugrevlog: changelog, manifest, dump
239 debugrevspec:
240 debugrevspec:
240 debugsetparents:
241 debugsetparents:
241 debugstate: nodates, datesort
242 debugstate: nodates, datesort
242 debugsub: rev
243 debugsub: rev
243 debugwalk: include, exclude
244 debugwalk: include, exclude
244 debugwireargs: three, four, five, ssh, remotecmd, insecure
245 debugwireargs: three, four, five, ssh, remotecmd, insecure
246 graft:
245 grep: print0, all, text, follow, ignore-case, files-with-matches, line-number, rev, user, date, include, exclude
247 grep: print0, all, text, follow, ignore-case, files-with-matches, line-number, rev, user, date, include, exclude
246 heads: rev, topo, active, closed, style, template
248 heads: rev, topo, active, closed, style, template
247 help: extension, command
249 help: extension, command
248 identify: rev, num, id, branch, tags, bookmarks
250 identify: rev, num, id, branch, tags, bookmarks
249 import: strip, base, edit, force, no-commit, bypass, exact, import-branch, message, logfile, date, user, similarity
251 import: strip, base, edit, force, no-commit, bypass, exact, import-branch, message, logfile, date, user, similarity
250 incoming: force, newest-first, bundle, rev, bookmarks, branch, patch, git, limit, no-merges, stat, style, template, ssh, remotecmd, insecure, subrepos
252 incoming: force, newest-first, bundle, rev, bookmarks, branch, patch, git, limit, no-merges, stat, style, template, ssh, remotecmd, insecure, subrepos
251 locate: rev, print0, fullpath, include, exclude
253 locate: rev, print0, fullpath, include, exclude
252 manifest: rev, all
254 manifest: rev, all
253 outgoing: force, rev, newest-first, bookmarks, branch, patch, git, limit, no-merges, stat, style, template, ssh, remotecmd, insecure, subrepos
255 outgoing: force, rev, newest-first, bookmarks, branch, patch, git, limit, no-merges, stat, style, template, ssh, remotecmd, insecure, subrepos
254 parents: rev, style, template
256 parents: rev, style, template
255 paths:
257 paths:
256 recover:
258 recover:
257 rename: after, force, include, exclude, dry-run
259 rename: after, force, include, exclude, dry-run
258 resolve: all, list, mark, unmark, no-status, tool, include, exclude
260 resolve: all, list, mark, unmark, no-status, tool, include, exclude
259 revert: all, date, rev, no-backup, include, exclude, dry-run
261 revert: all, date, rev, no-backup, include, exclude, dry-run
260 rollback: dry-run, force
262 rollback: dry-run, force
261 root:
263 root:
262 showconfig: untrusted
264 showconfig: untrusted
263 tag: force, local, rev, remove, edit, message, date, user
265 tag: force, local, rev, remove, edit, message, date, user
264 tags:
266 tags:
265 tip: patch, git, style, template
267 tip: patch, git, style, template
266 unbundle: update
268 unbundle: update
267 verify:
269 verify:
268 version:
270 version:
@@ -1,438 +1,440 b''
1 $ "$TESTDIR/hghave" no-outer-repo || exit 80
1 $ "$TESTDIR/hghave" no-outer-repo || exit 80
2
2
3 $ hg init a
3 $ hg init a
4 $ cd a
4 $ cd a
5 $ echo a > a
5 $ echo a > a
6 $ hg ci -A -d'1 0' -m a
6 $ hg ci -A -d'1 0' -m a
7 adding a
7 adding a
8
8
9 $ cd ..
9 $ cd ..
10
10
11 $ hg init b
11 $ hg init b
12 $ cd b
12 $ cd b
13 $ echo b > b
13 $ echo b > b
14 $ hg ci -A -d'1 0' -m b
14 $ hg ci -A -d'1 0' -m b
15 adding b
15 adding b
16
16
17 $ cd ..
17 $ cd ..
18
18
19 $ hg clone a c
19 $ hg clone a c
20 updating to branch default
20 updating to branch default
21 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
21 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
22 $ cd c
22 $ cd c
23 $ cat >> .hg/hgrc <<EOF
23 $ cat >> .hg/hgrc <<EOF
24 > [paths]
24 > [paths]
25 > relative = ../a
25 > relative = ../a
26 > EOF
26 > EOF
27 $ hg pull -f ../b
27 $ hg pull -f ../b
28 pulling from ../b
28 pulling from ../b
29 searching for changes
29 searching for changes
30 warning: repository is unrelated
30 warning: repository is unrelated
31 requesting all changes
31 requesting all changes
32 adding changesets
32 adding changesets
33 adding manifests
33 adding manifests
34 adding file changes
34 adding file changes
35 added 1 changesets with 1 changes to 1 files (+1 heads)
35 added 1 changesets with 1 changes to 1 files (+1 heads)
36 (run 'hg heads' to see heads, 'hg merge' to merge)
36 (run 'hg heads' to see heads, 'hg merge' to merge)
37 $ hg merge
37 $ hg merge
38 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
38 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
39 (branch merge, don't forget to commit)
39 (branch merge, don't forget to commit)
40
40
41 $ cd ..
41 $ cd ..
42
42
43 Testing -R/--repository:
43 Testing -R/--repository:
44
44
45 $ hg -R a tip
45 $ hg -R a tip
46 changeset: 0:8580ff50825a
46 changeset: 0:8580ff50825a
47 tag: tip
47 tag: tip
48 user: test
48 user: test
49 date: Thu Jan 01 00:00:01 1970 +0000
49 date: Thu Jan 01 00:00:01 1970 +0000
50 summary: a
50 summary: a
51
51
52 $ hg --repository b tip
52 $ hg --repository b tip
53 changeset: 0:b6c483daf290
53 changeset: 0:b6c483daf290
54 tag: tip
54 tag: tip
55 user: test
55 user: test
56 date: Thu Jan 01 00:00:01 1970 +0000
56 date: Thu Jan 01 00:00:01 1970 +0000
57 summary: b
57 summary: b
58
58
59
59
60 -R with a URL:
60 -R with a URL:
61
61
62 $ hg -R file:a identify
62 $ hg -R file:a identify
63 8580ff50825a tip
63 8580ff50825a tip
64 $ hg -R file://localhost/`pwd`/a/ identify
64 $ hg -R file://localhost/`pwd`/a/ identify
65 8580ff50825a tip
65 8580ff50825a tip
66
66
67 -R with path aliases:
67 -R with path aliases:
68
68
69 $ cd c
69 $ cd c
70 $ hg -R default identify
70 $ hg -R default identify
71 8580ff50825a tip
71 8580ff50825a tip
72 $ hg -R relative identify
72 $ hg -R relative identify
73 8580ff50825a tip
73 8580ff50825a tip
74 $ echo '[paths]' >> $HGRCPATH
74 $ echo '[paths]' >> $HGRCPATH
75 $ echo 'relativetohome = a' >> $HGRCPATH
75 $ echo 'relativetohome = a' >> $HGRCPATH
76 $ HOME=`pwd`/../ hg -R relativetohome identify
76 $ HOME=`pwd`/../ hg -R relativetohome identify
77 8580ff50825a tip
77 8580ff50825a tip
78 $ cd ..
78 $ cd ..
79
79
80 Implicit -R:
80 Implicit -R:
81
81
82 $ hg ann a/a
82 $ hg ann a/a
83 0: a
83 0: a
84 $ hg ann a/a a/a
84 $ hg ann a/a a/a
85 0: a
85 0: a
86 $ hg ann a/a b/b
86 $ hg ann a/a b/b
87 abort: no repository found in '$TESTTMP' (.hg not found)!
87 abort: no repository found in '$TESTTMP' (.hg not found)!
88 [255]
88 [255]
89 $ hg -R b ann a/a
89 $ hg -R b ann a/a
90 abort: a/a not under root
90 abort: a/a not under root
91 [255]
91 [255]
92 $ hg log
92 $ hg log
93 abort: no repository found in '$TESTTMP' (.hg not found)!
93 abort: no repository found in '$TESTTMP' (.hg not found)!
94 [255]
94 [255]
95
95
96 Abbreviation of long option:
96 Abbreviation of long option:
97
97
98 $ hg --repo c tip
98 $ hg --repo c tip
99 changeset: 1:b6c483daf290
99 changeset: 1:b6c483daf290
100 tag: tip
100 tag: tip
101 parent: -1:000000000000
101 parent: -1:000000000000
102 user: test
102 user: test
103 date: Thu Jan 01 00:00:01 1970 +0000
103 date: Thu Jan 01 00:00:01 1970 +0000
104 summary: b
104 summary: b
105
105
106
106
107 earlygetopt with duplicate options (36d23de02da1):
107 earlygetopt with duplicate options (36d23de02da1):
108
108
109 $ hg --cwd a --cwd b --cwd c tip
109 $ hg --cwd a --cwd b --cwd c tip
110 changeset: 1:b6c483daf290
110 changeset: 1:b6c483daf290
111 tag: tip
111 tag: tip
112 parent: -1:000000000000
112 parent: -1:000000000000
113 user: test
113 user: test
114 date: Thu Jan 01 00:00:01 1970 +0000
114 date: Thu Jan 01 00:00:01 1970 +0000
115 summary: b
115 summary: b
116
116
117 $ hg --repo c --repository b -R a tip
117 $ hg --repo c --repository b -R a tip
118 changeset: 0:8580ff50825a
118 changeset: 0:8580ff50825a
119 tag: tip
119 tag: tip
120 user: test
120 user: test
121 date: Thu Jan 01 00:00:01 1970 +0000
121 date: Thu Jan 01 00:00:01 1970 +0000
122 summary: a
122 summary: a
123
123
124
124
125 earlygetopt short option without following space:
125 earlygetopt short option without following space:
126
126
127 $ hg -q -Rb tip
127 $ hg -q -Rb tip
128 0:b6c483daf290
128 0:b6c483daf290
129
129
130 earlygetopt with illegal abbreviations:
130 earlygetopt with illegal abbreviations:
131
131
132 $ hg --confi "foo.bar=baz"
132 $ hg --confi "foo.bar=baz"
133 abort: option --config may not be abbreviated!
133 abort: option --config may not be abbreviated!
134 [255]
134 [255]
135 $ hg --cw a tip
135 $ hg --cw a tip
136 abort: option --cwd may not be abbreviated!
136 abort: option --cwd may not be abbreviated!
137 [255]
137 [255]
138 $ hg --rep a tip
138 $ hg --rep a tip
139 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
139 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
140 [255]
140 [255]
141 $ hg --repositor a tip
141 $ hg --repositor a tip
142 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
142 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
143 [255]
143 [255]
144 $ hg -qR a tip
144 $ hg -qR a tip
145 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
145 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
146 [255]
146 [255]
147 $ hg -qRa tip
147 $ hg -qRa tip
148 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
148 abort: Option -R has to be separated from other options (e.g. not -qR) and --repository may only be abbreviated as --repo!
149 [255]
149 [255]
150
150
151 Testing --cwd:
151 Testing --cwd:
152
152
153 $ hg --cwd a parents
153 $ hg --cwd a parents
154 changeset: 0:8580ff50825a
154 changeset: 0:8580ff50825a
155 tag: tip
155 tag: tip
156 user: test
156 user: test
157 date: Thu Jan 01 00:00:01 1970 +0000
157 date: Thu Jan 01 00:00:01 1970 +0000
158 summary: a
158 summary: a
159
159
160
160
161 Testing -y/--noninteractive - just be sure it is parsed:
161 Testing -y/--noninteractive - just be sure it is parsed:
162
162
163 $ hg --cwd a tip -q --noninteractive
163 $ hg --cwd a tip -q --noninteractive
164 0:8580ff50825a
164 0:8580ff50825a
165 $ hg --cwd a tip -q -y
165 $ hg --cwd a tip -q -y
166 0:8580ff50825a
166 0:8580ff50825a
167
167
168 Testing -q/--quiet:
168 Testing -q/--quiet:
169
169
170 $ hg -R a -q tip
170 $ hg -R a -q tip
171 0:8580ff50825a
171 0:8580ff50825a
172 $ hg -R b -q tip
172 $ hg -R b -q tip
173 0:b6c483daf290
173 0:b6c483daf290
174 $ hg -R c --quiet parents
174 $ hg -R c --quiet parents
175 0:8580ff50825a
175 0:8580ff50825a
176 1:b6c483daf290
176 1:b6c483daf290
177
177
178 Testing -v/--verbose:
178 Testing -v/--verbose:
179
179
180 $ hg --cwd c head -v
180 $ hg --cwd c head -v
181 changeset: 1:b6c483daf290
181 changeset: 1:b6c483daf290
182 tag: tip
182 tag: tip
183 parent: -1:000000000000
183 parent: -1:000000000000
184 user: test
184 user: test
185 date: Thu Jan 01 00:00:01 1970 +0000
185 date: Thu Jan 01 00:00:01 1970 +0000
186 files: b
186 files: b
187 description:
187 description:
188 b
188 b
189
189
190
190
191 changeset: 0:8580ff50825a
191 changeset: 0:8580ff50825a
192 user: test
192 user: test
193 date: Thu Jan 01 00:00:01 1970 +0000
193 date: Thu Jan 01 00:00:01 1970 +0000
194 files: a
194 files: a
195 description:
195 description:
196 a
196 a
197
197
198
198
199 $ hg --cwd b tip --verbose
199 $ hg --cwd b tip --verbose
200 changeset: 0:b6c483daf290
200 changeset: 0:b6c483daf290
201 tag: tip
201 tag: tip
202 user: test
202 user: test
203 date: Thu Jan 01 00:00:01 1970 +0000
203 date: Thu Jan 01 00:00:01 1970 +0000
204 files: b
204 files: b
205 description:
205 description:
206 b
206 b
207
207
208
208
209
209
210 Testing --config:
210 Testing --config:
211
211
212 $ hg --cwd c --config paths.quuxfoo=bar paths | grep quuxfoo > /dev/null && echo quuxfoo
212 $ hg --cwd c --config paths.quuxfoo=bar paths | grep quuxfoo > /dev/null && echo quuxfoo
213 quuxfoo
213 quuxfoo
214 $ hg --cwd c --config '' tip -q
214 $ hg --cwd c --config '' tip -q
215 abort: malformed --config option: '' (use --config section.name=value)
215 abort: malformed --config option: '' (use --config section.name=value)
216 [255]
216 [255]
217 $ hg --cwd c --config a.b tip -q
217 $ hg --cwd c --config a.b tip -q
218 abort: malformed --config option: 'a.b' (use --config section.name=value)
218 abort: malformed --config option: 'a.b' (use --config section.name=value)
219 [255]
219 [255]
220 $ hg --cwd c --config a tip -q
220 $ hg --cwd c --config a tip -q
221 abort: malformed --config option: 'a' (use --config section.name=value)
221 abort: malformed --config option: 'a' (use --config section.name=value)
222 [255]
222 [255]
223 $ hg --cwd c --config a.= tip -q
223 $ hg --cwd c --config a.= tip -q
224 abort: malformed --config option: 'a.=' (use --config section.name=value)
224 abort: malformed --config option: 'a.=' (use --config section.name=value)
225 [255]
225 [255]
226 $ hg --cwd c --config .b= tip -q
226 $ hg --cwd c --config .b= tip -q
227 abort: malformed --config option: '.b=' (use --config section.name=value)
227 abort: malformed --config option: '.b=' (use --config section.name=value)
228 [255]
228 [255]
229
229
230 Testing --debug:
230 Testing --debug:
231
231
232 $ hg --cwd c log --debug
232 $ hg --cwd c log --debug
233 changeset: 1:b6c483daf2907ce5825c0bb50f5716226281cc1a
233 changeset: 1:b6c483daf2907ce5825c0bb50f5716226281cc1a
234 tag: tip
234 tag: tip
235 parent: -1:0000000000000000000000000000000000000000
235 parent: -1:0000000000000000000000000000000000000000
236 parent: -1:0000000000000000000000000000000000000000
236 parent: -1:0000000000000000000000000000000000000000
237 manifest: 1:23226e7a252cacdc2d99e4fbdc3653441056de49
237 manifest: 1:23226e7a252cacdc2d99e4fbdc3653441056de49
238 user: test
238 user: test
239 date: Thu Jan 01 00:00:01 1970 +0000
239 date: Thu Jan 01 00:00:01 1970 +0000
240 files+: b
240 files+: b
241 extra: branch=default
241 extra: branch=default
242 description:
242 description:
243 b
243 b
244
244
245
245
246 changeset: 0:8580ff50825a50c8f716709acdf8de0deddcd6ab
246 changeset: 0:8580ff50825a50c8f716709acdf8de0deddcd6ab
247 parent: -1:0000000000000000000000000000000000000000
247 parent: -1:0000000000000000000000000000000000000000
248 parent: -1:0000000000000000000000000000000000000000
248 parent: -1:0000000000000000000000000000000000000000
249 manifest: 0:a0c8bcbbb45c63b90b70ad007bf38961f64f2af0
249 manifest: 0:a0c8bcbbb45c63b90b70ad007bf38961f64f2af0
250 user: test
250 user: test
251 date: Thu Jan 01 00:00:01 1970 +0000
251 date: Thu Jan 01 00:00:01 1970 +0000
252 files+: a
252 files+: a
253 extra: branch=default
253 extra: branch=default
254 description:
254 description:
255 a
255 a
256
256
257
257
258
258
259 Testing --traceback:
259 Testing --traceback:
260
260
261 $ hg --cwd c --config x --traceback id 2>&1 | grep -i 'traceback'
261 $ hg --cwd c --config x --traceback id 2>&1 | grep -i 'traceback'
262 Traceback (most recent call last):
262 Traceback (most recent call last):
263
263
264 Testing --time:
264 Testing --time:
265
265
266 $ hg --cwd a --time id
266 $ hg --cwd a --time id
267 8580ff50825a tip
267 8580ff50825a tip
268 Time: real * (glob)
268 Time: real * (glob)
269
269
270 Testing --version:
270 Testing --version:
271
271
272 $ hg --version -q
272 $ hg --version -q
273 Mercurial Distributed SCM * (glob)
273 Mercurial Distributed SCM * (glob)
274
274
275 Testing -h/--help:
275 Testing -h/--help:
276
276
277 $ hg -h
277 $ hg -h
278 Mercurial Distributed SCM
278 Mercurial Distributed SCM
279
279
280 list of commands:
280 list of commands:
281
281
282 add add the specified files on the next commit
282 add add the specified files on the next commit
283 addremove add all new files, delete all missing files
283 addremove add all new files, delete all missing files
284 annotate show changeset information by line for each file
284 annotate show changeset information by line for each file
285 archive create an unversioned archive of a repository revision
285 archive create an unversioned archive of a repository revision
286 backout reverse effect of earlier changeset
286 backout reverse effect of earlier changeset
287 bisect subdivision search of changesets
287 bisect subdivision search of changesets
288 bookmarks track a line of development with movable markers
288 bookmarks track a line of development with movable markers
289 branch set or show the current branch name
289 branch set or show the current branch name
290 branches list repository named branches
290 branches list repository named branches
291 bundle create a changegroup file
291 bundle create a changegroup file
292 cat output the current or given revision of files
292 cat output the current or given revision of files
293 clone make a copy of an existing repository
293 clone make a copy of an existing repository
294 commit commit the specified files or all outstanding changes
294 commit commit the specified files or all outstanding changes
295 copy mark files as copied for the next commit
295 copy mark files as copied for the next commit
296 diff diff repository (or selected files)
296 diff diff repository (or selected files)
297 export dump the header and diffs for one or more changesets
297 export dump the header and diffs for one or more changesets
298 forget forget the specified files on the next commit
298 forget forget the specified files on the next commit
299 graft copy changes from other branches onto the current branch
299 grep search for a pattern in specified files and revisions
300 grep search for a pattern in specified files and revisions
300 heads show current repository heads or show branch heads
301 heads show current repository heads or show branch heads
301 help show help for a given topic or a help overview
302 help show help for a given topic or a help overview
302 identify identify the working copy or specified revision
303 identify identify the working copy or specified revision
303 import import an ordered set of patches
304 import import an ordered set of patches
304 incoming show new changesets found in source
305 incoming show new changesets found in source
305 init create a new repository in the given directory
306 init create a new repository in the given directory
306 locate locate files matching specific patterns
307 locate locate files matching specific patterns
307 log show revision history of entire repository or files
308 log show revision history of entire repository or files
308 manifest output the current or given revision of the project manifest
309 manifest output the current or given revision of the project manifest
309 merge merge working directory with another revision
310 merge merge working directory with another revision
310 outgoing show changesets not found in the destination
311 outgoing show changesets not found in the destination
311 parents show the parents of the working directory or revision
312 parents show the parents of the working directory or revision
312 paths show aliases for remote repositories
313 paths show aliases for remote repositories
313 pull pull changes from the specified source
314 pull pull changes from the specified source
314 push push changes to the specified destination
315 push push changes to the specified destination
315 recover roll back an interrupted transaction
316 recover roll back an interrupted transaction
316 remove remove the specified files on the next commit
317 remove remove the specified files on the next commit
317 rename rename files; equivalent of copy + remove
318 rename rename files; equivalent of copy + remove
318 resolve redo merges or set/view the merge status of files
319 resolve redo merges or set/view the merge status of files
319 revert restore files to their checkout state
320 revert restore files to their checkout state
320 rollback roll back the last transaction (dangerous)
321 rollback roll back the last transaction (dangerous)
321 root print the root (top) of the current working directory
322 root print the root (top) of the current working directory
322 serve start stand-alone webserver
323 serve start stand-alone webserver
323 showconfig show combined config settings from all hgrc files
324 showconfig show combined config settings from all hgrc files
324 status show changed files in the working directory
325 status show changed files in the working directory
325 summary summarize working directory state
326 summary summarize working directory state
326 tag add one or more tags for the current or given revision
327 tag add one or more tags for the current or given revision
327 tags list repository tags
328 tags list repository tags
328 tip show the tip revision
329 tip show the tip revision
329 unbundle apply one or more changegroup files
330 unbundle apply one or more changegroup files
330 update update working directory (or switch revisions)
331 update update working directory (or switch revisions)
331 verify verify the integrity of the repository
332 verify verify the integrity of the repository
332 version output version and copyright information
333 version output version and copyright information
333
334
334 additional help topics:
335 additional help topics:
335
336
336 config Configuration Files
337 config Configuration Files
337 dates Date Formats
338 dates Date Formats
338 diffs Diff Formats
339 diffs Diff Formats
339 environment Environment Variables
340 environment Environment Variables
340 extensions Using additional features
341 extensions Using additional features
341 filesets Specifying File Sets
342 filesets Specifying File Sets
342 glossary Glossary
343 glossary Glossary
343 hgignore syntax for Mercurial ignore files
344 hgignore syntax for Mercurial ignore files
344 hgweb Configuring hgweb
345 hgweb Configuring hgweb
345 merge-tools Merge Tools
346 merge-tools Merge Tools
346 multirevs Specifying Multiple Revisions
347 multirevs Specifying Multiple Revisions
347 patterns File Name Patterns
348 patterns File Name Patterns
348 revisions Specifying Single Revisions
349 revisions Specifying Single Revisions
349 revsets Specifying Revision Sets
350 revsets Specifying Revision Sets
350 subrepos Subrepositories
351 subrepos Subrepositories
351 templating Template Usage
352 templating Template Usage
352 urls URL Paths
353 urls URL Paths
353
354
354 use "hg -v help" to show builtin aliases and global options
355 use "hg -v help" to show builtin aliases and global options
355
356
356
357
357
358
358 $ hg --help
359 $ hg --help
359 Mercurial Distributed SCM
360 Mercurial Distributed SCM
360
361
361 list of commands:
362 list of commands:
362
363
363 add add the specified files on the next commit
364 add add the specified files on the next commit
364 addremove add all new files, delete all missing files
365 addremove add all new files, delete all missing files
365 annotate show changeset information by line for each file
366 annotate show changeset information by line for each file
366 archive create an unversioned archive of a repository revision
367 archive create an unversioned archive of a repository revision
367 backout reverse effect of earlier changeset
368 backout reverse effect of earlier changeset
368 bisect subdivision search of changesets
369 bisect subdivision search of changesets
369 bookmarks track a line of development with movable markers
370 bookmarks track a line of development with movable markers
370 branch set or show the current branch name
371 branch set or show the current branch name
371 branches list repository named branches
372 branches list repository named branches
372 bundle create a changegroup file
373 bundle create a changegroup file
373 cat output the current or given revision of files
374 cat output the current or given revision of files
374 clone make a copy of an existing repository
375 clone make a copy of an existing repository
375 commit commit the specified files or all outstanding changes
376 commit commit the specified files or all outstanding changes
376 copy mark files as copied for the next commit
377 copy mark files as copied for the next commit
377 diff diff repository (or selected files)
378 diff diff repository (or selected files)
378 export dump the header and diffs for one or more changesets
379 export dump the header and diffs for one or more changesets
379 forget forget the specified files on the next commit
380 forget forget the specified files on the next commit
381 graft copy changes from other branches onto the current branch
380 grep search for a pattern in specified files and revisions
382 grep search for a pattern in specified files and revisions
381 heads show current repository heads or show branch heads
383 heads show current repository heads or show branch heads
382 help show help for a given topic or a help overview
384 help show help for a given topic or a help overview
383 identify identify the working copy or specified revision
385 identify identify the working copy or specified revision
384 import import an ordered set of patches
386 import import an ordered set of patches
385 incoming show new changesets found in source
387 incoming show new changesets found in source
386 init create a new repository in the given directory
388 init create a new repository in the given directory
387 locate locate files matching specific patterns
389 locate locate files matching specific patterns
388 log show revision history of entire repository or files
390 log show revision history of entire repository or files
389 manifest output the current or given revision of the project manifest
391 manifest output the current or given revision of the project manifest
390 merge merge working directory with another revision
392 merge merge working directory with another revision
391 outgoing show changesets not found in the destination
393 outgoing show changesets not found in the destination
392 parents show the parents of the working directory or revision
394 parents show the parents of the working directory or revision
393 paths show aliases for remote repositories
395 paths show aliases for remote repositories
394 pull pull changes from the specified source
396 pull pull changes from the specified source
395 push push changes to the specified destination
397 push push changes to the specified destination
396 recover roll back an interrupted transaction
398 recover roll back an interrupted transaction
397 remove remove the specified files on the next commit
399 remove remove the specified files on the next commit
398 rename rename files; equivalent of copy + remove
400 rename rename files; equivalent of copy + remove
399 resolve redo merges or set/view the merge status of files
401 resolve redo merges or set/view the merge status of files
400 revert restore files to their checkout state
402 revert restore files to their checkout state
401 rollback roll back the last transaction (dangerous)
403 rollback roll back the last transaction (dangerous)
402 root print the root (top) of the current working directory
404 root print the root (top) of the current working directory
403 serve start stand-alone webserver
405 serve start stand-alone webserver
404 showconfig show combined config settings from all hgrc files
406 showconfig show combined config settings from all hgrc files
405 status show changed files in the working directory
407 status show changed files in the working directory
406 summary summarize working directory state
408 summary summarize working directory state
407 tag add one or more tags for the current or given revision
409 tag add one or more tags for the current or given revision
408 tags list repository tags
410 tags list repository tags
409 tip show the tip revision
411 tip show the tip revision
410 unbundle apply one or more changegroup files
412 unbundle apply one or more changegroup files
411 update update working directory (or switch revisions)
413 update update working directory (or switch revisions)
412 verify verify the integrity of the repository
414 verify verify the integrity of the repository
413 version output version and copyright information
415 version output version and copyright information
414
416
415 additional help topics:
417 additional help topics:
416
418
417 config Configuration Files
419 config Configuration Files
418 dates Date Formats
420 dates Date Formats
419 diffs Diff Formats
421 diffs Diff Formats
420 environment Environment Variables
422 environment Environment Variables
421 extensions Using additional features
423 extensions Using additional features
422 filesets Specifying File Sets
424 filesets Specifying File Sets
423 glossary Glossary
425 glossary Glossary
424 hgignore syntax for Mercurial ignore files
426 hgignore syntax for Mercurial ignore files
425 hgweb Configuring hgweb
427 hgweb Configuring hgweb
426 merge-tools Merge Tools
428 merge-tools Merge Tools
427 multirevs Specifying Multiple Revisions
429 multirevs Specifying Multiple Revisions
428 patterns File Name Patterns
430 patterns File Name Patterns
429 revisions Specifying Single Revisions
431 revisions Specifying Single Revisions
430 revsets Specifying Revision Sets
432 revsets Specifying Revision Sets
431 subrepos Subrepositories
433 subrepos Subrepositories
432 templating Template Usage
434 templating Template Usage
433 urls URL Paths
435 urls URL Paths
434
436
435 use "hg -v help" to show builtin aliases and global options
437 use "hg -v help" to show builtin aliases and global options
436
438
437 Not tested: --debugger
439 Not tested: --debugger
438
440
@@ -1,769 +1,772 b''
1 Short help:
1 Short help:
2
2
3 $ hg
3 $ hg
4 Mercurial Distributed SCM
4 Mercurial Distributed SCM
5
5
6 basic commands:
6 basic commands:
7
7
8 add add the specified files on the next commit
8 add add the specified files on the next commit
9 annotate show changeset information by line for each file
9 annotate show changeset information by line for each file
10 clone make a copy of an existing repository
10 clone make a copy of an existing repository
11 commit commit the specified files or all outstanding changes
11 commit commit the specified files or all outstanding changes
12 diff diff repository (or selected files)
12 diff diff repository (or selected files)
13 export dump the header and diffs for one or more changesets
13 export dump the header and diffs for one or more changesets
14 forget forget the specified files on the next commit
14 forget forget the specified files on the next commit
15 init create a new repository in the given directory
15 init create a new repository in the given directory
16 log show revision history of entire repository or files
16 log show revision history of entire repository or files
17 merge merge working directory with another revision
17 merge merge working directory with another revision
18 pull pull changes from the specified source
18 pull pull changes from the specified source
19 push push changes to the specified destination
19 push push changes to the specified destination
20 remove remove the specified files on the next commit
20 remove remove the specified files on the next commit
21 serve start stand-alone webserver
21 serve start stand-alone webserver
22 status show changed files in the working directory
22 status show changed files in the working directory
23 summary summarize working directory state
23 summary summarize working directory state
24 update update working directory (or switch revisions)
24 update update working directory (or switch revisions)
25
25
26 use "hg help" for the full list of commands or "hg -v" for details
26 use "hg help" for the full list of commands or "hg -v" for details
27
27
28 $ hg -q
28 $ hg -q
29 add add the specified files on the next commit
29 add add the specified files on the next commit
30 annotate show changeset information by line for each file
30 annotate show changeset information by line for each file
31 clone make a copy of an existing repository
31 clone make a copy of an existing repository
32 commit commit the specified files or all outstanding changes
32 commit commit the specified files or all outstanding changes
33 diff diff repository (or selected files)
33 diff diff repository (or selected files)
34 export dump the header and diffs for one or more changesets
34 export dump the header and diffs for one or more changesets
35 forget forget the specified files on the next commit
35 forget forget the specified files on the next commit
36 init create a new repository in the given directory
36 init create a new repository in the given directory
37 log show revision history of entire repository or files
37 log show revision history of entire repository or files
38 merge merge working directory with another revision
38 merge merge working directory with another revision
39 pull pull changes from the specified source
39 pull pull changes from the specified source
40 push push changes to the specified destination
40 push push changes to the specified destination
41 remove remove the specified files on the next commit
41 remove remove the specified files on the next commit
42 serve start stand-alone webserver
42 serve start stand-alone webserver
43 status show changed files in the working directory
43 status show changed files in the working directory
44 summary summarize working directory state
44 summary summarize working directory state
45 update update working directory (or switch revisions)
45 update update working directory (or switch revisions)
46
46
47 $ hg help
47 $ hg help
48 Mercurial Distributed SCM
48 Mercurial Distributed SCM
49
49
50 list of commands:
50 list of commands:
51
51
52 add add the specified files on the next commit
52 add add the specified files on the next commit
53 addremove add all new files, delete all missing files
53 addremove add all new files, delete all missing files
54 annotate show changeset information by line for each file
54 annotate show changeset information by line for each file
55 archive create an unversioned archive of a repository revision
55 archive create an unversioned archive of a repository revision
56 backout reverse effect of earlier changeset
56 backout reverse effect of earlier changeset
57 bisect subdivision search of changesets
57 bisect subdivision search of changesets
58 bookmarks track a line of development with movable markers
58 bookmarks track a line of development with movable markers
59 branch set or show the current branch name
59 branch set or show the current branch name
60 branches list repository named branches
60 branches list repository named branches
61 bundle create a changegroup file
61 bundle create a changegroup file
62 cat output the current or given revision of files
62 cat output the current or given revision of files
63 clone make a copy of an existing repository
63 clone make a copy of an existing repository
64 commit commit the specified files or all outstanding changes
64 commit commit the specified files or all outstanding changes
65 copy mark files as copied for the next commit
65 copy mark files as copied for the next commit
66 diff diff repository (or selected files)
66 diff diff repository (or selected files)
67 export dump the header and diffs for one or more changesets
67 export dump the header and diffs for one or more changesets
68 forget forget the specified files on the next commit
68 forget forget the specified files on the next commit
69 graft copy changes from other branches onto the current branch
69 grep search for a pattern in specified files and revisions
70 grep search for a pattern in specified files and revisions
70 heads show current repository heads or show branch heads
71 heads show current repository heads or show branch heads
71 help show help for a given topic or a help overview
72 help show help for a given topic or a help overview
72 identify identify the working copy or specified revision
73 identify identify the working copy or specified revision
73 import import an ordered set of patches
74 import import an ordered set of patches
74 incoming show new changesets found in source
75 incoming show new changesets found in source
75 init create a new repository in the given directory
76 init create a new repository in the given directory
76 locate locate files matching specific patterns
77 locate locate files matching specific patterns
77 log show revision history of entire repository or files
78 log show revision history of entire repository or files
78 manifest output the current or given revision of the project manifest
79 manifest output the current or given revision of the project manifest
79 merge merge working directory with another revision
80 merge merge working directory with another revision
80 outgoing show changesets not found in the destination
81 outgoing show changesets not found in the destination
81 parents show the parents of the working directory or revision
82 parents show the parents of the working directory or revision
82 paths show aliases for remote repositories
83 paths show aliases for remote repositories
83 pull pull changes from the specified source
84 pull pull changes from the specified source
84 push push changes to the specified destination
85 push push changes to the specified destination
85 recover roll back an interrupted transaction
86 recover roll back an interrupted transaction
86 remove remove the specified files on the next commit
87 remove remove the specified files on the next commit
87 rename rename files; equivalent of copy + remove
88 rename rename files; equivalent of copy + remove
88 resolve redo merges or set/view the merge status of files
89 resolve redo merges or set/view the merge status of files
89 revert restore files to their checkout state
90 revert restore files to their checkout state
90 rollback roll back the last transaction (dangerous)
91 rollback roll back the last transaction (dangerous)
91 root print the root (top) of the current working directory
92 root print the root (top) of the current working directory
92 serve start stand-alone webserver
93 serve start stand-alone webserver
93 showconfig show combined config settings from all hgrc files
94 showconfig show combined config settings from all hgrc files
94 status show changed files in the working directory
95 status show changed files in the working directory
95 summary summarize working directory state
96 summary summarize working directory state
96 tag add one or more tags for the current or given revision
97 tag add one or more tags for the current or given revision
97 tags list repository tags
98 tags list repository tags
98 tip show the tip revision
99 tip show the tip revision
99 unbundle apply one or more changegroup files
100 unbundle apply one or more changegroup files
100 update update working directory (or switch revisions)
101 update update working directory (or switch revisions)
101 verify verify the integrity of the repository
102 verify verify the integrity of the repository
102 version output version and copyright information
103 version output version and copyright information
103
104
104 additional help topics:
105 additional help topics:
105
106
106 config Configuration Files
107 config Configuration Files
107 dates Date Formats
108 dates Date Formats
108 diffs Diff Formats
109 diffs Diff Formats
109 environment Environment Variables
110 environment Environment Variables
110 extensions Using additional features
111 extensions Using additional features
111 filesets Specifying File Sets
112 filesets Specifying File Sets
112 glossary Glossary
113 glossary Glossary
113 hgignore syntax for Mercurial ignore files
114 hgignore syntax for Mercurial ignore files
114 hgweb Configuring hgweb
115 hgweb Configuring hgweb
115 merge-tools Merge Tools
116 merge-tools Merge Tools
116 multirevs Specifying Multiple Revisions
117 multirevs Specifying Multiple Revisions
117 patterns File Name Patterns
118 patterns File Name Patterns
118 revisions Specifying Single Revisions
119 revisions Specifying Single Revisions
119 revsets Specifying Revision Sets
120 revsets Specifying Revision Sets
120 subrepos Subrepositories
121 subrepos Subrepositories
121 templating Template Usage
122 templating Template Usage
122 urls URL Paths
123 urls URL Paths
123
124
124 use "hg -v help" to show builtin aliases and global options
125 use "hg -v help" to show builtin aliases and global options
125
126
126 $ hg -q help
127 $ hg -q help
127 add add the specified files on the next commit
128 add add the specified files on the next commit
128 addremove add all new files, delete all missing files
129 addremove add all new files, delete all missing files
129 annotate show changeset information by line for each file
130 annotate show changeset information by line for each file
130 archive create an unversioned archive of a repository revision
131 archive create an unversioned archive of a repository revision
131 backout reverse effect of earlier changeset
132 backout reverse effect of earlier changeset
132 bisect subdivision search of changesets
133 bisect subdivision search of changesets
133 bookmarks track a line of development with movable markers
134 bookmarks track a line of development with movable markers
134 branch set or show the current branch name
135 branch set or show the current branch name
135 branches list repository named branches
136 branches list repository named branches
136 bundle create a changegroup file
137 bundle create a changegroup file
137 cat output the current or given revision of files
138 cat output the current or given revision of files
138 clone make a copy of an existing repository
139 clone make a copy of an existing repository
139 commit commit the specified files or all outstanding changes
140 commit commit the specified files or all outstanding changes
140 copy mark files as copied for the next commit
141 copy mark files as copied for the next commit
141 diff diff repository (or selected files)
142 diff diff repository (or selected files)
142 export dump the header and diffs for one or more changesets
143 export dump the header and diffs for one or more changesets
143 forget forget the specified files on the next commit
144 forget forget the specified files on the next commit
145 graft copy changes from other branches onto the current branch
144 grep search for a pattern in specified files and revisions
146 grep search for a pattern in specified files and revisions
145 heads show current repository heads or show branch heads
147 heads show current repository heads or show branch heads
146 help show help for a given topic or a help overview
148 help show help for a given topic or a help overview
147 identify identify the working copy or specified revision
149 identify identify the working copy or specified revision
148 import import an ordered set of patches
150 import import an ordered set of patches
149 incoming show new changesets found in source
151 incoming show new changesets found in source
150 init create a new repository in the given directory
152 init create a new repository in the given directory
151 locate locate files matching specific patterns
153 locate locate files matching specific patterns
152 log show revision history of entire repository or files
154 log show revision history of entire repository or files
153 manifest output the current or given revision of the project manifest
155 manifest output the current or given revision of the project manifest
154 merge merge working directory with another revision
156 merge merge working directory with another revision
155 outgoing show changesets not found in the destination
157 outgoing show changesets not found in the destination
156 parents show the parents of the working directory or revision
158 parents show the parents of the working directory or revision
157 paths show aliases for remote repositories
159 paths show aliases for remote repositories
158 pull pull changes from the specified source
160 pull pull changes from the specified source
159 push push changes to the specified destination
161 push push changes to the specified destination
160 recover roll back an interrupted transaction
162 recover roll back an interrupted transaction
161 remove remove the specified files on the next commit
163 remove remove the specified files on the next commit
162 rename rename files; equivalent of copy + remove
164 rename rename files; equivalent of copy + remove
163 resolve redo merges or set/view the merge status of files
165 resolve redo merges or set/view the merge status of files
164 revert restore files to their checkout state
166 revert restore files to their checkout state
165 rollback roll back the last transaction (dangerous)
167 rollback roll back the last transaction (dangerous)
166 root print the root (top) of the current working directory
168 root print the root (top) of the current working directory
167 serve start stand-alone webserver
169 serve start stand-alone webserver
168 showconfig show combined config settings from all hgrc files
170 showconfig show combined config settings from all hgrc files
169 status show changed files in the working directory
171 status show changed files in the working directory
170 summary summarize working directory state
172 summary summarize working directory state
171 tag add one or more tags for the current or given revision
173 tag add one or more tags for the current or given revision
172 tags list repository tags
174 tags list repository tags
173 tip show the tip revision
175 tip show the tip revision
174 unbundle apply one or more changegroup files
176 unbundle apply one or more changegroup files
175 update update working directory (or switch revisions)
177 update update working directory (or switch revisions)
176 verify verify the integrity of the repository
178 verify verify the integrity of the repository
177 version output version and copyright information
179 version output version and copyright information
178
180
179 additional help topics:
181 additional help topics:
180
182
181 config Configuration Files
183 config Configuration Files
182 dates Date Formats
184 dates Date Formats
183 diffs Diff Formats
185 diffs Diff Formats
184 environment Environment Variables
186 environment Environment Variables
185 extensions Using additional features
187 extensions Using additional features
186 filesets Specifying File Sets
188 filesets Specifying File Sets
187 glossary Glossary
189 glossary Glossary
188 hgignore syntax for Mercurial ignore files
190 hgignore syntax for Mercurial ignore files
189 hgweb Configuring hgweb
191 hgweb Configuring hgweb
190 merge-tools Merge Tools
192 merge-tools Merge Tools
191 multirevs Specifying Multiple Revisions
193 multirevs Specifying Multiple Revisions
192 patterns File Name Patterns
194 patterns File Name Patterns
193 revisions Specifying Single Revisions
195 revisions Specifying Single Revisions
194 revsets Specifying Revision Sets
196 revsets Specifying Revision Sets
195 subrepos Subrepositories
197 subrepos Subrepositories
196 templating Template Usage
198 templating Template Usage
197 urls URL Paths
199 urls URL Paths
198
200
199 Test short command list with verbose option
201 Test short command list with verbose option
200
202
201 $ hg -v help shortlist
203 $ hg -v help shortlist
202 Mercurial Distributed SCM
204 Mercurial Distributed SCM
203
205
204 basic commands:
206 basic commands:
205
207
206 add:
208 add:
207 add the specified files on the next commit
209 add the specified files on the next commit
208 annotate, blame:
210 annotate, blame:
209 show changeset information by line for each file
211 show changeset information by line for each file
210 clone:
212 clone:
211 make a copy of an existing repository
213 make a copy of an existing repository
212 commit, ci:
214 commit, ci:
213 commit the specified files or all outstanding changes
215 commit the specified files or all outstanding changes
214 diff:
216 diff:
215 diff repository (or selected files)
217 diff repository (or selected files)
216 export:
218 export:
217 dump the header and diffs for one or more changesets
219 dump the header and diffs for one or more changesets
218 forget:
220 forget:
219 forget the specified files on the next commit
221 forget the specified files on the next commit
220 init:
222 init:
221 create a new repository in the given directory
223 create a new repository in the given directory
222 log, history:
224 log, history:
223 show revision history of entire repository or files
225 show revision history of entire repository or files
224 merge:
226 merge:
225 merge working directory with another revision
227 merge working directory with another revision
226 pull:
228 pull:
227 pull changes from the specified source
229 pull changes from the specified source
228 push:
230 push:
229 push changes to the specified destination
231 push changes to the specified destination
230 remove, rm:
232 remove, rm:
231 remove the specified files on the next commit
233 remove the specified files on the next commit
232 serve:
234 serve:
233 start stand-alone webserver
235 start stand-alone webserver
234 status, st:
236 status, st:
235 show changed files in the working directory
237 show changed files in the working directory
236 summary, sum:
238 summary, sum:
237 summarize working directory state
239 summarize working directory state
238 update, up, checkout, co:
240 update, up, checkout, co:
239 update working directory (or switch revisions)
241 update working directory (or switch revisions)
240
242
241 global options:
243 global options:
242
244
243 -R --repository REPO repository root directory or name of overlay bundle
245 -R --repository REPO repository root directory or name of overlay bundle
244 file
246 file
245 --cwd DIR change working directory
247 --cwd DIR change working directory
246 -y --noninteractive do not prompt, automatically pick the first choice for
248 -y --noninteractive do not prompt, automatically pick the first choice for
247 all prompts
249 all prompts
248 -q --quiet suppress output
250 -q --quiet suppress output
249 -v --verbose enable additional output
251 -v --verbose enable additional output
250 --config CONFIG [+] set/override config option (use 'section.name=value')
252 --config CONFIG [+] set/override config option (use 'section.name=value')
251 --debug enable debugging output
253 --debug enable debugging output
252 --debugger start debugger
254 --debugger start debugger
253 --encoding ENCODE set the charset encoding (default: ascii)
255 --encoding ENCODE set the charset encoding (default: ascii)
254 --encodingmode MODE set the charset encoding mode (default: strict)
256 --encodingmode MODE set the charset encoding mode (default: strict)
255 --traceback always print a traceback on exception
257 --traceback always print a traceback on exception
256 --time time how long the command takes
258 --time time how long the command takes
257 --profile print command execution profile
259 --profile print command execution profile
258 --version output version information and exit
260 --version output version information and exit
259 -h --help display help and exit
261 -h --help display help and exit
260
262
261 [+] marked option can be specified multiple times
263 [+] marked option can be specified multiple times
262
264
263 use "hg help" for the full list of commands
265 use "hg help" for the full list of commands
264
266
265 $ hg add -h
267 $ hg add -h
266 hg add [OPTION]... [FILE]...
268 hg add [OPTION]... [FILE]...
267
269
268 add the specified files on the next commit
270 add the specified files on the next commit
269
271
270 Schedule files to be version controlled and added to the repository.
272 Schedule files to be version controlled and added to the repository.
271
273
272 The files will be added to the repository at the next commit. To undo an
274 The files will be added to the repository at the next commit. To undo an
273 add before that, see "hg forget".
275 add before that, see "hg forget".
274
276
275 If no names are given, add all files to the repository.
277 If no names are given, add all files to the repository.
276
278
277 Returns 0 if all files are successfully added.
279 Returns 0 if all files are successfully added.
278
280
279 options:
281 options:
280
282
281 -I --include PATTERN [+] include names matching the given patterns
283 -I --include PATTERN [+] include names matching the given patterns
282 -X --exclude PATTERN [+] exclude names matching the given patterns
284 -X --exclude PATTERN [+] exclude names matching the given patterns
283 -S --subrepos recurse into subrepositories
285 -S --subrepos recurse into subrepositories
284 -n --dry-run do not perform actions, just print output
286 -n --dry-run do not perform actions, just print output
285
287
286 [+] marked option can be specified multiple times
288 [+] marked option can be specified multiple times
287
289
288 use "hg -v help add" to show more info
290 use "hg -v help add" to show more info
289
291
290 Verbose help for add
292 Verbose help for add
291
293
292 $ hg add -hv
294 $ hg add -hv
293 hg add [OPTION]... [FILE]...
295 hg add [OPTION]... [FILE]...
294
296
295 add the specified files on the next commit
297 add the specified files on the next commit
296
298
297 Schedule files to be version controlled and added to the repository.
299 Schedule files to be version controlled and added to the repository.
298
300
299 The files will be added to the repository at the next commit. To undo an
301 The files will be added to the repository at the next commit. To undo an
300 add before that, see "hg forget".
302 add before that, see "hg forget".
301
303
302 If no names are given, add all files to the repository.
304 If no names are given, add all files to the repository.
303
305
304 An example showing how new (unknown) files are added automatically by "hg
306 An example showing how new (unknown) files are added automatically by "hg
305 add":
307 add":
306
308
307 $ ls
309 $ ls
308 foo.c
310 foo.c
309 $ hg status
311 $ hg status
310 ? foo.c
312 ? foo.c
311 $ hg add
313 $ hg add
312 adding foo.c
314 adding foo.c
313 $ hg status
315 $ hg status
314 A foo.c
316 A foo.c
315
317
316 Returns 0 if all files are successfully added.
318 Returns 0 if all files are successfully added.
317
319
318 options:
320 options:
319
321
320 -I --include PATTERN [+] include names matching the given patterns
322 -I --include PATTERN [+] include names matching the given patterns
321 -X --exclude PATTERN [+] exclude names matching the given patterns
323 -X --exclude PATTERN [+] exclude names matching the given patterns
322 -S --subrepos recurse into subrepositories
324 -S --subrepos recurse into subrepositories
323 -n --dry-run do not perform actions, just print output
325 -n --dry-run do not perform actions, just print output
324
326
325 [+] marked option can be specified multiple times
327 [+] marked option can be specified multiple times
326
328
327 global options:
329 global options:
328
330
329 -R --repository REPO repository root directory or name of overlay bundle
331 -R --repository REPO repository root directory or name of overlay bundle
330 file
332 file
331 --cwd DIR change working directory
333 --cwd DIR change working directory
332 -y --noninteractive do not prompt, automatically pick the first choice for
334 -y --noninteractive do not prompt, automatically pick the first choice for
333 all prompts
335 all prompts
334 -q --quiet suppress output
336 -q --quiet suppress output
335 -v --verbose enable additional output
337 -v --verbose enable additional output
336 --config CONFIG [+] set/override config option (use 'section.name=value')
338 --config CONFIG [+] set/override config option (use 'section.name=value')
337 --debug enable debugging output
339 --debug enable debugging output
338 --debugger start debugger
340 --debugger start debugger
339 --encoding ENCODE set the charset encoding (default: ascii)
341 --encoding ENCODE set the charset encoding (default: ascii)
340 --encodingmode MODE set the charset encoding mode (default: strict)
342 --encodingmode MODE set the charset encoding mode (default: strict)
341 --traceback always print a traceback on exception
343 --traceback always print a traceback on exception
342 --time time how long the command takes
344 --time time how long the command takes
343 --profile print command execution profile
345 --profile print command execution profile
344 --version output version information and exit
346 --version output version information and exit
345 -h --help display help and exit
347 -h --help display help and exit
346
348
347 [+] marked option can be specified multiple times
349 [+] marked option can be specified multiple times
348
350
349 Test help option with version option
351 Test help option with version option
350
352
351 $ hg add -h --version
353 $ hg add -h --version
352 Mercurial Distributed SCM (version *) (glob)
354 Mercurial Distributed SCM (version *) (glob)
353 (see http://mercurial.selenic.com for more information)
355 (see http://mercurial.selenic.com for more information)
354
356
355 Copyright (C) 2005-2011 Matt Mackall and others
357 Copyright (C) 2005-2011 Matt Mackall and others
356 This is free software; see the source for copying conditions. There is NO
358 This is free software; see the source for copying conditions. There is NO
357 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
359 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
358
360
359 $ hg add --skjdfks
361 $ hg add --skjdfks
360 hg add: option --skjdfks not recognized
362 hg add: option --skjdfks not recognized
361 hg add [OPTION]... [FILE]...
363 hg add [OPTION]... [FILE]...
362
364
363 add the specified files on the next commit
365 add the specified files on the next commit
364
366
365 options:
367 options:
366
368
367 -I --include PATTERN [+] include names matching the given patterns
369 -I --include PATTERN [+] include names matching the given patterns
368 -X --exclude PATTERN [+] exclude names matching the given patterns
370 -X --exclude PATTERN [+] exclude names matching the given patterns
369 -S --subrepos recurse into subrepositories
371 -S --subrepos recurse into subrepositories
370 -n --dry-run do not perform actions, just print output
372 -n --dry-run do not perform actions, just print output
371
373
372 [+] marked option can be specified multiple times
374 [+] marked option can be specified multiple times
373
375
374 use "hg help add" to show the full help text
376 use "hg help add" to show the full help text
375 [255]
377 [255]
376
378
377 Test ambiguous command help
379 Test ambiguous command help
378
380
379 $ hg help ad
381 $ hg help ad
380 list of commands:
382 list of commands:
381
383
382 add add the specified files on the next commit
384 add add the specified files on the next commit
383 addremove add all new files, delete all missing files
385 addremove add all new files, delete all missing files
384
386
385 use "hg -v help ad" to show builtin aliases and global options
387 use "hg -v help ad" to show builtin aliases and global options
386
388
387 Test command without options
389 Test command without options
388
390
389 $ hg help verify
391 $ hg help verify
390 hg verify
392 hg verify
391
393
392 verify the integrity of the repository
394 verify the integrity of the repository
393
395
394 Verify the integrity of the current repository.
396 Verify the integrity of the current repository.
395
397
396 This will perform an extensive check of the repository's integrity,
398 This will perform an extensive check of the repository's integrity,
397 validating the hashes and checksums of each entry in the changelog,
399 validating the hashes and checksums of each entry in the changelog,
398 manifest, and tracked files, as well as the integrity of their crosslinks
400 manifest, and tracked files, as well as the integrity of their crosslinks
399 and indices.
401 and indices.
400
402
401 Returns 0 on success, 1 if errors are encountered.
403 Returns 0 on success, 1 if errors are encountered.
402
404
403 use "hg -v help verify" to show more info
405 use "hg -v help verify" to show more info
404
406
405 $ hg help diff
407 $ hg help diff
406 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
408 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
407
409
408 diff repository (or selected files)
410 diff repository (or selected files)
409
411
410 Show differences between revisions for the specified files.
412 Show differences between revisions for the specified files.
411
413
412 Differences between files are shown using the unified diff format.
414 Differences between files are shown using the unified diff format.
413
415
414 Note:
416 Note:
415 diff may generate unexpected results for merges, as it will default to
417 diff may generate unexpected results for merges, as it will default to
416 comparing against the working directory's first parent changeset if no
418 comparing against the working directory's first parent changeset if no
417 revisions are specified.
419 revisions are specified.
418
420
419 When two revision arguments are given, then changes are shown between
421 When two revision arguments are given, then changes are shown between
420 those revisions. If only one revision is specified then that revision is
422 those revisions. If only one revision is specified then that revision is
421 compared to the working directory, and, when no revisions are specified,
423 compared to the working directory, and, when no revisions are specified,
422 the working directory files are compared to its parent.
424 the working directory files are compared to its parent.
423
425
424 Alternatively you can specify -c/--change with a revision to see the
426 Alternatively you can specify -c/--change with a revision to see the
425 changes in that changeset relative to its first parent.
427 changes in that changeset relative to its first parent.
426
428
427 Without the -a/--text option, diff will avoid generating diffs of files it
429 Without the -a/--text option, diff will avoid generating diffs of files it
428 detects as binary. With -a, diff will generate a diff anyway, probably
430 detects as binary. With -a, diff will generate a diff anyway, probably
429 with undesirable results.
431 with undesirable results.
430
432
431 Use the -g/--git option to generate diffs in the git extended diff format.
433 Use the -g/--git option to generate diffs in the git extended diff format.
432 For more information, read "hg help diffs".
434 For more information, read "hg help diffs".
433
435
434 Returns 0 on success.
436 Returns 0 on success.
435
437
436 options:
438 options:
437
439
438 -r --rev REV [+] revision
440 -r --rev REV [+] revision
439 -c --change REV change made by revision
441 -c --change REV change made by revision
440 -a --text treat all files as text
442 -a --text treat all files as text
441 -g --git use git extended diff format
443 -g --git use git extended diff format
442 --nodates omit dates from diff headers
444 --nodates omit dates from diff headers
443 -p --show-function show which function each change is in
445 -p --show-function show which function each change is in
444 --reverse produce a diff that undoes the changes
446 --reverse produce a diff that undoes the changes
445 -w --ignore-all-space ignore white space when comparing lines
447 -w --ignore-all-space ignore white space when comparing lines
446 -b --ignore-space-change ignore changes in the amount of white space
448 -b --ignore-space-change ignore changes in the amount of white space
447 -B --ignore-blank-lines ignore changes whose lines are all blank
449 -B --ignore-blank-lines ignore changes whose lines are all blank
448 -U --unified NUM number of lines of context to show
450 -U --unified NUM number of lines of context to show
449 --stat output diffstat-style summary of changes
451 --stat output diffstat-style summary of changes
450 -I --include PATTERN [+] include names matching the given patterns
452 -I --include PATTERN [+] include names matching the given patterns
451 -X --exclude PATTERN [+] exclude names matching the given patterns
453 -X --exclude PATTERN [+] exclude names matching the given patterns
452 -S --subrepos recurse into subrepositories
454 -S --subrepos recurse into subrepositories
453
455
454 [+] marked option can be specified multiple times
456 [+] marked option can be specified multiple times
455
457
456 use "hg -v help diff" to show more info
458 use "hg -v help diff" to show more info
457
459
458 $ hg help status
460 $ hg help status
459 hg status [OPTION]... [FILE]...
461 hg status [OPTION]... [FILE]...
460
462
461 aliases: st
463 aliases: st
462
464
463 show changed files in the working directory
465 show changed files in the working directory
464
466
465 Show status of files in the repository. If names are given, only files
467 Show status of files in the repository. If names are given, only files
466 that match are shown. Files that are clean or ignored or the source of a
468 that match are shown. Files that are clean or ignored or the source of a
467 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
469 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
468 -C/--copies or -A/--all are given. Unless options described with "show
470 -C/--copies or -A/--all are given. Unless options described with "show
469 only ..." are given, the options -mardu are used.
471 only ..." are given, the options -mardu are used.
470
472
471 Option -q/--quiet hides untracked (unknown and ignored) files unless
473 Option -q/--quiet hides untracked (unknown and ignored) files unless
472 explicitly requested with -u/--unknown or -i/--ignored.
474 explicitly requested with -u/--unknown or -i/--ignored.
473
475
474 Note:
476 Note:
475 status may appear to disagree with diff if permissions have changed or
477 status may appear to disagree with diff if permissions have changed or
476 a merge has occurred. The standard diff format does not report
478 a merge has occurred. The standard diff format does not report
477 permission changes and diff only reports changes relative to one merge
479 permission changes and diff only reports changes relative to one merge
478 parent.
480 parent.
479
481
480 If one revision is given, it is used as the base revision. If two
482 If one revision is given, it is used as the base revision. If two
481 revisions are given, the differences between them are shown. The --change
483 revisions are given, the differences between them are shown. The --change
482 option can also be used as a shortcut to list the changed files of a
484 option can also be used as a shortcut to list the changed files of a
483 revision from its first parent.
485 revision from its first parent.
484
486
485 The codes used to show the status of files are:
487 The codes used to show the status of files are:
486
488
487 M = modified
489 M = modified
488 A = added
490 A = added
489 R = removed
491 R = removed
490 C = clean
492 C = clean
491 ! = missing (deleted by non-hg command, but still tracked)
493 ! = missing (deleted by non-hg command, but still tracked)
492 ? = not tracked
494 ? = not tracked
493 I = ignored
495 I = ignored
494 = origin of the previous file listed as A (added)
496 = origin of the previous file listed as A (added)
495
497
496 Returns 0 on success.
498 Returns 0 on success.
497
499
498 options:
500 options:
499
501
500 -A --all show status of all files
502 -A --all show status of all files
501 -m --modified show only modified files
503 -m --modified show only modified files
502 -a --added show only added files
504 -a --added show only added files
503 -r --removed show only removed files
505 -r --removed show only removed files
504 -d --deleted show only deleted (but tracked) files
506 -d --deleted show only deleted (but tracked) files
505 -c --clean show only files without changes
507 -c --clean show only files without changes
506 -u --unknown show only unknown (not tracked) files
508 -u --unknown show only unknown (not tracked) files
507 -i --ignored show only ignored files
509 -i --ignored show only ignored files
508 -n --no-status hide status prefix
510 -n --no-status hide status prefix
509 -C --copies show source of copied files
511 -C --copies show source of copied files
510 -0 --print0 end filenames with NUL, for use with xargs
512 -0 --print0 end filenames with NUL, for use with xargs
511 --rev REV [+] show difference from revision
513 --rev REV [+] show difference from revision
512 --change REV list the changed files of a revision
514 --change REV list the changed files of a revision
513 -I --include PATTERN [+] include names matching the given patterns
515 -I --include PATTERN [+] include names matching the given patterns
514 -X --exclude PATTERN [+] exclude names matching the given patterns
516 -X --exclude PATTERN [+] exclude names matching the given patterns
515 -S --subrepos recurse into subrepositories
517 -S --subrepos recurse into subrepositories
516
518
517 [+] marked option can be specified multiple times
519 [+] marked option can be specified multiple times
518
520
519 use "hg -v help status" to show more info
521 use "hg -v help status" to show more info
520
522
521 $ hg -q help status
523 $ hg -q help status
522 hg status [OPTION]... [FILE]...
524 hg status [OPTION]... [FILE]...
523
525
524 show changed files in the working directory
526 show changed files in the working directory
525
527
526 $ hg help foo
528 $ hg help foo
527 hg: unknown command 'foo'
529 hg: unknown command 'foo'
528 Mercurial Distributed SCM
530 Mercurial Distributed SCM
529
531
530 basic commands:
532 basic commands:
531
533
532 add add the specified files on the next commit
534 add add the specified files on the next commit
533 annotate show changeset information by line for each file
535 annotate show changeset information by line for each file
534 clone make a copy of an existing repository
536 clone make a copy of an existing repository
535 commit commit the specified files or all outstanding changes
537 commit commit the specified files or all outstanding changes
536 diff diff repository (or selected files)
538 diff diff repository (or selected files)
537 export dump the header and diffs for one or more changesets
539 export dump the header and diffs for one or more changesets
538 forget forget the specified files on the next commit
540 forget forget the specified files on the next commit
539 init create a new repository in the given directory
541 init create a new repository in the given directory
540 log show revision history of entire repository or files
542 log show revision history of entire repository or files
541 merge merge working directory with another revision
543 merge merge working directory with another revision
542 pull pull changes from the specified source
544 pull pull changes from the specified source
543 push push changes to the specified destination
545 push push changes to the specified destination
544 remove remove the specified files on the next commit
546 remove remove the specified files on the next commit
545 serve start stand-alone webserver
547 serve start stand-alone webserver
546 status show changed files in the working directory
548 status show changed files in the working directory
547 summary summarize working directory state
549 summary summarize working directory state
548 update update working directory (or switch revisions)
550 update update working directory (or switch revisions)
549
551
550 use "hg help" for the full list of commands or "hg -v" for details
552 use "hg help" for the full list of commands or "hg -v" for details
551 [255]
553 [255]
552
554
553 $ hg skjdfks
555 $ hg skjdfks
554 hg: unknown command 'skjdfks'
556 hg: unknown command 'skjdfks'
555 Mercurial Distributed SCM
557 Mercurial Distributed SCM
556
558
557 basic commands:
559 basic commands:
558
560
559 add add the specified files on the next commit
561 add add the specified files on the next commit
560 annotate show changeset information by line for each file
562 annotate show changeset information by line for each file
561 clone make a copy of an existing repository
563 clone make a copy of an existing repository
562 commit commit the specified files or all outstanding changes
564 commit commit the specified files or all outstanding changes
563 diff diff repository (or selected files)
565 diff diff repository (or selected files)
564 export dump the header and diffs for one or more changesets
566 export dump the header and diffs for one or more changesets
565 forget forget the specified files on the next commit
567 forget forget the specified files on the next commit
566 init create a new repository in the given directory
568 init create a new repository in the given directory
567 log show revision history of entire repository or files
569 log show revision history of entire repository or files
568 merge merge working directory with another revision
570 merge merge working directory with another revision
569 pull pull changes from the specified source
571 pull pull changes from the specified source
570 push push changes to the specified destination
572 push push changes to the specified destination
571 remove remove the specified files on the next commit
573 remove remove the specified files on the next commit
572 serve start stand-alone webserver
574 serve start stand-alone webserver
573 status show changed files in the working directory
575 status show changed files in the working directory
574 summary summarize working directory state
576 summary summarize working directory state
575 update update working directory (or switch revisions)
577 update update working directory (or switch revisions)
576
578
577 use "hg help" for the full list of commands or "hg -v" for details
579 use "hg help" for the full list of commands or "hg -v" for details
578 [255]
580 [255]
579
581
580 $ cat > helpext.py <<EOF
582 $ cat > helpext.py <<EOF
581 > import os
583 > import os
582 > from mercurial import commands
584 > from mercurial import commands
583 >
585 >
584 > def nohelp(ui, *args, **kwargs):
586 > def nohelp(ui, *args, **kwargs):
585 > pass
587 > pass
586 >
588 >
587 > cmdtable = {
589 > cmdtable = {
588 > "nohelp": (nohelp, [], "hg nohelp"),
590 > "nohelp": (nohelp, [], "hg nohelp"),
589 > }
591 > }
590 >
592 >
591 > commands.norepo += ' nohelp'
593 > commands.norepo += ' nohelp'
592 > EOF
594 > EOF
593 $ echo '[extensions]' >> $HGRCPATH
595 $ echo '[extensions]' >> $HGRCPATH
594 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
596 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
595
597
596 Test command with no help text
598 Test command with no help text
597
599
598 $ hg help nohelp
600 $ hg help nohelp
599 hg nohelp
601 hg nohelp
600
602
601 (no help text available)
603 (no help text available)
602
604
603 use "hg -v help nohelp" to show more info
605 use "hg -v help nohelp" to show more info
604
606
605 Test that default list of commands omits extension commands
607 Test that default list of commands omits extension commands
606
608
607 $ hg help
609 $ hg help
608 Mercurial Distributed SCM
610 Mercurial Distributed SCM
609
611
610 list of commands:
612 list of commands:
611
613
612 add add the specified files on the next commit
614 add add the specified files on the next commit
613 addremove add all new files, delete all missing files
615 addremove add all new files, delete all missing files
614 annotate show changeset information by line for each file
616 annotate show changeset information by line for each file
615 archive create an unversioned archive of a repository revision
617 archive create an unversioned archive of a repository revision
616 backout reverse effect of earlier changeset
618 backout reverse effect of earlier changeset
617 bisect subdivision search of changesets
619 bisect subdivision search of changesets
618 bookmarks track a line of development with movable markers
620 bookmarks track a line of development with movable markers
619 branch set or show the current branch name
621 branch set or show the current branch name
620 branches list repository named branches
622 branches list repository named branches
621 bundle create a changegroup file
623 bundle create a changegroup file
622 cat output the current or given revision of files
624 cat output the current or given revision of files
623 clone make a copy of an existing repository
625 clone make a copy of an existing repository
624 commit commit the specified files or all outstanding changes
626 commit commit the specified files or all outstanding changes
625 copy mark files as copied for the next commit
627 copy mark files as copied for the next commit
626 diff diff repository (or selected files)
628 diff diff repository (or selected files)
627 export dump the header and diffs for one or more changesets
629 export dump the header and diffs for one or more changesets
628 forget forget the specified files on the next commit
630 forget forget the specified files on the next commit
631 graft copy changes from other branches onto the current branch
629 grep search for a pattern in specified files and revisions
632 grep search for a pattern in specified files and revisions
630 heads show current repository heads or show branch heads
633 heads show current repository heads or show branch heads
631 help show help for a given topic or a help overview
634 help show help for a given topic or a help overview
632 identify identify the working copy or specified revision
635 identify identify the working copy or specified revision
633 import import an ordered set of patches
636 import import an ordered set of patches
634 incoming show new changesets found in source
637 incoming show new changesets found in source
635 init create a new repository in the given directory
638 init create a new repository in the given directory
636 locate locate files matching specific patterns
639 locate locate files matching specific patterns
637 log show revision history of entire repository or files
640 log show revision history of entire repository or files
638 manifest output the current or given revision of the project manifest
641 manifest output the current or given revision of the project manifest
639 merge merge working directory with another revision
642 merge merge working directory with another revision
640 outgoing show changesets not found in the destination
643 outgoing show changesets not found in the destination
641 parents show the parents of the working directory or revision
644 parents show the parents of the working directory or revision
642 paths show aliases for remote repositories
645 paths show aliases for remote repositories
643 pull pull changes from the specified source
646 pull pull changes from the specified source
644 push push changes to the specified destination
647 push push changes to the specified destination
645 recover roll back an interrupted transaction
648 recover roll back an interrupted transaction
646 remove remove the specified files on the next commit
649 remove remove the specified files on the next commit
647 rename rename files; equivalent of copy + remove
650 rename rename files; equivalent of copy + remove
648 resolve redo merges or set/view the merge status of files
651 resolve redo merges or set/view the merge status of files
649 revert restore files to their checkout state
652 revert restore files to their checkout state
650 rollback roll back the last transaction (dangerous)
653 rollback roll back the last transaction (dangerous)
651 root print the root (top) of the current working directory
654 root print the root (top) of the current working directory
652 serve start stand-alone webserver
655 serve start stand-alone webserver
653 showconfig show combined config settings from all hgrc files
656 showconfig show combined config settings from all hgrc files
654 status show changed files in the working directory
657 status show changed files in the working directory
655 summary summarize working directory state
658 summary summarize working directory state
656 tag add one or more tags for the current or given revision
659 tag add one or more tags for the current or given revision
657 tags list repository tags
660 tags list repository tags
658 tip show the tip revision
661 tip show the tip revision
659 unbundle apply one or more changegroup files
662 unbundle apply one or more changegroup files
660 update update working directory (or switch revisions)
663 update update working directory (or switch revisions)
661 verify verify the integrity of the repository
664 verify verify the integrity of the repository
662 version output version and copyright information
665 version output version and copyright information
663
666
664 enabled extensions:
667 enabled extensions:
665
668
666 helpext (no help text available)
669 helpext (no help text available)
667
670
668 additional help topics:
671 additional help topics:
669
672
670 config Configuration Files
673 config Configuration Files
671 dates Date Formats
674 dates Date Formats
672 diffs Diff Formats
675 diffs Diff Formats
673 environment Environment Variables
676 environment Environment Variables
674 extensions Using additional features
677 extensions Using additional features
675 filesets Specifying File Sets
678 filesets Specifying File Sets
676 glossary Glossary
679 glossary Glossary
677 hgignore syntax for Mercurial ignore files
680 hgignore syntax for Mercurial ignore files
678 hgweb Configuring hgweb
681 hgweb Configuring hgweb
679 merge-tools Merge Tools
682 merge-tools Merge Tools
680 multirevs Specifying Multiple Revisions
683 multirevs Specifying Multiple Revisions
681 patterns File Name Patterns
684 patterns File Name Patterns
682 revisions Specifying Single Revisions
685 revisions Specifying Single Revisions
683 revsets Specifying Revision Sets
686 revsets Specifying Revision Sets
684 subrepos Subrepositories
687 subrepos Subrepositories
685 templating Template Usage
688 templating Template Usage
686 urls URL Paths
689 urls URL Paths
687
690
688 use "hg -v help" to show builtin aliases and global options
691 use "hg -v help" to show builtin aliases and global options
689
692
690
693
691
694
692 Test list of commands with command with no help text
695 Test list of commands with command with no help text
693
696
694 $ hg help helpext
697 $ hg help helpext
695 helpext extension - no help text available
698 helpext extension - no help text available
696
699
697 list of commands:
700 list of commands:
698
701
699 nohelp (no help text available)
702 nohelp (no help text available)
700
703
701 use "hg -v help helpext" to show builtin aliases and global options
704 use "hg -v help helpext" to show builtin aliases and global options
702
705
703 Test a help topic
706 Test a help topic
704
707
705 $ hg help revs
708 $ hg help revs
706 Specifying Single Revisions
709 Specifying Single Revisions
707
710
708 Mercurial supports several ways to specify individual revisions.
711 Mercurial supports several ways to specify individual revisions.
709
712
710 A plain integer is treated as a revision number. Negative integers are
713 A plain integer is treated as a revision number. Negative integers are
711 treated as sequential offsets from the tip, with -1 denoting the tip, -2
714 treated as sequential offsets from the tip, with -1 denoting the tip, -2
712 denoting the revision prior to the tip, and so forth.
715 denoting the revision prior to the tip, and so forth.
713
716
714 A 40-digit hexadecimal string is treated as a unique revision identifier.
717 A 40-digit hexadecimal string is treated as a unique revision identifier.
715
718
716 A hexadecimal string less than 40 characters long is treated as a unique
719 A hexadecimal string less than 40 characters long is treated as a unique
717 revision identifier and is referred to as a short-form identifier. A
720 revision identifier and is referred to as a short-form identifier. A
718 short-form identifier is only valid if it is the prefix of exactly one
721 short-form identifier is only valid if it is the prefix of exactly one
719 full-length identifier.
722 full-length identifier.
720
723
721 Any other string is treated as a tag or branch name. A tag name is a
724 Any other string is treated as a tag or branch name. A tag name is a
722 symbolic name associated with a revision identifier. A branch name denotes
725 symbolic name associated with a revision identifier. A branch name denotes
723 the tipmost revision of that branch. Tag and branch names must not contain
726 the tipmost revision of that branch. Tag and branch names must not contain
724 the ":" character.
727 the ":" character.
725
728
726 The reserved name "tip" is a special tag that always identifies the most
729 The reserved name "tip" is a special tag that always identifies the most
727 recent revision.
730 recent revision.
728
731
729 The reserved name "null" indicates the null revision. This is the revision
732 The reserved name "null" indicates the null revision. This is the revision
730 of an empty repository, and the parent of revision 0.
733 of an empty repository, and the parent of revision 0.
731
734
732 The reserved name "." indicates the working directory parent. If no
735 The reserved name "." indicates the working directory parent. If no
733 working directory is checked out, it is equivalent to null. If an
736 working directory is checked out, it is equivalent to null. If an
734 uncommitted merge is in progress, "." is the revision of the first parent.
737 uncommitted merge is in progress, "." is the revision of the first parent.
735
738
736 Test templating help
739 Test templating help
737
740
738 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
741 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
739 desc String. The text of the changeset description.
742 desc String. The text of the changeset description.
740 diffstat String. Statistics of changes with the following format:
743 diffstat String. Statistics of changes with the following format:
741 firstline Any text. Returns the first line of text.
744 firstline Any text. Returns the first line of text.
742 nonempty Any text. Returns '(none)' if the string is empty.
745 nonempty Any text. Returns '(none)' if the string is empty.
743
746
744 Test help hooks
747 Test help hooks
745
748
746 $ cat > helphook1.py <<EOF
749 $ cat > helphook1.py <<EOF
747 > from mercurial import help
750 > from mercurial import help
748 >
751 >
749 > def rewrite(topic, doc):
752 > def rewrite(topic, doc):
750 > return doc + '\nhelphook1\n'
753 > return doc + '\nhelphook1\n'
751 >
754 >
752 > def extsetup(ui):
755 > def extsetup(ui):
753 > help.addtopichook('revsets', rewrite)
756 > help.addtopichook('revsets', rewrite)
754 > EOF
757 > EOF
755 $ cat > helphook2.py <<EOF
758 $ cat > helphook2.py <<EOF
756 > from mercurial import help
759 > from mercurial import help
757 >
760 >
758 > def rewrite(topic, doc):
761 > def rewrite(topic, doc):
759 > return doc + '\nhelphook2\n'
762 > return doc + '\nhelphook2\n'
760 >
763 >
761 > def extsetup(ui):
764 > def extsetup(ui):
762 > help.addtopichook('revsets', rewrite)
765 > help.addtopichook('revsets', rewrite)
763 > EOF
766 > EOF
764 $ echo '[extensions]' >> $HGRCPATH
767 $ echo '[extensions]' >> $HGRCPATH
765 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
768 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
766 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
769 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
767 $ hg help revsets | grep helphook
770 $ hg help revsets | grep helphook
768 helphook1
771 helphook1
769 helphook2
772 helphook2
General Comments 0
You need to be logged in to leave comments. Login now