##// END OF EJS Templates
revert: rewrite help summary...
Matt Mackall -
r14540:944d9088 default
parent child Browse files
Show More
@@ -1,5089 +1,5089 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, sys, difflib, time, tempfile, errno
11 import os, re, sys, 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, sshserver, hbisect, hgweb, hgweb.server
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 import merge as mergemod
15 import merge as mergemod
16 import minirst, revset, fileset
16 import minirst, revset, fileset
17 import dagparser, context, simplemerge
17 import dagparser, context, simplemerge
18 import random, setdiscovery, treediscovery, dagutil
18 import random, setdiscovery, treediscovery, dagutil
19
19
20 table = {}
20 table = {}
21
21
22 command = cmdutil.command(table)
22 command = cmdutil.command(table)
23
23
24 # common command options
24 # common command options
25
25
26 globalopts = [
26 globalopts = [
27 ('R', 'repository', '',
27 ('R', 'repository', '',
28 _('repository root directory or name of overlay bundle file'),
28 _('repository root directory or name of overlay bundle file'),
29 _('REPO')),
29 _('REPO')),
30 ('', 'cwd', '',
30 ('', 'cwd', '',
31 _('change working directory'), _('DIR')),
31 _('change working directory'), _('DIR')),
32 ('y', 'noninteractive', None,
32 ('y', 'noninteractive', None,
33 _('do not prompt, assume \'yes\' for any required answers')),
33 _('do not prompt, assume \'yes\' for any required answers')),
34 ('q', 'quiet', None, _('suppress output')),
34 ('q', 'quiet', None, _('suppress output')),
35 ('v', 'verbose', None, _('enable additional output')),
35 ('v', 'verbose', None, _('enable additional output')),
36 ('', 'config', [],
36 ('', 'config', [],
37 _('set/override config option (use \'section.name=value\')'),
37 _('set/override config option (use \'section.name=value\')'),
38 _('CONFIG')),
38 _('CONFIG')),
39 ('', 'debug', None, _('enable debugging output')),
39 ('', 'debug', None, _('enable debugging output')),
40 ('', 'debugger', None, _('start debugger')),
40 ('', 'debugger', None, _('start debugger')),
41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 _('ENCODE')),
42 _('ENCODE')),
43 ('', 'encodingmode', encoding.encodingmode,
43 ('', 'encodingmode', encoding.encodingmode,
44 _('set the charset encoding mode'), _('MODE')),
44 _('set the charset encoding mode'), _('MODE')),
45 ('', 'traceback', None, _('always print a traceback on exception')),
45 ('', 'traceback', None, _('always print a traceback on exception')),
46 ('', 'time', None, _('time how long the command takes')),
46 ('', 'time', None, _('time how long the command takes')),
47 ('', 'profile', None, _('print command execution profile')),
47 ('', 'profile', None, _('print command execution profile')),
48 ('', 'version', None, _('output version information and exit')),
48 ('', 'version', None, _('output version information and exit')),
49 ('h', 'help', None, _('display help and exit')),
49 ('h', 'help', None, _('display help and exit')),
50 ]
50 ]
51
51
52 dryrunopts = [('n', 'dry-run', None,
52 dryrunopts = [('n', 'dry-run', None,
53 _('do not perform actions, just print output'))]
53 _('do not perform actions, just print output'))]
54
54
55 remoteopts = [
55 remoteopts = [
56 ('e', 'ssh', '',
56 ('e', 'ssh', '',
57 _('specify ssh command to use'), _('CMD')),
57 _('specify ssh command to use'), _('CMD')),
58 ('', 'remotecmd', '',
58 ('', 'remotecmd', '',
59 _('specify hg command to run on the remote side'), _('CMD')),
59 _('specify hg command to run on the remote side'), _('CMD')),
60 ('', 'insecure', None,
60 ('', 'insecure', None,
61 _('do not verify server certificate (ignoring web.cacerts config)')),
61 _('do not verify server certificate (ignoring web.cacerts config)')),
62 ]
62 ]
63
63
64 walkopts = [
64 walkopts = [
65 ('I', 'include', [],
65 ('I', 'include', [],
66 _('include names matching the given patterns'), _('PATTERN')),
66 _('include names matching the given patterns'), _('PATTERN')),
67 ('X', 'exclude', [],
67 ('X', 'exclude', [],
68 _('exclude names matching the given patterns'), _('PATTERN')),
68 _('exclude names matching the given patterns'), _('PATTERN')),
69 ]
69 ]
70
70
71 commitopts = [
71 commitopts = [
72 ('m', 'message', '',
72 ('m', 'message', '',
73 _('use text as commit message'), _('TEXT')),
73 _('use text as commit message'), _('TEXT')),
74 ('l', 'logfile', '',
74 ('l', 'logfile', '',
75 _('read commit message from file'), _('FILE')),
75 _('read commit message from file'), _('FILE')),
76 ]
76 ]
77
77
78 commitopts2 = [
78 commitopts2 = [
79 ('d', 'date', '',
79 ('d', 'date', '',
80 _('record the specified date as commit date'), _('DATE')),
80 _('record the specified date as commit date'), _('DATE')),
81 ('u', 'user', '',
81 ('u', 'user', '',
82 _('record the specified user as committer'), _('USER')),
82 _('record the specified user as committer'), _('USER')),
83 ]
83 ]
84
84
85 templateopts = [
85 templateopts = [
86 ('', 'style', '',
86 ('', 'style', '',
87 _('display using template map file'), _('STYLE')),
87 _('display using template map file'), _('STYLE')),
88 ('', 'template', '',
88 ('', 'template', '',
89 _('display with template'), _('TEMPLATE')),
89 _('display with template'), _('TEMPLATE')),
90 ]
90 ]
91
91
92 logopts = [
92 logopts = [
93 ('p', 'patch', None, _('show patch')),
93 ('p', 'patch', None, _('show patch')),
94 ('g', 'git', None, _('use git extended diff format')),
94 ('g', 'git', None, _('use git extended diff format')),
95 ('l', 'limit', '',
95 ('l', 'limit', '',
96 _('limit number of changes displayed'), _('NUM')),
96 _('limit number of changes displayed'), _('NUM')),
97 ('M', 'no-merges', None, _('do not show merges')),
97 ('M', 'no-merges', None, _('do not show merges')),
98 ('', 'stat', None, _('output diffstat-style summary of changes')),
98 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 ] + templateopts
99 ] + templateopts
100
100
101 diffopts = [
101 diffopts = [
102 ('a', 'text', None, _('treat all files as text')),
102 ('a', 'text', None, _('treat all files as text')),
103 ('g', 'git', None, _('use git extended diff format')),
103 ('g', 'git', None, _('use git extended diff format')),
104 ('', 'nodates', None, _('omit dates from diff headers'))
104 ('', 'nodates', None, _('omit dates from diff headers'))
105 ]
105 ]
106
106
107 diffopts2 = [
107 diffopts2 = [
108 ('p', 'show-function', None, _('show which function each change is in')),
108 ('p', 'show-function', None, _('show which function each change is in')),
109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 ('w', 'ignore-all-space', None,
110 ('w', 'ignore-all-space', None,
111 _('ignore white space when comparing lines')),
111 _('ignore white space when comparing lines')),
112 ('b', 'ignore-space-change', None,
112 ('b', 'ignore-space-change', None,
113 _('ignore changes in the amount of white space')),
113 _('ignore changes in the amount of white space')),
114 ('B', 'ignore-blank-lines', None,
114 ('B', 'ignore-blank-lines', None,
115 _('ignore changes whose lines are all blank')),
115 _('ignore changes whose lines are all blank')),
116 ('U', 'unified', '',
116 ('U', 'unified', '',
117 _('number of lines of context to show'), _('NUM')),
117 _('number of lines of context to show'), _('NUM')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ]
119 ]
120
120
121 similarityopts = [
121 similarityopts = [
122 ('s', 'similarity', '',
122 ('s', 'similarity', '',
123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
124 ]
124 ]
125
125
126 subrepoopts = [
126 subrepoopts = [
127 ('S', 'subrepos', None,
127 ('S', 'subrepos', None,
128 _('recurse into subrepositories'))
128 _('recurse into subrepositories'))
129 ]
129 ]
130
130
131 # Commands start here, listed alphabetically
131 # Commands start here, listed alphabetically
132
132
133 @command('^add',
133 @command('^add',
134 walkopts + subrepoopts + dryrunopts,
134 walkopts + subrepoopts + dryrunopts,
135 _('[OPTION]... [FILE]...'))
135 _('[OPTION]... [FILE]...'))
136 def add(ui, repo, *pats, **opts):
136 def add(ui, repo, *pats, **opts):
137 """add the specified files on the next commit
137 """add the specified files on the next commit
138
138
139 Schedule files to be version controlled and added to the
139 Schedule files to be version controlled and added to the
140 repository.
140 repository.
141
141
142 The files will be added to the repository at the next commit. To
142 The files will be added to the repository at the next commit. To
143 undo an add before that, see :hg:`forget`.
143 undo an add before that, see :hg:`forget`.
144
144
145 If no names are given, add all files to the repository.
145 If no names are given, add all files to the repository.
146
146
147 .. container:: verbose
147 .. container:: verbose
148
148
149 An example showing how new (unknown) files are added
149 An example showing how new (unknown) files are added
150 automatically by :hg:`add`::
150 automatically by :hg:`add`::
151
151
152 $ ls
152 $ ls
153 foo.c
153 foo.c
154 $ hg status
154 $ hg status
155 ? foo.c
155 ? foo.c
156 $ hg add
156 $ hg add
157 adding foo.c
157 adding foo.c
158 $ hg status
158 $ hg status
159 A foo.c
159 A foo.c
160
160
161 Returns 0 if all files are successfully added.
161 Returns 0 if all files are successfully added.
162 """
162 """
163
163
164 m = scmutil.match(repo, pats, opts)
164 m = scmutil.match(repo, pats, opts)
165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
166 opts.get('subrepos'), prefix="")
166 opts.get('subrepos'), prefix="")
167 return rejected and 1 or 0
167 return rejected and 1 or 0
168
168
169 @command('addremove',
169 @command('addremove',
170 similarityopts + walkopts + dryrunopts,
170 similarityopts + walkopts + dryrunopts,
171 _('[OPTION]... [FILE]...'))
171 _('[OPTION]... [FILE]...'))
172 def addremove(ui, repo, *pats, **opts):
172 def addremove(ui, repo, *pats, **opts):
173 """add all new files, delete all missing files
173 """add all new files, delete all missing files
174
174
175 Add all new files and remove all missing files from the
175 Add all new files and remove all missing files from the
176 repository.
176 repository.
177
177
178 New files are ignored if they match any of the patterns in
178 New files are ignored if they match any of the patterns in
179 ``.hgignore``. As with add, these changes take effect at the next
179 ``.hgignore``. As with add, these changes take effect at the next
180 commit.
180 commit.
181
181
182 Use the -s/--similarity option to detect renamed files. With a
182 Use the -s/--similarity option to detect renamed files. With a
183 parameter greater than 0, this compares every removed file with
183 parameter greater than 0, this compares every removed file with
184 every added file and records those similar enough as renames. This
184 every added file and records those similar enough as renames. This
185 option takes a percentage between 0 (disabled) and 100 (files must
185 option takes a percentage between 0 (disabled) and 100 (files must
186 be identical) as its parameter. Detecting renamed files this way
186 be identical) as its parameter. Detecting renamed files this way
187 can be expensive. After using this option, :hg:`status -C` can be
187 can be expensive. After using this option, :hg:`status -C` can be
188 used to check which files were identified as moved or renamed.
188 used to check which files were identified as moved or renamed.
189
189
190 Returns 0 if all files are successfully added.
190 Returns 0 if all files are successfully added.
191 """
191 """
192 try:
192 try:
193 sim = float(opts.get('similarity') or 100)
193 sim = float(opts.get('similarity') or 100)
194 except ValueError:
194 except ValueError:
195 raise util.Abort(_('similarity must be a number'))
195 raise util.Abort(_('similarity must be a number'))
196 if sim < 0 or sim > 100:
196 if sim < 0 or sim > 100:
197 raise util.Abort(_('similarity must be between 0 and 100'))
197 raise util.Abort(_('similarity must be between 0 and 100'))
198 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
198 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
199
199
200 @command('^annotate|blame',
200 @command('^annotate|blame',
201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
202 ('', 'follow', None,
202 ('', 'follow', None,
203 _('follow copies/renames and list the filename (DEPRECATED)')),
203 _('follow copies/renames and list the filename (DEPRECATED)')),
204 ('', 'no-follow', None, _("don't follow copies and renames")),
204 ('', 'no-follow', None, _("don't follow copies and renames")),
205 ('a', 'text', None, _('treat all files as text')),
205 ('a', 'text', None, _('treat all files as text')),
206 ('u', 'user', None, _('list the author (long with -v)')),
206 ('u', 'user', None, _('list the author (long with -v)')),
207 ('f', 'file', None, _('list the filename')),
207 ('f', 'file', None, _('list the filename')),
208 ('d', 'date', None, _('list the date (short with -q)')),
208 ('d', 'date', None, _('list the date (short with -q)')),
209 ('n', 'number', None, _('list the revision number (default)')),
209 ('n', 'number', None, _('list the revision number (default)')),
210 ('c', 'changeset', None, _('list the changeset')),
210 ('c', 'changeset', None, _('list the changeset')),
211 ('l', 'line-number', None, _('show line number at the first appearance'))
211 ('l', 'line-number', None, _('show line number at the first appearance'))
212 ] + walkopts,
212 ] + walkopts,
213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
214 def annotate(ui, repo, *pats, **opts):
214 def annotate(ui, repo, *pats, **opts):
215 """show changeset information by line for each file
215 """show changeset information by line for each file
216
216
217 List changes in files, showing the revision id responsible for
217 List changes in files, showing the revision id responsible for
218 each line
218 each line
219
219
220 This command is useful for discovering when a change was made and
220 This command is useful for discovering when a change was made and
221 by whom.
221 by whom.
222
222
223 Without the -a/--text option, annotate will avoid processing files
223 Without the -a/--text option, annotate will avoid processing files
224 it detects as binary. With -a, annotate will annotate the file
224 it detects as binary. With -a, annotate will annotate the file
225 anyway, although the results will probably be neither useful
225 anyway, although the results will probably be neither useful
226 nor desirable.
226 nor desirable.
227
227
228 Returns 0 on success.
228 Returns 0 on success.
229 """
229 """
230 if opts.get('follow'):
230 if opts.get('follow'):
231 # --follow is deprecated and now just an alias for -f/--file
231 # --follow is deprecated and now just an alias for -f/--file
232 # to mimic the behavior of Mercurial before version 1.5
232 # to mimic the behavior of Mercurial before version 1.5
233 opts['file'] = True
233 opts['file'] = True
234
234
235 datefunc = ui.quiet and util.shortdate or util.datestr
235 datefunc = ui.quiet and util.shortdate or util.datestr
236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
237
237
238 if not pats:
238 if not pats:
239 raise util.Abort(_('at least one filename or pattern is required'))
239 raise util.Abort(_('at least one filename or pattern is required'))
240
240
241 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
241 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
242 ('number', ' ', lambda x: str(x[0].rev())),
242 ('number', ' ', lambda x: str(x[0].rev())),
243 ('changeset', ' ', lambda x: short(x[0].node())),
243 ('changeset', ' ', lambda x: short(x[0].node())),
244 ('date', ' ', getdate),
244 ('date', ' ', getdate),
245 ('file', ' ', lambda x: x[0].path()),
245 ('file', ' ', lambda x: x[0].path()),
246 ('line_number', ':', lambda x: str(x[1])),
246 ('line_number', ':', lambda x: str(x[1])),
247 ]
247 ]
248
248
249 if (not opts.get('user') and not opts.get('changeset')
249 if (not opts.get('user') and not opts.get('changeset')
250 and not opts.get('date') and not opts.get('file')):
250 and not opts.get('date') and not opts.get('file')):
251 opts['number'] = True
251 opts['number'] = True
252
252
253 linenumber = opts.get('line_number') is not None
253 linenumber = opts.get('line_number') is not None
254 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
254 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
255 raise util.Abort(_('at least one of -n/-c is required for -l'))
255 raise util.Abort(_('at least one of -n/-c is required for -l'))
256
256
257 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
257 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
258 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
258 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
259
259
260 def bad(x, y):
260 def bad(x, y):
261 raise util.Abort("%s: %s" % (x, y))
261 raise util.Abort("%s: %s" % (x, y))
262
262
263 ctx = scmutil.revsingle(repo, opts.get('rev'))
263 ctx = scmutil.revsingle(repo, opts.get('rev'))
264 m = scmutil.match(repo, pats, opts)
264 m = scmutil.match(repo, pats, opts)
265 m.bad = bad
265 m.bad = bad
266 follow = not opts.get('no_follow')
266 follow = not opts.get('no_follow')
267 for abs in ctx.walk(m):
267 for abs in ctx.walk(m):
268 fctx = ctx[abs]
268 fctx = ctx[abs]
269 if not opts.get('text') and util.binary(fctx.data()):
269 if not opts.get('text') and util.binary(fctx.data()):
270 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
270 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
271 continue
271 continue
272
272
273 lines = fctx.annotate(follow=follow, linenumber=linenumber)
273 lines = fctx.annotate(follow=follow, linenumber=linenumber)
274 pieces = []
274 pieces = []
275
275
276 for f, sep in funcmap:
276 for f, sep in funcmap:
277 l = [f(n) for n, dummy in lines]
277 l = [f(n) for n, dummy in lines]
278 if l:
278 if l:
279 sized = [(x, encoding.colwidth(x)) for x in l]
279 sized = [(x, encoding.colwidth(x)) for x in l]
280 ml = max([w for x, w in sized])
280 ml = max([w for x, w in sized])
281 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
281 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
282 for x, w in sized])
282 for x, w in sized])
283
283
284 if pieces:
284 if pieces:
285 for p, l in zip(zip(*pieces), lines):
285 for p, l in zip(zip(*pieces), lines):
286 ui.write("%s: %s" % ("".join(p), l[1]))
286 ui.write("%s: %s" % ("".join(p), l[1]))
287
287
288 @command('archive',
288 @command('archive',
289 [('', 'no-decode', None, _('do not pass files through decoders')),
289 [('', 'no-decode', None, _('do not pass files through decoders')),
290 ('p', 'prefix', '', _('directory prefix for files in archive'),
290 ('p', 'prefix', '', _('directory prefix for files in archive'),
291 _('PREFIX')),
291 _('PREFIX')),
292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
294 ] + subrepoopts + walkopts,
294 ] + subrepoopts + walkopts,
295 _('[OPTION]... DEST'))
295 _('[OPTION]... DEST'))
296 def archive(ui, repo, dest, **opts):
296 def archive(ui, repo, dest, **opts):
297 '''create an unversioned archive of a repository revision
297 '''create an unversioned archive of a repository revision
298
298
299 By default, the revision used is the parent of the working
299 By default, the revision used is the parent of the working
300 directory; use -r/--rev to specify a different revision.
300 directory; use -r/--rev to specify a different revision.
301
301
302 The archive type is automatically detected based on file
302 The archive type is automatically detected based on file
303 extension (or override using -t/--type).
303 extension (or override using -t/--type).
304
304
305 Valid types are:
305 Valid types are:
306
306
307 :``files``: a directory full of files (default)
307 :``files``: a directory full of files (default)
308 :``tar``: tar archive, uncompressed
308 :``tar``: tar archive, uncompressed
309 :``tbz2``: tar archive, compressed using bzip2
309 :``tbz2``: tar archive, compressed using bzip2
310 :``tgz``: tar archive, compressed using gzip
310 :``tgz``: tar archive, compressed using gzip
311 :``uzip``: zip archive, uncompressed
311 :``uzip``: zip archive, uncompressed
312 :``zip``: zip archive, compressed using deflate
312 :``zip``: zip archive, compressed using deflate
313
313
314 The exact name of the destination archive or directory is given
314 The exact name of the destination archive or directory is given
315 using a format string; see :hg:`help export` for details.
315 using a format string; see :hg:`help export` for details.
316
316
317 Each member added to an archive file has a directory prefix
317 Each member added to an archive file has a directory prefix
318 prepended. Use -p/--prefix to specify a format string for the
318 prepended. Use -p/--prefix to specify a format string for the
319 prefix. The default is the basename of the archive, with suffixes
319 prefix. The default is the basename of the archive, with suffixes
320 removed.
320 removed.
321
321
322 Returns 0 on success.
322 Returns 0 on success.
323 '''
323 '''
324
324
325 ctx = scmutil.revsingle(repo, opts.get('rev'))
325 ctx = scmutil.revsingle(repo, opts.get('rev'))
326 if not ctx:
326 if not ctx:
327 raise util.Abort(_('no working directory: please specify a revision'))
327 raise util.Abort(_('no working directory: please specify a revision'))
328 node = ctx.node()
328 node = ctx.node()
329 dest = cmdutil.makefilename(repo, dest, node)
329 dest = cmdutil.makefilename(repo, dest, node)
330 if os.path.realpath(dest) == repo.root:
330 if os.path.realpath(dest) == repo.root:
331 raise util.Abort(_('repository root cannot be destination'))
331 raise util.Abort(_('repository root cannot be destination'))
332
332
333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
334 prefix = opts.get('prefix')
334 prefix = opts.get('prefix')
335
335
336 if dest == '-':
336 if dest == '-':
337 if kind == 'files':
337 if kind == 'files':
338 raise util.Abort(_('cannot archive plain files to stdout'))
338 raise util.Abort(_('cannot archive plain files to stdout'))
339 dest = sys.stdout
339 dest = sys.stdout
340 if not prefix:
340 if not prefix:
341 prefix = os.path.basename(repo.root) + '-%h'
341 prefix = os.path.basename(repo.root) + '-%h'
342
342
343 prefix = cmdutil.makefilename(repo, prefix, node)
343 prefix = cmdutil.makefilename(repo, prefix, node)
344 matchfn = scmutil.match(repo, [], opts)
344 matchfn = scmutil.match(repo, [], opts)
345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
346 matchfn, prefix, subrepos=opts.get('subrepos'))
346 matchfn, prefix, subrepos=opts.get('subrepos'))
347
347
348 @command('backout',
348 @command('backout',
349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
351 ('t', 'tool', '', _('specify merge tool')),
351 ('t', 'tool', '', _('specify merge tool')),
352 ('r', 'rev', '', _('revision to backout'), _('REV')),
352 ('r', 'rev', '', _('revision to backout'), _('REV')),
353 ] + walkopts + commitopts + commitopts2,
353 ] + walkopts + commitopts + commitopts2,
354 _('[OPTION]... [-r] REV'))
354 _('[OPTION]... [-r] REV'))
355 def backout(ui, repo, node=None, rev=None, **opts):
355 def backout(ui, repo, node=None, rev=None, **opts):
356 '''reverse effect of earlier changeset
356 '''reverse effect of earlier changeset
357
357
358 Prepare a new changeset with the effect of REV undone in the
358 Prepare a new changeset with the effect of REV undone in the
359 current working directory.
359 current working directory.
360
360
361 If REV is the parent of the working directory, then this new changeset
361 If REV is the parent of the working directory, then this new changeset
362 is committed automatically. Otherwise, hg needs to merge the
362 is committed automatically. Otherwise, hg needs to merge the
363 changes and the merged result is left uncommitted.
363 changes and the merged result is left uncommitted.
364
364
365 By default, the pending changeset will have one parent,
365 By default, the pending changeset will have one parent,
366 maintaining a linear history. With --merge, the pending changeset
366 maintaining a linear history. With --merge, the pending changeset
367 will instead have two parents: the old parent of the working
367 will instead have two parents: the old parent of the working
368 directory and a new child of REV that simply undoes REV.
368 directory and a new child of REV that simply undoes REV.
369
369
370 Before version 1.7, the behavior without --merge was equivalent to
370 Before version 1.7, the behavior without --merge was equivalent to
371 specifying --merge followed by :hg:`update --clean .` to cancel
371 specifying --merge followed by :hg:`update --clean .` to cancel
372 the merge and leave the child of REV as a head to be merged
372 the merge and leave the child of REV as a head to be merged
373 separately.
373 separately.
374
374
375 See :hg:`help dates` for a list of formats valid for -d/--date.
375 See :hg:`help dates` for a list of formats valid for -d/--date.
376
376
377 Returns 0 on success.
377 Returns 0 on success.
378 '''
378 '''
379 if rev and node:
379 if rev and node:
380 raise util.Abort(_("please specify just one revision"))
380 raise util.Abort(_("please specify just one revision"))
381
381
382 if not rev:
382 if not rev:
383 rev = node
383 rev = node
384
384
385 if not rev:
385 if not rev:
386 raise util.Abort(_("please specify a revision to backout"))
386 raise util.Abort(_("please specify a revision to backout"))
387
387
388 date = opts.get('date')
388 date = opts.get('date')
389 if date:
389 if date:
390 opts['date'] = util.parsedate(date)
390 opts['date'] = util.parsedate(date)
391
391
392 cmdutil.bailifchanged(repo)
392 cmdutil.bailifchanged(repo)
393 node = scmutil.revsingle(repo, rev).node()
393 node = scmutil.revsingle(repo, rev).node()
394
394
395 op1, op2 = repo.dirstate.parents()
395 op1, op2 = repo.dirstate.parents()
396 a = repo.changelog.ancestor(op1, node)
396 a = repo.changelog.ancestor(op1, node)
397 if a != node:
397 if a != node:
398 raise util.Abort(_('cannot backout change on a different branch'))
398 raise util.Abort(_('cannot backout change on a different branch'))
399
399
400 p1, p2 = repo.changelog.parents(node)
400 p1, p2 = repo.changelog.parents(node)
401 if p1 == nullid:
401 if p1 == nullid:
402 raise util.Abort(_('cannot backout a change with no parents'))
402 raise util.Abort(_('cannot backout a change with no parents'))
403 if p2 != nullid:
403 if p2 != nullid:
404 if not opts.get('parent'):
404 if not opts.get('parent'):
405 raise util.Abort(_('cannot backout a merge changeset without '
405 raise util.Abort(_('cannot backout a merge changeset without '
406 '--parent'))
406 '--parent'))
407 p = repo.lookup(opts['parent'])
407 p = repo.lookup(opts['parent'])
408 if p not in (p1, p2):
408 if p not in (p1, p2):
409 raise util.Abort(_('%s is not a parent of %s') %
409 raise util.Abort(_('%s is not a parent of %s') %
410 (short(p), short(node)))
410 (short(p), short(node)))
411 parent = p
411 parent = p
412 else:
412 else:
413 if opts.get('parent'):
413 if opts.get('parent'):
414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
415 parent = p1
415 parent = p1
416
416
417 # the backout should appear on the same branch
417 # the backout should appear on the same branch
418 branch = repo.dirstate.branch()
418 branch = repo.dirstate.branch()
419 hg.clean(repo, node, show_stats=False)
419 hg.clean(repo, node, show_stats=False)
420 repo.dirstate.setbranch(branch)
420 repo.dirstate.setbranch(branch)
421 revert_opts = opts.copy()
421 revert_opts = opts.copy()
422 revert_opts['date'] = None
422 revert_opts['date'] = None
423 revert_opts['all'] = True
423 revert_opts['all'] = True
424 revert_opts['rev'] = hex(parent)
424 revert_opts['rev'] = hex(parent)
425 revert_opts['no_backup'] = None
425 revert_opts['no_backup'] = None
426 revert(ui, repo, **revert_opts)
426 revert(ui, repo, **revert_opts)
427 if not opts.get('merge') and op1 != node:
427 if not opts.get('merge') and op1 != node:
428 try:
428 try:
429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
430 return hg.update(repo, op1)
430 return hg.update(repo, op1)
431 finally:
431 finally:
432 ui.setconfig('ui', 'forcemerge', '')
432 ui.setconfig('ui', 'forcemerge', '')
433
433
434 commit_opts = opts.copy()
434 commit_opts = opts.copy()
435 commit_opts['addremove'] = False
435 commit_opts['addremove'] = False
436 if not commit_opts['message'] and not commit_opts['logfile']:
436 if not commit_opts['message'] and not commit_opts['logfile']:
437 # we don't translate commit messages
437 # we don't translate commit messages
438 commit_opts['message'] = "Backed out changeset %s" % short(node)
438 commit_opts['message'] = "Backed out changeset %s" % short(node)
439 commit_opts['force_editor'] = True
439 commit_opts['force_editor'] = True
440 commit(ui, repo, **commit_opts)
440 commit(ui, repo, **commit_opts)
441 def nice(node):
441 def nice(node):
442 return '%d:%s' % (repo.changelog.rev(node), short(node))
442 return '%d:%s' % (repo.changelog.rev(node), short(node))
443 ui.status(_('changeset %s backs out changeset %s\n') %
443 ui.status(_('changeset %s backs out changeset %s\n') %
444 (nice(repo.changelog.tip()), nice(node)))
444 (nice(repo.changelog.tip()), nice(node)))
445 if opts.get('merge') and op1 != node:
445 if opts.get('merge') and op1 != node:
446 hg.clean(repo, op1, show_stats=False)
446 hg.clean(repo, op1, show_stats=False)
447 ui.status(_('merging with changeset %s\n')
447 ui.status(_('merging with changeset %s\n')
448 % nice(repo.changelog.tip()))
448 % nice(repo.changelog.tip()))
449 try:
449 try:
450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 return hg.merge(repo, hex(repo.changelog.tip()))
451 return hg.merge(repo, hex(repo.changelog.tip()))
452 finally:
452 finally:
453 ui.setconfig('ui', 'forcemerge', '')
453 ui.setconfig('ui', 'forcemerge', '')
454 return 0
454 return 0
455
455
456 @command('bisect',
456 @command('bisect',
457 [('r', 'reset', False, _('reset bisect state')),
457 [('r', 'reset', False, _('reset bisect state')),
458 ('g', 'good', False, _('mark changeset good')),
458 ('g', 'good', False, _('mark changeset good')),
459 ('b', 'bad', False, _('mark changeset bad')),
459 ('b', 'bad', False, _('mark changeset bad')),
460 ('s', 'skip', False, _('skip testing changeset')),
460 ('s', 'skip', False, _('skip testing changeset')),
461 ('e', 'extend', False, _('extend the bisect range')),
461 ('e', 'extend', False, _('extend the bisect range')),
462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
463 ('U', 'noupdate', False, _('do not update to target'))],
463 ('U', 'noupdate', False, _('do not update to target'))],
464 _("[-gbsr] [-U] [-c CMD] [REV]"))
464 _("[-gbsr] [-U] [-c CMD] [REV]"))
465 def bisect(ui, repo, rev=None, extra=None, command=None,
465 def bisect(ui, repo, rev=None, extra=None, command=None,
466 reset=None, good=None, bad=None, skip=None, extend=None,
466 reset=None, good=None, bad=None, skip=None, extend=None,
467 noupdate=None):
467 noupdate=None):
468 """subdivision search of changesets
468 """subdivision search of changesets
469
469
470 This command helps to find changesets which introduce problems. To
470 This command helps to find changesets which introduce problems. To
471 use, mark the earliest changeset you know exhibits the problem as
471 use, mark the earliest changeset you know exhibits the problem as
472 bad, then mark the latest changeset which is free from the problem
472 bad, then mark the latest changeset which is free from the problem
473 as good. Bisect will update your working directory to a revision
473 as good. Bisect will update your working directory to a revision
474 for testing (unless the -U/--noupdate option is specified). Once
474 for testing (unless the -U/--noupdate option is specified). Once
475 you have performed tests, mark the working directory as good or
475 you have performed tests, mark the working directory as good or
476 bad, and bisect will either update to another candidate changeset
476 bad, and bisect will either update to another candidate changeset
477 or announce that it has found the bad revision.
477 or announce that it has found the bad revision.
478
478
479 As a shortcut, you can also use the revision argument to mark a
479 As a shortcut, you can also use the revision argument to mark a
480 revision as good or bad without checking it out first.
480 revision as good or bad without checking it out first.
481
481
482 If you supply a command, it will be used for automatic bisection.
482 If you supply a command, it will be used for automatic bisection.
483 Its exit status will be used to mark revisions as good or bad:
483 Its exit status will be used to mark revisions as good or bad:
484 status 0 means good, 125 means to skip the revision, 127
484 status 0 means good, 125 means to skip the revision, 127
485 (command not found) will abort the bisection, and any other
485 (command not found) will abort the bisection, and any other
486 non-zero exit status means the revision is bad.
486 non-zero exit status means the revision is bad.
487
487
488 Returns 0 on success.
488 Returns 0 on success.
489 """
489 """
490 def extendbisectrange(nodes, good):
490 def extendbisectrange(nodes, good):
491 # bisect is incomplete when it ends on a merge node and
491 # bisect is incomplete when it ends on a merge node and
492 # one of the parent was not checked.
492 # one of the parent was not checked.
493 parents = repo[nodes[0]].parents()
493 parents = repo[nodes[0]].parents()
494 if len(parents) > 1:
494 if len(parents) > 1:
495 side = good and state['bad'] or state['good']
495 side = good and state['bad'] or state['good']
496 num = len(set(i.node() for i in parents) & set(side))
496 num = len(set(i.node() for i in parents) & set(side))
497 if num == 1:
497 if num == 1:
498 return parents[0].ancestor(parents[1])
498 return parents[0].ancestor(parents[1])
499 return None
499 return None
500
500
501 def print_result(nodes, good):
501 def print_result(nodes, good):
502 displayer = cmdutil.show_changeset(ui, repo, {})
502 displayer = cmdutil.show_changeset(ui, repo, {})
503 if len(nodes) == 1:
503 if len(nodes) == 1:
504 # narrowed it down to a single revision
504 # narrowed it down to a single revision
505 if good:
505 if good:
506 ui.write(_("The first good revision is:\n"))
506 ui.write(_("The first good revision is:\n"))
507 else:
507 else:
508 ui.write(_("The first bad revision is:\n"))
508 ui.write(_("The first bad revision is:\n"))
509 displayer.show(repo[nodes[0]])
509 displayer.show(repo[nodes[0]])
510 extendnode = extendbisectrange(nodes, good)
510 extendnode = extendbisectrange(nodes, good)
511 if extendnode is not None:
511 if extendnode is not None:
512 ui.write(_('Not all ancestors of this changeset have been'
512 ui.write(_('Not all ancestors of this changeset have been'
513 ' checked.\nUse bisect --extend to continue the '
513 ' checked.\nUse bisect --extend to continue the '
514 'bisection from\nthe common ancestor, %s.\n')
514 'bisection from\nthe common ancestor, %s.\n')
515 % extendnode)
515 % extendnode)
516 else:
516 else:
517 # multiple possible revisions
517 # multiple possible revisions
518 if good:
518 if good:
519 ui.write(_("Due to skipped revisions, the first "
519 ui.write(_("Due to skipped revisions, the first "
520 "good revision could be any of:\n"))
520 "good revision could be any of:\n"))
521 else:
521 else:
522 ui.write(_("Due to skipped revisions, the first "
522 ui.write(_("Due to skipped revisions, the first "
523 "bad revision could be any of:\n"))
523 "bad revision could be any of:\n"))
524 for n in nodes:
524 for n in nodes:
525 displayer.show(repo[n])
525 displayer.show(repo[n])
526 displayer.close()
526 displayer.close()
527
527
528 def check_state(state, interactive=True):
528 def check_state(state, interactive=True):
529 if not state['good'] or not state['bad']:
529 if not state['good'] or not state['bad']:
530 if (good or bad or skip or reset) and interactive:
530 if (good or bad or skip or reset) and interactive:
531 return
531 return
532 if not state['good']:
532 if not state['good']:
533 raise util.Abort(_('cannot bisect (no known good revisions)'))
533 raise util.Abort(_('cannot bisect (no known good revisions)'))
534 else:
534 else:
535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
536 return True
536 return True
537
537
538 # backward compatibility
538 # backward compatibility
539 if rev in "good bad reset init".split():
539 if rev in "good bad reset init".split():
540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
541 cmd, rev, extra = rev, extra, None
541 cmd, rev, extra = rev, extra, None
542 if cmd == "good":
542 if cmd == "good":
543 good = True
543 good = True
544 elif cmd == "bad":
544 elif cmd == "bad":
545 bad = True
545 bad = True
546 else:
546 else:
547 reset = True
547 reset = True
548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
549 raise util.Abort(_('incompatible arguments'))
549 raise util.Abort(_('incompatible arguments'))
550
550
551 if reset:
551 if reset:
552 p = repo.join("bisect.state")
552 p = repo.join("bisect.state")
553 if os.path.exists(p):
553 if os.path.exists(p):
554 os.unlink(p)
554 os.unlink(p)
555 return
555 return
556
556
557 state = hbisect.load_state(repo)
557 state = hbisect.load_state(repo)
558
558
559 if command:
559 if command:
560 changesets = 1
560 changesets = 1
561 try:
561 try:
562 while changesets:
562 while changesets:
563 # update state
563 # update state
564 status = util.system(command)
564 status = util.system(command)
565 if status == 125:
565 if status == 125:
566 transition = "skip"
566 transition = "skip"
567 elif status == 0:
567 elif status == 0:
568 transition = "good"
568 transition = "good"
569 # status < 0 means process was killed
569 # status < 0 means process was killed
570 elif status == 127:
570 elif status == 127:
571 raise util.Abort(_("failed to execute %s") % command)
571 raise util.Abort(_("failed to execute %s") % command)
572 elif status < 0:
572 elif status < 0:
573 raise util.Abort(_("%s killed") % command)
573 raise util.Abort(_("%s killed") % command)
574 else:
574 else:
575 transition = "bad"
575 transition = "bad"
576 ctx = scmutil.revsingle(repo, rev)
576 ctx = scmutil.revsingle(repo, rev)
577 rev = None # clear for future iterations
577 rev = None # clear for future iterations
578 state[transition].append(ctx.node())
578 state[transition].append(ctx.node())
579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
580 check_state(state, interactive=False)
580 check_state(state, interactive=False)
581 # bisect
581 # bisect
582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
583 # update to next check
583 # update to next check
584 cmdutil.bailifchanged(repo)
584 cmdutil.bailifchanged(repo)
585 hg.clean(repo, nodes[0], show_stats=False)
585 hg.clean(repo, nodes[0], show_stats=False)
586 finally:
586 finally:
587 hbisect.save_state(repo, state)
587 hbisect.save_state(repo, state)
588 print_result(nodes, good)
588 print_result(nodes, good)
589 return
589 return
590
590
591 # update state
591 # update state
592
592
593 if rev:
593 if rev:
594 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
594 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
595 else:
595 else:
596 nodes = [repo.lookup('.')]
596 nodes = [repo.lookup('.')]
597
597
598 if good or bad or skip:
598 if good or bad or skip:
599 if good:
599 if good:
600 state['good'] += nodes
600 state['good'] += nodes
601 elif bad:
601 elif bad:
602 state['bad'] += nodes
602 state['bad'] += nodes
603 elif skip:
603 elif skip:
604 state['skip'] += nodes
604 state['skip'] += nodes
605 hbisect.save_state(repo, state)
605 hbisect.save_state(repo, state)
606
606
607 if not check_state(state):
607 if not check_state(state):
608 return
608 return
609
609
610 # actually bisect
610 # actually bisect
611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
612 if extend:
612 if extend:
613 if not changesets:
613 if not changesets:
614 extendnode = extendbisectrange(nodes, good)
614 extendnode = extendbisectrange(nodes, good)
615 if extendnode is not None:
615 if extendnode is not None:
616 ui.write(_("Extending search to changeset %d:%s\n"
616 ui.write(_("Extending search to changeset %d:%s\n"
617 % (extendnode.rev(), extendnode)))
617 % (extendnode.rev(), extendnode)))
618 if noupdate:
618 if noupdate:
619 return
619 return
620 cmdutil.bailifchanged(repo)
620 cmdutil.bailifchanged(repo)
621 return hg.clean(repo, extendnode.node())
621 return hg.clean(repo, extendnode.node())
622 raise util.Abort(_("nothing to extend"))
622 raise util.Abort(_("nothing to extend"))
623
623
624 if changesets == 0:
624 if changesets == 0:
625 print_result(nodes, good)
625 print_result(nodes, good)
626 else:
626 else:
627 assert len(nodes) == 1 # only a single node can be tested next
627 assert len(nodes) == 1 # only a single node can be tested next
628 node = nodes[0]
628 node = nodes[0]
629 # compute the approximate number of remaining tests
629 # compute the approximate number of remaining tests
630 tests, size = 0, 2
630 tests, size = 0, 2
631 while size <= changesets:
631 while size <= changesets:
632 tests, size = tests + 1, size * 2
632 tests, size = tests + 1, size * 2
633 rev = repo.changelog.rev(node)
633 rev = repo.changelog.rev(node)
634 ui.write(_("Testing changeset %d:%s "
634 ui.write(_("Testing changeset %d:%s "
635 "(%d changesets remaining, ~%d tests)\n")
635 "(%d changesets remaining, ~%d tests)\n")
636 % (rev, short(node), changesets, tests))
636 % (rev, short(node), changesets, tests))
637 if not noupdate:
637 if not noupdate:
638 cmdutil.bailifchanged(repo)
638 cmdutil.bailifchanged(repo)
639 return hg.clean(repo, node)
639 return hg.clean(repo, node)
640
640
641 @command('bookmarks',
641 @command('bookmarks',
642 [('f', 'force', False, _('force')),
642 [('f', 'force', False, _('force')),
643 ('r', 'rev', '', _('revision'), _('REV')),
643 ('r', 'rev', '', _('revision'), _('REV')),
644 ('d', 'delete', False, _('delete a given bookmark')),
644 ('d', 'delete', False, _('delete a given bookmark')),
645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
649 rename=None, inactive=False):
649 rename=None, inactive=False):
650 '''track a line of development with movable markers
650 '''track a line of development with movable markers
651
651
652 Bookmarks are pointers to certain commits that move when
652 Bookmarks are pointers to certain commits that move when
653 committing. Bookmarks are local. They can be renamed, copied and
653 committing. Bookmarks are local. They can be renamed, copied and
654 deleted. It is possible to use bookmark names in :hg:`merge` and
654 deleted. It is possible to use bookmark names in :hg:`merge` and
655 :hg:`update` to merge and update respectively to a given bookmark.
655 :hg:`update` to merge and update respectively to a given bookmark.
656
656
657 You can use :hg:`bookmark NAME` to set a bookmark on the working
657 You can use :hg:`bookmark NAME` to set a bookmark on the working
658 directory's parent revision with the given name. If you specify
658 directory's parent revision with the given name. If you specify
659 a revision using -r REV (where REV may be an existing bookmark),
659 a revision using -r REV (where REV may be an existing bookmark),
660 the bookmark is assigned to that revision.
660 the bookmark is assigned to that revision.
661
661
662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
663 push` and :hg:`help pull`). This requires both the local and remote
663 push` and :hg:`help pull`). This requires both the local and remote
664 repositories to support bookmarks. For versions prior to 1.8, this means
664 repositories to support bookmarks. For versions prior to 1.8, this means
665 the bookmarks extension must be enabled.
665 the bookmarks extension must be enabled.
666 '''
666 '''
667 hexfn = ui.debugflag and hex or short
667 hexfn = ui.debugflag and hex or short
668 marks = repo._bookmarks
668 marks = repo._bookmarks
669 cur = repo.changectx('.').node()
669 cur = repo.changectx('.').node()
670
670
671 if rename:
671 if rename:
672 if rename not in marks:
672 if rename not in marks:
673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
674 if mark in marks and not force:
674 if mark in marks and not force:
675 raise util.Abort(_("bookmark '%s' already exists "
675 raise util.Abort(_("bookmark '%s' already exists "
676 "(use -f to force)") % mark)
676 "(use -f to force)") % mark)
677 if mark is None:
677 if mark is None:
678 raise util.Abort(_("new bookmark name required"))
678 raise util.Abort(_("new bookmark name required"))
679 marks[mark] = marks[rename]
679 marks[mark] = marks[rename]
680 if repo._bookmarkcurrent == rename and not inactive:
680 if repo._bookmarkcurrent == rename and not inactive:
681 bookmarks.setcurrent(repo, mark)
681 bookmarks.setcurrent(repo, mark)
682 del marks[rename]
682 del marks[rename]
683 bookmarks.write(repo)
683 bookmarks.write(repo)
684 return
684 return
685
685
686 if delete:
686 if delete:
687 if mark is None:
687 if mark is None:
688 raise util.Abort(_("bookmark name required"))
688 raise util.Abort(_("bookmark name required"))
689 if mark not in marks:
689 if mark not in marks:
690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
691 if mark == repo._bookmarkcurrent:
691 if mark == repo._bookmarkcurrent:
692 bookmarks.setcurrent(repo, None)
692 bookmarks.setcurrent(repo, None)
693 del marks[mark]
693 del marks[mark]
694 bookmarks.write(repo)
694 bookmarks.write(repo)
695 return
695 return
696
696
697 if mark is not None:
697 if mark is not None:
698 if "\n" in mark:
698 if "\n" in mark:
699 raise util.Abort(_("bookmark name cannot contain newlines"))
699 raise util.Abort(_("bookmark name cannot contain newlines"))
700 mark = mark.strip()
700 mark = mark.strip()
701 if not mark:
701 if not mark:
702 raise util.Abort(_("bookmark names cannot consist entirely of "
702 raise util.Abort(_("bookmark names cannot consist entirely of "
703 "whitespace"))
703 "whitespace"))
704 if inactive and mark == repo._bookmarkcurrent:
704 if inactive and mark == repo._bookmarkcurrent:
705 bookmarks.setcurrent(repo, None)
705 bookmarks.setcurrent(repo, None)
706 return
706 return
707 if mark in marks and not force:
707 if mark in marks and not force:
708 raise util.Abort(_("bookmark '%s' already exists "
708 raise util.Abort(_("bookmark '%s' already exists "
709 "(use -f to force)") % mark)
709 "(use -f to force)") % mark)
710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
711 and not force):
711 and not force):
712 raise util.Abort(
712 raise util.Abort(
713 _("a bookmark cannot have the name of an existing branch"))
713 _("a bookmark cannot have the name of an existing branch"))
714 if rev:
714 if rev:
715 marks[mark] = repo.lookup(rev)
715 marks[mark] = repo.lookup(rev)
716 else:
716 else:
717 marks[mark] = repo.changectx('.').node()
717 marks[mark] = repo.changectx('.').node()
718 if not inactive and repo.changectx('.').node() == marks[mark]:
718 if not inactive and repo.changectx('.').node() == marks[mark]:
719 bookmarks.setcurrent(repo, mark)
719 bookmarks.setcurrent(repo, mark)
720 bookmarks.write(repo)
720 bookmarks.write(repo)
721 return
721 return
722
722
723 if mark is None:
723 if mark is None:
724 if rev:
724 if rev:
725 raise util.Abort(_("bookmark name required"))
725 raise util.Abort(_("bookmark name required"))
726 if len(marks) == 0:
726 if len(marks) == 0:
727 ui.status(_("no bookmarks set\n"))
727 ui.status(_("no bookmarks set\n"))
728 else:
728 else:
729 for bmark, n in sorted(marks.iteritems()):
729 for bmark, n in sorted(marks.iteritems()):
730 current = repo._bookmarkcurrent
730 current = repo._bookmarkcurrent
731 if bmark == current and n == cur:
731 if bmark == current and n == cur:
732 prefix, label = '*', 'bookmarks.current'
732 prefix, label = '*', 'bookmarks.current'
733 else:
733 else:
734 prefix, label = ' ', ''
734 prefix, label = ' ', ''
735
735
736 if ui.quiet:
736 if ui.quiet:
737 ui.write("%s\n" % bmark, label=label)
737 ui.write("%s\n" % bmark, label=label)
738 else:
738 else:
739 ui.write(" %s %-25s %d:%s\n" % (
739 ui.write(" %s %-25s %d:%s\n" % (
740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
741 label=label)
741 label=label)
742 return
742 return
743
743
744 @command('branch',
744 @command('branch',
745 [('f', 'force', None,
745 [('f', 'force', None,
746 _('set branch name even if it shadows an existing branch')),
746 _('set branch name even if it shadows an existing branch')),
747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
748 _('[-fC] [NAME]'))
748 _('[-fC] [NAME]'))
749 def branch(ui, repo, label=None, **opts):
749 def branch(ui, repo, label=None, **opts):
750 """set or show the current branch name
750 """set or show the current branch name
751
751
752 With no argument, show the current branch name. With one argument,
752 With no argument, show the current branch name. With one argument,
753 set the working directory branch name (the branch will not exist
753 set the working directory branch name (the branch will not exist
754 in the repository until the next commit). Standard practice
754 in the repository until the next commit). Standard practice
755 recommends that primary development take place on the 'default'
755 recommends that primary development take place on the 'default'
756 branch.
756 branch.
757
757
758 Unless -f/--force is specified, branch will not let you set a
758 Unless -f/--force is specified, branch will not let you set a
759 branch name that already exists, even if it's inactive.
759 branch name that already exists, even if it's inactive.
760
760
761 Use -C/--clean to reset the working directory branch to that of
761 Use -C/--clean to reset the working directory branch to that of
762 the parent of the working directory, negating a previous branch
762 the parent of the working directory, negating a previous branch
763 change.
763 change.
764
764
765 Use the command :hg:`update` to switch to an existing branch. Use
765 Use the command :hg:`update` to switch to an existing branch. Use
766 :hg:`commit --close-branch` to mark this branch as closed.
766 :hg:`commit --close-branch` to mark this branch as closed.
767
767
768 Returns 0 on success.
768 Returns 0 on success.
769 """
769 """
770
770
771 if opts.get('clean'):
771 if opts.get('clean'):
772 label = repo[None].p1().branch()
772 label = repo[None].p1().branch()
773 repo.dirstate.setbranch(label)
773 repo.dirstate.setbranch(label)
774 ui.status(_('reset working directory to branch %s\n') % label)
774 ui.status(_('reset working directory to branch %s\n') % label)
775 elif label:
775 elif label:
776 if not opts.get('force') and label in repo.branchtags():
776 if not opts.get('force') and label in repo.branchtags():
777 if label not in [p.branch() for p in repo.parents()]:
777 if label not in [p.branch() for p in repo.parents()]:
778 raise util.Abort(_('a branch of the same name already exists'),
778 raise util.Abort(_('a branch of the same name already exists'),
779 # i18n: "it" refers to an existing branch
779 # i18n: "it" refers to an existing branch
780 hint=_("use 'hg update' to switch to it"))
780 hint=_("use 'hg update' to switch to it"))
781 repo.dirstate.setbranch(label)
781 repo.dirstate.setbranch(label)
782 ui.status(_('marked working directory as branch %s\n') % label)
782 ui.status(_('marked working directory as branch %s\n') % label)
783 else:
783 else:
784 ui.write("%s\n" % repo.dirstate.branch())
784 ui.write("%s\n" % repo.dirstate.branch())
785
785
786 @command('branches',
786 @command('branches',
787 [('a', 'active', False, _('show only branches that have unmerged heads')),
787 [('a', 'active', False, _('show only branches that have unmerged heads')),
788 ('c', 'closed', False, _('show normal and closed branches'))],
788 ('c', 'closed', False, _('show normal and closed branches'))],
789 _('[-ac]'))
789 _('[-ac]'))
790 def branches(ui, repo, active=False, closed=False):
790 def branches(ui, repo, active=False, closed=False):
791 """list repository named branches
791 """list repository named branches
792
792
793 List the repository's named branches, indicating which ones are
793 List the repository's named branches, indicating which ones are
794 inactive. If -c/--closed is specified, also list branches which have
794 inactive. If -c/--closed is specified, also list branches which have
795 been marked closed (see :hg:`commit --close-branch`).
795 been marked closed (see :hg:`commit --close-branch`).
796
796
797 If -a/--active is specified, only show active branches. A branch
797 If -a/--active is specified, only show active branches. A branch
798 is considered active if it contains repository heads.
798 is considered active if it contains repository heads.
799
799
800 Use the command :hg:`update` to switch to an existing branch.
800 Use the command :hg:`update` to switch to an existing branch.
801
801
802 Returns 0.
802 Returns 0.
803 """
803 """
804
804
805 hexfunc = ui.debugflag and hex or short
805 hexfunc = ui.debugflag and hex or short
806 activebranches = [repo[n].branch() for n in repo.heads()]
806 activebranches = [repo[n].branch() for n in repo.heads()]
807 def testactive(tag, node):
807 def testactive(tag, node):
808 realhead = tag in activebranches
808 realhead = tag in activebranches
809 open = node in repo.branchheads(tag, closed=False)
809 open = node in repo.branchheads(tag, closed=False)
810 return realhead and open
810 return realhead and open
811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
811 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
812 for tag, node in repo.branchtags().items()],
812 for tag, node in repo.branchtags().items()],
813 reverse=True)
813 reverse=True)
814
814
815 for isactive, node, tag in branches:
815 for isactive, node, tag in branches:
816 if (not active) or isactive:
816 if (not active) or isactive:
817 if ui.quiet:
817 if ui.quiet:
818 ui.write("%s\n" % tag)
818 ui.write("%s\n" % tag)
819 else:
819 else:
820 hn = repo.lookup(node)
820 hn = repo.lookup(node)
821 if isactive:
821 if isactive:
822 label = 'branches.active'
822 label = 'branches.active'
823 notice = ''
823 notice = ''
824 elif hn not in repo.branchheads(tag, closed=False):
824 elif hn not in repo.branchheads(tag, closed=False):
825 if not closed:
825 if not closed:
826 continue
826 continue
827 label = 'branches.closed'
827 label = 'branches.closed'
828 notice = _(' (closed)')
828 notice = _(' (closed)')
829 else:
829 else:
830 label = 'branches.inactive'
830 label = 'branches.inactive'
831 notice = _(' (inactive)')
831 notice = _(' (inactive)')
832 if tag == repo.dirstate.branch():
832 if tag == repo.dirstate.branch():
833 label = 'branches.current'
833 label = 'branches.current'
834 rev = str(node).rjust(31 - encoding.colwidth(tag))
834 rev = str(node).rjust(31 - encoding.colwidth(tag))
835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
835 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
836 tag = ui.label(tag, label)
836 tag = ui.label(tag, label)
837 ui.write("%s %s%s\n" % (tag, rev, notice))
837 ui.write("%s %s%s\n" % (tag, rev, notice))
838
838
839 @command('bundle',
839 @command('bundle',
840 [('f', 'force', None, _('run even when the destination is unrelated')),
840 [('f', 'force', None, _('run even when the destination is unrelated')),
841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
841 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
842 _('REV')),
842 _('REV')),
843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
843 ('b', 'branch', [], _('a specific branch you would like to bundle'),
844 _('BRANCH')),
844 _('BRANCH')),
845 ('', 'base', [],
845 ('', 'base', [],
846 _('a base changeset assumed to be available at the destination'),
846 _('a base changeset assumed to be available at the destination'),
847 _('REV')),
847 _('REV')),
848 ('a', 'all', None, _('bundle all changesets in the repository')),
848 ('a', 'all', None, _('bundle all changesets in the repository')),
849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
849 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
850 ] + remoteopts,
850 ] + remoteopts,
851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
851 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
852 def bundle(ui, repo, fname, dest=None, **opts):
852 def bundle(ui, repo, fname, dest=None, **opts):
853 """create a changegroup file
853 """create a changegroup file
854
854
855 Generate a compressed changegroup file collecting changesets not
855 Generate a compressed changegroup file collecting changesets not
856 known to be in another repository.
856 known to be in another repository.
857
857
858 If you omit the destination repository, then hg assumes the
858 If you omit the destination repository, then hg assumes the
859 destination will have all the nodes you specify with --base
859 destination will have all the nodes you specify with --base
860 parameters. To create a bundle containing all changesets, use
860 parameters. To create a bundle containing all changesets, use
861 -a/--all (or --base null).
861 -a/--all (or --base null).
862
862
863 You can change compression method with the -t/--type option.
863 You can change compression method with the -t/--type option.
864 The available compression methods are: none, bzip2, and
864 The available compression methods are: none, bzip2, and
865 gzip (by default, bundles are compressed using bzip2).
865 gzip (by default, bundles are compressed using bzip2).
866
866
867 The bundle file can then be transferred using conventional means
867 The bundle file can then be transferred using conventional means
868 and applied to another repository with the unbundle or pull
868 and applied to another repository with the unbundle or pull
869 command. This is useful when direct push and pull are not
869 command. This is useful when direct push and pull are not
870 available or when exporting an entire repository is undesirable.
870 available or when exporting an entire repository is undesirable.
871
871
872 Applying bundles preserves all changeset contents including
872 Applying bundles preserves all changeset contents including
873 permissions, copy/rename information, and revision history.
873 permissions, copy/rename information, and revision history.
874
874
875 Returns 0 on success, 1 if no changes found.
875 Returns 0 on success, 1 if no changes found.
876 """
876 """
877 revs = None
877 revs = None
878 if 'rev' in opts:
878 if 'rev' in opts:
879 revs = scmutil.revrange(repo, opts['rev'])
879 revs = scmutil.revrange(repo, opts['rev'])
880
880
881 if opts.get('all'):
881 if opts.get('all'):
882 base = ['null']
882 base = ['null']
883 else:
883 else:
884 base = scmutil.revrange(repo, opts.get('base'))
884 base = scmutil.revrange(repo, opts.get('base'))
885 if base:
885 if base:
886 if dest:
886 if dest:
887 raise util.Abort(_("--base is incompatible with specifying "
887 raise util.Abort(_("--base is incompatible with specifying "
888 "a destination"))
888 "a destination"))
889 common = [repo.lookup(rev) for rev in base]
889 common = [repo.lookup(rev) for rev in base]
890 heads = revs and map(repo.lookup, revs) or revs
890 heads = revs and map(repo.lookup, revs) or revs
891 else:
891 else:
892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
892 dest = ui.expandpath(dest or 'default-push', dest or 'default')
893 dest, branches = hg.parseurl(dest, opts.get('branch'))
893 dest, branches = hg.parseurl(dest, opts.get('branch'))
894 other = hg.repository(hg.remoteui(repo, opts), dest)
894 other = hg.repository(hg.remoteui(repo, opts), dest)
895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
895 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
896 heads = revs and map(repo.lookup, revs) or revs
896 heads = revs and map(repo.lookup, revs) or revs
897 common, outheads = discovery.findcommonoutgoing(repo, other,
897 common, outheads = discovery.findcommonoutgoing(repo, other,
898 onlyheads=heads,
898 onlyheads=heads,
899 force=opts.get('force'))
899 force=opts.get('force'))
900
900
901 cg = repo.getbundle('bundle', common=common, heads=heads)
901 cg = repo.getbundle('bundle', common=common, heads=heads)
902 if not cg:
902 if not cg:
903 ui.status(_("no changes found\n"))
903 ui.status(_("no changes found\n"))
904 return 1
904 return 1
905
905
906 bundletype = opts.get('type', 'bzip2').lower()
906 bundletype = opts.get('type', 'bzip2').lower()
907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
907 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
908 bundletype = btypes.get(bundletype)
908 bundletype = btypes.get(bundletype)
909 if bundletype not in changegroup.bundletypes:
909 if bundletype not in changegroup.bundletypes:
910 raise util.Abort(_('unknown bundle type specified with --type'))
910 raise util.Abort(_('unknown bundle type specified with --type'))
911
911
912 changegroup.writebundle(cg, fname, bundletype)
912 changegroup.writebundle(cg, fname, bundletype)
913
913
914 @command('cat',
914 @command('cat',
915 [('o', 'output', '',
915 [('o', 'output', '',
916 _('print output to file with formatted name'), _('FORMAT')),
916 _('print output to file with formatted name'), _('FORMAT')),
917 ('r', 'rev', '', _('print the given revision'), _('REV')),
917 ('r', 'rev', '', _('print the given revision'), _('REV')),
918 ('', 'decode', None, _('apply any matching decode filter')),
918 ('', 'decode', None, _('apply any matching decode filter')),
919 ] + walkopts,
919 ] + walkopts,
920 _('[OPTION]... FILE...'))
920 _('[OPTION]... FILE...'))
921 def cat(ui, repo, file1, *pats, **opts):
921 def cat(ui, repo, file1, *pats, **opts):
922 """output the current or given revision of files
922 """output the current or given revision of files
923
923
924 Print the specified files as they were at the given revision. If
924 Print the specified files as they were at the given revision. If
925 no revision is given, the parent of the working directory is used,
925 no revision is given, the parent of the working directory is used,
926 or tip if no revision is checked out.
926 or tip if no revision is checked out.
927
927
928 Output may be to a file, in which case the name of the file is
928 Output may be to a file, in which case the name of the file is
929 given using a format string. The formatting rules are the same as
929 given using a format string. The formatting rules are the same as
930 for the export command, with the following additions:
930 for the export command, with the following additions:
931
931
932 :``%s``: basename of file being printed
932 :``%s``: basename of file being printed
933 :``%d``: dirname of file being printed, or '.' if in repository root
933 :``%d``: dirname of file being printed, or '.' if in repository root
934 :``%p``: root-relative path name of file being printed
934 :``%p``: root-relative path name of file being printed
935
935
936 Returns 0 on success.
936 Returns 0 on success.
937 """
937 """
938 ctx = scmutil.revsingle(repo, opts.get('rev'))
938 ctx = scmutil.revsingle(repo, opts.get('rev'))
939 err = 1
939 err = 1
940 m = scmutil.match(repo, (file1,) + pats, opts)
940 m = scmutil.match(repo, (file1,) + pats, opts)
941 for abs in ctx.walk(m):
941 for abs in ctx.walk(m):
942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
942 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
943 pathname=abs)
943 pathname=abs)
944 data = ctx[abs].data()
944 data = ctx[abs].data()
945 if opts.get('decode'):
945 if opts.get('decode'):
946 data = repo.wwritedata(abs, data)
946 data = repo.wwritedata(abs, data)
947 fp.write(data)
947 fp.write(data)
948 fp.close()
948 fp.close()
949 err = 0
949 err = 0
950 return err
950 return err
951
951
952 @command('^clone',
952 @command('^clone',
953 [('U', 'noupdate', None,
953 [('U', 'noupdate', None,
954 _('the clone will include an empty working copy (only a repository)')),
954 _('the clone will include an empty working copy (only a repository)')),
955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
955 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
956 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
957 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
958 ('', 'pull', None, _('use pull protocol to copy metadata')),
958 ('', 'pull', None, _('use pull protocol to copy metadata')),
959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
959 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
960 ] + remoteopts,
960 ] + remoteopts,
961 _('[OPTION]... SOURCE [DEST]'))
961 _('[OPTION]... SOURCE [DEST]'))
962 def clone(ui, source, dest=None, **opts):
962 def clone(ui, source, dest=None, **opts):
963 """make a copy of an existing repository
963 """make a copy of an existing repository
964
964
965 Create a copy of an existing repository in a new directory.
965 Create a copy of an existing repository in a new directory.
966
966
967 If no destination directory name is specified, it defaults to the
967 If no destination directory name is specified, it defaults to the
968 basename of the source.
968 basename of the source.
969
969
970 The location of the source is added to the new repository's
970 The location of the source is added to the new repository's
971 ``.hg/hgrc`` file, as the default to be used for future pulls.
971 ``.hg/hgrc`` file, as the default to be used for future pulls.
972
972
973 See :hg:`help urls` for valid source format details.
973 See :hg:`help urls` for valid source format details.
974
974
975 It is possible to specify an ``ssh://`` URL as the destination, but no
975 It is possible to specify an ``ssh://`` URL as the destination, but no
976 ``.hg/hgrc`` and working directory will be created on the remote side.
976 ``.hg/hgrc`` and working directory will be created on the remote side.
977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
977 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
978
978
979 A set of changesets (tags, or branch names) to pull may be specified
979 A set of changesets (tags, or branch names) to pull may be specified
980 by listing each changeset (tag, or branch name) with -r/--rev.
980 by listing each changeset (tag, or branch name) with -r/--rev.
981 If -r/--rev is used, the cloned repository will contain only a subset
981 If -r/--rev is used, the cloned repository will contain only a subset
982 of the changesets of the source repository. Only the set of changesets
982 of the changesets of the source repository. Only the set of changesets
983 defined by all -r/--rev options (including all their ancestors)
983 defined by all -r/--rev options (including all their ancestors)
984 will be pulled into the destination repository.
984 will be pulled into the destination repository.
985 No subsequent changesets (including subsequent tags) will be present
985 No subsequent changesets (including subsequent tags) will be present
986 in the destination.
986 in the destination.
987
987
988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
988 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
989 local source repositories.
989 local source repositories.
990
990
991 For efficiency, hardlinks are used for cloning whenever the source
991 For efficiency, hardlinks are used for cloning whenever the source
992 and destination are on the same filesystem (note this applies only
992 and destination are on the same filesystem (note this applies only
993 to the repository data, not to the working directory). Some
993 to the repository data, not to the working directory). Some
994 filesystems, such as AFS, implement hardlinking incorrectly, but
994 filesystems, such as AFS, implement hardlinking incorrectly, but
995 do not report errors. In these cases, use the --pull option to
995 do not report errors. In these cases, use the --pull option to
996 avoid hardlinking.
996 avoid hardlinking.
997
997
998 In some cases, you can clone repositories and the working directory
998 In some cases, you can clone repositories and the working directory
999 using full hardlinks with ::
999 using full hardlinks with ::
1000
1000
1001 $ cp -al REPO REPOCLONE
1001 $ cp -al REPO REPOCLONE
1002
1002
1003 This is the fastest way to clone, but it is not always safe. The
1003 This is the fastest way to clone, but it is not always safe. The
1004 operation is not atomic (making sure REPO is not modified during
1004 operation is not atomic (making sure REPO is not modified during
1005 the operation is up to you) and you have to make sure your editor
1005 the operation is up to you) and you have to make sure your editor
1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1006 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1007 this is not compatible with certain extensions that place their
1007 this is not compatible with certain extensions that place their
1008 metadata under the .hg directory, such as mq.
1008 metadata under the .hg directory, such as mq.
1009
1009
1010 Mercurial will update the working directory to the first applicable
1010 Mercurial will update the working directory to the first applicable
1011 revision from this list:
1011 revision from this list:
1012
1012
1013 a) null if -U or the source repository has no changesets
1013 a) null if -U or the source repository has no changesets
1014 b) if -u . and the source repository is local, the first parent of
1014 b) if -u . and the source repository is local, the first parent of
1015 the source repository's working directory
1015 the source repository's working directory
1016 c) the changeset specified with -u (if a branch name, this means the
1016 c) the changeset specified with -u (if a branch name, this means the
1017 latest head of that branch)
1017 latest head of that branch)
1018 d) the changeset specified with -r
1018 d) the changeset specified with -r
1019 e) the tipmost head specified with -b
1019 e) the tipmost head specified with -b
1020 f) the tipmost head specified with the url#branch source syntax
1020 f) the tipmost head specified with the url#branch source syntax
1021 g) the tipmost head of the default branch
1021 g) the tipmost head of the default branch
1022 h) tip
1022 h) tip
1023
1023
1024 Returns 0 on success.
1024 Returns 0 on success.
1025 """
1025 """
1026 if opts.get('noupdate') and opts.get('updaterev'):
1026 if opts.get('noupdate') and opts.get('updaterev'):
1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1027 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1028
1028
1029 r = hg.clone(hg.remoteui(ui, opts), source, dest,
1029 r = hg.clone(hg.remoteui(ui, opts), source, dest,
1030 pull=opts.get('pull'),
1030 pull=opts.get('pull'),
1031 stream=opts.get('uncompressed'),
1031 stream=opts.get('uncompressed'),
1032 rev=opts.get('rev'),
1032 rev=opts.get('rev'),
1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1033 update=opts.get('updaterev') or not opts.get('noupdate'),
1034 branch=opts.get('branch'))
1034 branch=opts.get('branch'))
1035
1035
1036 return r is None
1036 return r is None
1037
1037
1038 @command('^commit|ci',
1038 @command('^commit|ci',
1039 [('A', 'addremove', None,
1039 [('A', 'addremove', None,
1040 _('mark new/missing files as added/removed before committing')),
1040 _('mark new/missing files as added/removed before committing')),
1041 ('', 'close-branch', None,
1041 ('', 'close-branch', None,
1042 _('mark a branch as closed, hiding it from the branch list')),
1042 _('mark a branch as closed, hiding it from the branch list')),
1043 ] + walkopts + commitopts + commitopts2,
1043 ] + walkopts + commitopts + commitopts2,
1044 _('[OPTION]... [FILE]...'))
1044 _('[OPTION]... [FILE]...'))
1045 def commit(ui, repo, *pats, **opts):
1045 def commit(ui, repo, *pats, **opts):
1046 """commit the specified files or all outstanding changes
1046 """commit the specified files or all outstanding changes
1047
1047
1048 Commit changes to the given files into the repository. Unlike a
1048 Commit changes to the given files into the repository. Unlike a
1049 centralized SCM, this operation is a local operation. See
1049 centralized SCM, this operation is a local operation. See
1050 :hg:`push` for a way to actively distribute your changes.
1050 :hg:`push` for a way to actively distribute your changes.
1051
1051
1052 If a list of files is omitted, all changes reported by :hg:`status`
1052 If a list of files is omitted, all changes reported by :hg:`status`
1053 will be committed.
1053 will be committed.
1054
1054
1055 If you are committing the result of a merge, do not provide any
1055 If you are committing the result of a merge, do not provide any
1056 filenames or -I/-X filters.
1056 filenames or -I/-X filters.
1057
1057
1058 If no commit message is specified, Mercurial starts your
1058 If no commit message is specified, Mercurial starts your
1059 configured editor where you can enter a message. In case your
1059 configured editor where you can enter a message. In case your
1060 commit fails, you will find a backup of your message in
1060 commit fails, you will find a backup of your message in
1061 ``.hg/last-message.txt``.
1061 ``.hg/last-message.txt``.
1062
1062
1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1063 See :hg:`help dates` for a list of formats valid for -d/--date.
1064
1064
1065 Returns 0 on success, 1 if nothing changed.
1065 Returns 0 on success, 1 if nothing changed.
1066 """
1066 """
1067 extra = {}
1067 extra = {}
1068 if opts.get('close_branch'):
1068 if opts.get('close_branch'):
1069 if repo['.'].node() not in repo.branchheads():
1069 if repo['.'].node() not in repo.branchheads():
1070 # The topo heads set is included in the branch heads set of the
1070 # The topo heads set is included in the branch heads set of the
1071 # current branch, so it's sufficient to test branchheads
1071 # current branch, so it's sufficient to test branchheads
1072 raise util.Abort(_('can only close branch heads'))
1072 raise util.Abort(_('can only close branch heads'))
1073 extra['close'] = 1
1073 extra['close'] = 1
1074 e = cmdutil.commiteditor
1074 e = cmdutil.commiteditor
1075 if opts.get('force_editor'):
1075 if opts.get('force_editor'):
1076 e = cmdutil.commitforceeditor
1076 e = cmdutil.commitforceeditor
1077
1077
1078 def commitfunc(ui, repo, message, match, opts):
1078 def commitfunc(ui, repo, message, match, opts):
1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1079 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1080 editor=e, extra=extra)
1080 editor=e, extra=extra)
1081
1081
1082 branch = repo[None].branch()
1082 branch = repo[None].branch()
1083 bheads = repo.branchheads(branch)
1083 bheads = repo.branchheads(branch)
1084
1084
1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1085 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1086 if not node:
1086 if not node:
1087 stat = repo.status(match=scmutil.match(repo, pats, opts))
1087 stat = repo.status(match=scmutil.match(repo, pats, opts))
1088 if stat[3]:
1088 if stat[3]:
1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1089 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1090 % len(stat[3]))
1090 % len(stat[3]))
1091 else:
1091 else:
1092 ui.status(_("nothing changed\n"))
1092 ui.status(_("nothing changed\n"))
1093 return 1
1093 return 1
1094
1094
1095 ctx = repo[node]
1095 ctx = repo[node]
1096 parents = ctx.parents()
1096 parents = ctx.parents()
1097
1097
1098 if bheads and not [x for x in parents
1098 if bheads and not [x for x in parents
1099 if x.node() in bheads and x.branch() == branch]:
1099 if x.node() in bheads and x.branch() == branch]:
1100 ui.status(_('created new head\n'))
1100 ui.status(_('created new head\n'))
1101 # The message is not printed for initial roots. For the other
1101 # The message is not printed for initial roots. For the other
1102 # changesets, it is printed in the following situations:
1102 # changesets, it is printed in the following situations:
1103 #
1103 #
1104 # Par column: for the 2 parents with ...
1104 # Par column: for the 2 parents with ...
1105 # N: null or no parent
1105 # N: null or no parent
1106 # B: parent is on another named branch
1106 # B: parent is on another named branch
1107 # C: parent is a regular non head changeset
1107 # C: parent is a regular non head changeset
1108 # H: parent was a branch head of the current branch
1108 # H: parent was a branch head of the current branch
1109 # Msg column: whether we print "created new head" message
1109 # Msg column: whether we print "created new head" message
1110 # In the following, it is assumed that there already exists some
1110 # In the following, it is assumed that there already exists some
1111 # initial branch heads of the current branch, otherwise nothing is
1111 # initial branch heads of the current branch, otherwise nothing is
1112 # printed anyway.
1112 # printed anyway.
1113 #
1113 #
1114 # Par Msg Comment
1114 # Par Msg Comment
1115 # NN y additional topo root
1115 # NN y additional topo root
1116 #
1116 #
1117 # BN y additional branch root
1117 # BN y additional branch root
1118 # CN y additional topo head
1118 # CN y additional topo head
1119 # HN n usual case
1119 # HN n usual case
1120 #
1120 #
1121 # BB y weird additional branch root
1121 # BB y weird additional branch root
1122 # CB y branch merge
1122 # CB y branch merge
1123 # HB n merge with named branch
1123 # HB n merge with named branch
1124 #
1124 #
1125 # CC y additional head from merge
1125 # CC y additional head from merge
1126 # CH n merge with a head
1126 # CH n merge with a head
1127 #
1127 #
1128 # HH n head merge: head count decreases
1128 # HH n head merge: head count decreases
1129
1129
1130 if not opts.get('close_branch'):
1130 if not opts.get('close_branch'):
1131 for r in parents:
1131 for r in parents:
1132 if r.extra().get('close') and r.branch() == branch:
1132 if r.extra().get('close') and r.branch() == branch:
1133 ui.status(_('reopening closed branch head %d\n') % r)
1133 ui.status(_('reopening closed branch head %d\n') % r)
1134
1134
1135 if ui.debugflag:
1135 if ui.debugflag:
1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1136 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1137 elif ui.verbose:
1137 elif ui.verbose:
1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1138 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1139
1139
1140 @command('copy|cp',
1140 @command('copy|cp',
1141 [('A', 'after', None, _('record a copy that has already occurred')),
1141 [('A', 'after', None, _('record a copy that has already occurred')),
1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1142 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1143 ] + walkopts + dryrunopts,
1143 ] + walkopts + dryrunopts,
1144 _('[OPTION]... [SOURCE]... DEST'))
1144 _('[OPTION]... [SOURCE]... DEST'))
1145 def copy(ui, repo, *pats, **opts):
1145 def copy(ui, repo, *pats, **opts):
1146 """mark files as copied for the next commit
1146 """mark files as copied for the next commit
1147
1147
1148 Mark dest as having copies of source files. If dest is a
1148 Mark dest as having copies of source files. If dest is a
1149 directory, copies are put in that directory. If dest is a file,
1149 directory, copies are put in that directory. If dest is a file,
1150 the source must be a single file.
1150 the source must be a single file.
1151
1151
1152 By default, this command copies the contents of files as they
1152 By default, this command copies the contents of files as they
1153 exist in the working directory. If invoked with -A/--after, the
1153 exist in the working directory. If invoked with -A/--after, the
1154 operation is recorded, but no copying is performed.
1154 operation is recorded, but no copying is performed.
1155
1155
1156 This command takes effect with the next commit. To undo a copy
1156 This command takes effect with the next commit. To undo a copy
1157 before that, see :hg:`revert`.
1157 before that, see :hg:`revert`.
1158
1158
1159 Returns 0 on success, 1 if errors are encountered.
1159 Returns 0 on success, 1 if errors are encountered.
1160 """
1160 """
1161 wlock = repo.wlock(False)
1161 wlock = repo.wlock(False)
1162 try:
1162 try:
1163 return cmdutil.copy(ui, repo, pats, opts)
1163 return cmdutil.copy(ui, repo, pats, opts)
1164 finally:
1164 finally:
1165 wlock.release()
1165 wlock.release()
1166
1166
1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1167 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1168 def debugancestor(ui, repo, *args):
1168 def debugancestor(ui, repo, *args):
1169 """find the ancestor revision of two revisions in a given index"""
1169 """find the ancestor revision of two revisions in a given index"""
1170 if len(args) == 3:
1170 if len(args) == 3:
1171 index, rev1, rev2 = args
1171 index, rev1, rev2 = args
1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1172 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1173 lookup = r.lookup
1173 lookup = r.lookup
1174 elif len(args) == 2:
1174 elif len(args) == 2:
1175 if not repo:
1175 if not repo:
1176 raise util.Abort(_("there is no Mercurial repository here "
1176 raise util.Abort(_("there is no Mercurial repository here "
1177 "(.hg not found)"))
1177 "(.hg not found)"))
1178 rev1, rev2 = args
1178 rev1, rev2 = args
1179 r = repo.changelog
1179 r = repo.changelog
1180 lookup = repo.lookup
1180 lookup = repo.lookup
1181 else:
1181 else:
1182 raise util.Abort(_('either two or three arguments required'))
1182 raise util.Abort(_('either two or three arguments required'))
1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1183 a = r.ancestor(lookup(rev1), lookup(rev2))
1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1184 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1185
1185
1186 @command('debugbuilddag',
1186 @command('debugbuilddag',
1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1187 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1188 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1189 ('n', 'new-file', None, _('add new file at each rev'))],
1189 ('n', 'new-file', None, _('add new file at each rev'))],
1190 _('[OPTION]... [TEXT]'))
1190 _('[OPTION]... [TEXT]'))
1191 def debugbuilddag(ui, repo, text=None,
1191 def debugbuilddag(ui, repo, text=None,
1192 mergeable_file=False,
1192 mergeable_file=False,
1193 overwritten_file=False,
1193 overwritten_file=False,
1194 new_file=False):
1194 new_file=False):
1195 """builds a repo with a given DAG from scratch in the current empty repo
1195 """builds a repo with a given DAG from scratch in the current empty repo
1196
1196
1197 The description of the DAG is read from stdin if not given on the
1197 The description of the DAG is read from stdin if not given on the
1198 command line.
1198 command line.
1199
1199
1200 Elements:
1200 Elements:
1201
1201
1202 - "+n" is a linear run of n nodes based on the current default parent
1202 - "+n" is a linear run of n nodes based on the current default parent
1203 - "." is a single node based on the current default parent
1203 - "." is a single node based on the current default parent
1204 - "$" resets the default parent to null (implied at the start);
1204 - "$" resets the default parent to null (implied at the start);
1205 otherwise the default parent is always the last node created
1205 otherwise the default parent is always the last node created
1206 - "<p" sets the default parent to the backref p
1206 - "<p" sets the default parent to the backref p
1207 - "*p" is a fork at parent p, which is a backref
1207 - "*p" is a fork at parent p, which is a backref
1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1208 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1209 - "/p2" is a merge of the preceding node and p2
1209 - "/p2" is a merge of the preceding node and p2
1210 - ":tag" defines a local tag for the preceding node
1210 - ":tag" defines a local tag for the preceding node
1211 - "@branch" sets the named branch for subsequent nodes
1211 - "@branch" sets the named branch for subsequent nodes
1212 - "#...\\n" is a comment up to the end of the line
1212 - "#...\\n" is a comment up to the end of the line
1213
1213
1214 Whitespace between the above elements is ignored.
1214 Whitespace between the above elements is ignored.
1215
1215
1216 A backref is either
1216 A backref is either
1217
1217
1218 - a number n, which references the node curr-n, where curr is the current
1218 - a number n, which references the node curr-n, where curr is the current
1219 node, or
1219 node, or
1220 - the name of a local tag you placed earlier using ":tag", or
1220 - the name of a local tag you placed earlier using ":tag", or
1221 - empty to denote the default parent.
1221 - empty to denote the default parent.
1222
1222
1223 All string valued-elements are either strictly alphanumeric, or must
1223 All string valued-elements are either strictly alphanumeric, or must
1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1224 be enclosed in double quotes ("..."), with "\\" as escape character.
1225 """
1225 """
1226
1226
1227 if text is None:
1227 if text is None:
1228 ui.status(_("reading DAG from stdin\n"))
1228 ui.status(_("reading DAG from stdin\n"))
1229 text = sys.stdin.read()
1229 text = sys.stdin.read()
1230
1230
1231 cl = repo.changelog
1231 cl = repo.changelog
1232 if len(cl) > 0:
1232 if len(cl) > 0:
1233 raise util.Abort(_('repository is not empty'))
1233 raise util.Abort(_('repository is not empty'))
1234
1234
1235 # determine number of revs in DAG
1235 # determine number of revs in DAG
1236 total = 0
1236 total = 0
1237 for type, data in dagparser.parsedag(text):
1237 for type, data in dagparser.parsedag(text):
1238 if type == 'n':
1238 if type == 'n':
1239 total += 1
1239 total += 1
1240
1240
1241 if mergeable_file:
1241 if mergeable_file:
1242 linesperrev = 2
1242 linesperrev = 2
1243 # make a file with k lines per rev
1243 # make a file with k lines per rev
1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1244 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1245 initialmergedlines.append("")
1245 initialmergedlines.append("")
1246
1246
1247 tags = []
1247 tags = []
1248
1248
1249 tr = repo.transaction("builddag")
1249 tr = repo.transaction("builddag")
1250 try:
1250 try:
1251
1251
1252 at = -1
1252 at = -1
1253 atbranch = 'default'
1253 atbranch = 'default'
1254 nodeids = []
1254 nodeids = []
1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1255 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1256 for type, data in dagparser.parsedag(text):
1256 for type, data in dagparser.parsedag(text):
1257 if type == 'n':
1257 if type == 'n':
1258 ui.note('node %s\n' % str(data))
1258 ui.note('node %s\n' % str(data))
1259 id, ps = data
1259 id, ps = data
1260
1260
1261 files = []
1261 files = []
1262 fctxs = {}
1262 fctxs = {}
1263
1263
1264 p2 = None
1264 p2 = None
1265 if mergeable_file:
1265 if mergeable_file:
1266 fn = "mf"
1266 fn = "mf"
1267 p1 = repo[ps[0]]
1267 p1 = repo[ps[0]]
1268 if len(ps) > 1:
1268 if len(ps) > 1:
1269 p2 = repo[ps[1]]
1269 p2 = repo[ps[1]]
1270 pa = p1.ancestor(p2)
1270 pa = p1.ancestor(p2)
1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1271 base, local, other = [x[fn].data() for x in pa, p1, p2]
1272 m3 = simplemerge.Merge3Text(base, local, other)
1272 m3 = simplemerge.Merge3Text(base, local, other)
1273 ml = [l.strip() for l in m3.merge_lines()]
1273 ml = [l.strip() for l in m3.merge_lines()]
1274 ml.append("")
1274 ml.append("")
1275 elif at > 0:
1275 elif at > 0:
1276 ml = p1[fn].data().split("\n")
1276 ml = p1[fn].data().split("\n")
1277 else:
1277 else:
1278 ml = initialmergedlines
1278 ml = initialmergedlines
1279 ml[id * linesperrev] += " r%i" % id
1279 ml[id * linesperrev] += " r%i" % id
1280 mergedtext = "\n".join(ml)
1280 mergedtext = "\n".join(ml)
1281 files.append(fn)
1281 files.append(fn)
1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1282 fctxs[fn] = context.memfilectx(fn, mergedtext)
1283
1283
1284 if overwritten_file:
1284 if overwritten_file:
1285 fn = "of"
1285 fn = "of"
1286 files.append(fn)
1286 files.append(fn)
1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1287 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1288
1288
1289 if new_file:
1289 if new_file:
1290 fn = "nf%i" % id
1290 fn = "nf%i" % id
1291 files.append(fn)
1291 files.append(fn)
1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1292 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1293 if len(ps) > 1:
1293 if len(ps) > 1:
1294 if not p2:
1294 if not p2:
1295 p2 = repo[ps[1]]
1295 p2 = repo[ps[1]]
1296 for fn in p2:
1296 for fn in p2:
1297 if fn.startswith("nf"):
1297 if fn.startswith("nf"):
1298 files.append(fn)
1298 files.append(fn)
1299 fctxs[fn] = p2[fn]
1299 fctxs[fn] = p2[fn]
1300
1300
1301 def fctxfn(repo, cx, path):
1301 def fctxfn(repo, cx, path):
1302 return fctxs.get(path)
1302 return fctxs.get(path)
1303
1303
1304 if len(ps) == 0 or ps[0] < 0:
1304 if len(ps) == 0 or ps[0] < 0:
1305 pars = [None, None]
1305 pars = [None, None]
1306 elif len(ps) == 1:
1306 elif len(ps) == 1:
1307 pars = [nodeids[ps[0]], None]
1307 pars = [nodeids[ps[0]], None]
1308 else:
1308 else:
1309 pars = [nodeids[p] for p in ps]
1309 pars = [nodeids[p] for p in ps]
1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1310 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1311 date=(id, 0),
1311 date=(id, 0),
1312 user="debugbuilddag",
1312 user="debugbuilddag",
1313 extra={'branch': atbranch})
1313 extra={'branch': atbranch})
1314 nodeid = repo.commitctx(cx)
1314 nodeid = repo.commitctx(cx)
1315 nodeids.append(nodeid)
1315 nodeids.append(nodeid)
1316 at = id
1316 at = id
1317 elif type == 'l':
1317 elif type == 'l':
1318 id, name = data
1318 id, name = data
1319 ui.note('tag %s\n' % name)
1319 ui.note('tag %s\n' % name)
1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1320 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1321 elif type == 'a':
1321 elif type == 'a':
1322 ui.note('branch %s\n' % data)
1322 ui.note('branch %s\n' % data)
1323 atbranch = data
1323 atbranch = data
1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1324 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1325 tr.close()
1325 tr.close()
1326 finally:
1326 finally:
1327 ui.progress(_('building'), None)
1327 ui.progress(_('building'), None)
1328 tr.release()
1328 tr.release()
1329
1329
1330 if tags:
1330 if tags:
1331 repo.opener.write("localtags", "".join(tags))
1331 repo.opener.write("localtags", "".join(tags))
1332
1332
1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1333 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1334 def debugbundle(ui, bundlepath, all=None, **opts):
1334 def debugbundle(ui, bundlepath, all=None, **opts):
1335 """lists the contents of a bundle"""
1335 """lists the contents of a bundle"""
1336 f = url.open(ui, bundlepath)
1336 f = url.open(ui, bundlepath)
1337 try:
1337 try:
1338 gen = changegroup.readbundle(f, bundlepath)
1338 gen = changegroup.readbundle(f, bundlepath)
1339 if all:
1339 if all:
1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1340 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1341
1341
1342 def showchunks(named):
1342 def showchunks(named):
1343 ui.write("\n%s\n" % named)
1343 ui.write("\n%s\n" % named)
1344 chain = None
1344 chain = None
1345 while True:
1345 while True:
1346 chunkdata = gen.deltachunk(chain)
1346 chunkdata = gen.deltachunk(chain)
1347 if not chunkdata:
1347 if not chunkdata:
1348 break
1348 break
1349 node = chunkdata['node']
1349 node = chunkdata['node']
1350 p1 = chunkdata['p1']
1350 p1 = chunkdata['p1']
1351 p2 = chunkdata['p2']
1351 p2 = chunkdata['p2']
1352 cs = chunkdata['cs']
1352 cs = chunkdata['cs']
1353 deltabase = chunkdata['deltabase']
1353 deltabase = chunkdata['deltabase']
1354 delta = chunkdata['delta']
1354 delta = chunkdata['delta']
1355 ui.write("%s %s %s %s %s %s\n" %
1355 ui.write("%s %s %s %s %s %s\n" %
1356 (hex(node), hex(p1), hex(p2),
1356 (hex(node), hex(p1), hex(p2),
1357 hex(cs), hex(deltabase), len(delta)))
1357 hex(cs), hex(deltabase), len(delta)))
1358 chain = node
1358 chain = node
1359
1359
1360 chunkdata = gen.changelogheader()
1360 chunkdata = gen.changelogheader()
1361 showchunks("changelog")
1361 showchunks("changelog")
1362 chunkdata = gen.manifestheader()
1362 chunkdata = gen.manifestheader()
1363 showchunks("manifest")
1363 showchunks("manifest")
1364 while True:
1364 while True:
1365 chunkdata = gen.filelogheader()
1365 chunkdata = gen.filelogheader()
1366 if not chunkdata:
1366 if not chunkdata:
1367 break
1367 break
1368 fname = chunkdata['filename']
1368 fname = chunkdata['filename']
1369 showchunks(fname)
1369 showchunks(fname)
1370 else:
1370 else:
1371 chunkdata = gen.changelogheader()
1371 chunkdata = gen.changelogheader()
1372 chain = None
1372 chain = None
1373 while True:
1373 while True:
1374 chunkdata = gen.deltachunk(chain)
1374 chunkdata = gen.deltachunk(chain)
1375 if not chunkdata:
1375 if not chunkdata:
1376 break
1376 break
1377 node = chunkdata['node']
1377 node = chunkdata['node']
1378 ui.write("%s\n" % hex(node))
1378 ui.write("%s\n" % hex(node))
1379 chain = node
1379 chain = node
1380 finally:
1380 finally:
1381 f.close()
1381 f.close()
1382
1382
1383 @command('debugcheckstate', [], '')
1383 @command('debugcheckstate', [], '')
1384 def debugcheckstate(ui, repo):
1384 def debugcheckstate(ui, repo):
1385 """validate the correctness of the current dirstate"""
1385 """validate the correctness of the current dirstate"""
1386 parent1, parent2 = repo.dirstate.parents()
1386 parent1, parent2 = repo.dirstate.parents()
1387 m1 = repo[parent1].manifest()
1387 m1 = repo[parent1].manifest()
1388 m2 = repo[parent2].manifest()
1388 m2 = repo[parent2].manifest()
1389 errors = 0
1389 errors = 0
1390 for f in repo.dirstate:
1390 for f in repo.dirstate:
1391 state = repo.dirstate[f]
1391 state = repo.dirstate[f]
1392 if state in "nr" and f not in m1:
1392 if state in "nr" and f not in m1:
1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1393 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1394 errors += 1
1394 errors += 1
1395 if state in "a" and f in m1:
1395 if state in "a" and f in m1:
1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1396 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1397 errors += 1
1397 errors += 1
1398 if state in "m" and f not in m1 and f not in m2:
1398 if state in "m" and f not in m1 and f not in m2:
1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1399 ui.warn(_("%s in state %s, but not in either manifest\n") %
1400 (f, state))
1400 (f, state))
1401 errors += 1
1401 errors += 1
1402 for f in m1:
1402 for f in m1:
1403 state = repo.dirstate[f]
1403 state = repo.dirstate[f]
1404 if state not in "nrm":
1404 if state not in "nrm":
1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1405 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1406 errors += 1
1406 errors += 1
1407 if errors:
1407 if errors:
1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1408 error = _(".hg/dirstate inconsistent with current parent's manifest")
1409 raise util.Abort(error)
1409 raise util.Abort(error)
1410
1410
1411 @command('debugcommands', [], _('[COMMAND]'))
1411 @command('debugcommands', [], _('[COMMAND]'))
1412 def debugcommands(ui, cmd='', *args):
1412 def debugcommands(ui, cmd='', *args):
1413 """list all available commands and options"""
1413 """list all available commands and options"""
1414 for cmd, vals in sorted(table.iteritems()):
1414 for cmd, vals in sorted(table.iteritems()):
1415 cmd = cmd.split('|')[0].strip('^')
1415 cmd = cmd.split('|')[0].strip('^')
1416 opts = ', '.join([i[1] for i in vals[1]])
1416 opts = ', '.join([i[1] for i in vals[1]])
1417 ui.write('%s: %s\n' % (cmd, opts))
1417 ui.write('%s: %s\n' % (cmd, opts))
1418
1418
1419 @command('debugcomplete',
1419 @command('debugcomplete',
1420 [('o', 'options', None, _('show the command options'))],
1420 [('o', 'options', None, _('show the command options'))],
1421 _('[-o] CMD'))
1421 _('[-o] CMD'))
1422 def debugcomplete(ui, cmd='', **opts):
1422 def debugcomplete(ui, cmd='', **opts):
1423 """returns the completion list associated with the given command"""
1423 """returns the completion list associated with the given command"""
1424
1424
1425 if opts.get('options'):
1425 if opts.get('options'):
1426 options = []
1426 options = []
1427 otables = [globalopts]
1427 otables = [globalopts]
1428 if cmd:
1428 if cmd:
1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1429 aliases, entry = cmdutil.findcmd(cmd, table, False)
1430 otables.append(entry[1])
1430 otables.append(entry[1])
1431 for t in otables:
1431 for t in otables:
1432 for o in t:
1432 for o in t:
1433 if "(DEPRECATED)" in o[3]:
1433 if "(DEPRECATED)" in o[3]:
1434 continue
1434 continue
1435 if o[0]:
1435 if o[0]:
1436 options.append('-%s' % o[0])
1436 options.append('-%s' % o[0])
1437 options.append('--%s' % o[1])
1437 options.append('--%s' % o[1])
1438 ui.write("%s\n" % "\n".join(options))
1438 ui.write("%s\n" % "\n".join(options))
1439 return
1439 return
1440
1440
1441 cmdlist = cmdutil.findpossible(cmd, table)
1441 cmdlist = cmdutil.findpossible(cmd, table)
1442 if ui.verbose:
1442 if ui.verbose:
1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1443 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1444 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1445
1445
1446 @command('debugdag',
1446 @command('debugdag',
1447 [('t', 'tags', None, _('use tags as labels')),
1447 [('t', 'tags', None, _('use tags as labels')),
1448 ('b', 'branches', None, _('annotate with branch names')),
1448 ('b', 'branches', None, _('annotate with branch names')),
1449 ('', 'dots', None, _('use dots for runs')),
1449 ('', 'dots', None, _('use dots for runs')),
1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1450 ('s', 'spaces', None, _('separate elements by spaces'))],
1451 _('[OPTION]... [FILE [REV]...]'))
1451 _('[OPTION]... [FILE [REV]...]'))
1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1452 def debugdag(ui, repo, file_=None, *revs, **opts):
1453 """format the changelog or an index DAG as a concise textual description
1453 """format the changelog or an index DAG as a concise textual description
1454
1454
1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1455 If you pass a revlog index, the revlog's DAG is emitted. If you list
1456 revision numbers, they get labelled in the output as rN.
1456 revision numbers, they get labelled in the output as rN.
1457
1457
1458 Otherwise, the changelog DAG of the current repo is emitted.
1458 Otherwise, the changelog DAG of the current repo is emitted.
1459 """
1459 """
1460 spaces = opts.get('spaces')
1460 spaces = opts.get('spaces')
1461 dots = opts.get('dots')
1461 dots = opts.get('dots')
1462 if file_:
1462 if file_:
1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1463 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1464 revs = set((int(r) for r in revs))
1464 revs = set((int(r) for r in revs))
1465 def events():
1465 def events():
1466 for r in rlog:
1466 for r in rlog:
1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1467 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1468 if r in revs:
1468 if r in revs:
1469 yield 'l', (r, "r%i" % r)
1469 yield 'l', (r, "r%i" % r)
1470 elif repo:
1470 elif repo:
1471 cl = repo.changelog
1471 cl = repo.changelog
1472 tags = opts.get('tags')
1472 tags = opts.get('tags')
1473 branches = opts.get('branches')
1473 branches = opts.get('branches')
1474 if tags:
1474 if tags:
1475 labels = {}
1475 labels = {}
1476 for l, n in repo.tags().items():
1476 for l, n in repo.tags().items():
1477 labels.setdefault(cl.rev(n), []).append(l)
1477 labels.setdefault(cl.rev(n), []).append(l)
1478 def events():
1478 def events():
1479 b = "default"
1479 b = "default"
1480 for r in cl:
1480 for r in cl:
1481 if branches:
1481 if branches:
1482 newb = cl.read(cl.node(r))[5]['branch']
1482 newb = cl.read(cl.node(r))[5]['branch']
1483 if newb != b:
1483 if newb != b:
1484 yield 'a', newb
1484 yield 'a', newb
1485 b = newb
1485 b = newb
1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1486 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1487 if tags:
1487 if tags:
1488 ls = labels.get(r)
1488 ls = labels.get(r)
1489 if ls:
1489 if ls:
1490 for l in ls:
1490 for l in ls:
1491 yield 'l', (r, l)
1491 yield 'l', (r, l)
1492 else:
1492 else:
1493 raise util.Abort(_('need repo for changelog dag'))
1493 raise util.Abort(_('need repo for changelog dag'))
1494
1494
1495 for line in dagparser.dagtextlines(events(),
1495 for line in dagparser.dagtextlines(events(),
1496 addspaces=spaces,
1496 addspaces=spaces,
1497 wraplabels=True,
1497 wraplabels=True,
1498 wrapannotations=True,
1498 wrapannotations=True,
1499 wrapnonlinear=dots,
1499 wrapnonlinear=dots,
1500 usedots=dots,
1500 usedots=dots,
1501 maxlinewidth=70):
1501 maxlinewidth=70):
1502 ui.write(line)
1502 ui.write(line)
1503 ui.write("\n")
1503 ui.write("\n")
1504
1504
1505 @command('debugdata',
1505 @command('debugdata',
1506 [('c', 'changelog', False, _('open changelog')),
1506 [('c', 'changelog', False, _('open changelog')),
1507 ('m', 'manifest', False, _('open manifest'))],
1507 ('m', 'manifest', False, _('open manifest'))],
1508 _('-c|-m|FILE REV'))
1508 _('-c|-m|FILE REV'))
1509 def debugdata(ui, repo, file_, rev = None, **opts):
1509 def debugdata(ui, repo, file_, rev = None, **opts):
1510 """dump the contents of a data file revision"""
1510 """dump the contents of a data file revision"""
1511 if opts.get('changelog') or opts.get('manifest'):
1511 if opts.get('changelog') or opts.get('manifest'):
1512 file_, rev = None, file_
1512 file_, rev = None, file_
1513 elif rev is None:
1513 elif rev is None:
1514 raise error.CommandError('debugdata', _('invalid arguments'))
1514 raise error.CommandError('debugdata', _('invalid arguments'))
1515 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1515 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1516 try:
1516 try:
1517 ui.write(r.revision(r.lookup(rev)))
1517 ui.write(r.revision(r.lookup(rev)))
1518 except KeyError:
1518 except KeyError:
1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1519 raise util.Abort(_('invalid revision identifier %s') % rev)
1520
1520
1521 @command('debugdate',
1521 @command('debugdate',
1522 [('e', 'extended', None, _('try extended date formats'))],
1522 [('e', 'extended', None, _('try extended date formats'))],
1523 _('[-e] DATE [RANGE]'))
1523 _('[-e] DATE [RANGE]'))
1524 def debugdate(ui, date, range=None, **opts):
1524 def debugdate(ui, date, range=None, **opts):
1525 """parse and display a date"""
1525 """parse and display a date"""
1526 if opts["extended"]:
1526 if opts["extended"]:
1527 d = util.parsedate(date, util.extendeddateformats)
1527 d = util.parsedate(date, util.extendeddateformats)
1528 else:
1528 else:
1529 d = util.parsedate(date)
1529 d = util.parsedate(date)
1530 ui.write("internal: %s %s\n" % d)
1530 ui.write("internal: %s %s\n" % d)
1531 ui.write("standard: %s\n" % util.datestr(d))
1531 ui.write("standard: %s\n" % util.datestr(d))
1532 if range:
1532 if range:
1533 m = util.matchdate(range)
1533 m = util.matchdate(range)
1534 ui.write("match: %s\n" % m(d[0]))
1534 ui.write("match: %s\n" % m(d[0]))
1535
1535
1536 @command('debugdiscovery',
1536 @command('debugdiscovery',
1537 [('', 'old', None, _('use old-style discovery')),
1537 [('', 'old', None, _('use old-style discovery')),
1538 ('', 'nonheads', None,
1538 ('', 'nonheads', None,
1539 _('use old-style discovery with non-heads included')),
1539 _('use old-style discovery with non-heads included')),
1540 ] + remoteopts,
1540 ] + remoteopts,
1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1541 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1542 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1543 """runs the changeset discovery protocol in isolation"""
1543 """runs the changeset discovery protocol in isolation"""
1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1544 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1545 remote = hg.repository(hg.remoteui(repo, opts), remoteurl)
1545 remote = hg.repository(hg.remoteui(repo, opts), remoteurl)
1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1546 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1547
1547
1548 # make sure tests are repeatable
1548 # make sure tests are repeatable
1549 random.seed(12323)
1549 random.seed(12323)
1550
1550
1551 def doit(localheads, remoteheads):
1551 def doit(localheads, remoteheads):
1552 if opts.get('old'):
1552 if opts.get('old'):
1553 if localheads:
1553 if localheads:
1554 raise util.Abort('cannot use localheads with old style discovery')
1554 raise util.Abort('cannot use localheads with old style discovery')
1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1555 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1556 force=True)
1556 force=True)
1557 common = set(common)
1557 common = set(common)
1558 if not opts.get('nonheads'):
1558 if not opts.get('nonheads'):
1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1559 ui.write("unpruned common: %s\n" % " ".join([short(n)
1560 for n in common]))
1560 for n in common]))
1561 dag = dagutil.revlogdag(repo.changelog)
1561 dag = dagutil.revlogdag(repo.changelog)
1562 all = dag.ancestorset(dag.internalizeall(common))
1562 all = dag.ancestorset(dag.internalizeall(common))
1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1563 common = dag.externalizeall(dag.headsetofconnecteds(all))
1564 else:
1564 else:
1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1565 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1566 common = set(common)
1566 common = set(common)
1567 rheads = set(hds)
1567 rheads = set(hds)
1568 lheads = set(repo.heads())
1568 lheads = set(repo.heads())
1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1569 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1570 if lheads <= common:
1570 if lheads <= common:
1571 ui.write("local is subset\n")
1571 ui.write("local is subset\n")
1572 elif rheads <= common:
1572 elif rheads <= common:
1573 ui.write("remote is subset\n")
1573 ui.write("remote is subset\n")
1574
1574
1575 serverlogs = opts.get('serverlog')
1575 serverlogs = opts.get('serverlog')
1576 if serverlogs:
1576 if serverlogs:
1577 for filename in serverlogs:
1577 for filename in serverlogs:
1578 logfile = open(filename, 'r')
1578 logfile = open(filename, 'r')
1579 try:
1579 try:
1580 line = logfile.readline()
1580 line = logfile.readline()
1581 while line:
1581 while line:
1582 parts = line.strip().split(';')
1582 parts = line.strip().split(';')
1583 op = parts[1]
1583 op = parts[1]
1584 if op == 'cg':
1584 if op == 'cg':
1585 pass
1585 pass
1586 elif op == 'cgss':
1586 elif op == 'cgss':
1587 doit(parts[2].split(' '), parts[3].split(' '))
1587 doit(parts[2].split(' '), parts[3].split(' '))
1588 elif op == 'unb':
1588 elif op == 'unb':
1589 doit(parts[3].split(' '), parts[2].split(' '))
1589 doit(parts[3].split(' '), parts[2].split(' '))
1590 line = logfile.readline()
1590 line = logfile.readline()
1591 finally:
1591 finally:
1592 logfile.close()
1592 logfile.close()
1593
1593
1594 else:
1594 else:
1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1595 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1596 opts.get('remote_head'))
1596 opts.get('remote_head'))
1597 localrevs = opts.get('local_head')
1597 localrevs = opts.get('local_head')
1598 doit(localrevs, remoterevs)
1598 doit(localrevs, remoterevs)
1599
1599
1600 @command('debugfileset', [], ('REVSPEC'))
1600 @command('debugfileset', [], ('REVSPEC'))
1601 def debugfileset(ui, repo, expr):
1601 def debugfileset(ui, repo, expr):
1602 '''parse and apply a fileset specification'''
1602 '''parse and apply a fileset specification'''
1603 if ui.verbose:
1603 if ui.verbose:
1604 tree = fileset.parse(expr)[0]
1604 tree = fileset.parse(expr)[0]
1605 ui.note(tree, "\n")
1605 ui.note(tree, "\n")
1606
1606
1607 @command('debugfsinfo', [], _('[PATH]'))
1607 @command('debugfsinfo', [], _('[PATH]'))
1608 def debugfsinfo(ui, path = "."):
1608 def debugfsinfo(ui, path = "."):
1609 """show information detected about current filesystem"""
1609 """show information detected about current filesystem"""
1610 util.writefile('.debugfsinfo', '')
1610 util.writefile('.debugfsinfo', '')
1611 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1611 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1612 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1612 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1613 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1613 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1614 and 'yes' or 'no'))
1614 and 'yes' or 'no'))
1615 os.unlink('.debugfsinfo')
1615 os.unlink('.debugfsinfo')
1616
1616
1617 @command('debuggetbundle',
1617 @command('debuggetbundle',
1618 [('H', 'head', [], _('id of head node'), _('ID')),
1618 [('H', 'head', [], _('id of head node'), _('ID')),
1619 ('C', 'common', [], _('id of common node'), _('ID')),
1619 ('C', 'common', [], _('id of common node'), _('ID')),
1620 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1620 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1621 _('REPO FILE [-H|-C ID]...'))
1621 _('REPO FILE [-H|-C ID]...'))
1622 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1622 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1623 """retrieves a bundle from a repo
1623 """retrieves a bundle from a repo
1624
1624
1625 Every ID must be a full-length hex node id string. Saves the bundle to the
1625 Every ID must be a full-length hex node id string. Saves the bundle to the
1626 given file.
1626 given file.
1627 """
1627 """
1628 repo = hg.repository(ui, repopath)
1628 repo = hg.repository(ui, repopath)
1629 if not repo.capable('getbundle'):
1629 if not repo.capable('getbundle'):
1630 raise util.Abort("getbundle() not supported by target repository")
1630 raise util.Abort("getbundle() not supported by target repository")
1631 args = {}
1631 args = {}
1632 if common:
1632 if common:
1633 args['common'] = [bin(s) for s in common]
1633 args['common'] = [bin(s) for s in common]
1634 if head:
1634 if head:
1635 args['heads'] = [bin(s) for s in head]
1635 args['heads'] = [bin(s) for s in head]
1636 bundle = repo.getbundle('debug', **args)
1636 bundle = repo.getbundle('debug', **args)
1637
1637
1638 bundletype = opts.get('type', 'bzip2').lower()
1638 bundletype = opts.get('type', 'bzip2').lower()
1639 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1639 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1640 bundletype = btypes.get(bundletype)
1640 bundletype = btypes.get(bundletype)
1641 if bundletype not in changegroup.bundletypes:
1641 if bundletype not in changegroup.bundletypes:
1642 raise util.Abort(_('unknown bundle type specified with --type'))
1642 raise util.Abort(_('unknown bundle type specified with --type'))
1643 changegroup.writebundle(bundle, bundlepath, bundletype)
1643 changegroup.writebundle(bundle, bundlepath, bundletype)
1644
1644
1645 @command('debugignore', [], '')
1645 @command('debugignore', [], '')
1646 def debugignore(ui, repo, *values, **opts):
1646 def debugignore(ui, repo, *values, **opts):
1647 """display the combined ignore pattern"""
1647 """display the combined ignore pattern"""
1648 ignore = repo.dirstate._ignore
1648 ignore = repo.dirstate._ignore
1649 if hasattr(ignore, 'includepat'):
1649 if hasattr(ignore, 'includepat'):
1650 ui.write("%s\n" % ignore.includepat)
1650 ui.write("%s\n" % ignore.includepat)
1651 else:
1651 else:
1652 raise util.Abort(_("no ignore patterns found"))
1652 raise util.Abort(_("no ignore patterns found"))
1653
1653
1654 @command('debugindex',
1654 @command('debugindex',
1655 [('c', 'changelog', False, _('open changelog')),
1655 [('c', 'changelog', False, _('open changelog')),
1656 ('m', 'manifest', False, _('open manifest')),
1656 ('m', 'manifest', False, _('open manifest')),
1657 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1657 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1658 _('[-f FORMAT] -c|-m|FILE'))
1658 _('[-f FORMAT] -c|-m|FILE'))
1659 def debugindex(ui, repo, file_ = None, **opts):
1659 def debugindex(ui, repo, file_ = None, **opts):
1660 """dump the contents of an index file"""
1660 """dump the contents of an index file"""
1661 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1661 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1662 format = opts.get('format', 0)
1662 format = opts.get('format', 0)
1663 if format not in (0, 1):
1663 if format not in (0, 1):
1664 raise util.Abort(_("unknown format %d") % format)
1664 raise util.Abort(_("unknown format %d") % format)
1665
1665
1666 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1666 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1667 if generaldelta:
1667 if generaldelta:
1668 basehdr = ' delta'
1668 basehdr = ' delta'
1669 else:
1669 else:
1670 basehdr = ' base'
1670 basehdr = ' base'
1671
1671
1672 if format == 0:
1672 if format == 0:
1673 ui.write(" rev offset length " + basehdr + " linkrev"
1673 ui.write(" rev offset length " + basehdr + " linkrev"
1674 " nodeid p1 p2\n")
1674 " nodeid p1 p2\n")
1675 elif format == 1:
1675 elif format == 1:
1676 ui.write(" rev flag offset length"
1676 ui.write(" rev flag offset length"
1677 " size " + basehdr + " link p1 p2 nodeid\n")
1677 " size " + basehdr + " link p1 p2 nodeid\n")
1678
1678
1679 for i in r:
1679 for i in r:
1680 node = r.node(i)
1680 node = r.node(i)
1681 if generaldelta:
1681 if generaldelta:
1682 base = r.deltaparent(i)
1682 base = r.deltaparent(i)
1683 else:
1683 else:
1684 base = r.chainbase(i)
1684 base = r.chainbase(i)
1685 if format == 0:
1685 if format == 0:
1686 try:
1686 try:
1687 pp = r.parents(node)
1687 pp = r.parents(node)
1688 except:
1688 except:
1689 pp = [nullid, nullid]
1689 pp = [nullid, nullid]
1690 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1690 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1691 i, r.start(i), r.length(i), base, r.linkrev(i),
1691 i, r.start(i), r.length(i), base, r.linkrev(i),
1692 short(node), short(pp[0]), short(pp[1])))
1692 short(node), short(pp[0]), short(pp[1])))
1693 elif format == 1:
1693 elif format == 1:
1694 pr = r.parentrevs(i)
1694 pr = r.parentrevs(i)
1695 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1695 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1696 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1696 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1697 base, r.linkrev(i), pr[0], pr[1], short(node)))
1697 base, r.linkrev(i), pr[0], pr[1], short(node)))
1698
1698
1699 @command('debugindexdot', [], _('FILE'))
1699 @command('debugindexdot', [], _('FILE'))
1700 def debugindexdot(ui, repo, file_):
1700 def debugindexdot(ui, repo, file_):
1701 """dump an index DAG as a graphviz dot file"""
1701 """dump an index DAG as a graphviz dot file"""
1702 r = None
1702 r = None
1703 if repo:
1703 if repo:
1704 filelog = repo.file(file_)
1704 filelog = repo.file(file_)
1705 if len(filelog):
1705 if len(filelog):
1706 r = filelog
1706 r = filelog
1707 if not r:
1707 if not r:
1708 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1708 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1709 ui.write("digraph G {\n")
1709 ui.write("digraph G {\n")
1710 for i in r:
1710 for i in r:
1711 node = r.node(i)
1711 node = r.node(i)
1712 pp = r.parents(node)
1712 pp = r.parents(node)
1713 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1713 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1714 if pp[1] != nullid:
1714 if pp[1] != nullid:
1715 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1715 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1716 ui.write("}\n")
1716 ui.write("}\n")
1717
1717
1718 @command('debuginstall', [], '')
1718 @command('debuginstall', [], '')
1719 def debuginstall(ui):
1719 def debuginstall(ui):
1720 '''test Mercurial installation
1720 '''test Mercurial installation
1721
1721
1722 Returns 0 on success.
1722 Returns 0 on success.
1723 '''
1723 '''
1724
1724
1725 def writetemp(contents):
1725 def writetemp(contents):
1726 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1726 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1727 f = os.fdopen(fd, "wb")
1727 f = os.fdopen(fd, "wb")
1728 f.write(contents)
1728 f.write(contents)
1729 f.close()
1729 f.close()
1730 return name
1730 return name
1731
1731
1732 problems = 0
1732 problems = 0
1733
1733
1734 # encoding
1734 # encoding
1735 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1735 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1736 try:
1736 try:
1737 encoding.fromlocal("test")
1737 encoding.fromlocal("test")
1738 except util.Abort, inst:
1738 except util.Abort, inst:
1739 ui.write(" %s\n" % inst)
1739 ui.write(" %s\n" % inst)
1740 ui.write(_(" (check that your locale is properly set)\n"))
1740 ui.write(_(" (check that your locale is properly set)\n"))
1741 problems += 1
1741 problems += 1
1742
1742
1743 # compiled modules
1743 # compiled modules
1744 ui.status(_("Checking installed modules (%s)...\n")
1744 ui.status(_("Checking installed modules (%s)...\n")
1745 % os.path.dirname(__file__))
1745 % os.path.dirname(__file__))
1746 try:
1746 try:
1747 import bdiff, mpatch, base85, osutil
1747 import bdiff, mpatch, base85, osutil
1748 except Exception, inst:
1748 except Exception, inst:
1749 ui.write(" %s\n" % inst)
1749 ui.write(" %s\n" % inst)
1750 ui.write(_(" One or more extensions could not be found"))
1750 ui.write(_(" One or more extensions could not be found"))
1751 ui.write(_(" (check that you compiled the extensions)\n"))
1751 ui.write(_(" (check that you compiled the extensions)\n"))
1752 problems += 1
1752 problems += 1
1753
1753
1754 # templates
1754 # templates
1755 ui.status(_("Checking templates...\n"))
1755 ui.status(_("Checking templates...\n"))
1756 try:
1756 try:
1757 import templater
1757 import templater
1758 templater.templater(templater.templatepath("map-cmdline.default"))
1758 templater.templater(templater.templatepath("map-cmdline.default"))
1759 except Exception, inst:
1759 except Exception, inst:
1760 ui.write(" %s\n" % inst)
1760 ui.write(" %s\n" % inst)
1761 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1761 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1762 problems += 1
1762 problems += 1
1763
1763
1764 # editor
1764 # editor
1765 ui.status(_("Checking commit editor...\n"))
1765 ui.status(_("Checking commit editor...\n"))
1766 editor = ui.geteditor()
1766 editor = ui.geteditor()
1767 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1767 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1768 if not cmdpath:
1768 if not cmdpath:
1769 if editor == 'vi':
1769 if editor == 'vi':
1770 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1770 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1771 ui.write(_(" (specify a commit editor in your configuration"
1771 ui.write(_(" (specify a commit editor in your configuration"
1772 " file)\n"))
1772 " file)\n"))
1773 else:
1773 else:
1774 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1774 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1775 ui.write(_(" (specify a commit editor in your configuration"
1775 ui.write(_(" (specify a commit editor in your configuration"
1776 " file)\n"))
1776 " file)\n"))
1777 problems += 1
1777 problems += 1
1778
1778
1779 # check username
1779 # check username
1780 ui.status(_("Checking username...\n"))
1780 ui.status(_("Checking username...\n"))
1781 try:
1781 try:
1782 ui.username()
1782 ui.username()
1783 except util.Abort, e:
1783 except util.Abort, e:
1784 ui.write(" %s\n" % e)
1784 ui.write(" %s\n" % e)
1785 ui.write(_(" (specify a username in your configuration file)\n"))
1785 ui.write(_(" (specify a username in your configuration file)\n"))
1786 problems += 1
1786 problems += 1
1787
1787
1788 if not problems:
1788 if not problems:
1789 ui.status(_("No problems detected\n"))
1789 ui.status(_("No problems detected\n"))
1790 else:
1790 else:
1791 ui.write(_("%s problems detected,"
1791 ui.write(_("%s problems detected,"
1792 " please check your install!\n") % problems)
1792 " please check your install!\n") % problems)
1793
1793
1794 return problems
1794 return problems
1795
1795
1796 @command('debugknown', [], _('REPO ID...'))
1796 @command('debugknown', [], _('REPO ID...'))
1797 def debugknown(ui, repopath, *ids, **opts):
1797 def debugknown(ui, repopath, *ids, **opts):
1798 """test whether node ids are known to a repo
1798 """test whether node ids are known to a repo
1799
1799
1800 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1800 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1801 indicating unknown/known.
1801 indicating unknown/known.
1802 """
1802 """
1803 repo = hg.repository(ui, repopath)
1803 repo = hg.repository(ui, repopath)
1804 if not repo.capable('known'):
1804 if not repo.capable('known'):
1805 raise util.Abort("known() not supported by target repository")
1805 raise util.Abort("known() not supported by target repository")
1806 flags = repo.known([bin(s) for s in ids])
1806 flags = repo.known([bin(s) for s in ids])
1807 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1807 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1808
1808
1809 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1809 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1810 def debugpushkey(ui, repopath, namespace, *keyinfo):
1810 def debugpushkey(ui, repopath, namespace, *keyinfo):
1811 '''access the pushkey key/value protocol
1811 '''access the pushkey key/value protocol
1812
1812
1813 With two args, list the keys in the given namespace.
1813 With two args, list the keys in the given namespace.
1814
1814
1815 With five args, set a key to new if it currently is set to old.
1815 With five args, set a key to new if it currently is set to old.
1816 Reports success or failure.
1816 Reports success or failure.
1817 '''
1817 '''
1818
1818
1819 target = hg.repository(ui, repopath)
1819 target = hg.repository(ui, repopath)
1820 if keyinfo:
1820 if keyinfo:
1821 key, old, new = keyinfo
1821 key, old, new = keyinfo
1822 r = target.pushkey(namespace, key, old, new)
1822 r = target.pushkey(namespace, key, old, new)
1823 ui.status(str(r) + '\n')
1823 ui.status(str(r) + '\n')
1824 return not r
1824 return not r
1825 else:
1825 else:
1826 for k, v in target.listkeys(namespace).iteritems():
1826 for k, v in target.listkeys(namespace).iteritems():
1827 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1827 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1828 v.encode('string-escape')))
1828 v.encode('string-escape')))
1829
1829
1830 @command('debugrebuildstate',
1830 @command('debugrebuildstate',
1831 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1831 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1832 _('[-r REV] [REV]'))
1832 _('[-r REV] [REV]'))
1833 def debugrebuildstate(ui, repo, rev="tip"):
1833 def debugrebuildstate(ui, repo, rev="tip"):
1834 """rebuild the dirstate as it would look like for the given revision"""
1834 """rebuild the dirstate as it would look like for the given revision"""
1835 ctx = scmutil.revsingle(repo, rev)
1835 ctx = scmutil.revsingle(repo, rev)
1836 wlock = repo.wlock()
1836 wlock = repo.wlock()
1837 try:
1837 try:
1838 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1838 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1839 finally:
1839 finally:
1840 wlock.release()
1840 wlock.release()
1841
1841
1842 @command('debugrename',
1842 @command('debugrename',
1843 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1843 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1844 _('[-r REV] FILE'))
1844 _('[-r REV] FILE'))
1845 def debugrename(ui, repo, file1, *pats, **opts):
1845 def debugrename(ui, repo, file1, *pats, **opts):
1846 """dump rename information"""
1846 """dump rename information"""
1847
1847
1848 ctx = scmutil.revsingle(repo, opts.get('rev'))
1848 ctx = scmutil.revsingle(repo, opts.get('rev'))
1849 m = scmutil.match(repo, (file1,) + pats, opts)
1849 m = scmutil.match(repo, (file1,) + pats, opts)
1850 for abs in ctx.walk(m):
1850 for abs in ctx.walk(m):
1851 fctx = ctx[abs]
1851 fctx = ctx[abs]
1852 o = fctx.filelog().renamed(fctx.filenode())
1852 o = fctx.filelog().renamed(fctx.filenode())
1853 rel = m.rel(abs)
1853 rel = m.rel(abs)
1854 if o:
1854 if o:
1855 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1855 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1856 else:
1856 else:
1857 ui.write(_("%s not renamed\n") % rel)
1857 ui.write(_("%s not renamed\n") % rel)
1858
1858
1859 @command('debugrevlog',
1859 @command('debugrevlog',
1860 [('c', 'changelog', False, _('open changelog')),
1860 [('c', 'changelog', False, _('open changelog')),
1861 ('m', 'manifest', False, _('open manifest')),
1861 ('m', 'manifest', False, _('open manifest')),
1862 ('d', 'dump', False, _('dump index data'))],
1862 ('d', 'dump', False, _('dump index data'))],
1863 _('-c|-m|FILE'))
1863 _('-c|-m|FILE'))
1864 def debugrevlog(ui, repo, file_ = None, **opts):
1864 def debugrevlog(ui, repo, file_ = None, **opts):
1865 """show data and statistics about a revlog"""
1865 """show data and statistics about a revlog"""
1866 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1866 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1867
1867
1868 if opts.get("dump"):
1868 if opts.get("dump"):
1869 numrevs = len(r)
1869 numrevs = len(r)
1870 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1870 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1871 " rawsize totalsize compression heads\n")
1871 " rawsize totalsize compression heads\n")
1872 ts = 0
1872 ts = 0
1873 heads = set()
1873 heads = set()
1874 for rev in xrange(numrevs):
1874 for rev in xrange(numrevs):
1875 dbase = r.deltaparent(rev)
1875 dbase = r.deltaparent(rev)
1876 if dbase == -1:
1876 if dbase == -1:
1877 dbase = rev
1877 dbase = rev
1878 cbase = r.chainbase(rev)
1878 cbase = r.chainbase(rev)
1879 p1, p2 = r.parentrevs(rev)
1879 p1, p2 = r.parentrevs(rev)
1880 rs = r.rawsize(rev)
1880 rs = r.rawsize(rev)
1881 ts = ts + rs
1881 ts = ts + rs
1882 heads -= set(r.parentrevs(rev))
1882 heads -= set(r.parentrevs(rev))
1883 heads.add(rev)
1883 heads.add(rev)
1884 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1884 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1885 (rev, p1, p2, r.start(rev), r.end(rev),
1885 (rev, p1, p2, r.start(rev), r.end(rev),
1886 r.start(dbase), r.start(cbase),
1886 r.start(dbase), r.start(cbase),
1887 r.start(p1), r.start(p2),
1887 r.start(p1), r.start(p2),
1888 rs, ts, ts / r.end(rev), len(heads)))
1888 rs, ts, ts / r.end(rev), len(heads)))
1889 return 0
1889 return 0
1890
1890
1891 v = r.version
1891 v = r.version
1892 format = v & 0xFFFF
1892 format = v & 0xFFFF
1893 flags = []
1893 flags = []
1894 gdelta = False
1894 gdelta = False
1895 if v & revlog.REVLOGNGINLINEDATA:
1895 if v & revlog.REVLOGNGINLINEDATA:
1896 flags.append('inline')
1896 flags.append('inline')
1897 if v & revlog.REVLOGGENERALDELTA:
1897 if v & revlog.REVLOGGENERALDELTA:
1898 gdelta = True
1898 gdelta = True
1899 flags.append('generaldelta')
1899 flags.append('generaldelta')
1900 if not flags:
1900 if not flags:
1901 flags = ['(none)']
1901 flags = ['(none)']
1902
1902
1903 nummerges = 0
1903 nummerges = 0
1904 numfull = 0
1904 numfull = 0
1905 numprev = 0
1905 numprev = 0
1906 nump1 = 0
1906 nump1 = 0
1907 nump2 = 0
1907 nump2 = 0
1908 numother = 0
1908 numother = 0
1909 nump1prev = 0
1909 nump1prev = 0
1910 nump2prev = 0
1910 nump2prev = 0
1911 chainlengths = []
1911 chainlengths = []
1912
1912
1913 datasize = [None, 0, 0L]
1913 datasize = [None, 0, 0L]
1914 fullsize = [None, 0, 0L]
1914 fullsize = [None, 0, 0L]
1915 deltasize = [None, 0, 0L]
1915 deltasize = [None, 0, 0L]
1916
1916
1917 def addsize(size, l):
1917 def addsize(size, l):
1918 if l[0] is None or size < l[0]:
1918 if l[0] is None or size < l[0]:
1919 l[0] = size
1919 l[0] = size
1920 if size > l[1]:
1920 if size > l[1]:
1921 l[1] = size
1921 l[1] = size
1922 l[2] += size
1922 l[2] += size
1923
1923
1924 numrevs = len(r)
1924 numrevs = len(r)
1925 for rev in xrange(numrevs):
1925 for rev in xrange(numrevs):
1926 p1, p2 = r.parentrevs(rev)
1926 p1, p2 = r.parentrevs(rev)
1927 delta = r.deltaparent(rev)
1927 delta = r.deltaparent(rev)
1928 if format > 0:
1928 if format > 0:
1929 addsize(r.rawsize(rev), datasize)
1929 addsize(r.rawsize(rev), datasize)
1930 if p2 != nullrev:
1930 if p2 != nullrev:
1931 nummerges += 1
1931 nummerges += 1
1932 size = r.length(rev)
1932 size = r.length(rev)
1933 if delta == nullrev:
1933 if delta == nullrev:
1934 chainlengths.append(0)
1934 chainlengths.append(0)
1935 numfull += 1
1935 numfull += 1
1936 addsize(size, fullsize)
1936 addsize(size, fullsize)
1937 else:
1937 else:
1938 chainlengths.append(chainlengths[delta] + 1)
1938 chainlengths.append(chainlengths[delta] + 1)
1939 addsize(size, deltasize)
1939 addsize(size, deltasize)
1940 if delta == rev - 1:
1940 if delta == rev - 1:
1941 numprev += 1
1941 numprev += 1
1942 if delta == p1:
1942 if delta == p1:
1943 nump1prev += 1
1943 nump1prev += 1
1944 elif delta == p2:
1944 elif delta == p2:
1945 nump2prev += 1
1945 nump2prev += 1
1946 elif delta == p1:
1946 elif delta == p1:
1947 nump1 += 1
1947 nump1 += 1
1948 elif delta == p2:
1948 elif delta == p2:
1949 nump2 += 1
1949 nump2 += 1
1950 elif delta != nullrev:
1950 elif delta != nullrev:
1951 numother += 1
1951 numother += 1
1952
1952
1953 numdeltas = numrevs - numfull
1953 numdeltas = numrevs - numfull
1954 numoprev = numprev - nump1prev - nump2prev
1954 numoprev = numprev - nump1prev - nump2prev
1955 totalrawsize = datasize[2]
1955 totalrawsize = datasize[2]
1956 datasize[2] /= numrevs
1956 datasize[2] /= numrevs
1957 fulltotal = fullsize[2]
1957 fulltotal = fullsize[2]
1958 fullsize[2] /= numfull
1958 fullsize[2] /= numfull
1959 deltatotal = deltasize[2]
1959 deltatotal = deltasize[2]
1960 deltasize[2] /= numrevs - numfull
1960 deltasize[2] /= numrevs - numfull
1961 totalsize = fulltotal + deltatotal
1961 totalsize = fulltotal + deltatotal
1962 avgchainlen = sum(chainlengths) / numrevs
1962 avgchainlen = sum(chainlengths) / numrevs
1963 compratio = totalrawsize / totalsize
1963 compratio = totalrawsize / totalsize
1964
1964
1965 basedfmtstr = '%%%dd\n'
1965 basedfmtstr = '%%%dd\n'
1966 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1966 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1967
1967
1968 def dfmtstr(max):
1968 def dfmtstr(max):
1969 return basedfmtstr % len(str(max))
1969 return basedfmtstr % len(str(max))
1970 def pcfmtstr(max, padding=0):
1970 def pcfmtstr(max, padding=0):
1971 return basepcfmtstr % (len(str(max)), ' ' * padding)
1971 return basepcfmtstr % (len(str(max)), ' ' * padding)
1972
1972
1973 def pcfmt(value, total):
1973 def pcfmt(value, total):
1974 return (value, 100 * float(value) / total)
1974 return (value, 100 * float(value) / total)
1975
1975
1976 ui.write('format : %d\n' % format)
1976 ui.write('format : %d\n' % format)
1977 ui.write('flags : %s\n' % ', '.join(flags))
1977 ui.write('flags : %s\n' % ', '.join(flags))
1978
1978
1979 ui.write('\n')
1979 ui.write('\n')
1980 fmt = pcfmtstr(totalsize)
1980 fmt = pcfmtstr(totalsize)
1981 fmt2 = dfmtstr(totalsize)
1981 fmt2 = dfmtstr(totalsize)
1982 ui.write('revisions : ' + fmt2 % numrevs)
1982 ui.write('revisions : ' + fmt2 % numrevs)
1983 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1983 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1984 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1984 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1985 ui.write('revisions : ' + fmt2 % numrevs)
1985 ui.write('revisions : ' + fmt2 % numrevs)
1986 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1986 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1987 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1987 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1988 ui.write('revision size : ' + fmt2 % totalsize)
1988 ui.write('revision size : ' + fmt2 % totalsize)
1989 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1989 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
1990 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1990 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
1991
1991
1992 ui.write('\n')
1992 ui.write('\n')
1993 fmt = dfmtstr(max(avgchainlen, compratio))
1993 fmt = dfmtstr(max(avgchainlen, compratio))
1994 ui.write('avg chain length : ' + fmt % avgchainlen)
1994 ui.write('avg chain length : ' + fmt % avgchainlen)
1995 ui.write('compression ratio : ' + fmt % compratio)
1995 ui.write('compression ratio : ' + fmt % compratio)
1996
1996
1997 if format > 0:
1997 if format > 0:
1998 ui.write('\n')
1998 ui.write('\n')
1999 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
1999 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2000 % tuple(datasize))
2000 % tuple(datasize))
2001 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2001 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2002 % tuple(fullsize))
2002 % tuple(fullsize))
2003 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2003 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2004 % tuple(deltasize))
2004 % tuple(deltasize))
2005
2005
2006 if numdeltas > 0:
2006 if numdeltas > 0:
2007 ui.write('\n')
2007 ui.write('\n')
2008 fmt = pcfmtstr(numdeltas)
2008 fmt = pcfmtstr(numdeltas)
2009 fmt2 = pcfmtstr(numdeltas, 4)
2009 fmt2 = pcfmtstr(numdeltas, 4)
2010 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2010 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2011 if numprev > 0:
2011 if numprev > 0:
2012 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2012 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2013 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2013 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2014 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2014 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2015 if gdelta:
2015 if gdelta:
2016 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2016 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2017 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2017 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2018 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2018 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2019
2019
2020 @command('debugrevspec', [], ('REVSPEC'))
2020 @command('debugrevspec', [], ('REVSPEC'))
2021 def debugrevspec(ui, repo, expr):
2021 def debugrevspec(ui, repo, expr):
2022 '''parse and apply a revision specification'''
2022 '''parse and apply a revision specification'''
2023 if ui.verbose:
2023 if ui.verbose:
2024 tree = revset.parse(expr)[0]
2024 tree = revset.parse(expr)[0]
2025 ui.note(tree, "\n")
2025 ui.note(tree, "\n")
2026 newtree = revset.findaliases(ui, tree)
2026 newtree = revset.findaliases(ui, tree)
2027 if newtree != tree:
2027 if newtree != tree:
2028 ui.note(newtree, "\n")
2028 ui.note(newtree, "\n")
2029 func = revset.match(ui, expr)
2029 func = revset.match(ui, expr)
2030 for c in func(repo, range(len(repo))):
2030 for c in func(repo, range(len(repo))):
2031 ui.write("%s\n" % c)
2031 ui.write("%s\n" % c)
2032
2032
2033 @command('debugsetparents', [], _('REV1 [REV2]'))
2033 @command('debugsetparents', [], _('REV1 [REV2]'))
2034 def debugsetparents(ui, repo, rev1, rev2=None):
2034 def debugsetparents(ui, repo, rev1, rev2=None):
2035 """manually set the parents of the current working directory
2035 """manually set the parents of the current working directory
2036
2036
2037 This is useful for writing repository conversion tools, but should
2037 This is useful for writing repository conversion tools, but should
2038 be used with care.
2038 be used with care.
2039
2039
2040 Returns 0 on success.
2040 Returns 0 on success.
2041 """
2041 """
2042
2042
2043 r1 = scmutil.revsingle(repo, rev1).node()
2043 r1 = scmutil.revsingle(repo, rev1).node()
2044 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2044 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2045
2045
2046 wlock = repo.wlock()
2046 wlock = repo.wlock()
2047 try:
2047 try:
2048 repo.dirstate.setparents(r1, r2)
2048 repo.dirstate.setparents(r1, r2)
2049 finally:
2049 finally:
2050 wlock.release()
2050 wlock.release()
2051
2051
2052 @command('debugstate',
2052 @command('debugstate',
2053 [('', 'nodates', None, _('do not display the saved mtime')),
2053 [('', 'nodates', None, _('do not display the saved mtime')),
2054 ('', 'datesort', None, _('sort by saved mtime'))],
2054 ('', 'datesort', None, _('sort by saved mtime'))],
2055 _('[OPTION]...'))
2055 _('[OPTION]...'))
2056 def debugstate(ui, repo, nodates=None, datesort=None):
2056 def debugstate(ui, repo, nodates=None, datesort=None):
2057 """show the contents of the current dirstate"""
2057 """show the contents of the current dirstate"""
2058 timestr = ""
2058 timestr = ""
2059 showdate = not nodates
2059 showdate = not nodates
2060 if datesort:
2060 if datesort:
2061 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2061 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2062 else:
2062 else:
2063 keyfunc = None # sort by filename
2063 keyfunc = None # sort by filename
2064 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2064 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2065 if showdate:
2065 if showdate:
2066 if ent[3] == -1:
2066 if ent[3] == -1:
2067 # Pad or slice to locale representation
2067 # Pad or slice to locale representation
2068 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2068 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2069 time.localtime(0)))
2069 time.localtime(0)))
2070 timestr = 'unset'
2070 timestr = 'unset'
2071 timestr = (timestr[:locale_len] +
2071 timestr = (timestr[:locale_len] +
2072 ' ' * (locale_len - len(timestr)))
2072 ' ' * (locale_len - len(timestr)))
2073 else:
2073 else:
2074 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2074 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2075 time.localtime(ent[3]))
2075 time.localtime(ent[3]))
2076 if ent[1] & 020000:
2076 if ent[1] & 020000:
2077 mode = 'lnk'
2077 mode = 'lnk'
2078 else:
2078 else:
2079 mode = '%3o' % (ent[1] & 0777)
2079 mode = '%3o' % (ent[1] & 0777)
2080 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2080 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2081 for f in repo.dirstate.copies():
2081 for f in repo.dirstate.copies():
2082 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2082 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2083
2083
2084 @command('debugsub',
2084 @command('debugsub',
2085 [('r', 'rev', '',
2085 [('r', 'rev', '',
2086 _('revision to check'), _('REV'))],
2086 _('revision to check'), _('REV'))],
2087 _('[-r REV] [REV]'))
2087 _('[-r REV] [REV]'))
2088 def debugsub(ui, repo, rev=None):
2088 def debugsub(ui, repo, rev=None):
2089 ctx = scmutil.revsingle(repo, rev, None)
2089 ctx = scmutil.revsingle(repo, rev, None)
2090 for k, v in sorted(ctx.substate.items()):
2090 for k, v in sorted(ctx.substate.items()):
2091 ui.write('path %s\n' % k)
2091 ui.write('path %s\n' % k)
2092 ui.write(' source %s\n' % v[0])
2092 ui.write(' source %s\n' % v[0])
2093 ui.write(' revision %s\n' % v[1])
2093 ui.write(' revision %s\n' % v[1])
2094
2094
2095 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2095 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2096 def debugwalk(ui, repo, *pats, **opts):
2096 def debugwalk(ui, repo, *pats, **opts):
2097 """show how files match on given patterns"""
2097 """show how files match on given patterns"""
2098 m = scmutil.match(repo, pats, opts)
2098 m = scmutil.match(repo, pats, opts)
2099 items = list(repo.walk(m))
2099 items = list(repo.walk(m))
2100 if not items:
2100 if not items:
2101 return
2101 return
2102 fmt = 'f %%-%ds %%-%ds %%s' % (
2102 fmt = 'f %%-%ds %%-%ds %%s' % (
2103 max([len(abs) for abs in items]),
2103 max([len(abs) for abs in items]),
2104 max([len(m.rel(abs)) for abs in items]))
2104 max([len(m.rel(abs)) for abs in items]))
2105 for abs in items:
2105 for abs in items:
2106 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2106 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2107 ui.write("%s\n" % line.rstrip())
2107 ui.write("%s\n" % line.rstrip())
2108
2108
2109 @command('debugwireargs',
2109 @command('debugwireargs',
2110 [('', 'three', '', 'three'),
2110 [('', 'three', '', 'three'),
2111 ('', 'four', '', 'four'),
2111 ('', 'four', '', 'four'),
2112 ('', 'five', '', 'five'),
2112 ('', 'five', '', 'five'),
2113 ] + remoteopts,
2113 ] + remoteopts,
2114 _('REPO [OPTIONS]... [ONE [TWO]]'))
2114 _('REPO [OPTIONS]... [ONE [TWO]]'))
2115 def debugwireargs(ui, repopath, *vals, **opts):
2115 def debugwireargs(ui, repopath, *vals, **opts):
2116 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2116 repo = hg.repository(hg.remoteui(ui, opts), repopath)
2117 for opt in remoteopts:
2117 for opt in remoteopts:
2118 del opts[opt[1]]
2118 del opts[opt[1]]
2119 args = {}
2119 args = {}
2120 for k, v in opts.iteritems():
2120 for k, v in opts.iteritems():
2121 if v:
2121 if v:
2122 args[k] = v
2122 args[k] = v
2123 # run twice to check that we don't mess up the stream for the next command
2123 # run twice to check that we don't mess up the stream for the next command
2124 res1 = repo.debugwireargs(*vals, **args)
2124 res1 = repo.debugwireargs(*vals, **args)
2125 res2 = repo.debugwireargs(*vals, **args)
2125 res2 = repo.debugwireargs(*vals, **args)
2126 ui.write("%s\n" % res1)
2126 ui.write("%s\n" % res1)
2127 if res1 != res2:
2127 if res1 != res2:
2128 ui.warn("%s\n" % res2)
2128 ui.warn("%s\n" % res2)
2129
2129
2130 @command('^diff',
2130 @command('^diff',
2131 [('r', 'rev', [], _('revision'), _('REV')),
2131 [('r', 'rev', [], _('revision'), _('REV')),
2132 ('c', 'change', '', _('change made by revision'), _('REV'))
2132 ('c', 'change', '', _('change made by revision'), _('REV'))
2133 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2133 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2134 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2134 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2135 def diff(ui, repo, *pats, **opts):
2135 def diff(ui, repo, *pats, **opts):
2136 """diff repository (or selected files)
2136 """diff repository (or selected files)
2137
2137
2138 Show differences between revisions for the specified files.
2138 Show differences between revisions for the specified files.
2139
2139
2140 Differences between files are shown using the unified diff format.
2140 Differences between files are shown using the unified diff format.
2141
2141
2142 .. note::
2142 .. note::
2143 diff may generate unexpected results for merges, as it will
2143 diff may generate unexpected results for merges, as it will
2144 default to comparing against the working directory's first
2144 default to comparing against the working directory's first
2145 parent changeset if no revisions are specified.
2145 parent changeset if no revisions are specified.
2146
2146
2147 When two revision arguments are given, then changes are shown
2147 When two revision arguments are given, then changes are shown
2148 between those revisions. If only one revision is specified then
2148 between those revisions. If only one revision is specified then
2149 that revision is compared to the working directory, and, when no
2149 that revision is compared to the working directory, and, when no
2150 revisions are specified, the working directory files are compared
2150 revisions are specified, the working directory files are compared
2151 to its parent.
2151 to its parent.
2152
2152
2153 Alternatively you can specify -c/--change with a revision to see
2153 Alternatively you can specify -c/--change with a revision to see
2154 the changes in that changeset relative to its first parent.
2154 the changes in that changeset relative to its first parent.
2155
2155
2156 Without the -a/--text option, diff will avoid generating diffs of
2156 Without the -a/--text option, diff will avoid generating diffs of
2157 files it detects as binary. With -a, diff will generate a diff
2157 files it detects as binary. With -a, diff will generate a diff
2158 anyway, probably with undesirable results.
2158 anyway, probably with undesirable results.
2159
2159
2160 Use the -g/--git option to generate diffs in the git extended diff
2160 Use the -g/--git option to generate diffs in the git extended diff
2161 format. For more information, read :hg:`help diffs`.
2161 format. For more information, read :hg:`help diffs`.
2162
2162
2163 Returns 0 on success.
2163 Returns 0 on success.
2164 """
2164 """
2165
2165
2166 revs = opts.get('rev')
2166 revs = opts.get('rev')
2167 change = opts.get('change')
2167 change = opts.get('change')
2168 stat = opts.get('stat')
2168 stat = opts.get('stat')
2169 reverse = opts.get('reverse')
2169 reverse = opts.get('reverse')
2170
2170
2171 if revs and change:
2171 if revs and change:
2172 msg = _('cannot specify --rev and --change at the same time')
2172 msg = _('cannot specify --rev and --change at the same time')
2173 raise util.Abort(msg)
2173 raise util.Abort(msg)
2174 elif change:
2174 elif change:
2175 node2 = scmutil.revsingle(repo, change, None).node()
2175 node2 = scmutil.revsingle(repo, change, None).node()
2176 node1 = repo[node2].p1().node()
2176 node1 = repo[node2].p1().node()
2177 else:
2177 else:
2178 node1, node2 = scmutil.revpair(repo, revs)
2178 node1, node2 = scmutil.revpair(repo, revs)
2179
2179
2180 if reverse:
2180 if reverse:
2181 node1, node2 = node2, node1
2181 node1, node2 = node2, node1
2182
2182
2183 diffopts = patch.diffopts(ui, opts)
2183 diffopts = patch.diffopts(ui, opts)
2184 m = scmutil.match(repo, pats, opts)
2184 m = scmutil.match(repo, pats, opts)
2185 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2185 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2186 listsubrepos=opts.get('subrepos'))
2186 listsubrepos=opts.get('subrepos'))
2187
2187
2188 @command('^export',
2188 @command('^export',
2189 [('o', 'output', '',
2189 [('o', 'output', '',
2190 _('print output to file with formatted name'), _('FORMAT')),
2190 _('print output to file with formatted name'), _('FORMAT')),
2191 ('', 'switch-parent', None, _('diff against the second parent')),
2191 ('', 'switch-parent', None, _('diff against the second parent')),
2192 ('r', 'rev', [], _('revisions to export'), _('REV')),
2192 ('r', 'rev', [], _('revisions to export'), _('REV')),
2193 ] + diffopts,
2193 ] + diffopts,
2194 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2194 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2195 def export(ui, repo, *changesets, **opts):
2195 def export(ui, repo, *changesets, **opts):
2196 """dump the header and diffs for one or more changesets
2196 """dump the header and diffs for one or more changesets
2197
2197
2198 Print the changeset header and diffs for one or more revisions.
2198 Print the changeset header and diffs for one or more revisions.
2199
2199
2200 The information shown in the changeset header is: author, date,
2200 The information shown in the changeset header is: author, date,
2201 branch name (if non-default), changeset hash, parent(s) and commit
2201 branch name (if non-default), changeset hash, parent(s) and commit
2202 comment.
2202 comment.
2203
2203
2204 .. note::
2204 .. note::
2205 export may generate unexpected diff output for merge
2205 export may generate unexpected diff output for merge
2206 changesets, as it will compare the merge changeset against its
2206 changesets, as it will compare the merge changeset against its
2207 first parent only.
2207 first parent only.
2208
2208
2209 Output may be to a file, in which case the name of the file is
2209 Output may be to a file, in which case the name of the file is
2210 given using a format string. The formatting rules are as follows:
2210 given using a format string. The formatting rules are as follows:
2211
2211
2212 :``%%``: literal "%" character
2212 :``%%``: literal "%" character
2213 :``%H``: changeset hash (40 hexadecimal digits)
2213 :``%H``: changeset hash (40 hexadecimal digits)
2214 :``%N``: number of patches being generated
2214 :``%N``: number of patches being generated
2215 :``%R``: changeset revision number
2215 :``%R``: changeset revision number
2216 :``%b``: basename of the exporting repository
2216 :``%b``: basename of the exporting repository
2217 :``%h``: short-form changeset hash (12 hexadecimal digits)
2217 :``%h``: short-form changeset hash (12 hexadecimal digits)
2218 :``%n``: zero-padded sequence number, starting at 1
2218 :``%n``: zero-padded sequence number, starting at 1
2219 :``%r``: zero-padded changeset revision number
2219 :``%r``: zero-padded changeset revision number
2220
2220
2221 Without the -a/--text option, export will avoid generating diffs
2221 Without the -a/--text option, export will avoid generating diffs
2222 of files it detects as binary. With -a, export will generate a
2222 of files it detects as binary. With -a, export will generate a
2223 diff anyway, probably with undesirable results.
2223 diff anyway, probably with undesirable results.
2224
2224
2225 Use the -g/--git option to generate diffs in the git extended diff
2225 Use the -g/--git option to generate diffs in the git extended diff
2226 format. See :hg:`help diffs` for more information.
2226 format. See :hg:`help diffs` for more information.
2227
2227
2228 With the --switch-parent option, the diff will be against the
2228 With the --switch-parent option, the diff will be against the
2229 second parent. It can be useful to review a merge.
2229 second parent. It can be useful to review a merge.
2230
2230
2231 Returns 0 on success.
2231 Returns 0 on success.
2232 """
2232 """
2233 changesets += tuple(opts.get('rev', []))
2233 changesets += tuple(opts.get('rev', []))
2234 if not changesets:
2234 if not changesets:
2235 raise util.Abort(_("export requires at least one changeset"))
2235 raise util.Abort(_("export requires at least one changeset"))
2236 revs = scmutil.revrange(repo, changesets)
2236 revs = scmutil.revrange(repo, changesets)
2237 if len(revs) > 1:
2237 if len(revs) > 1:
2238 ui.note(_('exporting patches:\n'))
2238 ui.note(_('exporting patches:\n'))
2239 else:
2239 else:
2240 ui.note(_('exporting patch:\n'))
2240 ui.note(_('exporting patch:\n'))
2241 cmdutil.export(repo, revs, template=opts.get('output'),
2241 cmdutil.export(repo, revs, template=opts.get('output'),
2242 switch_parent=opts.get('switch_parent'),
2242 switch_parent=opts.get('switch_parent'),
2243 opts=patch.diffopts(ui, opts))
2243 opts=patch.diffopts(ui, opts))
2244
2244
2245 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2245 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2246 def forget(ui, repo, *pats, **opts):
2246 def forget(ui, repo, *pats, **opts):
2247 """forget the specified files on the next commit
2247 """forget the specified files on the next commit
2248
2248
2249 Mark the specified files so they will no longer be tracked
2249 Mark the specified files so they will no longer be tracked
2250 after the next commit.
2250 after the next commit.
2251
2251
2252 This only removes files from the current branch, not from the
2252 This only removes files from the current branch, not from the
2253 entire project history, and it does not delete them from the
2253 entire project history, and it does not delete them from the
2254 working directory.
2254 working directory.
2255
2255
2256 To undo a forget before the next commit, see :hg:`add`.
2256 To undo a forget before the next commit, see :hg:`add`.
2257
2257
2258 Returns 0 on success.
2258 Returns 0 on success.
2259 """
2259 """
2260
2260
2261 if not pats:
2261 if not pats:
2262 raise util.Abort(_('no files specified'))
2262 raise util.Abort(_('no files specified'))
2263
2263
2264 m = scmutil.match(repo, pats, opts)
2264 m = scmutil.match(repo, pats, opts)
2265 s = repo.status(match=m, clean=True)
2265 s = repo.status(match=m, clean=True)
2266 forget = sorted(s[0] + s[1] + s[3] + s[6])
2266 forget = sorted(s[0] + s[1] + s[3] + s[6])
2267 errs = 0
2267 errs = 0
2268
2268
2269 for f in m.files():
2269 for f in m.files():
2270 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2270 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2271 ui.warn(_('not removing %s: file is already untracked\n')
2271 ui.warn(_('not removing %s: file is already untracked\n')
2272 % m.rel(f))
2272 % m.rel(f))
2273 errs = 1
2273 errs = 1
2274
2274
2275 for f in forget:
2275 for f in forget:
2276 if ui.verbose or not m.exact(f):
2276 if ui.verbose or not m.exact(f):
2277 ui.status(_('removing %s\n') % m.rel(f))
2277 ui.status(_('removing %s\n') % m.rel(f))
2278
2278
2279 repo[None].forget(forget)
2279 repo[None].forget(forget)
2280 return errs
2280 return errs
2281
2281
2282 @command('grep',
2282 @command('grep',
2283 [('0', 'print0', None, _('end fields with NUL')),
2283 [('0', 'print0', None, _('end fields with NUL')),
2284 ('', 'all', None, _('print all revisions that match')),
2284 ('', 'all', None, _('print all revisions that match')),
2285 ('a', 'text', None, _('treat all files as text')),
2285 ('a', 'text', None, _('treat all files as text')),
2286 ('f', 'follow', None,
2286 ('f', 'follow', None,
2287 _('follow changeset history,'
2287 _('follow changeset history,'
2288 ' or file history across copies and renames')),
2288 ' or file history across copies and renames')),
2289 ('i', 'ignore-case', None, _('ignore case when matching')),
2289 ('i', 'ignore-case', None, _('ignore case when matching')),
2290 ('l', 'files-with-matches', None,
2290 ('l', 'files-with-matches', None,
2291 _('print only filenames and revisions that match')),
2291 _('print only filenames and revisions that match')),
2292 ('n', 'line-number', None, _('print matching line numbers')),
2292 ('n', 'line-number', None, _('print matching line numbers')),
2293 ('r', 'rev', [],
2293 ('r', 'rev', [],
2294 _('only search files changed within revision range'), _('REV')),
2294 _('only search files changed within revision range'), _('REV')),
2295 ('u', 'user', None, _('list the author (long with -v)')),
2295 ('u', 'user', None, _('list the author (long with -v)')),
2296 ('d', 'date', None, _('list the date (short with -q)')),
2296 ('d', 'date', None, _('list the date (short with -q)')),
2297 ] + walkopts,
2297 ] + walkopts,
2298 _('[OPTION]... PATTERN [FILE]...'))
2298 _('[OPTION]... PATTERN [FILE]...'))
2299 def grep(ui, repo, pattern, *pats, **opts):
2299 def grep(ui, repo, pattern, *pats, **opts):
2300 """search for a pattern in specified files and revisions
2300 """search for a pattern in specified files and revisions
2301
2301
2302 Search revisions of files for a regular expression.
2302 Search revisions of files for a regular expression.
2303
2303
2304 This command behaves differently than Unix grep. It only accepts
2304 This command behaves differently than Unix grep. It only accepts
2305 Python/Perl regexps. It searches repository history, not the
2305 Python/Perl regexps. It searches repository history, not the
2306 working directory. It always prints the revision number in which a
2306 working directory. It always prints the revision number in which a
2307 match appears.
2307 match appears.
2308
2308
2309 By default, grep only prints output for the first revision of a
2309 By default, grep only prints output for the first revision of a
2310 file in which it finds a match. To get it to print every revision
2310 file in which it finds a match. To get it to print every revision
2311 that contains a change in match status ("-" for a match that
2311 that contains a change in match status ("-" for a match that
2312 becomes a non-match, or "+" for a non-match that becomes a match),
2312 becomes a non-match, or "+" for a non-match that becomes a match),
2313 use the --all flag.
2313 use the --all flag.
2314
2314
2315 Returns 0 if a match is found, 1 otherwise.
2315 Returns 0 if a match is found, 1 otherwise.
2316 """
2316 """
2317 reflags = 0
2317 reflags = 0
2318 if opts.get('ignore_case'):
2318 if opts.get('ignore_case'):
2319 reflags |= re.I
2319 reflags |= re.I
2320 try:
2320 try:
2321 regexp = re.compile(pattern, reflags)
2321 regexp = re.compile(pattern, reflags)
2322 except re.error, inst:
2322 except re.error, inst:
2323 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2323 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2324 return 1
2324 return 1
2325 sep, eol = ':', '\n'
2325 sep, eol = ':', '\n'
2326 if opts.get('print0'):
2326 if opts.get('print0'):
2327 sep = eol = '\0'
2327 sep = eol = '\0'
2328
2328
2329 getfile = util.lrucachefunc(repo.file)
2329 getfile = util.lrucachefunc(repo.file)
2330
2330
2331 def matchlines(body):
2331 def matchlines(body):
2332 begin = 0
2332 begin = 0
2333 linenum = 0
2333 linenum = 0
2334 while True:
2334 while True:
2335 match = regexp.search(body, begin)
2335 match = regexp.search(body, begin)
2336 if not match:
2336 if not match:
2337 break
2337 break
2338 mstart, mend = match.span()
2338 mstart, mend = match.span()
2339 linenum += body.count('\n', begin, mstart) + 1
2339 linenum += body.count('\n', begin, mstart) + 1
2340 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2340 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2341 begin = body.find('\n', mend) + 1 or len(body)
2341 begin = body.find('\n', mend) + 1 or len(body)
2342 lend = begin - 1
2342 lend = begin - 1
2343 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2343 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2344
2344
2345 class linestate(object):
2345 class linestate(object):
2346 def __init__(self, line, linenum, colstart, colend):
2346 def __init__(self, line, linenum, colstart, colend):
2347 self.line = line
2347 self.line = line
2348 self.linenum = linenum
2348 self.linenum = linenum
2349 self.colstart = colstart
2349 self.colstart = colstart
2350 self.colend = colend
2350 self.colend = colend
2351
2351
2352 def __hash__(self):
2352 def __hash__(self):
2353 return hash((self.linenum, self.line))
2353 return hash((self.linenum, self.line))
2354
2354
2355 def __eq__(self, other):
2355 def __eq__(self, other):
2356 return self.line == other.line
2356 return self.line == other.line
2357
2357
2358 matches = {}
2358 matches = {}
2359 copies = {}
2359 copies = {}
2360 def grepbody(fn, rev, body):
2360 def grepbody(fn, rev, body):
2361 matches[rev].setdefault(fn, [])
2361 matches[rev].setdefault(fn, [])
2362 m = matches[rev][fn]
2362 m = matches[rev][fn]
2363 for lnum, cstart, cend, line in matchlines(body):
2363 for lnum, cstart, cend, line in matchlines(body):
2364 s = linestate(line, lnum, cstart, cend)
2364 s = linestate(line, lnum, cstart, cend)
2365 m.append(s)
2365 m.append(s)
2366
2366
2367 def difflinestates(a, b):
2367 def difflinestates(a, b):
2368 sm = difflib.SequenceMatcher(None, a, b)
2368 sm = difflib.SequenceMatcher(None, a, b)
2369 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2369 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2370 if tag == 'insert':
2370 if tag == 'insert':
2371 for i in xrange(blo, bhi):
2371 for i in xrange(blo, bhi):
2372 yield ('+', b[i])
2372 yield ('+', b[i])
2373 elif tag == 'delete':
2373 elif tag == 'delete':
2374 for i in xrange(alo, ahi):
2374 for i in xrange(alo, ahi):
2375 yield ('-', a[i])
2375 yield ('-', a[i])
2376 elif tag == 'replace':
2376 elif tag == 'replace':
2377 for i in xrange(alo, ahi):
2377 for i in xrange(alo, ahi):
2378 yield ('-', a[i])
2378 yield ('-', a[i])
2379 for i in xrange(blo, bhi):
2379 for i in xrange(blo, bhi):
2380 yield ('+', b[i])
2380 yield ('+', b[i])
2381
2381
2382 def display(fn, ctx, pstates, states):
2382 def display(fn, ctx, pstates, states):
2383 rev = ctx.rev()
2383 rev = ctx.rev()
2384 datefunc = ui.quiet and util.shortdate or util.datestr
2384 datefunc = ui.quiet and util.shortdate or util.datestr
2385 found = False
2385 found = False
2386 filerevmatches = {}
2386 filerevmatches = {}
2387 def binary():
2387 def binary():
2388 flog = getfile(fn)
2388 flog = getfile(fn)
2389 return util.binary(flog.read(ctx.filenode(fn)))
2389 return util.binary(flog.read(ctx.filenode(fn)))
2390
2390
2391 if opts.get('all'):
2391 if opts.get('all'):
2392 iter = difflinestates(pstates, states)
2392 iter = difflinestates(pstates, states)
2393 else:
2393 else:
2394 iter = [('', l) for l in states]
2394 iter = [('', l) for l in states]
2395 for change, l in iter:
2395 for change, l in iter:
2396 cols = [fn, str(rev)]
2396 cols = [fn, str(rev)]
2397 before, match, after = None, None, None
2397 before, match, after = None, None, None
2398 if opts.get('line_number'):
2398 if opts.get('line_number'):
2399 cols.append(str(l.linenum))
2399 cols.append(str(l.linenum))
2400 if opts.get('all'):
2400 if opts.get('all'):
2401 cols.append(change)
2401 cols.append(change)
2402 if opts.get('user'):
2402 if opts.get('user'):
2403 cols.append(ui.shortuser(ctx.user()))
2403 cols.append(ui.shortuser(ctx.user()))
2404 if opts.get('date'):
2404 if opts.get('date'):
2405 cols.append(datefunc(ctx.date()))
2405 cols.append(datefunc(ctx.date()))
2406 if opts.get('files_with_matches'):
2406 if opts.get('files_with_matches'):
2407 c = (fn, rev)
2407 c = (fn, rev)
2408 if c in filerevmatches:
2408 if c in filerevmatches:
2409 continue
2409 continue
2410 filerevmatches[c] = 1
2410 filerevmatches[c] = 1
2411 else:
2411 else:
2412 before = l.line[:l.colstart]
2412 before = l.line[:l.colstart]
2413 match = l.line[l.colstart:l.colend]
2413 match = l.line[l.colstart:l.colend]
2414 after = l.line[l.colend:]
2414 after = l.line[l.colend:]
2415 ui.write(sep.join(cols))
2415 ui.write(sep.join(cols))
2416 if before is not None:
2416 if before is not None:
2417 if not opts.get('text') and binary():
2417 if not opts.get('text') and binary():
2418 ui.write(sep + " Binary file matches")
2418 ui.write(sep + " Binary file matches")
2419 else:
2419 else:
2420 ui.write(sep + before)
2420 ui.write(sep + before)
2421 ui.write(match, label='grep.match')
2421 ui.write(match, label='grep.match')
2422 ui.write(after)
2422 ui.write(after)
2423 ui.write(eol)
2423 ui.write(eol)
2424 found = True
2424 found = True
2425 return found
2425 return found
2426
2426
2427 skip = {}
2427 skip = {}
2428 revfiles = {}
2428 revfiles = {}
2429 matchfn = scmutil.match(repo, pats, opts)
2429 matchfn = scmutil.match(repo, pats, opts)
2430 found = False
2430 found = False
2431 follow = opts.get('follow')
2431 follow = opts.get('follow')
2432
2432
2433 def prep(ctx, fns):
2433 def prep(ctx, fns):
2434 rev = ctx.rev()
2434 rev = ctx.rev()
2435 pctx = ctx.p1()
2435 pctx = ctx.p1()
2436 parent = pctx.rev()
2436 parent = pctx.rev()
2437 matches.setdefault(rev, {})
2437 matches.setdefault(rev, {})
2438 matches.setdefault(parent, {})
2438 matches.setdefault(parent, {})
2439 files = revfiles.setdefault(rev, [])
2439 files = revfiles.setdefault(rev, [])
2440 for fn in fns:
2440 for fn in fns:
2441 flog = getfile(fn)
2441 flog = getfile(fn)
2442 try:
2442 try:
2443 fnode = ctx.filenode(fn)
2443 fnode = ctx.filenode(fn)
2444 except error.LookupError:
2444 except error.LookupError:
2445 continue
2445 continue
2446
2446
2447 copied = flog.renamed(fnode)
2447 copied = flog.renamed(fnode)
2448 copy = follow and copied and copied[0]
2448 copy = follow and copied and copied[0]
2449 if copy:
2449 if copy:
2450 copies.setdefault(rev, {})[fn] = copy
2450 copies.setdefault(rev, {})[fn] = copy
2451 if fn in skip:
2451 if fn in skip:
2452 if copy:
2452 if copy:
2453 skip[copy] = True
2453 skip[copy] = True
2454 continue
2454 continue
2455 files.append(fn)
2455 files.append(fn)
2456
2456
2457 if fn not in matches[rev]:
2457 if fn not in matches[rev]:
2458 grepbody(fn, rev, flog.read(fnode))
2458 grepbody(fn, rev, flog.read(fnode))
2459
2459
2460 pfn = copy or fn
2460 pfn = copy or fn
2461 if pfn not in matches[parent]:
2461 if pfn not in matches[parent]:
2462 try:
2462 try:
2463 fnode = pctx.filenode(pfn)
2463 fnode = pctx.filenode(pfn)
2464 grepbody(pfn, parent, flog.read(fnode))
2464 grepbody(pfn, parent, flog.read(fnode))
2465 except error.LookupError:
2465 except error.LookupError:
2466 pass
2466 pass
2467
2467
2468 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2468 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2469 rev = ctx.rev()
2469 rev = ctx.rev()
2470 parent = ctx.p1().rev()
2470 parent = ctx.p1().rev()
2471 for fn in sorted(revfiles.get(rev, [])):
2471 for fn in sorted(revfiles.get(rev, [])):
2472 states = matches[rev][fn]
2472 states = matches[rev][fn]
2473 copy = copies.get(rev, {}).get(fn)
2473 copy = copies.get(rev, {}).get(fn)
2474 if fn in skip:
2474 if fn in skip:
2475 if copy:
2475 if copy:
2476 skip[copy] = True
2476 skip[copy] = True
2477 continue
2477 continue
2478 pstates = matches.get(parent, {}).get(copy or fn, [])
2478 pstates = matches.get(parent, {}).get(copy or fn, [])
2479 if pstates or states:
2479 if pstates or states:
2480 r = display(fn, ctx, pstates, states)
2480 r = display(fn, ctx, pstates, states)
2481 found = found or r
2481 found = found or r
2482 if r and not opts.get('all'):
2482 if r and not opts.get('all'):
2483 skip[fn] = True
2483 skip[fn] = True
2484 if copy:
2484 if copy:
2485 skip[copy] = True
2485 skip[copy] = True
2486 del matches[rev]
2486 del matches[rev]
2487 del revfiles[rev]
2487 del revfiles[rev]
2488
2488
2489 return not found
2489 return not found
2490
2490
2491 @command('heads',
2491 @command('heads',
2492 [('r', 'rev', '',
2492 [('r', 'rev', '',
2493 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2493 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2494 ('t', 'topo', False, _('show topological heads only')),
2494 ('t', 'topo', False, _('show topological heads only')),
2495 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2495 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2496 ('c', 'closed', False, _('show normal and closed branch heads')),
2496 ('c', 'closed', False, _('show normal and closed branch heads')),
2497 ] + templateopts,
2497 ] + templateopts,
2498 _('[-ac] [-r STARTREV] [REV]...'))
2498 _('[-ac] [-r STARTREV] [REV]...'))
2499 def heads(ui, repo, *branchrevs, **opts):
2499 def heads(ui, repo, *branchrevs, **opts):
2500 """show current repository heads or show branch heads
2500 """show current repository heads or show branch heads
2501
2501
2502 With no arguments, show all repository branch heads.
2502 With no arguments, show all repository branch heads.
2503
2503
2504 Repository "heads" are changesets with no child changesets. They are
2504 Repository "heads" are changesets with no child changesets. They are
2505 where development generally takes place and are the usual targets
2505 where development generally takes place and are the usual targets
2506 for update and merge operations. Branch heads are changesets that have
2506 for update and merge operations. Branch heads are changesets that have
2507 no child changeset on the same branch.
2507 no child changeset on the same branch.
2508
2508
2509 If one or more REVs are given, only branch heads on the branches
2509 If one or more REVs are given, only branch heads on the branches
2510 associated with the specified changesets are shown.
2510 associated with the specified changesets are shown.
2511
2511
2512 If -c/--closed is specified, also show branch heads marked closed
2512 If -c/--closed is specified, also show branch heads marked closed
2513 (see :hg:`commit --close-branch`).
2513 (see :hg:`commit --close-branch`).
2514
2514
2515 If STARTREV is specified, only those heads that are descendants of
2515 If STARTREV is specified, only those heads that are descendants of
2516 STARTREV will be displayed.
2516 STARTREV will be displayed.
2517
2517
2518 If -t/--topo is specified, named branch mechanics will be ignored and only
2518 If -t/--topo is specified, named branch mechanics will be ignored and only
2519 changesets without children will be shown.
2519 changesets without children will be shown.
2520
2520
2521 Returns 0 if matching heads are found, 1 if not.
2521 Returns 0 if matching heads are found, 1 if not.
2522 """
2522 """
2523
2523
2524 start = None
2524 start = None
2525 if 'rev' in opts:
2525 if 'rev' in opts:
2526 start = scmutil.revsingle(repo, opts['rev'], None).node()
2526 start = scmutil.revsingle(repo, opts['rev'], None).node()
2527
2527
2528 if opts.get('topo'):
2528 if opts.get('topo'):
2529 heads = [repo[h] for h in repo.heads(start)]
2529 heads = [repo[h] for h in repo.heads(start)]
2530 else:
2530 else:
2531 heads = []
2531 heads = []
2532 for branch in repo.branchmap():
2532 for branch in repo.branchmap():
2533 heads += repo.branchheads(branch, start, opts.get('closed'))
2533 heads += repo.branchheads(branch, start, opts.get('closed'))
2534 heads = [repo[h] for h in heads]
2534 heads = [repo[h] for h in heads]
2535
2535
2536 if branchrevs:
2536 if branchrevs:
2537 branches = set(repo[br].branch() for br in branchrevs)
2537 branches = set(repo[br].branch() for br in branchrevs)
2538 heads = [h for h in heads if h.branch() in branches]
2538 heads = [h for h in heads if h.branch() in branches]
2539
2539
2540 if opts.get('active') and branchrevs:
2540 if opts.get('active') and branchrevs:
2541 dagheads = repo.heads(start)
2541 dagheads = repo.heads(start)
2542 heads = [h for h in heads if h.node() in dagheads]
2542 heads = [h for h in heads if h.node() in dagheads]
2543
2543
2544 if branchrevs:
2544 if branchrevs:
2545 haveheads = set(h.branch() for h in heads)
2545 haveheads = set(h.branch() for h in heads)
2546 if branches - haveheads:
2546 if branches - haveheads:
2547 headless = ', '.join(b for b in branches - haveheads)
2547 headless = ', '.join(b for b in branches - haveheads)
2548 msg = _('no open branch heads found on branches %s')
2548 msg = _('no open branch heads found on branches %s')
2549 if opts.get('rev'):
2549 if opts.get('rev'):
2550 msg += _(' (started at %s)' % opts['rev'])
2550 msg += _(' (started at %s)' % opts['rev'])
2551 ui.warn((msg + '\n') % headless)
2551 ui.warn((msg + '\n') % headless)
2552
2552
2553 if not heads:
2553 if not heads:
2554 return 1
2554 return 1
2555
2555
2556 heads = sorted(heads, key=lambda x: -x.rev())
2556 heads = sorted(heads, key=lambda x: -x.rev())
2557 displayer = cmdutil.show_changeset(ui, repo, opts)
2557 displayer = cmdutil.show_changeset(ui, repo, opts)
2558 for ctx in heads:
2558 for ctx in heads:
2559 displayer.show(ctx)
2559 displayer.show(ctx)
2560 displayer.close()
2560 displayer.close()
2561
2561
2562 @command('help',
2562 @command('help',
2563 [('e', 'extension', None, _('show only help for extensions')),
2563 [('e', 'extension', None, _('show only help for extensions')),
2564 ('c', 'command', None, _('show only help for commands'))],
2564 ('c', 'command', None, _('show only help for commands'))],
2565 _('[-ec] [TOPIC]'))
2565 _('[-ec] [TOPIC]'))
2566 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2566 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2567 """show help for a given topic or a help overview
2567 """show help for a given topic or a help overview
2568
2568
2569 With no arguments, print a list of commands with short help messages.
2569 With no arguments, print a list of commands with short help messages.
2570
2570
2571 Given a topic, extension, or command name, print help for that
2571 Given a topic, extension, or command name, print help for that
2572 topic.
2572 topic.
2573
2573
2574 Returns 0 if successful.
2574 Returns 0 if successful.
2575 """
2575 """
2576 option_lists = []
2576 option_lists = []
2577 textwidth = min(ui.termwidth(), 80) - 2
2577 textwidth = min(ui.termwidth(), 80) - 2
2578
2578
2579 def addglobalopts(aliases):
2579 def addglobalopts(aliases):
2580 if ui.verbose:
2580 if ui.verbose:
2581 option_lists.append((_("global options:"), globalopts))
2581 option_lists.append((_("global options:"), globalopts))
2582 if name == 'shortlist':
2582 if name == 'shortlist':
2583 option_lists.append((_('use "hg help" for the full list '
2583 option_lists.append((_('use "hg help" for the full list '
2584 'of commands'), ()))
2584 'of commands'), ()))
2585 else:
2585 else:
2586 if name == 'shortlist':
2586 if name == 'shortlist':
2587 msg = _('use "hg help" for the full list of commands '
2587 msg = _('use "hg help" for the full list of commands '
2588 'or "hg -v" for details')
2588 'or "hg -v" for details')
2589 elif name and not full:
2589 elif name and not full:
2590 msg = _('use "hg help %s" to show the full help text' % name)
2590 msg = _('use "hg help %s" to show the full help text' % name)
2591 elif aliases:
2591 elif aliases:
2592 msg = _('use "hg -v help%s" to show builtin aliases and '
2592 msg = _('use "hg -v help%s" to show builtin aliases and '
2593 'global options') % (name and " " + name or "")
2593 'global options') % (name and " " + name or "")
2594 else:
2594 else:
2595 msg = _('use "hg -v help %s" to show global options') % name
2595 msg = _('use "hg -v help %s" to show global options') % name
2596 option_lists.append((msg, ()))
2596 option_lists.append((msg, ()))
2597
2597
2598 def helpcmd(name):
2598 def helpcmd(name):
2599 if with_version:
2599 if with_version:
2600 version_(ui)
2600 version_(ui)
2601 ui.write('\n')
2601 ui.write('\n')
2602
2602
2603 try:
2603 try:
2604 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2604 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2605 except error.AmbiguousCommand, inst:
2605 except error.AmbiguousCommand, inst:
2606 # py3k fix: except vars can't be used outside the scope of the
2606 # py3k fix: except vars can't be used outside the scope of the
2607 # except block, nor can be used inside a lambda. python issue4617
2607 # except block, nor can be used inside a lambda. python issue4617
2608 prefix = inst.args[0]
2608 prefix = inst.args[0]
2609 select = lambda c: c.lstrip('^').startswith(prefix)
2609 select = lambda c: c.lstrip('^').startswith(prefix)
2610 helplist(_('list of commands:\n\n'), select)
2610 helplist(_('list of commands:\n\n'), select)
2611 return
2611 return
2612
2612
2613 # check if it's an invalid alias and display its error if it is
2613 # check if it's an invalid alias and display its error if it is
2614 if getattr(entry[0], 'badalias', False):
2614 if getattr(entry[0], 'badalias', False):
2615 if not unknowncmd:
2615 if not unknowncmd:
2616 entry[0](ui)
2616 entry[0](ui)
2617 return
2617 return
2618
2618
2619 # synopsis
2619 # synopsis
2620 if len(entry) > 2:
2620 if len(entry) > 2:
2621 if entry[2].startswith('hg'):
2621 if entry[2].startswith('hg'):
2622 ui.write("%s\n" % entry[2])
2622 ui.write("%s\n" % entry[2])
2623 else:
2623 else:
2624 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2624 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2625 else:
2625 else:
2626 ui.write('hg %s\n' % aliases[0])
2626 ui.write('hg %s\n' % aliases[0])
2627
2627
2628 # aliases
2628 # aliases
2629 if full and not ui.quiet and len(aliases) > 1:
2629 if full and not ui.quiet and len(aliases) > 1:
2630 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2630 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2631
2631
2632 # description
2632 # description
2633 doc = gettext(entry[0].__doc__)
2633 doc = gettext(entry[0].__doc__)
2634 if not doc:
2634 if not doc:
2635 doc = _("(no help text available)")
2635 doc = _("(no help text available)")
2636 if hasattr(entry[0], 'definition'): # aliased command
2636 if hasattr(entry[0], 'definition'): # aliased command
2637 if entry[0].definition.startswith('!'): # shell alias
2637 if entry[0].definition.startswith('!'): # shell alias
2638 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2638 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2639 else:
2639 else:
2640 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2640 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2641 if ui.quiet or not full:
2641 if ui.quiet or not full:
2642 doc = doc.splitlines()[0]
2642 doc = doc.splitlines()[0]
2643 keep = ui.verbose and ['verbose'] or []
2643 keep = ui.verbose and ['verbose'] or []
2644 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2644 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2645 ui.write("\n%s\n" % formatted)
2645 ui.write("\n%s\n" % formatted)
2646 if pruned:
2646 if pruned:
2647 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2647 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2648
2648
2649 if not ui.quiet:
2649 if not ui.quiet:
2650 # options
2650 # options
2651 if entry[1]:
2651 if entry[1]:
2652 option_lists.append((_("options:\n"), entry[1]))
2652 option_lists.append((_("options:\n"), entry[1]))
2653
2653
2654 addglobalopts(False)
2654 addglobalopts(False)
2655
2655
2656 # check if this command shadows a non-trivial (multi-line)
2656 # check if this command shadows a non-trivial (multi-line)
2657 # extension help text
2657 # extension help text
2658 try:
2658 try:
2659 mod = extensions.find(name)
2659 mod = extensions.find(name)
2660 doc = gettext(mod.__doc__) or ''
2660 doc = gettext(mod.__doc__) or ''
2661 if '\n' in doc.strip():
2661 if '\n' in doc.strip():
2662 msg = _('use "hg help -e %s" to show help for '
2662 msg = _('use "hg help -e %s" to show help for '
2663 'the %s extension') % (name, name)
2663 'the %s extension') % (name, name)
2664 ui.write('\n%s\n' % msg)
2664 ui.write('\n%s\n' % msg)
2665 except KeyError:
2665 except KeyError:
2666 pass
2666 pass
2667
2667
2668 def helplist(header, select=None):
2668 def helplist(header, select=None):
2669 h = {}
2669 h = {}
2670 cmds = {}
2670 cmds = {}
2671 for c, e in table.iteritems():
2671 for c, e in table.iteritems():
2672 f = c.split("|", 1)[0]
2672 f = c.split("|", 1)[0]
2673 if select and not select(f):
2673 if select and not select(f):
2674 continue
2674 continue
2675 if (not select and name != 'shortlist' and
2675 if (not select and name != 'shortlist' and
2676 e[0].__module__ != __name__):
2676 e[0].__module__ != __name__):
2677 continue
2677 continue
2678 if name == "shortlist" and not f.startswith("^"):
2678 if name == "shortlist" and not f.startswith("^"):
2679 continue
2679 continue
2680 f = f.lstrip("^")
2680 f = f.lstrip("^")
2681 if not ui.debugflag and f.startswith("debug"):
2681 if not ui.debugflag and f.startswith("debug"):
2682 continue
2682 continue
2683 doc = e[0].__doc__
2683 doc = e[0].__doc__
2684 if doc and 'DEPRECATED' in doc and not ui.verbose:
2684 if doc and 'DEPRECATED' in doc and not ui.verbose:
2685 continue
2685 continue
2686 doc = gettext(doc)
2686 doc = gettext(doc)
2687 if not doc:
2687 if not doc:
2688 doc = _("(no help text available)")
2688 doc = _("(no help text available)")
2689 h[f] = doc.splitlines()[0].rstrip()
2689 h[f] = doc.splitlines()[0].rstrip()
2690 cmds[f] = c.lstrip("^")
2690 cmds[f] = c.lstrip("^")
2691
2691
2692 if not h:
2692 if not h:
2693 ui.status(_('no commands defined\n'))
2693 ui.status(_('no commands defined\n'))
2694 return
2694 return
2695
2695
2696 ui.status(header)
2696 ui.status(header)
2697 fns = sorted(h)
2697 fns = sorted(h)
2698 m = max(map(len, fns))
2698 m = max(map(len, fns))
2699 for f in fns:
2699 for f in fns:
2700 if ui.verbose:
2700 if ui.verbose:
2701 commands = cmds[f].replace("|",", ")
2701 commands = cmds[f].replace("|",", ")
2702 ui.write(" %s:\n %s\n"%(commands, h[f]))
2702 ui.write(" %s:\n %s\n"%(commands, h[f]))
2703 else:
2703 else:
2704 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2704 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2705 initindent=' %-*s ' % (m, f),
2705 initindent=' %-*s ' % (m, f),
2706 hangindent=' ' * (m + 4))))
2706 hangindent=' ' * (m + 4))))
2707
2707
2708 if not ui.quiet:
2708 if not ui.quiet:
2709 addglobalopts(True)
2709 addglobalopts(True)
2710
2710
2711 def helptopic(name):
2711 def helptopic(name):
2712 for names, header, doc in help.helptable:
2712 for names, header, doc in help.helptable:
2713 if name in names:
2713 if name in names:
2714 break
2714 break
2715 else:
2715 else:
2716 raise error.UnknownCommand(name)
2716 raise error.UnknownCommand(name)
2717
2717
2718 # description
2718 # description
2719 if not doc:
2719 if not doc:
2720 doc = _("(no help text available)")
2720 doc = _("(no help text available)")
2721 if hasattr(doc, '__call__'):
2721 if hasattr(doc, '__call__'):
2722 doc = doc()
2722 doc = doc()
2723
2723
2724 ui.write("%s\n\n" % header)
2724 ui.write("%s\n\n" % header)
2725 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2725 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2726 try:
2726 try:
2727 cmdutil.findcmd(name, table)
2727 cmdutil.findcmd(name, table)
2728 ui.write(_('\nuse "hg help -c %s" to see help for '
2728 ui.write(_('\nuse "hg help -c %s" to see help for '
2729 'the %s command\n') % (name, name))
2729 'the %s command\n') % (name, name))
2730 except error.UnknownCommand:
2730 except error.UnknownCommand:
2731 pass
2731 pass
2732
2732
2733 def helpext(name):
2733 def helpext(name):
2734 try:
2734 try:
2735 mod = extensions.find(name)
2735 mod = extensions.find(name)
2736 doc = gettext(mod.__doc__) or _('no help text available')
2736 doc = gettext(mod.__doc__) or _('no help text available')
2737 except KeyError:
2737 except KeyError:
2738 mod = None
2738 mod = None
2739 doc = extensions.disabledext(name)
2739 doc = extensions.disabledext(name)
2740 if not doc:
2740 if not doc:
2741 raise error.UnknownCommand(name)
2741 raise error.UnknownCommand(name)
2742
2742
2743 if '\n' not in doc:
2743 if '\n' not in doc:
2744 head, tail = doc, ""
2744 head, tail = doc, ""
2745 else:
2745 else:
2746 head, tail = doc.split('\n', 1)
2746 head, tail = doc.split('\n', 1)
2747 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2747 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2748 if tail:
2748 if tail:
2749 ui.write(minirst.format(tail, textwidth))
2749 ui.write(minirst.format(tail, textwidth))
2750 ui.status('\n\n')
2750 ui.status('\n\n')
2751
2751
2752 if mod:
2752 if mod:
2753 try:
2753 try:
2754 ct = mod.cmdtable
2754 ct = mod.cmdtable
2755 except AttributeError:
2755 except AttributeError:
2756 ct = {}
2756 ct = {}
2757 modcmds = set([c.split('|', 1)[0] for c in ct])
2757 modcmds = set([c.split('|', 1)[0] for c in ct])
2758 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2758 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2759 else:
2759 else:
2760 ui.write(_('use "hg help extensions" for information on enabling '
2760 ui.write(_('use "hg help extensions" for information on enabling '
2761 'extensions\n'))
2761 'extensions\n'))
2762
2762
2763 def helpextcmd(name):
2763 def helpextcmd(name):
2764 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2764 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2765 doc = gettext(mod.__doc__).splitlines()[0]
2765 doc = gettext(mod.__doc__).splitlines()[0]
2766
2766
2767 msg = help.listexts(_("'%s' is provided by the following "
2767 msg = help.listexts(_("'%s' is provided by the following "
2768 "extension:") % cmd, {ext: doc}, indent=4)
2768 "extension:") % cmd, {ext: doc}, indent=4)
2769 ui.write(minirst.format(msg, textwidth))
2769 ui.write(minirst.format(msg, textwidth))
2770 ui.write('\n\n')
2770 ui.write('\n\n')
2771 ui.write(_('use "hg help extensions" for information on enabling '
2771 ui.write(_('use "hg help extensions" for information on enabling '
2772 'extensions\n'))
2772 'extensions\n'))
2773
2773
2774 if name and name != 'shortlist':
2774 if name and name != 'shortlist':
2775 i = None
2775 i = None
2776 if unknowncmd:
2776 if unknowncmd:
2777 queries = (helpextcmd,)
2777 queries = (helpextcmd,)
2778 elif opts.get('extension'):
2778 elif opts.get('extension'):
2779 queries = (helpext,)
2779 queries = (helpext,)
2780 elif opts.get('command'):
2780 elif opts.get('command'):
2781 queries = (helpcmd,)
2781 queries = (helpcmd,)
2782 else:
2782 else:
2783 queries = (helptopic, helpcmd, helpext, helpextcmd)
2783 queries = (helptopic, helpcmd, helpext, helpextcmd)
2784 for f in queries:
2784 for f in queries:
2785 try:
2785 try:
2786 f(name)
2786 f(name)
2787 i = None
2787 i = None
2788 break
2788 break
2789 except error.UnknownCommand, inst:
2789 except error.UnknownCommand, inst:
2790 i = inst
2790 i = inst
2791 if i:
2791 if i:
2792 raise i
2792 raise i
2793
2793
2794 else:
2794 else:
2795 # program name
2795 # program name
2796 if ui.verbose or with_version:
2796 if ui.verbose or with_version:
2797 version_(ui)
2797 version_(ui)
2798 else:
2798 else:
2799 ui.status(_("Mercurial Distributed SCM\n"))
2799 ui.status(_("Mercurial Distributed SCM\n"))
2800 ui.status('\n')
2800 ui.status('\n')
2801
2801
2802 # list of commands
2802 # list of commands
2803 if name == "shortlist":
2803 if name == "shortlist":
2804 header = _('basic commands:\n\n')
2804 header = _('basic commands:\n\n')
2805 else:
2805 else:
2806 header = _('list of commands:\n\n')
2806 header = _('list of commands:\n\n')
2807
2807
2808 helplist(header)
2808 helplist(header)
2809 if name != 'shortlist':
2809 if name != 'shortlist':
2810 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2810 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2811 if text:
2811 if text:
2812 ui.write("\n%s\n" % minirst.format(text, textwidth))
2812 ui.write("\n%s\n" % minirst.format(text, textwidth))
2813
2813
2814 # list all option lists
2814 # list all option lists
2815 opt_output = []
2815 opt_output = []
2816 multioccur = False
2816 multioccur = False
2817 for title, options in option_lists:
2817 for title, options in option_lists:
2818 opt_output.append(("\n%s" % title, None))
2818 opt_output.append(("\n%s" % title, None))
2819 for option in options:
2819 for option in options:
2820 if len(option) == 5:
2820 if len(option) == 5:
2821 shortopt, longopt, default, desc, optlabel = option
2821 shortopt, longopt, default, desc, optlabel = option
2822 else:
2822 else:
2823 shortopt, longopt, default, desc = option
2823 shortopt, longopt, default, desc = option
2824 optlabel = _("VALUE") # default label
2824 optlabel = _("VALUE") # default label
2825
2825
2826 if _("DEPRECATED") in desc and not ui.verbose:
2826 if _("DEPRECATED") in desc and not ui.verbose:
2827 continue
2827 continue
2828 if isinstance(default, list):
2828 if isinstance(default, list):
2829 numqualifier = " %s [+]" % optlabel
2829 numqualifier = " %s [+]" % optlabel
2830 multioccur = True
2830 multioccur = True
2831 elif (default is not None) and not isinstance(default, bool):
2831 elif (default is not None) and not isinstance(default, bool):
2832 numqualifier = " %s" % optlabel
2832 numqualifier = " %s" % optlabel
2833 else:
2833 else:
2834 numqualifier = ""
2834 numqualifier = ""
2835 opt_output.append(("%2s%s" %
2835 opt_output.append(("%2s%s" %
2836 (shortopt and "-%s" % shortopt,
2836 (shortopt and "-%s" % shortopt,
2837 longopt and " --%s%s" %
2837 longopt and " --%s%s" %
2838 (longopt, numqualifier)),
2838 (longopt, numqualifier)),
2839 "%s%s" % (desc,
2839 "%s%s" % (desc,
2840 default
2840 default
2841 and _(" (default: %s)") % default
2841 and _(" (default: %s)") % default
2842 or "")))
2842 or "")))
2843 if multioccur:
2843 if multioccur:
2844 msg = _("\n[+] marked option can be specified multiple times")
2844 msg = _("\n[+] marked option can be specified multiple times")
2845 if ui.verbose and name != 'shortlist':
2845 if ui.verbose and name != 'shortlist':
2846 opt_output.append((msg, None))
2846 opt_output.append((msg, None))
2847 else:
2847 else:
2848 opt_output.insert(-1, (msg, None))
2848 opt_output.insert(-1, (msg, None))
2849
2849
2850 if not name:
2850 if not name:
2851 ui.write(_("\nadditional help topics:\n\n"))
2851 ui.write(_("\nadditional help topics:\n\n"))
2852 topics = []
2852 topics = []
2853 for names, header, doc in help.helptable:
2853 for names, header, doc in help.helptable:
2854 topics.append((sorted(names, key=len, reverse=True)[0], header))
2854 topics.append((sorted(names, key=len, reverse=True)[0], header))
2855 topics_len = max([len(s[0]) for s in topics])
2855 topics_len = max([len(s[0]) for s in topics])
2856 for t, desc in topics:
2856 for t, desc in topics:
2857 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2857 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2858
2858
2859 if opt_output:
2859 if opt_output:
2860 colwidth = encoding.colwidth
2860 colwidth = encoding.colwidth
2861 # normalize: (opt or message, desc or None, width of opt)
2861 # normalize: (opt or message, desc or None, width of opt)
2862 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2862 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2863 for opt, desc in opt_output]
2863 for opt, desc in opt_output]
2864 hanging = max([e[2] for e in entries])
2864 hanging = max([e[2] for e in entries])
2865 for opt, desc, width in entries:
2865 for opt, desc, width in entries:
2866 if desc:
2866 if desc:
2867 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2867 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2868 hangindent = ' ' * (hanging + 3)
2868 hangindent = ' ' * (hanging + 3)
2869 ui.write('%s\n' % (util.wrap(desc, textwidth,
2869 ui.write('%s\n' % (util.wrap(desc, textwidth,
2870 initindent=initindent,
2870 initindent=initindent,
2871 hangindent=hangindent)))
2871 hangindent=hangindent)))
2872 else:
2872 else:
2873 ui.write("%s\n" % opt)
2873 ui.write("%s\n" % opt)
2874
2874
2875 @command('identify|id',
2875 @command('identify|id',
2876 [('r', 'rev', '',
2876 [('r', 'rev', '',
2877 _('identify the specified revision'), _('REV')),
2877 _('identify the specified revision'), _('REV')),
2878 ('n', 'num', None, _('show local revision number')),
2878 ('n', 'num', None, _('show local revision number')),
2879 ('i', 'id', None, _('show global revision id')),
2879 ('i', 'id', None, _('show global revision id')),
2880 ('b', 'branch', None, _('show branch')),
2880 ('b', 'branch', None, _('show branch')),
2881 ('t', 'tags', None, _('show tags')),
2881 ('t', 'tags', None, _('show tags')),
2882 ('B', 'bookmarks', None, _('show bookmarks'))],
2882 ('B', 'bookmarks', None, _('show bookmarks'))],
2883 _('[-nibtB] [-r REV] [SOURCE]'))
2883 _('[-nibtB] [-r REV] [SOURCE]'))
2884 def identify(ui, repo, source=None, rev=None,
2884 def identify(ui, repo, source=None, rev=None,
2885 num=None, id=None, branch=None, tags=None, bookmarks=None):
2885 num=None, id=None, branch=None, tags=None, bookmarks=None):
2886 """identify the working copy or specified revision
2886 """identify the working copy or specified revision
2887
2887
2888 Print a summary identifying the repository state at REV using one or
2888 Print a summary identifying the repository state at REV using one or
2889 two parent hash identifiers, followed by a "+" if the working
2889 two parent hash identifiers, followed by a "+" if the working
2890 directory has uncommitted changes, the branch name (if not default),
2890 directory has uncommitted changes, the branch name (if not default),
2891 a list of tags, and a list of bookmarks.
2891 a list of tags, and a list of bookmarks.
2892
2892
2893 When REV is not given, print a summary of the current state of the
2893 When REV is not given, print a summary of the current state of the
2894 repository.
2894 repository.
2895
2895
2896 Specifying a path to a repository root or Mercurial bundle will
2896 Specifying a path to a repository root or Mercurial bundle will
2897 cause lookup to operate on that repository/bundle.
2897 cause lookup to operate on that repository/bundle.
2898
2898
2899 Returns 0 if successful.
2899 Returns 0 if successful.
2900 """
2900 """
2901
2901
2902 if not repo and not source:
2902 if not repo and not source:
2903 raise util.Abort(_("there is no Mercurial repository here "
2903 raise util.Abort(_("there is no Mercurial repository here "
2904 "(.hg not found)"))
2904 "(.hg not found)"))
2905
2905
2906 hexfunc = ui.debugflag and hex or short
2906 hexfunc = ui.debugflag and hex or short
2907 default = not (num or id or branch or tags or bookmarks)
2907 default = not (num or id or branch or tags or bookmarks)
2908 output = []
2908 output = []
2909 revs = []
2909 revs = []
2910
2910
2911 if source:
2911 if source:
2912 source, branches = hg.parseurl(ui.expandpath(source))
2912 source, branches = hg.parseurl(ui.expandpath(source))
2913 repo = hg.repository(ui, source)
2913 repo = hg.repository(ui, source)
2914 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2914 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2915
2915
2916 if not repo.local():
2916 if not repo.local():
2917 if num or branch or tags:
2917 if num or branch or tags:
2918 raise util.Abort(
2918 raise util.Abort(
2919 _("can't query remote revision number, branch, or tags"))
2919 _("can't query remote revision number, branch, or tags"))
2920 if not rev and revs:
2920 if not rev and revs:
2921 rev = revs[0]
2921 rev = revs[0]
2922 if not rev:
2922 if not rev:
2923 rev = "tip"
2923 rev = "tip"
2924
2924
2925 remoterev = repo.lookup(rev)
2925 remoterev = repo.lookup(rev)
2926 if default or id:
2926 if default or id:
2927 output = [hexfunc(remoterev)]
2927 output = [hexfunc(remoterev)]
2928
2928
2929 def getbms():
2929 def getbms():
2930 bms = []
2930 bms = []
2931
2931
2932 if 'bookmarks' in repo.listkeys('namespaces'):
2932 if 'bookmarks' in repo.listkeys('namespaces'):
2933 hexremoterev = hex(remoterev)
2933 hexremoterev = hex(remoterev)
2934 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2934 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2935 if bmr == hexremoterev]
2935 if bmr == hexremoterev]
2936
2936
2937 return bms
2937 return bms
2938
2938
2939 if bookmarks:
2939 if bookmarks:
2940 output.extend(getbms())
2940 output.extend(getbms())
2941 elif default and not ui.quiet:
2941 elif default and not ui.quiet:
2942 # multiple bookmarks for a single parent separated by '/'
2942 # multiple bookmarks for a single parent separated by '/'
2943 bm = '/'.join(getbms())
2943 bm = '/'.join(getbms())
2944 if bm:
2944 if bm:
2945 output.append(bm)
2945 output.append(bm)
2946 else:
2946 else:
2947 if not rev:
2947 if not rev:
2948 ctx = repo[None]
2948 ctx = repo[None]
2949 parents = ctx.parents()
2949 parents = ctx.parents()
2950 changed = ""
2950 changed = ""
2951 if default or id or num:
2951 if default or id or num:
2952 changed = util.any(repo.status()) and "+" or ""
2952 changed = util.any(repo.status()) and "+" or ""
2953 if default or id:
2953 if default or id:
2954 output = ["%s%s" %
2954 output = ["%s%s" %
2955 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2955 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2956 if num:
2956 if num:
2957 output.append("%s%s" %
2957 output.append("%s%s" %
2958 ('+'.join([str(p.rev()) for p in parents]), changed))
2958 ('+'.join([str(p.rev()) for p in parents]), changed))
2959 else:
2959 else:
2960 ctx = scmutil.revsingle(repo, rev)
2960 ctx = scmutil.revsingle(repo, rev)
2961 if default or id:
2961 if default or id:
2962 output = [hexfunc(ctx.node())]
2962 output = [hexfunc(ctx.node())]
2963 if num:
2963 if num:
2964 output.append(str(ctx.rev()))
2964 output.append(str(ctx.rev()))
2965
2965
2966 if default and not ui.quiet:
2966 if default and not ui.quiet:
2967 b = ctx.branch()
2967 b = ctx.branch()
2968 if b != 'default':
2968 if b != 'default':
2969 output.append("(%s)" % b)
2969 output.append("(%s)" % b)
2970
2970
2971 # multiple tags for a single parent separated by '/'
2971 # multiple tags for a single parent separated by '/'
2972 t = '/'.join(ctx.tags())
2972 t = '/'.join(ctx.tags())
2973 if t:
2973 if t:
2974 output.append(t)
2974 output.append(t)
2975
2975
2976 # multiple bookmarks for a single parent separated by '/'
2976 # multiple bookmarks for a single parent separated by '/'
2977 bm = '/'.join(ctx.bookmarks())
2977 bm = '/'.join(ctx.bookmarks())
2978 if bm:
2978 if bm:
2979 output.append(bm)
2979 output.append(bm)
2980 else:
2980 else:
2981 if branch:
2981 if branch:
2982 output.append(ctx.branch())
2982 output.append(ctx.branch())
2983
2983
2984 if tags:
2984 if tags:
2985 output.extend(ctx.tags())
2985 output.extend(ctx.tags())
2986
2986
2987 if bookmarks:
2987 if bookmarks:
2988 output.extend(ctx.bookmarks())
2988 output.extend(ctx.bookmarks())
2989
2989
2990 ui.write("%s\n" % ' '.join(output))
2990 ui.write("%s\n" % ' '.join(output))
2991
2991
2992 @command('import|patch',
2992 @command('import|patch',
2993 [('p', 'strip', 1,
2993 [('p', 'strip', 1,
2994 _('directory strip option for patch. This has the same '
2994 _('directory strip option for patch. This has the same '
2995 'meaning as the corresponding patch option'), _('NUM')),
2995 'meaning as the corresponding patch option'), _('NUM')),
2996 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2996 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
2997 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
2997 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
2998 ('', 'no-commit', None,
2998 ('', 'no-commit', None,
2999 _("don't commit, just update the working directory")),
2999 _("don't commit, just update the working directory")),
3000 ('', 'exact', None,
3000 ('', 'exact', None,
3001 _('apply patch to the nodes from which it was generated')),
3001 _('apply patch to the nodes from which it was generated')),
3002 ('', 'import-branch', None,
3002 ('', 'import-branch', None,
3003 _('use any branch information in patch (implied by --exact)'))] +
3003 _('use any branch information in patch (implied by --exact)'))] +
3004 commitopts + commitopts2 + similarityopts,
3004 commitopts + commitopts2 + similarityopts,
3005 _('[OPTION]... PATCH...'))
3005 _('[OPTION]... PATCH...'))
3006 def import_(ui, repo, patch1, *patches, **opts):
3006 def import_(ui, repo, patch1, *patches, **opts):
3007 """import an ordered set of patches
3007 """import an ordered set of patches
3008
3008
3009 Import a list of patches and commit them individually (unless
3009 Import a list of patches and commit them individually (unless
3010 --no-commit is specified).
3010 --no-commit is specified).
3011
3011
3012 If there are outstanding changes in the working directory, import
3012 If there are outstanding changes in the working directory, import
3013 will abort unless given the -f/--force flag.
3013 will abort unless given the -f/--force flag.
3014
3014
3015 You can import a patch straight from a mail message. Even patches
3015 You can import a patch straight from a mail message. Even patches
3016 as attachments work (to use the body part, it must have type
3016 as attachments work (to use the body part, it must have type
3017 text/plain or text/x-patch). From and Subject headers of email
3017 text/plain or text/x-patch). From and Subject headers of email
3018 message are used as default committer and commit message. All
3018 message are used as default committer and commit message. All
3019 text/plain body parts before first diff are added to commit
3019 text/plain body parts before first diff are added to commit
3020 message.
3020 message.
3021
3021
3022 If the imported patch was generated by :hg:`export`, user and
3022 If the imported patch was generated by :hg:`export`, user and
3023 description from patch override values from message headers and
3023 description from patch override values from message headers and
3024 body. Values given on command line with -m/--message and -u/--user
3024 body. Values given on command line with -m/--message and -u/--user
3025 override these.
3025 override these.
3026
3026
3027 If --exact is specified, import will set the working directory to
3027 If --exact is specified, import will set the working directory to
3028 the parent of each patch before applying it, and will abort if the
3028 the parent of each patch before applying it, and will abort if the
3029 resulting changeset has a different ID than the one recorded in
3029 resulting changeset has a different ID than the one recorded in
3030 the patch. This may happen due to character set problems or other
3030 the patch. This may happen due to character set problems or other
3031 deficiencies in the text patch format.
3031 deficiencies in the text patch format.
3032
3032
3033 With -s/--similarity, hg will attempt to discover renames and
3033 With -s/--similarity, hg will attempt to discover renames and
3034 copies in the patch in the same way as 'addremove'.
3034 copies in the patch in the same way as 'addremove'.
3035
3035
3036 To read a patch from standard input, use "-" as the patch name. If
3036 To read a patch from standard input, use "-" as the patch name. If
3037 a URL is specified, the patch will be downloaded from it.
3037 a URL is specified, the patch will be downloaded from it.
3038 See :hg:`help dates` for a list of formats valid for -d/--date.
3038 See :hg:`help dates` for a list of formats valid for -d/--date.
3039
3039
3040 Returns 0 on success.
3040 Returns 0 on success.
3041 """
3041 """
3042 patches = (patch1,) + patches
3042 patches = (patch1,) + patches
3043
3043
3044 date = opts.get('date')
3044 date = opts.get('date')
3045 if date:
3045 if date:
3046 opts['date'] = util.parsedate(date)
3046 opts['date'] = util.parsedate(date)
3047
3047
3048 try:
3048 try:
3049 sim = float(opts.get('similarity') or 0)
3049 sim = float(opts.get('similarity') or 0)
3050 except ValueError:
3050 except ValueError:
3051 raise util.Abort(_('similarity must be a number'))
3051 raise util.Abort(_('similarity must be a number'))
3052 if sim < 0 or sim > 100:
3052 if sim < 0 or sim > 100:
3053 raise util.Abort(_('similarity must be between 0 and 100'))
3053 raise util.Abort(_('similarity must be between 0 and 100'))
3054
3054
3055 if opts.get('exact') or not opts.get('force'):
3055 if opts.get('exact') or not opts.get('force'):
3056 cmdutil.bailifchanged(repo)
3056 cmdutil.bailifchanged(repo)
3057
3057
3058 d = opts["base"]
3058 d = opts["base"]
3059 strip = opts["strip"]
3059 strip = opts["strip"]
3060 wlock = lock = None
3060 wlock = lock = None
3061 msgs = []
3061 msgs = []
3062
3062
3063 def tryone(ui, hunk):
3063 def tryone(ui, hunk):
3064 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3064 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3065 patch.extract(ui, hunk)
3065 patch.extract(ui, hunk)
3066
3066
3067 if not tmpname:
3067 if not tmpname:
3068 return None
3068 return None
3069 commitid = _('to working directory')
3069 commitid = _('to working directory')
3070
3070
3071 try:
3071 try:
3072 cmdline_message = cmdutil.logmessage(opts)
3072 cmdline_message = cmdutil.logmessage(opts)
3073 if cmdline_message:
3073 if cmdline_message:
3074 # pickup the cmdline msg
3074 # pickup the cmdline msg
3075 message = cmdline_message
3075 message = cmdline_message
3076 elif message:
3076 elif message:
3077 # pickup the patch msg
3077 # pickup the patch msg
3078 message = message.strip()
3078 message = message.strip()
3079 else:
3079 else:
3080 # launch the editor
3080 # launch the editor
3081 message = None
3081 message = None
3082 ui.debug('message:\n%s\n' % message)
3082 ui.debug('message:\n%s\n' % message)
3083
3083
3084 wp = repo.parents()
3084 wp = repo.parents()
3085 if opts.get('exact'):
3085 if opts.get('exact'):
3086 if not nodeid or not p1:
3086 if not nodeid or not p1:
3087 raise util.Abort(_('not a Mercurial patch'))
3087 raise util.Abort(_('not a Mercurial patch'))
3088 p1 = repo.lookup(p1)
3088 p1 = repo.lookup(p1)
3089 p2 = repo.lookup(p2 or hex(nullid))
3089 p2 = repo.lookup(p2 or hex(nullid))
3090
3090
3091 if p1 != wp[0].node():
3091 if p1 != wp[0].node():
3092 hg.clean(repo, p1)
3092 hg.clean(repo, p1)
3093 repo.dirstate.setparents(p1, p2)
3093 repo.dirstate.setparents(p1, p2)
3094 elif p2:
3094 elif p2:
3095 try:
3095 try:
3096 p1 = repo.lookup(p1)
3096 p1 = repo.lookup(p1)
3097 p2 = repo.lookup(p2)
3097 p2 = repo.lookup(p2)
3098 if p1 == wp[0].node():
3098 if p1 == wp[0].node():
3099 repo.dirstate.setparents(p1, p2)
3099 repo.dirstate.setparents(p1, p2)
3100 except error.RepoError:
3100 except error.RepoError:
3101 pass
3101 pass
3102 if opts.get('exact') or opts.get('import_branch'):
3102 if opts.get('exact') or opts.get('import_branch'):
3103 repo.dirstate.setbranch(branch or 'default')
3103 repo.dirstate.setbranch(branch or 'default')
3104
3104
3105 files = {}
3105 files = {}
3106 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3106 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3107 eolmode=None, similarity=sim / 100.0)
3107 eolmode=None, similarity=sim / 100.0)
3108 files = list(files)
3108 files = list(files)
3109 if opts.get('no_commit'):
3109 if opts.get('no_commit'):
3110 if message:
3110 if message:
3111 msgs.append(message)
3111 msgs.append(message)
3112 else:
3112 else:
3113 if opts.get('exact'):
3113 if opts.get('exact'):
3114 m = None
3114 m = None
3115 else:
3115 else:
3116 m = scmutil.matchfiles(repo, files or [])
3116 m = scmutil.matchfiles(repo, files or [])
3117 n = repo.commit(message, opts.get('user') or user,
3117 n = repo.commit(message, opts.get('user') or user,
3118 opts.get('date') or date, match=m,
3118 opts.get('date') or date, match=m,
3119 editor=cmdutil.commiteditor)
3119 editor=cmdutil.commiteditor)
3120 if opts.get('exact'):
3120 if opts.get('exact'):
3121 if hex(n) != nodeid:
3121 if hex(n) != nodeid:
3122 repo.rollback()
3122 repo.rollback()
3123 raise util.Abort(_('patch is damaged'
3123 raise util.Abort(_('patch is damaged'
3124 ' or loses information'))
3124 ' or loses information'))
3125 # Force a dirstate write so that the next transaction
3125 # Force a dirstate write so that the next transaction
3126 # backups an up-do-date file.
3126 # backups an up-do-date file.
3127 repo.dirstate.write()
3127 repo.dirstate.write()
3128 if n:
3128 if n:
3129 commitid = short(n)
3129 commitid = short(n)
3130
3130
3131 return commitid
3131 return commitid
3132 finally:
3132 finally:
3133 os.unlink(tmpname)
3133 os.unlink(tmpname)
3134
3134
3135 try:
3135 try:
3136 wlock = repo.wlock()
3136 wlock = repo.wlock()
3137 lock = repo.lock()
3137 lock = repo.lock()
3138 lastcommit = None
3138 lastcommit = None
3139 for p in patches:
3139 for p in patches:
3140 pf = os.path.join(d, p)
3140 pf = os.path.join(d, p)
3141
3141
3142 if pf == '-':
3142 if pf == '-':
3143 ui.status(_("applying patch from stdin\n"))
3143 ui.status(_("applying patch from stdin\n"))
3144 pf = sys.stdin
3144 pf = sys.stdin
3145 else:
3145 else:
3146 ui.status(_("applying %s\n") % p)
3146 ui.status(_("applying %s\n") % p)
3147 pf = url.open(ui, pf)
3147 pf = url.open(ui, pf)
3148
3148
3149 haspatch = False
3149 haspatch = False
3150 for hunk in patch.split(pf):
3150 for hunk in patch.split(pf):
3151 commitid = tryone(ui, hunk)
3151 commitid = tryone(ui, hunk)
3152 if commitid:
3152 if commitid:
3153 haspatch = True
3153 haspatch = True
3154 if lastcommit:
3154 if lastcommit:
3155 ui.status(_('applied %s\n') % lastcommit)
3155 ui.status(_('applied %s\n') % lastcommit)
3156 lastcommit = commitid
3156 lastcommit = commitid
3157
3157
3158 if not haspatch:
3158 if not haspatch:
3159 raise util.Abort(_('no diffs found'))
3159 raise util.Abort(_('no diffs found'))
3160
3160
3161 if msgs:
3161 if msgs:
3162 repo.savecommitmessage('\n* * *\n'.join(msgs))
3162 repo.savecommitmessage('\n* * *\n'.join(msgs))
3163 finally:
3163 finally:
3164 release(lock, wlock)
3164 release(lock, wlock)
3165
3165
3166 @command('incoming|in',
3166 @command('incoming|in',
3167 [('f', 'force', None,
3167 [('f', 'force', None,
3168 _('run even if remote repository is unrelated')),
3168 _('run even if remote repository is unrelated')),
3169 ('n', 'newest-first', None, _('show newest record first')),
3169 ('n', 'newest-first', None, _('show newest record first')),
3170 ('', 'bundle', '',
3170 ('', 'bundle', '',
3171 _('file to store the bundles into'), _('FILE')),
3171 _('file to store the bundles into'), _('FILE')),
3172 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3172 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3173 ('B', 'bookmarks', False, _("compare bookmarks")),
3173 ('B', 'bookmarks', False, _("compare bookmarks")),
3174 ('b', 'branch', [],
3174 ('b', 'branch', [],
3175 _('a specific branch you would like to pull'), _('BRANCH')),
3175 _('a specific branch you would like to pull'), _('BRANCH')),
3176 ] + logopts + remoteopts + subrepoopts,
3176 ] + logopts + remoteopts + subrepoopts,
3177 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3177 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3178 def incoming(ui, repo, source="default", **opts):
3178 def incoming(ui, repo, source="default", **opts):
3179 """show new changesets found in source
3179 """show new changesets found in source
3180
3180
3181 Show new changesets found in the specified path/URL or the default
3181 Show new changesets found in the specified path/URL or the default
3182 pull location. These are the changesets that would have been pulled
3182 pull location. These are the changesets that would have been pulled
3183 if a pull at the time you issued this command.
3183 if a pull at the time you issued this command.
3184
3184
3185 For remote repository, using --bundle avoids downloading the
3185 For remote repository, using --bundle avoids downloading the
3186 changesets twice if the incoming is followed by a pull.
3186 changesets twice if the incoming is followed by a pull.
3187
3187
3188 See pull for valid source format details.
3188 See pull for valid source format details.
3189
3189
3190 Returns 0 if there are incoming changes, 1 otherwise.
3190 Returns 0 if there are incoming changes, 1 otherwise.
3191 """
3191 """
3192 if opts.get('bundle') and opts.get('subrepos'):
3192 if opts.get('bundle') and opts.get('subrepos'):
3193 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3193 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3194
3194
3195 if opts.get('bookmarks'):
3195 if opts.get('bookmarks'):
3196 source, branches = hg.parseurl(ui.expandpath(source),
3196 source, branches = hg.parseurl(ui.expandpath(source),
3197 opts.get('branch'))
3197 opts.get('branch'))
3198 other = hg.repository(hg.remoteui(repo, opts), source)
3198 other = hg.repository(hg.remoteui(repo, opts), source)
3199 if 'bookmarks' not in other.listkeys('namespaces'):
3199 if 'bookmarks' not in other.listkeys('namespaces'):
3200 ui.warn(_("remote doesn't support bookmarks\n"))
3200 ui.warn(_("remote doesn't support bookmarks\n"))
3201 return 0
3201 return 0
3202 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3202 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3203 return bookmarks.diff(ui, repo, other)
3203 return bookmarks.diff(ui, repo, other)
3204
3204
3205 repo._subtoppath = ui.expandpath(source)
3205 repo._subtoppath = ui.expandpath(source)
3206 try:
3206 try:
3207 return hg.incoming(ui, repo, source, opts)
3207 return hg.incoming(ui, repo, source, opts)
3208 finally:
3208 finally:
3209 del repo._subtoppath
3209 del repo._subtoppath
3210
3210
3211
3211
3212 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3212 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3213 def init(ui, dest=".", **opts):
3213 def init(ui, dest=".", **opts):
3214 """create a new repository in the given directory
3214 """create a new repository in the given directory
3215
3215
3216 Initialize a new repository in the given directory. If the given
3216 Initialize a new repository in the given directory. If the given
3217 directory does not exist, it will be created.
3217 directory does not exist, it will be created.
3218
3218
3219 If no directory is given, the current directory is used.
3219 If no directory is given, the current directory is used.
3220
3220
3221 It is possible to specify an ``ssh://`` URL as the destination.
3221 It is possible to specify an ``ssh://`` URL as the destination.
3222 See :hg:`help urls` for more information.
3222 See :hg:`help urls` for more information.
3223
3223
3224 Returns 0 on success.
3224 Returns 0 on success.
3225 """
3225 """
3226 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=True)
3226 hg.repository(hg.remoteui(ui, opts), ui.expandpath(dest), create=True)
3227
3227
3228 @command('locate',
3228 @command('locate',
3229 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3229 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3230 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3230 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3231 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3231 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3232 ] + walkopts,
3232 ] + walkopts,
3233 _('[OPTION]... [PATTERN]...'))
3233 _('[OPTION]... [PATTERN]...'))
3234 def locate(ui, repo, *pats, **opts):
3234 def locate(ui, repo, *pats, **opts):
3235 """locate files matching specific patterns
3235 """locate files matching specific patterns
3236
3236
3237 Print files under Mercurial control in the working directory whose
3237 Print files under Mercurial control in the working directory whose
3238 names match the given patterns.
3238 names match the given patterns.
3239
3239
3240 By default, this command searches all directories in the working
3240 By default, this command searches all directories in the working
3241 directory. To search just the current directory and its
3241 directory. To search just the current directory and its
3242 subdirectories, use "--include .".
3242 subdirectories, use "--include .".
3243
3243
3244 If no patterns are given to match, this command prints the names
3244 If no patterns are given to match, this command prints the names
3245 of all files under Mercurial control in the working directory.
3245 of all files under Mercurial control in the working directory.
3246
3246
3247 If you want to feed the output of this command into the "xargs"
3247 If you want to feed the output of this command into the "xargs"
3248 command, use the -0 option to both this command and "xargs". This
3248 command, use the -0 option to both this command and "xargs". This
3249 will avoid the problem of "xargs" treating single filenames that
3249 will avoid the problem of "xargs" treating single filenames that
3250 contain whitespace as multiple filenames.
3250 contain whitespace as multiple filenames.
3251
3251
3252 Returns 0 if a match is found, 1 otherwise.
3252 Returns 0 if a match is found, 1 otherwise.
3253 """
3253 """
3254 end = opts.get('print0') and '\0' or '\n'
3254 end = opts.get('print0') and '\0' or '\n'
3255 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3255 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3256
3256
3257 ret = 1
3257 ret = 1
3258 m = scmutil.match(repo, pats, opts, default='relglob')
3258 m = scmutil.match(repo, pats, opts, default='relglob')
3259 m.bad = lambda x, y: False
3259 m.bad = lambda x, y: False
3260 for abs in repo[rev].walk(m):
3260 for abs in repo[rev].walk(m):
3261 if not rev and abs not in repo.dirstate:
3261 if not rev and abs not in repo.dirstate:
3262 continue
3262 continue
3263 if opts.get('fullpath'):
3263 if opts.get('fullpath'):
3264 ui.write(repo.wjoin(abs), end)
3264 ui.write(repo.wjoin(abs), end)
3265 else:
3265 else:
3266 ui.write(((pats and m.rel(abs)) or abs), end)
3266 ui.write(((pats and m.rel(abs)) or abs), end)
3267 ret = 0
3267 ret = 0
3268
3268
3269 return ret
3269 return ret
3270
3270
3271 @command('^log|history',
3271 @command('^log|history',
3272 [('f', 'follow', None,
3272 [('f', 'follow', None,
3273 _('follow changeset history, or file history across copies and renames')),
3273 _('follow changeset history, or file history across copies and renames')),
3274 ('', 'follow-first', None,
3274 ('', 'follow-first', None,
3275 _('only follow the first parent of merge changesets')),
3275 _('only follow the first parent of merge changesets')),
3276 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3276 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3277 ('C', 'copies', None, _('show copied files')),
3277 ('C', 'copies', None, _('show copied files')),
3278 ('k', 'keyword', [],
3278 ('k', 'keyword', [],
3279 _('do case-insensitive search for a given text'), _('TEXT')),
3279 _('do case-insensitive search for a given text'), _('TEXT')),
3280 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3280 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3281 ('', 'removed', None, _('include revisions where files were removed')),
3281 ('', 'removed', None, _('include revisions where files were removed')),
3282 ('m', 'only-merges', None, _('show only merges')),
3282 ('m', 'only-merges', None, _('show only merges')),
3283 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3283 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3284 ('', 'only-branch', [],
3284 ('', 'only-branch', [],
3285 _('show only changesets within the given named branch (DEPRECATED)'),
3285 _('show only changesets within the given named branch (DEPRECATED)'),
3286 _('BRANCH')),
3286 _('BRANCH')),
3287 ('b', 'branch', [],
3287 ('b', 'branch', [],
3288 _('show changesets within the given named branch'), _('BRANCH')),
3288 _('show changesets within the given named branch'), _('BRANCH')),
3289 ('P', 'prune', [],
3289 ('P', 'prune', [],
3290 _('do not display revision or any of its ancestors'), _('REV')),
3290 _('do not display revision or any of its ancestors'), _('REV')),
3291 ] + logopts + walkopts,
3291 ] + logopts + walkopts,
3292 _('[OPTION]... [FILE]'))
3292 _('[OPTION]... [FILE]'))
3293 def log(ui, repo, *pats, **opts):
3293 def log(ui, repo, *pats, **opts):
3294 """show revision history of entire repository or files
3294 """show revision history of entire repository or files
3295
3295
3296 Print the revision history of the specified files or the entire
3296 Print the revision history of the specified files or the entire
3297 project.
3297 project.
3298
3298
3299 File history is shown without following rename or copy history of
3299 File history is shown without following rename or copy history of
3300 files. Use -f/--follow with a filename to follow history across
3300 files. Use -f/--follow with a filename to follow history across
3301 renames and copies. --follow without a filename will only show
3301 renames and copies. --follow without a filename will only show
3302 ancestors or descendants of the starting revision. --follow-first
3302 ancestors or descendants of the starting revision. --follow-first
3303 only follows the first parent of merge revisions.
3303 only follows the first parent of merge revisions.
3304
3304
3305 If no revision range is specified, the default is ``tip:0`` unless
3305 If no revision range is specified, the default is ``tip:0`` unless
3306 --follow is set, in which case the working directory parent is
3306 --follow is set, in which case the working directory parent is
3307 used as the starting revision. You can specify a revision set for
3307 used as the starting revision. You can specify a revision set for
3308 log, see :hg:`help revsets` for more information.
3308 log, see :hg:`help revsets` for more information.
3309
3309
3310 See :hg:`help dates` for a list of formats valid for -d/--date.
3310 See :hg:`help dates` for a list of formats valid for -d/--date.
3311
3311
3312 By default this command prints revision number and changeset id,
3312 By default this command prints revision number and changeset id,
3313 tags, non-trivial parents, user, date and time, and a summary for
3313 tags, non-trivial parents, user, date and time, and a summary for
3314 each commit. When the -v/--verbose switch is used, the list of
3314 each commit. When the -v/--verbose switch is used, the list of
3315 changed files and full commit message are shown.
3315 changed files and full commit message are shown.
3316
3316
3317 .. note::
3317 .. note::
3318 log -p/--patch may generate unexpected diff output for merge
3318 log -p/--patch may generate unexpected diff output for merge
3319 changesets, as it will only compare the merge changeset against
3319 changesets, as it will only compare the merge changeset against
3320 its first parent. Also, only files different from BOTH parents
3320 its first parent. Also, only files different from BOTH parents
3321 will appear in files:.
3321 will appear in files:.
3322
3322
3323 Returns 0 on success.
3323 Returns 0 on success.
3324 """
3324 """
3325
3325
3326 matchfn = scmutil.match(repo, pats, opts)
3326 matchfn = scmutil.match(repo, pats, opts)
3327 limit = cmdutil.loglimit(opts)
3327 limit = cmdutil.loglimit(opts)
3328 count = 0
3328 count = 0
3329
3329
3330 endrev = None
3330 endrev = None
3331 if opts.get('copies') and opts.get('rev'):
3331 if opts.get('copies') and opts.get('rev'):
3332 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3332 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3333
3333
3334 df = False
3334 df = False
3335 if opts["date"]:
3335 if opts["date"]:
3336 df = util.matchdate(opts["date"])
3336 df = util.matchdate(opts["date"])
3337
3337
3338 branches = opts.get('branch', []) + opts.get('only_branch', [])
3338 branches = opts.get('branch', []) + opts.get('only_branch', [])
3339 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3339 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3340
3340
3341 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3341 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3342 def prep(ctx, fns):
3342 def prep(ctx, fns):
3343 rev = ctx.rev()
3343 rev = ctx.rev()
3344 parents = [p for p in repo.changelog.parentrevs(rev)
3344 parents = [p for p in repo.changelog.parentrevs(rev)
3345 if p != nullrev]
3345 if p != nullrev]
3346 if opts.get('no_merges') and len(parents) == 2:
3346 if opts.get('no_merges') and len(parents) == 2:
3347 return
3347 return
3348 if opts.get('only_merges') and len(parents) != 2:
3348 if opts.get('only_merges') and len(parents) != 2:
3349 return
3349 return
3350 if opts.get('branch') and ctx.branch() not in opts['branch']:
3350 if opts.get('branch') and ctx.branch() not in opts['branch']:
3351 return
3351 return
3352 if df and not df(ctx.date()[0]):
3352 if df and not df(ctx.date()[0]):
3353 return
3353 return
3354 if opts['user'] and not [k for k in opts['user']
3354 if opts['user'] and not [k for k in opts['user']
3355 if k.lower() in ctx.user().lower()]:
3355 if k.lower() in ctx.user().lower()]:
3356 return
3356 return
3357 if opts.get('keyword'):
3357 if opts.get('keyword'):
3358 for k in [kw.lower() for kw in opts['keyword']]:
3358 for k in [kw.lower() for kw in opts['keyword']]:
3359 if (k in ctx.user().lower() or
3359 if (k in ctx.user().lower() or
3360 k in ctx.description().lower() or
3360 k in ctx.description().lower() or
3361 k in " ".join(ctx.files()).lower()):
3361 k in " ".join(ctx.files()).lower()):
3362 break
3362 break
3363 else:
3363 else:
3364 return
3364 return
3365
3365
3366 copies = None
3366 copies = None
3367 if opts.get('copies') and rev:
3367 if opts.get('copies') and rev:
3368 copies = []
3368 copies = []
3369 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3369 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3370 for fn in ctx.files():
3370 for fn in ctx.files():
3371 rename = getrenamed(fn, rev)
3371 rename = getrenamed(fn, rev)
3372 if rename:
3372 if rename:
3373 copies.append((fn, rename[0]))
3373 copies.append((fn, rename[0]))
3374
3374
3375 revmatchfn = None
3375 revmatchfn = None
3376 if opts.get('patch') or opts.get('stat'):
3376 if opts.get('patch') or opts.get('stat'):
3377 if opts.get('follow') or opts.get('follow_first'):
3377 if opts.get('follow') or opts.get('follow_first'):
3378 # note: this might be wrong when following through merges
3378 # note: this might be wrong when following through merges
3379 revmatchfn = scmutil.match(repo, fns, default='path')
3379 revmatchfn = scmutil.match(repo, fns, default='path')
3380 else:
3380 else:
3381 revmatchfn = matchfn
3381 revmatchfn = matchfn
3382
3382
3383 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3383 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3384
3384
3385 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3385 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3386 if count == limit:
3386 if count == limit:
3387 break
3387 break
3388 if displayer.flush(ctx.rev()):
3388 if displayer.flush(ctx.rev()):
3389 count += 1
3389 count += 1
3390 displayer.close()
3390 displayer.close()
3391
3391
3392 @command('manifest',
3392 @command('manifest',
3393 [('r', 'rev', '', _('revision to display'), _('REV')),
3393 [('r', 'rev', '', _('revision to display'), _('REV')),
3394 ('', 'all', False, _("list files from all revisions"))],
3394 ('', 'all', False, _("list files from all revisions"))],
3395 _('[-r REV]'))
3395 _('[-r REV]'))
3396 def manifest(ui, repo, node=None, rev=None, **opts):
3396 def manifest(ui, repo, node=None, rev=None, **opts):
3397 """output the current or given revision of the project manifest
3397 """output the current or given revision of the project manifest
3398
3398
3399 Print a list of version controlled files for the given revision.
3399 Print a list of version controlled files for the given revision.
3400 If no revision is given, the first parent of the working directory
3400 If no revision is given, the first parent of the working directory
3401 is used, or the null revision if no revision is checked out.
3401 is used, or the null revision if no revision is checked out.
3402
3402
3403 With -v, print file permissions, symlink and executable bits.
3403 With -v, print file permissions, symlink and executable bits.
3404 With --debug, print file revision hashes.
3404 With --debug, print file revision hashes.
3405
3405
3406 If option --all is specified, the list of all files from all revisions
3406 If option --all is specified, the list of all files from all revisions
3407 is printed. This includes deleted and renamed files.
3407 is printed. This includes deleted and renamed files.
3408
3408
3409 Returns 0 on success.
3409 Returns 0 on success.
3410 """
3410 """
3411 if opts.get('all'):
3411 if opts.get('all'):
3412 if rev or node:
3412 if rev or node:
3413 raise util.Abort(_("can't specify a revision with --all"))
3413 raise util.Abort(_("can't specify a revision with --all"))
3414
3414
3415 res = []
3415 res = []
3416 prefix = "data/"
3416 prefix = "data/"
3417 suffix = ".i"
3417 suffix = ".i"
3418 plen = len(prefix)
3418 plen = len(prefix)
3419 slen = len(suffix)
3419 slen = len(suffix)
3420 lock = repo.lock()
3420 lock = repo.lock()
3421 try:
3421 try:
3422 for fn, b, size in repo.store.datafiles():
3422 for fn, b, size in repo.store.datafiles():
3423 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3423 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3424 res.append(fn[plen:-slen])
3424 res.append(fn[plen:-slen])
3425 finally:
3425 finally:
3426 lock.release()
3426 lock.release()
3427 for f in sorted(res):
3427 for f in sorted(res):
3428 ui.write("%s\n" % f)
3428 ui.write("%s\n" % f)
3429 return
3429 return
3430
3430
3431 if rev and node:
3431 if rev and node:
3432 raise util.Abort(_("please specify just one revision"))
3432 raise util.Abort(_("please specify just one revision"))
3433
3433
3434 if not node:
3434 if not node:
3435 node = rev
3435 node = rev
3436
3436
3437 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3437 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3438 ctx = scmutil.revsingle(repo, node)
3438 ctx = scmutil.revsingle(repo, node)
3439 for f in ctx:
3439 for f in ctx:
3440 if ui.debugflag:
3440 if ui.debugflag:
3441 ui.write("%40s " % hex(ctx.manifest()[f]))
3441 ui.write("%40s " % hex(ctx.manifest()[f]))
3442 if ui.verbose:
3442 if ui.verbose:
3443 ui.write(decor[ctx.flags(f)])
3443 ui.write(decor[ctx.flags(f)])
3444 ui.write("%s\n" % f)
3444 ui.write("%s\n" % f)
3445
3445
3446 @command('^merge',
3446 @command('^merge',
3447 [('f', 'force', None, _('force a merge with outstanding changes')),
3447 [('f', 'force', None, _('force a merge with outstanding changes')),
3448 ('t', 'tool', '', _('specify merge tool')),
3448 ('t', 'tool', '', _('specify merge tool')),
3449 ('r', 'rev', '', _('revision to merge'), _('REV')),
3449 ('r', 'rev', '', _('revision to merge'), _('REV')),
3450 ('P', 'preview', None,
3450 ('P', 'preview', None,
3451 _('review revisions to merge (no merge is performed)'))],
3451 _('review revisions to merge (no merge is performed)'))],
3452 _('[-P] [-f] [[-r] REV]'))
3452 _('[-P] [-f] [[-r] REV]'))
3453 def merge(ui, repo, node=None, **opts):
3453 def merge(ui, repo, node=None, **opts):
3454 """merge working directory with another revision
3454 """merge working directory with another revision
3455
3455
3456 The current working directory is updated with all changes made in
3456 The current working directory is updated with all changes made in
3457 the requested revision since the last common predecessor revision.
3457 the requested revision since the last common predecessor revision.
3458
3458
3459 Files that changed between either parent are marked as changed for
3459 Files that changed between either parent are marked as changed for
3460 the next commit and a commit must be performed before any further
3460 the next commit and a commit must be performed before any further
3461 updates to the repository are allowed. The next commit will have
3461 updates to the repository are allowed. The next commit will have
3462 two parents.
3462 two parents.
3463
3463
3464 ``--tool`` can be used to specify the merge tool used for file
3464 ``--tool`` can be used to specify the merge tool used for file
3465 merges. It overrides the HGMERGE environment variable and your
3465 merges. It overrides the HGMERGE environment variable and your
3466 configuration files. See :hg:`help merge-tools` for options.
3466 configuration files. See :hg:`help merge-tools` for options.
3467
3467
3468 If no revision is specified, the working directory's parent is a
3468 If no revision is specified, the working directory's parent is a
3469 head revision, and the current branch contains exactly one other
3469 head revision, and the current branch contains exactly one other
3470 head, the other head is merged with by default. Otherwise, an
3470 head, the other head is merged with by default. Otherwise, an
3471 explicit revision with which to merge with must be provided.
3471 explicit revision with which to merge with must be provided.
3472
3472
3473 :hg:`resolve` must be used to resolve unresolved files.
3473 :hg:`resolve` must be used to resolve unresolved files.
3474
3474
3475 To undo an uncommitted merge, use :hg:`update --clean .` which
3475 To undo an uncommitted merge, use :hg:`update --clean .` which
3476 will check out a clean copy of the original merge parent, losing
3476 will check out a clean copy of the original merge parent, losing
3477 all changes.
3477 all changes.
3478
3478
3479 Returns 0 on success, 1 if there are unresolved files.
3479 Returns 0 on success, 1 if there are unresolved files.
3480 """
3480 """
3481
3481
3482 if opts.get('rev') and node:
3482 if opts.get('rev') and node:
3483 raise util.Abort(_("please specify just one revision"))
3483 raise util.Abort(_("please specify just one revision"))
3484 if not node:
3484 if not node:
3485 node = opts.get('rev')
3485 node = opts.get('rev')
3486
3486
3487 if not node:
3487 if not node:
3488 branch = repo[None].branch()
3488 branch = repo[None].branch()
3489 bheads = repo.branchheads(branch)
3489 bheads = repo.branchheads(branch)
3490 if len(bheads) > 2:
3490 if len(bheads) > 2:
3491 raise util.Abort(_("branch '%s' has %d heads - "
3491 raise util.Abort(_("branch '%s' has %d heads - "
3492 "please merge with an explicit rev")
3492 "please merge with an explicit rev")
3493 % (branch, len(bheads)),
3493 % (branch, len(bheads)),
3494 hint=_("run 'hg heads .' to see heads"))
3494 hint=_("run 'hg heads .' to see heads"))
3495
3495
3496 parent = repo.dirstate.p1()
3496 parent = repo.dirstate.p1()
3497 if len(bheads) == 1:
3497 if len(bheads) == 1:
3498 if len(repo.heads()) > 1:
3498 if len(repo.heads()) > 1:
3499 raise util.Abort(_("branch '%s' has one head - "
3499 raise util.Abort(_("branch '%s' has one head - "
3500 "please merge with an explicit rev")
3500 "please merge with an explicit rev")
3501 % branch,
3501 % branch,
3502 hint=_("run 'hg heads' to see all heads"))
3502 hint=_("run 'hg heads' to see all heads"))
3503 msg = _('there is nothing to merge')
3503 msg = _('there is nothing to merge')
3504 if parent != repo.lookup(repo[None].branch()):
3504 if parent != repo.lookup(repo[None].branch()):
3505 msg = _('%s - use "hg update" instead') % msg
3505 msg = _('%s - use "hg update" instead') % msg
3506 raise util.Abort(msg)
3506 raise util.Abort(msg)
3507
3507
3508 if parent not in bheads:
3508 if parent not in bheads:
3509 raise util.Abort(_('working directory not at a head revision'),
3509 raise util.Abort(_('working directory not at a head revision'),
3510 hint=_("use 'hg update' or merge with an "
3510 hint=_("use 'hg update' or merge with an "
3511 "explicit revision"))
3511 "explicit revision"))
3512 node = parent == bheads[0] and bheads[-1] or bheads[0]
3512 node = parent == bheads[0] and bheads[-1] or bheads[0]
3513 else:
3513 else:
3514 node = scmutil.revsingle(repo, node).node()
3514 node = scmutil.revsingle(repo, node).node()
3515
3515
3516 if opts.get('preview'):
3516 if opts.get('preview'):
3517 # find nodes that are ancestors of p2 but not of p1
3517 # find nodes that are ancestors of p2 but not of p1
3518 p1 = repo.lookup('.')
3518 p1 = repo.lookup('.')
3519 p2 = repo.lookup(node)
3519 p2 = repo.lookup(node)
3520 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3520 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3521
3521
3522 displayer = cmdutil.show_changeset(ui, repo, opts)
3522 displayer = cmdutil.show_changeset(ui, repo, opts)
3523 for node in nodes:
3523 for node in nodes:
3524 displayer.show(repo[node])
3524 displayer.show(repo[node])
3525 displayer.close()
3525 displayer.close()
3526 return 0
3526 return 0
3527
3527
3528 try:
3528 try:
3529 # ui.forcemerge is an internal variable, do not document
3529 # ui.forcemerge is an internal variable, do not document
3530 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3530 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3531 return hg.merge(repo, node, force=opts.get('force'))
3531 return hg.merge(repo, node, force=opts.get('force'))
3532 finally:
3532 finally:
3533 ui.setconfig('ui', 'forcemerge', '')
3533 ui.setconfig('ui', 'forcemerge', '')
3534
3534
3535 @command('outgoing|out',
3535 @command('outgoing|out',
3536 [('f', 'force', None, _('run even when the destination is unrelated')),
3536 [('f', 'force', None, _('run even when the destination is unrelated')),
3537 ('r', 'rev', [],
3537 ('r', 'rev', [],
3538 _('a changeset intended to be included in the destination'), _('REV')),
3538 _('a changeset intended to be included in the destination'), _('REV')),
3539 ('n', 'newest-first', None, _('show newest record first')),
3539 ('n', 'newest-first', None, _('show newest record first')),
3540 ('B', 'bookmarks', False, _('compare bookmarks')),
3540 ('B', 'bookmarks', False, _('compare bookmarks')),
3541 ('b', 'branch', [], _('a specific branch you would like to push'),
3541 ('b', 'branch', [], _('a specific branch you would like to push'),
3542 _('BRANCH')),
3542 _('BRANCH')),
3543 ] + logopts + remoteopts + subrepoopts,
3543 ] + logopts + remoteopts + subrepoopts,
3544 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3544 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3545 def outgoing(ui, repo, dest=None, **opts):
3545 def outgoing(ui, repo, dest=None, **opts):
3546 """show changesets not found in the destination
3546 """show changesets not found in the destination
3547
3547
3548 Show changesets not found in the specified destination repository
3548 Show changesets not found in the specified destination repository
3549 or the default push location. These are the changesets that would
3549 or the default push location. These are the changesets that would
3550 be pushed if a push was requested.
3550 be pushed if a push was requested.
3551
3551
3552 See pull for details of valid destination formats.
3552 See pull for details of valid destination formats.
3553
3553
3554 Returns 0 if there are outgoing changes, 1 otherwise.
3554 Returns 0 if there are outgoing changes, 1 otherwise.
3555 """
3555 """
3556
3556
3557 if opts.get('bookmarks'):
3557 if opts.get('bookmarks'):
3558 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3558 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3559 dest, branches = hg.parseurl(dest, opts.get('branch'))
3559 dest, branches = hg.parseurl(dest, opts.get('branch'))
3560 other = hg.repository(hg.remoteui(repo, opts), dest)
3560 other = hg.repository(hg.remoteui(repo, opts), dest)
3561 if 'bookmarks' not in other.listkeys('namespaces'):
3561 if 'bookmarks' not in other.listkeys('namespaces'):
3562 ui.warn(_("remote doesn't support bookmarks\n"))
3562 ui.warn(_("remote doesn't support bookmarks\n"))
3563 return 0
3563 return 0
3564 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3564 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3565 return bookmarks.diff(ui, other, repo)
3565 return bookmarks.diff(ui, other, repo)
3566
3566
3567 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3567 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3568 try:
3568 try:
3569 return hg.outgoing(ui, repo, dest, opts)
3569 return hg.outgoing(ui, repo, dest, opts)
3570 finally:
3570 finally:
3571 del repo._subtoppath
3571 del repo._subtoppath
3572
3572
3573 @command('parents',
3573 @command('parents',
3574 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3574 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3575 ] + templateopts,
3575 ] + templateopts,
3576 _('[-r REV] [FILE]'))
3576 _('[-r REV] [FILE]'))
3577 def parents(ui, repo, file_=None, **opts):
3577 def parents(ui, repo, file_=None, **opts):
3578 """show the parents of the working directory or revision
3578 """show the parents of the working directory or revision
3579
3579
3580 Print the working directory's parent revisions. If a revision is
3580 Print the working directory's parent revisions. If a revision is
3581 given via -r/--rev, the parent of that revision will be printed.
3581 given via -r/--rev, the parent of that revision will be printed.
3582 If a file argument is given, the revision in which the file was
3582 If a file argument is given, the revision in which the file was
3583 last changed (before the working directory revision or the
3583 last changed (before the working directory revision or the
3584 argument to --rev if given) is printed.
3584 argument to --rev if given) is printed.
3585
3585
3586 Returns 0 on success.
3586 Returns 0 on success.
3587 """
3587 """
3588
3588
3589 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3589 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3590
3590
3591 if file_:
3591 if file_:
3592 m = scmutil.match(repo, (file_,), opts)
3592 m = scmutil.match(repo, (file_,), opts)
3593 if m.anypats() or len(m.files()) != 1:
3593 if m.anypats() or len(m.files()) != 1:
3594 raise util.Abort(_('can only specify an explicit filename'))
3594 raise util.Abort(_('can only specify an explicit filename'))
3595 file_ = m.files()[0]
3595 file_ = m.files()[0]
3596 filenodes = []
3596 filenodes = []
3597 for cp in ctx.parents():
3597 for cp in ctx.parents():
3598 if not cp:
3598 if not cp:
3599 continue
3599 continue
3600 try:
3600 try:
3601 filenodes.append(cp.filenode(file_))
3601 filenodes.append(cp.filenode(file_))
3602 except error.LookupError:
3602 except error.LookupError:
3603 pass
3603 pass
3604 if not filenodes:
3604 if not filenodes:
3605 raise util.Abort(_("'%s' not found in manifest!") % file_)
3605 raise util.Abort(_("'%s' not found in manifest!") % file_)
3606 fl = repo.file(file_)
3606 fl = repo.file(file_)
3607 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3607 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3608 else:
3608 else:
3609 p = [cp.node() for cp in ctx.parents()]
3609 p = [cp.node() for cp in ctx.parents()]
3610
3610
3611 displayer = cmdutil.show_changeset(ui, repo, opts)
3611 displayer = cmdutil.show_changeset(ui, repo, opts)
3612 for n in p:
3612 for n in p:
3613 if n != nullid:
3613 if n != nullid:
3614 displayer.show(repo[n])
3614 displayer.show(repo[n])
3615 displayer.close()
3615 displayer.close()
3616
3616
3617 @command('paths', [], _('[NAME]'))
3617 @command('paths', [], _('[NAME]'))
3618 def paths(ui, repo, search=None):
3618 def paths(ui, repo, search=None):
3619 """show aliases for remote repositories
3619 """show aliases for remote repositories
3620
3620
3621 Show definition of symbolic path name NAME. If no name is given,
3621 Show definition of symbolic path name NAME. If no name is given,
3622 show definition of all available names.
3622 show definition of all available names.
3623
3623
3624 Option -q/--quiet suppresses all output when searching for NAME
3624 Option -q/--quiet suppresses all output when searching for NAME
3625 and shows only the path names when listing all definitions.
3625 and shows only the path names when listing all definitions.
3626
3626
3627 Path names are defined in the [paths] section of your
3627 Path names are defined in the [paths] section of your
3628 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3628 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3629 repository, ``.hg/hgrc`` is used, too.
3629 repository, ``.hg/hgrc`` is used, too.
3630
3630
3631 The path names ``default`` and ``default-push`` have a special
3631 The path names ``default`` and ``default-push`` have a special
3632 meaning. When performing a push or pull operation, they are used
3632 meaning. When performing a push or pull operation, they are used
3633 as fallbacks if no location is specified on the command-line.
3633 as fallbacks if no location is specified on the command-line.
3634 When ``default-push`` is set, it will be used for push and
3634 When ``default-push`` is set, it will be used for push and
3635 ``default`` will be used for pull; otherwise ``default`` is used
3635 ``default`` will be used for pull; otherwise ``default`` is used
3636 as the fallback for both. When cloning a repository, the clone
3636 as the fallback for both. When cloning a repository, the clone
3637 source is written as ``default`` in ``.hg/hgrc``. Note that
3637 source is written as ``default`` in ``.hg/hgrc``. Note that
3638 ``default`` and ``default-push`` apply to all inbound (e.g.
3638 ``default`` and ``default-push`` apply to all inbound (e.g.
3639 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3639 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3640 :hg:`bundle`) operations.
3640 :hg:`bundle`) operations.
3641
3641
3642 See :hg:`help urls` for more information.
3642 See :hg:`help urls` for more information.
3643
3643
3644 Returns 0 on success.
3644 Returns 0 on success.
3645 """
3645 """
3646 if search:
3646 if search:
3647 for name, path in ui.configitems("paths"):
3647 for name, path in ui.configitems("paths"):
3648 if name == search:
3648 if name == search:
3649 ui.status("%s\n" % util.hidepassword(path))
3649 ui.status("%s\n" % util.hidepassword(path))
3650 return
3650 return
3651 if not ui.quiet:
3651 if not ui.quiet:
3652 ui.warn(_("not found!\n"))
3652 ui.warn(_("not found!\n"))
3653 return 1
3653 return 1
3654 else:
3654 else:
3655 for name, path in ui.configitems("paths"):
3655 for name, path in ui.configitems("paths"):
3656 if ui.quiet:
3656 if ui.quiet:
3657 ui.write("%s\n" % name)
3657 ui.write("%s\n" % name)
3658 else:
3658 else:
3659 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3659 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3660
3660
3661 def postincoming(ui, repo, modheads, optupdate, checkout):
3661 def postincoming(ui, repo, modheads, optupdate, checkout):
3662 if modheads == 0:
3662 if modheads == 0:
3663 return
3663 return
3664 if optupdate:
3664 if optupdate:
3665 try:
3665 try:
3666 return hg.update(repo, checkout)
3666 return hg.update(repo, checkout)
3667 except util.Abort, inst:
3667 except util.Abort, inst:
3668 ui.warn(_("not updating: %s\n" % str(inst)))
3668 ui.warn(_("not updating: %s\n" % str(inst)))
3669 return 0
3669 return 0
3670 if modheads > 1:
3670 if modheads > 1:
3671 currentbranchheads = len(repo.branchheads())
3671 currentbranchheads = len(repo.branchheads())
3672 if currentbranchheads == modheads:
3672 if currentbranchheads == modheads:
3673 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3673 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3674 elif currentbranchheads > 1:
3674 elif currentbranchheads > 1:
3675 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3675 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3676 else:
3676 else:
3677 ui.status(_("(run 'hg heads' to see heads)\n"))
3677 ui.status(_("(run 'hg heads' to see heads)\n"))
3678 else:
3678 else:
3679 ui.status(_("(run 'hg update' to get a working copy)\n"))
3679 ui.status(_("(run 'hg update' to get a working copy)\n"))
3680
3680
3681 @command('^pull',
3681 @command('^pull',
3682 [('u', 'update', None,
3682 [('u', 'update', None,
3683 _('update to new branch head if changesets were pulled')),
3683 _('update to new branch head if changesets were pulled')),
3684 ('f', 'force', None, _('run even when remote repository is unrelated')),
3684 ('f', 'force', None, _('run even when remote repository is unrelated')),
3685 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3685 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3686 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3686 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3687 ('b', 'branch', [], _('a specific branch you would like to pull'),
3687 ('b', 'branch', [], _('a specific branch you would like to pull'),
3688 _('BRANCH')),
3688 _('BRANCH')),
3689 ] + remoteopts,
3689 ] + remoteopts,
3690 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3690 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3691 def pull(ui, repo, source="default", **opts):
3691 def pull(ui, repo, source="default", **opts):
3692 """pull changes from the specified source
3692 """pull changes from the specified source
3693
3693
3694 Pull changes from a remote repository to a local one.
3694 Pull changes from a remote repository to a local one.
3695
3695
3696 This finds all changes from the repository at the specified path
3696 This finds all changes from the repository at the specified path
3697 or URL and adds them to a local repository (the current one unless
3697 or URL and adds them to a local repository (the current one unless
3698 -R is specified). By default, this does not update the copy of the
3698 -R is specified). By default, this does not update the copy of the
3699 project in the working directory.
3699 project in the working directory.
3700
3700
3701 Use :hg:`incoming` if you want to see what would have been added
3701 Use :hg:`incoming` if you want to see what would have been added
3702 by a pull at the time you issued this command. If you then decide
3702 by a pull at the time you issued this command. If you then decide
3703 to add those changes to the repository, you should use :hg:`pull
3703 to add those changes to the repository, you should use :hg:`pull
3704 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3704 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3705
3705
3706 If SOURCE is omitted, the 'default' path will be used.
3706 If SOURCE is omitted, the 'default' path will be used.
3707 See :hg:`help urls` for more information.
3707 See :hg:`help urls` for more information.
3708
3708
3709 Returns 0 on success, 1 if an update had unresolved files.
3709 Returns 0 on success, 1 if an update had unresolved files.
3710 """
3710 """
3711 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3711 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3712 other = hg.repository(hg.remoteui(repo, opts), source)
3712 other = hg.repository(hg.remoteui(repo, opts), source)
3713 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3713 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3714 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3714 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3715
3715
3716 if opts.get('bookmark'):
3716 if opts.get('bookmark'):
3717 if not revs:
3717 if not revs:
3718 revs = []
3718 revs = []
3719 rb = other.listkeys('bookmarks')
3719 rb = other.listkeys('bookmarks')
3720 for b in opts['bookmark']:
3720 for b in opts['bookmark']:
3721 if b not in rb:
3721 if b not in rb:
3722 raise util.Abort(_('remote bookmark %s not found!') % b)
3722 raise util.Abort(_('remote bookmark %s not found!') % b)
3723 revs.append(rb[b])
3723 revs.append(rb[b])
3724
3724
3725 if revs:
3725 if revs:
3726 try:
3726 try:
3727 revs = [other.lookup(rev) for rev in revs]
3727 revs = [other.lookup(rev) for rev in revs]
3728 except error.CapabilityError:
3728 except error.CapabilityError:
3729 err = _("other repository doesn't support revision lookup, "
3729 err = _("other repository doesn't support revision lookup, "
3730 "so a rev cannot be specified.")
3730 "so a rev cannot be specified.")
3731 raise util.Abort(err)
3731 raise util.Abort(err)
3732
3732
3733 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3733 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3734 bookmarks.updatefromremote(ui, repo, other)
3734 bookmarks.updatefromremote(ui, repo, other)
3735 if checkout:
3735 if checkout:
3736 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3736 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3737 repo._subtoppath = source
3737 repo._subtoppath = source
3738 try:
3738 try:
3739 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3739 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3740
3740
3741 finally:
3741 finally:
3742 del repo._subtoppath
3742 del repo._subtoppath
3743
3743
3744 # update specified bookmarks
3744 # update specified bookmarks
3745 if opts.get('bookmark'):
3745 if opts.get('bookmark'):
3746 for b in opts['bookmark']:
3746 for b in opts['bookmark']:
3747 # explicit pull overrides local bookmark if any
3747 # explicit pull overrides local bookmark if any
3748 ui.status(_("importing bookmark %s\n") % b)
3748 ui.status(_("importing bookmark %s\n") % b)
3749 repo._bookmarks[b] = repo[rb[b]].node()
3749 repo._bookmarks[b] = repo[rb[b]].node()
3750 bookmarks.write(repo)
3750 bookmarks.write(repo)
3751
3751
3752 return ret
3752 return ret
3753
3753
3754 @command('^push',
3754 @command('^push',
3755 [('f', 'force', None, _('force push')),
3755 [('f', 'force', None, _('force push')),
3756 ('r', 'rev', [],
3756 ('r', 'rev', [],
3757 _('a changeset intended to be included in the destination'),
3757 _('a changeset intended to be included in the destination'),
3758 _('REV')),
3758 _('REV')),
3759 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3759 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3760 ('b', 'branch', [],
3760 ('b', 'branch', [],
3761 _('a specific branch you would like to push'), _('BRANCH')),
3761 _('a specific branch you would like to push'), _('BRANCH')),
3762 ('', 'new-branch', False, _('allow pushing a new branch')),
3762 ('', 'new-branch', False, _('allow pushing a new branch')),
3763 ] + remoteopts,
3763 ] + remoteopts,
3764 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3764 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3765 def push(ui, repo, dest=None, **opts):
3765 def push(ui, repo, dest=None, **opts):
3766 """push changes to the specified destination
3766 """push changes to the specified destination
3767
3767
3768 Push changesets from the local repository to the specified
3768 Push changesets from the local repository to the specified
3769 destination.
3769 destination.
3770
3770
3771 This operation is symmetrical to pull: it is identical to a pull
3771 This operation is symmetrical to pull: it is identical to a pull
3772 in the destination repository from the current one.
3772 in the destination repository from the current one.
3773
3773
3774 By default, push will not allow creation of new heads at the
3774 By default, push will not allow creation of new heads at the
3775 destination, since multiple heads would make it unclear which head
3775 destination, since multiple heads would make it unclear which head
3776 to use. In this situation, it is recommended to pull and merge
3776 to use. In this situation, it is recommended to pull and merge
3777 before pushing.
3777 before pushing.
3778
3778
3779 Use --new-branch if you want to allow push to create a new named
3779 Use --new-branch if you want to allow push to create a new named
3780 branch that is not present at the destination. This allows you to
3780 branch that is not present at the destination. This allows you to
3781 only create a new branch without forcing other changes.
3781 only create a new branch without forcing other changes.
3782
3782
3783 Use -f/--force to override the default behavior and push all
3783 Use -f/--force to override the default behavior and push all
3784 changesets on all branches.
3784 changesets on all branches.
3785
3785
3786 If -r/--rev is used, the specified revision and all its ancestors
3786 If -r/--rev is used, the specified revision and all its ancestors
3787 will be pushed to the remote repository.
3787 will be pushed to the remote repository.
3788
3788
3789 Please see :hg:`help urls` for important details about ``ssh://``
3789 Please see :hg:`help urls` for important details about ``ssh://``
3790 URLs. If DESTINATION is omitted, a default path will be used.
3790 URLs. If DESTINATION is omitted, a default path will be used.
3791
3791
3792 Returns 0 if push was successful, 1 if nothing to push.
3792 Returns 0 if push was successful, 1 if nothing to push.
3793 """
3793 """
3794
3794
3795 if opts.get('bookmark'):
3795 if opts.get('bookmark'):
3796 for b in opts['bookmark']:
3796 for b in opts['bookmark']:
3797 # translate -B options to -r so changesets get pushed
3797 # translate -B options to -r so changesets get pushed
3798 if b in repo._bookmarks:
3798 if b in repo._bookmarks:
3799 opts.setdefault('rev', []).append(b)
3799 opts.setdefault('rev', []).append(b)
3800 else:
3800 else:
3801 # if we try to push a deleted bookmark, translate it to null
3801 # if we try to push a deleted bookmark, translate it to null
3802 # this lets simultaneous -r, -b options continue working
3802 # this lets simultaneous -r, -b options continue working
3803 opts.setdefault('rev', []).append("null")
3803 opts.setdefault('rev', []).append("null")
3804
3804
3805 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3805 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3806 dest, branches = hg.parseurl(dest, opts.get('branch'))
3806 dest, branches = hg.parseurl(dest, opts.get('branch'))
3807 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3807 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3808 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3808 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3809 other = hg.repository(hg.remoteui(repo, opts), dest)
3809 other = hg.repository(hg.remoteui(repo, opts), dest)
3810 if revs:
3810 if revs:
3811 revs = [repo.lookup(rev) for rev in revs]
3811 revs = [repo.lookup(rev) for rev in revs]
3812
3812
3813 repo._subtoppath = dest
3813 repo._subtoppath = dest
3814 try:
3814 try:
3815 # push subrepos depth-first for coherent ordering
3815 # push subrepos depth-first for coherent ordering
3816 c = repo['']
3816 c = repo['']
3817 subs = c.substate # only repos that are committed
3817 subs = c.substate # only repos that are committed
3818 for s in sorted(subs):
3818 for s in sorted(subs):
3819 if not c.sub(s).push(opts.get('force')):
3819 if not c.sub(s).push(opts.get('force')):
3820 return False
3820 return False
3821 finally:
3821 finally:
3822 del repo._subtoppath
3822 del repo._subtoppath
3823 result = repo.push(other, opts.get('force'), revs=revs,
3823 result = repo.push(other, opts.get('force'), revs=revs,
3824 newbranch=opts.get('new_branch'))
3824 newbranch=opts.get('new_branch'))
3825
3825
3826 result = (result == 0)
3826 result = (result == 0)
3827
3827
3828 if opts.get('bookmark'):
3828 if opts.get('bookmark'):
3829 rb = other.listkeys('bookmarks')
3829 rb = other.listkeys('bookmarks')
3830 for b in opts['bookmark']:
3830 for b in opts['bookmark']:
3831 # explicit push overrides remote bookmark if any
3831 # explicit push overrides remote bookmark if any
3832 if b in repo._bookmarks:
3832 if b in repo._bookmarks:
3833 ui.status(_("exporting bookmark %s\n") % b)
3833 ui.status(_("exporting bookmark %s\n") % b)
3834 new = repo[b].hex()
3834 new = repo[b].hex()
3835 elif b in rb:
3835 elif b in rb:
3836 ui.status(_("deleting remote bookmark %s\n") % b)
3836 ui.status(_("deleting remote bookmark %s\n") % b)
3837 new = '' # delete
3837 new = '' # delete
3838 else:
3838 else:
3839 ui.warn(_('bookmark %s does not exist on the local '
3839 ui.warn(_('bookmark %s does not exist on the local '
3840 'or remote repository!\n') % b)
3840 'or remote repository!\n') % b)
3841 return 2
3841 return 2
3842 old = rb.get(b, '')
3842 old = rb.get(b, '')
3843 r = other.pushkey('bookmarks', b, old, new)
3843 r = other.pushkey('bookmarks', b, old, new)
3844 if not r:
3844 if not r:
3845 ui.warn(_('updating bookmark %s failed!\n') % b)
3845 ui.warn(_('updating bookmark %s failed!\n') % b)
3846 if not result:
3846 if not result:
3847 result = 2
3847 result = 2
3848
3848
3849 return result
3849 return result
3850
3850
3851 @command('recover', [])
3851 @command('recover', [])
3852 def recover(ui, repo):
3852 def recover(ui, repo):
3853 """roll back an interrupted transaction
3853 """roll back an interrupted transaction
3854
3854
3855 Recover from an interrupted commit or pull.
3855 Recover from an interrupted commit or pull.
3856
3856
3857 This command tries to fix the repository status after an
3857 This command tries to fix the repository status after an
3858 interrupted operation. It should only be necessary when Mercurial
3858 interrupted operation. It should only be necessary when Mercurial
3859 suggests it.
3859 suggests it.
3860
3860
3861 Returns 0 if successful, 1 if nothing to recover or verify fails.
3861 Returns 0 if successful, 1 if nothing to recover or verify fails.
3862 """
3862 """
3863 if repo.recover():
3863 if repo.recover():
3864 return hg.verify(repo)
3864 return hg.verify(repo)
3865 return 1
3865 return 1
3866
3866
3867 @command('^remove|rm',
3867 @command('^remove|rm',
3868 [('A', 'after', None, _('record delete for missing files')),
3868 [('A', 'after', None, _('record delete for missing files')),
3869 ('f', 'force', None,
3869 ('f', 'force', None,
3870 _('remove (and delete) file even if added or modified')),
3870 _('remove (and delete) file even if added or modified')),
3871 ] + walkopts,
3871 ] + walkopts,
3872 _('[OPTION]... FILE...'))
3872 _('[OPTION]... FILE...'))
3873 def remove(ui, repo, *pats, **opts):
3873 def remove(ui, repo, *pats, **opts):
3874 """remove the specified files on the next commit
3874 """remove the specified files on the next commit
3875
3875
3876 Schedule the indicated files for removal from the repository.
3876 Schedule the indicated files for removal from the repository.
3877
3877
3878 This only removes files from the current branch, not from the
3878 This only removes files from the current branch, not from the
3879 entire project history. -A/--after can be used to remove only
3879 entire project history. -A/--after can be used to remove only
3880 files that have already been deleted, -f/--force can be used to
3880 files that have already been deleted, -f/--force can be used to
3881 force deletion, and -Af can be used to remove files from the next
3881 force deletion, and -Af can be used to remove files from the next
3882 revision without deleting them from the working directory.
3882 revision without deleting them from the working directory.
3883
3883
3884 The following table details the behavior of remove for different
3884 The following table details the behavior of remove for different
3885 file states (columns) and option combinations (rows). The file
3885 file states (columns) and option combinations (rows). The file
3886 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3886 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3887 reported by :hg:`status`). The actions are Warn, Remove (from
3887 reported by :hg:`status`). The actions are Warn, Remove (from
3888 branch) and Delete (from disk)::
3888 branch) and Delete (from disk)::
3889
3889
3890 A C M !
3890 A C M !
3891 none W RD W R
3891 none W RD W R
3892 -f R RD RD R
3892 -f R RD RD R
3893 -A W W W R
3893 -A W W W R
3894 -Af R R R R
3894 -Af R R R R
3895
3895
3896 Note that remove never deletes files in Added [A] state from the
3896 Note that remove never deletes files in Added [A] state from the
3897 working directory, not even if option --force is specified.
3897 working directory, not even if option --force is specified.
3898
3898
3899 This command schedules the files to be removed at the next commit.
3899 This command schedules the files to be removed at the next commit.
3900 To undo a remove before that, see :hg:`revert`.
3900 To undo a remove before that, see :hg:`revert`.
3901
3901
3902 Returns 0 on success, 1 if any warnings encountered.
3902 Returns 0 on success, 1 if any warnings encountered.
3903 """
3903 """
3904
3904
3905 ret = 0
3905 ret = 0
3906 after, force = opts.get('after'), opts.get('force')
3906 after, force = opts.get('after'), opts.get('force')
3907 if not pats and not after:
3907 if not pats and not after:
3908 raise util.Abort(_('no files specified'))
3908 raise util.Abort(_('no files specified'))
3909
3909
3910 m = scmutil.match(repo, pats, opts)
3910 m = scmutil.match(repo, pats, opts)
3911 s = repo.status(match=m, clean=True)
3911 s = repo.status(match=m, clean=True)
3912 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3912 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3913
3913
3914 for f in m.files():
3914 for f in m.files():
3915 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3915 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3916 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3916 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3917 ret = 1
3917 ret = 1
3918
3918
3919 if force:
3919 if force:
3920 list = modified + deleted + clean + added
3920 list = modified + deleted + clean + added
3921 elif after:
3921 elif after:
3922 list = deleted
3922 list = deleted
3923 for f in modified + added + clean:
3923 for f in modified + added + clean:
3924 ui.warn(_('not removing %s: file still exists (use -f'
3924 ui.warn(_('not removing %s: file still exists (use -f'
3925 ' to force removal)\n') % m.rel(f))
3925 ' to force removal)\n') % m.rel(f))
3926 ret = 1
3926 ret = 1
3927 else:
3927 else:
3928 list = deleted + clean
3928 list = deleted + clean
3929 for f in modified:
3929 for f in modified:
3930 ui.warn(_('not removing %s: file is modified (use -f'
3930 ui.warn(_('not removing %s: file is modified (use -f'
3931 ' to force removal)\n') % m.rel(f))
3931 ' to force removal)\n') % m.rel(f))
3932 ret = 1
3932 ret = 1
3933 for f in added:
3933 for f in added:
3934 ui.warn(_('not removing %s: file has been marked for add (use -f'
3934 ui.warn(_('not removing %s: file has been marked for add (use -f'
3935 ' to force removal)\n') % m.rel(f))
3935 ' to force removal)\n') % m.rel(f))
3936 ret = 1
3936 ret = 1
3937
3937
3938 for f in sorted(list):
3938 for f in sorted(list):
3939 if ui.verbose or not m.exact(f):
3939 if ui.verbose or not m.exact(f):
3940 ui.status(_('removing %s\n') % m.rel(f))
3940 ui.status(_('removing %s\n') % m.rel(f))
3941
3941
3942 wlock = repo.wlock()
3942 wlock = repo.wlock()
3943 try:
3943 try:
3944 if not after:
3944 if not after:
3945 for f in list:
3945 for f in list:
3946 if f in added:
3946 if f in added:
3947 continue # we never unlink added files on remove
3947 continue # we never unlink added files on remove
3948 try:
3948 try:
3949 util.unlinkpath(repo.wjoin(f))
3949 util.unlinkpath(repo.wjoin(f))
3950 except OSError, inst:
3950 except OSError, inst:
3951 if inst.errno != errno.ENOENT:
3951 if inst.errno != errno.ENOENT:
3952 raise
3952 raise
3953 repo[None].forget(list)
3953 repo[None].forget(list)
3954 finally:
3954 finally:
3955 wlock.release()
3955 wlock.release()
3956
3956
3957 return ret
3957 return ret
3958
3958
3959 @command('rename|move|mv',
3959 @command('rename|move|mv',
3960 [('A', 'after', None, _('record a rename that has already occurred')),
3960 [('A', 'after', None, _('record a rename that has already occurred')),
3961 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3961 ('f', 'force', None, _('forcibly copy over an existing managed file')),
3962 ] + walkopts + dryrunopts,
3962 ] + walkopts + dryrunopts,
3963 _('[OPTION]... SOURCE... DEST'))
3963 _('[OPTION]... SOURCE... DEST'))
3964 def rename(ui, repo, *pats, **opts):
3964 def rename(ui, repo, *pats, **opts):
3965 """rename files; equivalent of copy + remove
3965 """rename files; equivalent of copy + remove
3966
3966
3967 Mark dest as copies of sources; mark sources for deletion. If dest
3967 Mark dest as copies of sources; mark sources for deletion. If dest
3968 is a directory, copies are put in that directory. If dest is a
3968 is a directory, copies are put in that directory. If dest is a
3969 file, there can only be one source.
3969 file, there can only be one source.
3970
3970
3971 By default, this command copies the contents of files as they
3971 By default, this command copies the contents of files as they
3972 exist in the working directory. If invoked with -A/--after, the
3972 exist in the working directory. If invoked with -A/--after, the
3973 operation is recorded, but no copying is performed.
3973 operation is recorded, but no copying is performed.
3974
3974
3975 This command takes effect at the next commit. To undo a rename
3975 This command takes effect at the next commit. To undo a rename
3976 before that, see :hg:`revert`.
3976 before that, see :hg:`revert`.
3977
3977
3978 Returns 0 on success, 1 if errors are encountered.
3978 Returns 0 on success, 1 if errors are encountered.
3979 """
3979 """
3980 wlock = repo.wlock(False)
3980 wlock = repo.wlock(False)
3981 try:
3981 try:
3982 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3982 return cmdutil.copy(ui, repo, pats, opts, rename=True)
3983 finally:
3983 finally:
3984 wlock.release()
3984 wlock.release()
3985
3985
3986 @command('resolve',
3986 @command('resolve',
3987 [('a', 'all', None, _('select all unresolved files')),
3987 [('a', 'all', None, _('select all unresolved files')),
3988 ('l', 'list', None, _('list state of files needing merge')),
3988 ('l', 'list', None, _('list state of files needing merge')),
3989 ('m', 'mark', None, _('mark files as resolved')),
3989 ('m', 'mark', None, _('mark files as resolved')),
3990 ('u', 'unmark', None, _('mark files as unresolved')),
3990 ('u', 'unmark', None, _('mark files as unresolved')),
3991 ('t', 'tool', '', _('specify merge tool')),
3991 ('t', 'tool', '', _('specify merge tool')),
3992 ('n', 'no-status', None, _('hide status prefix'))]
3992 ('n', 'no-status', None, _('hide status prefix'))]
3993 + walkopts,
3993 + walkopts,
3994 _('[OPTION]... [FILE]...'))
3994 _('[OPTION]... [FILE]...'))
3995 def resolve(ui, repo, *pats, **opts):
3995 def resolve(ui, repo, *pats, **opts):
3996 """redo merges or set/view the merge status of files
3996 """redo merges or set/view the merge status of files
3997
3997
3998 Merges with unresolved conflicts are often the result of
3998 Merges with unresolved conflicts are often the result of
3999 non-interactive merging using the ``internal:merge`` configuration
3999 non-interactive merging using the ``internal:merge`` configuration
4000 setting, or a command-line merge tool like ``diff3``. The resolve
4000 setting, or a command-line merge tool like ``diff3``. The resolve
4001 command is used to manage the files involved in a merge, after
4001 command is used to manage the files involved in a merge, after
4002 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4002 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4003 working directory must have two parents).
4003 working directory must have two parents).
4004
4004
4005 The resolve command can be used in the following ways:
4005 The resolve command can be used in the following ways:
4006
4006
4007 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4007 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4008 files, discarding any previous merge attempts. Re-merging is not
4008 files, discarding any previous merge attempts. Re-merging is not
4009 performed for files already marked as resolved. Use ``--all/-a``
4009 performed for files already marked as resolved. Use ``--all/-a``
4010 to selects all unresolved files. ``--tool`` can be used to specify
4010 to selects all unresolved files. ``--tool`` can be used to specify
4011 the merge tool used for the given files. It overrides the HGMERGE
4011 the merge tool used for the given files. It overrides the HGMERGE
4012 environment variable and your configuration files.
4012 environment variable and your configuration files.
4013
4013
4014 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4014 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4015 (e.g. after having manually fixed-up the files). The default is
4015 (e.g. after having manually fixed-up the files). The default is
4016 to mark all unresolved files.
4016 to mark all unresolved files.
4017
4017
4018 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4018 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4019 default is to mark all resolved files.
4019 default is to mark all resolved files.
4020
4020
4021 - :hg:`resolve -l`: list files which had or still have conflicts.
4021 - :hg:`resolve -l`: list files which had or still have conflicts.
4022 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4022 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4023
4023
4024 Note that Mercurial will not let you commit files with unresolved
4024 Note that Mercurial will not let you commit files with unresolved
4025 merge conflicts. You must use :hg:`resolve -m ...` before you can
4025 merge conflicts. You must use :hg:`resolve -m ...` before you can
4026 commit after a conflicting merge.
4026 commit after a conflicting merge.
4027
4027
4028 Returns 0 on success, 1 if any files fail a resolve attempt.
4028 Returns 0 on success, 1 if any files fail a resolve attempt.
4029 """
4029 """
4030
4030
4031 all, mark, unmark, show, nostatus = \
4031 all, mark, unmark, show, nostatus = \
4032 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4032 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4033
4033
4034 if (show and (mark or unmark)) or (mark and unmark):
4034 if (show and (mark or unmark)) or (mark and unmark):
4035 raise util.Abort(_("too many options specified"))
4035 raise util.Abort(_("too many options specified"))
4036 if pats and all:
4036 if pats and all:
4037 raise util.Abort(_("can't specify --all and patterns"))
4037 raise util.Abort(_("can't specify --all and patterns"))
4038 if not (all or pats or show or mark or unmark):
4038 if not (all or pats or show or mark or unmark):
4039 raise util.Abort(_('no files or directories specified; '
4039 raise util.Abort(_('no files or directories specified; '
4040 'use --all to remerge all files'))
4040 'use --all to remerge all files'))
4041
4041
4042 ms = mergemod.mergestate(repo)
4042 ms = mergemod.mergestate(repo)
4043 m = scmutil.match(repo, pats, opts)
4043 m = scmutil.match(repo, pats, opts)
4044 ret = 0
4044 ret = 0
4045
4045
4046 for f in ms:
4046 for f in ms:
4047 if m(f):
4047 if m(f):
4048 if show:
4048 if show:
4049 if nostatus:
4049 if nostatus:
4050 ui.write("%s\n" % f)
4050 ui.write("%s\n" % f)
4051 else:
4051 else:
4052 ui.write("%s %s\n" % (ms[f].upper(), f),
4052 ui.write("%s %s\n" % (ms[f].upper(), f),
4053 label='resolve.' +
4053 label='resolve.' +
4054 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4054 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4055 elif mark:
4055 elif mark:
4056 ms.mark(f, "r")
4056 ms.mark(f, "r")
4057 elif unmark:
4057 elif unmark:
4058 ms.mark(f, "u")
4058 ms.mark(f, "u")
4059 else:
4059 else:
4060 wctx = repo[None]
4060 wctx = repo[None]
4061 mctx = wctx.parents()[-1]
4061 mctx = wctx.parents()[-1]
4062
4062
4063 # backup pre-resolve (merge uses .orig for its own purposes)
4063 # backup pre-resolve (merge uses .orig for its own purposes)
4064 a = repo.wjoin(f)
4064 a = repo.wjoin(f)
4065 util.copyfile(a, a + ".resolve")
4065 util.copyfile(a, a + ".resolve")
4066
4066
4067 try:
4067 try:
4068 # resolve file
4068 # resolve file
4069 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4069 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4070 if ms.resolve(f, wctx, mctx):
4070 if ms.resolve(f, wctx, mctx):
4071 ret = 1
4071 ret = 1
4072 finally:
4072 finally:
4073 ui.setconfig('ui', 'forcemerge', '')
4073 ui.setconfig('ui', 'forcemerge', '')
4074
4074
4075 # replace filemerge's .orig file with our resolve file
4075 # replace filemerge's .orig file with our resolve file
4076 util.rename(a + ".resolve", a + ".orig")
4076 util.rename(a + ".resolve", a + ".orig")
4077
4077
4078 ms.commit()
4078 ms.commit()
4079 return ret
4079 return ret
4080
4080
4081 @command('revert',
4081 @command('revert',
4082 [('a', 'all', None, _('revert all changes when no arguments given')),
4082 [('a', 'all', None, _('revert all changes when no arguments given')),
4083 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4083 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4084 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4084 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4085 ('', 'no-backup', None, _('do not save backup copies of files')),
4085 ('', 'no-backup', None, _('do not save backup copies of files')),
4086 ] + walkopts + dryrunopts,
4086 ] + walkopts + dryrunopts,
4087 _('[OPTION]... [-r REV] [NAME]...'))
4087 _('[OPTION]... [-r REV] [NAME]...'))
4088 def revert(ui, repo, *pats, **opts):
4088 def revert(ui, repo, *pats, **opts):
4089 """restore individual files or directories to an earlier state
4089 """restore files to their checkout state
4090
4090
4091 .. note::
4091 .. note::
4092 This command is most likely not what you are looking for.
4092 This command is most likely not what you are looking for.
4093 Revert will partially overwrite content in the working
4093 Revert will partially overwrite content in the working
4094 directory without changing the working directory parents. Use
4094 directory without changing the working directory parents. Use
4095 :hg:`update -r rev` to check out earlier revisions, or
4095 :hg:`update -r rev` to check out earlier revisions, or
4096 :hg:`update --clean .` to undo a merge which has added another
4096 :hg:`update --clean .` to undo a merge which has added another
4097 parent.
4097 parent.
4098
4098
4099 With no revision specified, revert the named files or directories
4099 With no revision specified, revert the named files or directories
4100 to the contents they had in the parent of the working directory.
4100 to the contents they had in the parent of the working directory.
4101 This restores the contents of the affected files to an unmodified
4101 This restores the contents of the affected files to an unmodified
4102 state and unschedules adds, removes, copies, and renames. If the
4102 state and unschedules adds, removes, copies, and renames. If the
4103 working directory has two parents, you must explicitly specify a
4103 working directory has two parents, you must explicitly specify a
4104 revision.
4104 revision.
4105
4105
4106 Using the -r/--rev option, revert the given files or directories
4106 Using the -r/--rev option, revert the given files or directories
4107 to their contents as of a specific revision. This can be helpful
4107 to their contents as of a specific revision. This can be helpful
4108 to "roll back" some or all of an earlier change. See :hg:`help
4108 to "roll back" some or all of an earlier change. See :hg:`help
4109 dates` for a list of formats valid for -d/--date.
4109 dates` for a list of formats valid for -d/--date.
4110
4110
4111 Revert modifies the working directory. It does not commit any
4111 Revert modifies the working directory. It does not commit any
4112 changes, or change the parent of the working directory. If you
4112 changes, or change the parent of the working directory. If you
4113 revert to a revision other than the parent of the working
4113 revert to a revision other than the parent of the working
4114 directory, the reverted files will thus appear modified
4114 directory, the reverted files will thus appear modified
4115 afterwards.
4115 afterwards.
4116
4116
4117 If a file has been deleted, it is restored. Files scheduled for
4117 If a file has been deleted, it is restored. Files scheduled for
4118 addition are just unscheduled and left as they are. If the
4118 addition are just unscheduled and left as they are. If the
4119 executable mode of a file was changed, it is reset.
4119 executable mode of a file was changed, it is reset.
4120
4120
4121 If names are given, all files matching the names are reverted.
4121 If names are given, all files matching the names are reverted.
4122 If no arguments are given, no files are reverted.
4122 If no arguments are given, no files are reverted.
4123
4123
4124 Modified files are saved with a .orig suffix before reverting.
4124 Modified files are saved with a .orig suffix before reverting.
4125 To disable these backups, use --no-backup.
4125 To disable these backups, use --no-backup.
4126
4126
4127 Returns 0 on success.
4127 Returns 0 on success.
4128 """
4128 """
4129
4129
4130 if opts.get("date"):
4130 if opts.get("date"):
4131 if opts.get("rev"):
4131 if opts.get("rev"):
4132 raise util.Abort(_("you can't specify a revision and a date"))
4132 raise util.Abort(_("you can't specify a revision and a date"))
4133 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4133 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4134
4134
4135 parent, p2 = repo.dirstate.parents()
4135 parent, p2 = repo.dirstate.parents()
4136 if not opts.get('rev') and p2 != nullid:
4136 if not opts.get('rev') and p2 != nullid:
4137 raise util.Abort(_('uncommitted merge - '
4137 raise util.Abort(_('uncommitted merge - '
4138 'use "hg update", see "hg help revert"'))
4138 'use "hg update", see "hg help revert"'))
4139
4139
4140 if not pats and not opts.get('all'):
4140 if not pats and not opts.get('all'):
4141 raise util.Abort(_('no files or directories specified; '
4141 raise util.Abort(_('no files or directories specified; '
4142 'use --all to revert the whole repo'))
4142 'use --all to revert the whole repo'))
4143
4143
4144 ctx = scmutil.revsingle(repo, opts.get('rev'))
4144 ctx = scmutil.revsingle(repo, opts.get('rev'))
4145 node = ctx.node()
4145 node = ctx.node()
4146 mf = ctx.manifest()
4146 mf = ctx.manifest()
4147 if node == parent:
4147 if node == parent:
4148 pmf = mf
4148 pmf = mf
4149 else:
4149 else:
4150 pmf = None
4150 pmf = None
4151
4151
4152 # need all matching names in dirstate and manifest of target rev,
4152 # need all matching names in dirstate and manifest of target rev,
4153 # so have to walk both. do not print errors if files exist in one
4153 # so have to walk both. do not print errors if files exist in one
4154 # but not other.
4154 # but not other.
4155
4155
4156 names = {}
4156 names = {}
4157
4157
4158 wlock = repo.wlock()
4158 wlock = repo.wlock()
4159 try:
4159 try:
4160 # walk dirstate.
4160 # walk dirstate.
4161
4161
4162 m = scmutil.match(repo, pats, opts)
4162 m = scmutil.match(repo, pats, opts)
4163 m.bad = lambda x, y: False
4163 m.bad = lambda x, y: False
4164 for abs in repo.walk(m):
4164 for abs in repo.walk(m):
4165 names[abs] = m.rel(abs), m.exact(abs)
4165 names[abs] = m.rel(abs), m.exact(abs)
4166
4166
4167 # walk target manifest.
4167 # walk target manifest.
4168
4168
4169 def badfn(path, msg):
4169 def badfn(path, msg):
4170 if path in names:
4170 if path in names:
4171 return
4171 return
4172 path_ = path + '/'
4172 path_ = path + '/'
4173 for f in names:
4173 for f in names:
4174 if f.startswith(path_):
4174 if f.startswith(path_):
4175 return
4175 return
4176 ui.warn("%s: %s\n" % (m.rel(path), msg))
4176 ui.warn("%s: %s\n" % (m.rel(path), msg))
4177
4177
4178 m = scmutil.match(repo, pats, opts)
4178 m = scmutil.match(repo, pats, opts)
4179 m.bad = badfn
4179 m.bad = badfn
4180 for abs in repo[node].walk(m):
4180 for abs in repo[node].walk(m):
4181 if abs not in names:
4181 if abs not in names:
4182 names[abs] = m.rel(abs), m.exact(abs)
4182 names[abs] = m.rel(abs), m.exact(abs)
4183
4183
4184 m = scmutil.matchfiles(repo, names)
4184 m = scmutil.matchfiles(repo, names)
4185 changes = repo.status(match=m)[:4]
4185 changes = repo.status(match=m)[:4]
4186 modified, added, removed, deleted = map(set, changes)
4186 modified, added, removed, deleted = map(set, changes)
4187
4187
4188 # if f is a rename, also revert the source
4188 # if f is a rename, also revert the source
4189 cwd = repo.getcwd()
4189 cwd = repo.getcwd()
4190 for f in added:
4190 for f in added:
4191 src = repo.dirstate.copied(f)
4191 src = repo.dirstate.copied(f)
4192 if src and src not in names and repo.dirstate[src] == 'r':
4192 if src and src not in names and repo.dirstate[src] == 'r':
4193 removed.add(src)
4193 removed.add(src)
4194 names[src] = (repo.pathto(src, cwd), True)
4194 names[src] = (repo.pathto(src, cwd), True)
4195
4195
4196 def removeforget(abs):
4196 def removeforget(abs):
4197 if repo.dirstate[abs] == 'a':
4197 if repo.dirstate[abs] == 'a':
4198 return _('forgetting %s\n')
4198 return _('forgetting %s\n')
4199 return _('removing %s\n')
4199 return _('removing %s\n')
4200
4200
4201 revert = ([], _('reverting %s\n'))
4201 revert = ([], _('reverting %s\n'))
4202 add = ([], _('adding %s\n'))
4202 add = ([], _('adding %s\n'))
4203 remove = ([], removeforget)
4203 remove = ([], removeforget)
4204 undelete = ([], _('undeleting %s\n'))
4204 undelete = ([], _('undeleting %s\n'))
4205
4205
4206 disptable = (
4206 disptable = (
4207 # dispatch table:
4207 # dispatch table:
4208 # file state
4208 # file state
4209 # action if in target manifest
4209 # action if in target manifest
4210 # action if not in target manifest
4210 # action if not in target manifest
4211 # make backup if in target manifest
4211 # make backup if in target manifest
4212 # make backup if not in target manifest
4212 # make backup if not in target manifest
4213 (modified, revert, remove, True, True),
4213 (modified, revert, remove, True, True),
4214 (added, revert, remove, True, False),
4214 (added, revert, remove, True, False),
4215 (removed, undelete, None, False, False),
4215 (removed, undelete, None, False, False),
4216 (deleted, revert, remove, False, False),
4216 (deleted, revert, remove, False, False),
4217 )
4217 )
4218
4218
4219 for abs, (rel, exact) in sorted(names.items()):
4219 for abs, (rel, exact) in sorted(names.items()):
4220 mfentry = mf.get(abs)
4220 mfentry = mf.get(abs)
4221 target = repo.wjoin(abs)
4221 target = repo.wjoin(abs)
4222 def handle(xlist, dobackup):
4222 def handle(xlist, dobackup):
4223 xlist[0].append(abs)
4223 xlist[0].append(abs)
4224 if (dobackup and not opts.get('no_backup') and
4224 if (dobackup and not opts.get('no_backup') and
4225 os.path.lexists(target)):
4225 os.path.lexists(target)):
4226 bakname = "%s.orig" % rel
4226 bakname = "%s.orig" % rel
4227 ui.note(_('saving current version of %s as %s\n') %
4227 ui.note(_('saving current version of %s as %s\n') %
4228 (rel, bakname))
4228 (rel, bakname))
4229 if not opts.get('dry_run'):
4229 if not opts.get('dry_run'):
4230 util.rename(target, bakname)
4230 util.rename(target, bakname)
4231 if ui.verbose or not exact:
4231 if ui.verbose or not exact:
4232 msg = xlist[1]
4232 msg = xlist[1]
4233 if not isinstance(msg, basestring):
4233 if not isinstance(msg, basestring):
4234 msg = msg(abs)
4234 msg = msg(abs)
4235 ui.status(msg % rel)
4235 ui.status(msg % rel)
4236 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4236 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4237 if abs not in table:
4237 if abs not in table:
4238 continue
4238 continue
4239 # file has changed in dirstate
4239 # file has changed in dirstate
4240 if mfentry:
4240 if mfentry:
4241 handle(hitlist, backuphit)
4241 handle(hitlist, backuphit)
4242 elif misslist is not None:
4242 elif misslist is not None:
4243 handle(misslist, backupmiss)
4243 handle(misslist, backupmiss)
4244 break
4244 break
4245 else:
4245 else:
4246 if abs not in repo.dirstate:
4246 if abs not in repo.dirstate:
4247 if mfentry:
4247 if mfentry:
4248 handle(add, True)
4248 handle(add, True)
4249 elif exact:
4249 elif exact:
4250 ui.warn(_('file not managed: %s\n') % rel)
4250 ui.warn(_('file not managed: %s\n') % rel)
4251 continue
4251 continue
4252 # file has not changed in dirstate
4252 # file has not changed in dirstate
4253 if node == parent:
4253 if node == parent:
4254 if exact:
4254 if exact:
4255 ui.warn(_('no changes needed to %s\n') % rel)
4255 ui.warn(_('no changes needed to %s\n') % rel)
4256 continue
4256 continue
4257 if pmf is None:
4257 if pmf is None:
4258 # only need parent manifest in this unlikely case,
4258 # only need parent manifest in this unlikely case,
4259 # so do not read by default
4259 # so do not read by default
4260 pmf = repo[parent].manifest()
4260 pmf = repo[parent].manifest()
4261 if abs in pmf:
4261 if abs in pmf:
4262 if mfentry:
4262 if mfentry:
4263 # if version of file is same in parent and target
4263 # if version of file is same in parent and target
4264 # manifests, do nothing
4264 # manifests, do nothing
4265 if (pmf[abs] != mfentry or
4265 if (pmf[abs] != mfentry or
4266 pmf.flags(abs) != mf.flags(abs)):
4266 pmf.flags(abs) != mf.flags(abs)):
4267 handle(revert, False)
4267 handle(revert, False)
4268 else:
4268 else:
4269 handle(remove, False)
4269 handle(remove, False)
4270
4270
4271 if not opts.get('dry_run'):
4271 if not opts.get('dry_run'):
4272 def checkout(f):
4272 def checkout(f):
4273 fc = ctx[f]
4273 fc = ctx[f]
4274 repo.wwrite(f, fc.data(), fc.flags())
4274 repo.wwrite(f, fc.data(), fc.flags())
4275
4275
4276 audit_path = scmutil.pathauditor(repo.root)
4276 audit_path = scmutil.pathauditor(repo.root)
4277 for f in remove[0]:
4277 for f in remove[0]:
4278 if repo.dirstate[f] == 'a':
4278 if repo.dirstate[f] == 'a':
4279 repo.dirstate.drop(f)
4279 repo.dirstate.drop(f)
4280 continue
4280 continue
4281 audit_path(f)
4281 audit_path(f)
4282 try:
4282 try:
4283 util.unlinkpath(repo.wjoin(f))
4283 util.unlinkpath(repo.wjoin(f))
4284 except OSError:
4284 except OSError:
4285 pass
4285 pass
4286 repo.dirstate.remove(f)
4286 repo.dirstate.remove(f)
4287
4287
4288 normal = None
4288 normal = None
4289 if node == parent:
4289 if node == parent:
4290 # We're reverting to our parent. If possible, we'd like status
4290 # We're reverting to our parent. If possible, we'd like status
4291 # to report the file as clean. We have to use normallookup for
4291 # to report the file as clean. We have to use normallookup for
4292 # merges to avoid losing information about merged/dirty files.
4292 # merges to avoid losing information about merged/dirty files.
4293 if p2 != nullid:
4293 if p2 != nullid:
4294 normal = repo.dirstate.normallookup
4294 normal = repo.dirstate.normallookup
4295 else:
4295 else:
4296 normal = repo.dirstate.normal
4296 normal = repo.dirstate.normal
4297 for f in revert[0]:
4297 for f in revert[0]:
4298 checkout(f)
4298 checkout(f)
4299 if normal:
4299 if normal:
4300 normal(f)
4300 normal(f)
4301
4301
4302 for f in add[0]:
4302 for f in add[0]:
4303 checkout(f)
4303 checkout(f)
4304 repo.dirstate.add(f)
4304 repo.dirstate.add(f)
4305
4305
4306 normal = repo.dirstate.normallookup
4306 normal = repo.dirstate.normallookup
4307 if node == parent and p2 == nullid:
4307 if node == parent and p2 == nullid:
4308 normal = repo.dirstate.normal
4308 normal = repo.dirstate.normal
4309 for f in undelete[0]:
4309 for f in undelete[0]:
4310 checkout(f)
4310 checkout(f)
4311 normal(f)
4311 normal(f)
4312
4312
4313 finally:
4313 finally:
4314 wlock.release()
4314 wlock.release()
4315
4315
4316 @command('rollback', dryrunopts)
4316 @command('rollback', dryrunopts)
4317 def rollback(ui, repo, **opts):
4317 def rollback(ui, repo, **opts):
4318 """roll back the last transaction (dangerous)
4318 """roll back the last transaction (dangerous)
4319
4319
4320 This command should be used with care. There is only one level of
4320 This command should be used with care. There is only one level of
4321 rollback, and there is no way to undo a rollback. It will also
4321 rollback, and there is no way to undo a rollback. It will also
4322 restore the dirstate at the time of the last transaction, losing
4322 restore the dirstate at the time of the last transaction, losing
4323 any dirstate changes since that time. This command does not alter
4323 any dirstate changes since that time. This command does not alter
4324 the working directory.
4324 the working directory.
4325
4325
4326 Transactions are used to encapsulate the effects of all commands
4326 Transactions are used to encapsulate the effects of all commands
4327 that create new changesets or propagate existing changesets into a
4327 that create new changesets or propagate existing changesets into a
4328 repository. For example, the following commands are transactional,
4328 repository. For example, the following commands are transactional,
4329 and their effects can be rolled back:
4329 and their effects can be rolled back:
4330
4330
4331 - commit
4331 - commit
4332 - import
4332 - import
4333 - pull
4333 - pull
4334 - push (with this repository as the destination)
4334 - push (with this repository as the destination)
4335 - unbundle
4335 - unbundle
4336
4336
4337 This command is not intended for use on public repositories. Once
4337 This command is not intended for use on public repositories. Once
4338 changes are visible for pull by other users, rolling a transaction
4338 changes are visible for pull by other users, rolling a transaction
4339 back locally is ineffective (someone else may already have pulled
4339 back locally is ineffective (someone else may already have pulled
4340 the changes). Furthermore, a race is possible with readers of the
4340 the changes). Furthermore, a race is possible with readers of the
4341 repository; for example an in-progress pull from the repository
4341 repository; for example an in-progress pull from the repository
4342 may fail if a rollback is performed.
4342 may fail if a rollback is performed.
4343
4343
4344 Returns 0 on success, 1 if no rollback data is available.
4344 Returns 0 on success, 1 if no rollback data is available.
4345 """
4345 """
4346 return repo.rollback(opts.get('dry_run'))
4346 return repo.rollback(opts.get('dry_run'))
4347
4347
4348 @command('root', [])
4348 @command('root', [])
4349 def root(ui, repo):
4349 def root(ui, repo):
4350 """print the root (top) of the current working directory
4350 """print the root (top) of the current working directory
4351
4351
4352 Print the root directory of the current repository.
4352 Print the root directory of the current repository.
4353
4353
4354 Returns 0 on success.
4354 Returns 0 on success.
4355 """
4355 """
4356 ui.write(repo.root + "\n")
4356 ui.write(repo.root + "\n")
4357
4357
4358 @command('^serve',
4358 @command('^serve',
4359 [('A', 'accesslog', '', _('name of access log file to write to'),
4359 [('A', 'accesslog', '', _('name of access log file to write to'),
4360 _('FILE')),
4360 _('FILE')),
4361 ('d', 'daemon', None, _('run server in background')),
4361 ('d', 'daemon', None, _('run server in background')),
4362 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4362 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4363 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4363 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4364 # use string type, then we can check if something was passed
4364 # use string type, then we can check if something was passed
4365 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4365 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4366 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4366 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4367 _('ADDR')),
4367 _('ADDR')),
4368 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4368 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4369 _('PREFIX')),
4369 _('PREFIX')),
4370 ('n', 'name', '',
4370 ('n', 'name', '',
4371 _('name to show in web pages (default: working directory)'), _('NAME')),
4371 _('name to show in web pages (default: working directory)'), _('NAME')),
4372 ('', 'web-conf', '',
4372 ('', 'web-conf', '',
4373 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4373 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4374 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4374 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4375 _('FILE')),
4375 _('FILE')),
4376 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4376 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4377 ('', 'stdio', None, _('for remote clients')),
4377 ('', 'stdio', None, _('for remote clients')),
4378 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4378 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4379 ('', 'style', '', _('template style to use'), _('STYLE')),
4379 ('', 'style', '', _('template style to use'), _('STYLE')),
4380 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4380 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4381 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4381 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4382 _('[OPTION]...'))
4382 _('[OPTION]...'))
4383 def serve(ui, repo, **opts):
4383 def serve(ui, repo, **opts):
4384 """start stand-alone webserver
4384 """start stand-alone webserver
4385
4385
4386 Start a local HTTP repository browser and pull server. You can use
4386 Start a local HTTP repository browser and pull server. You can use
4387 this for ad-hoc sharing and browsing of repositories. It is
4387 this for ad-hoc sharing and browsing of repositories. It is
4388 recommended to use a real web server to serve a repository for
4388 recommended to use a real web server to serve a repository for
4389 longer periods of time.
4389 longer periods of time.
4390
4390
4391 Please note that the server does not implement access control.
4391 Please note that the server does not implement access control.
4392 This means that, by default, anybody can read from the server and
4392 This means that, by default, anybody can read from the server and
4393 nobody can write to it by default. Set the ``web.allow_push``
4393 nobody can write to it by default. Set the ``web.allow_push``
4394 option to ``*`` to allow everybody to push to the server. You
4394 option to ``*`` to allow everybody to push to the server. You
4395 should use a real web server if you need to authenticate users.
4395 should use a real web server if you need to authenticate users.
4396
4396
4397 By default, the server logs accesses to stdout and errors to
4397 By default, the server logs accesses to stdout and errors to
4398 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4398 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4399 files.
4399 files.
4400
4400
4401 To have the server choose a free port number to listen on, specify
4401 To have the server choose a free port number to listen on, specify
4402 a port number of 0; in this case, the server will print the port
4402 a port number of 0; in this case, the server will print the port
4403 number it uses.
4403 number it uses.
4404
4404
4405 Returns 0 on success.
4405 Returns 0 on success.
4406 """
4406 """
4407
4407
4408 if opts["stdio"]:
4408 if opts["stdio"]:
4409 if repo is None:
4409 if repo is None:
4410 raise error.RepoError(_("There is no Mercurial repository here"
4410 raise error.RepoError(_("There is no Mercurial repository here"
4411 " (.hg not found)"))
4411 " (.hg not found)"))
4412 s = sshserver.sshserver(ui, repo)
4412 s = sshserver.sshserver(ui, repo)
4413 s.serve_forever()
4413 s.serve_forever()
4414
4414
4415 # this way we can check if something was given in the command-line
4415 # this way we can check if something was given in the command-line
4416 if opts.get('port'):
4416 if opts.get('port'):
4417 opts['port'] = util.getport(opts.get('port'))
4417 opts['port'] = util.getport(opts.get('port'))
4418
4418
4419 baseui = repo and repo.baseui or ui
4419 baseui = repo and repo.baseui or ui
4420 optlist = ("name templates style address port prefix ipv6"
4420 optlist = ("name templates style address port prefix ipv6"
4421 " accesslog errorlog certificate encoding")
4421 " accesslog errorlog certificate encoding")
4422 for o in optlist.split():
4422 for o in optlist.split():
4423 val = opts.get(o, '')
4423 val = opts.get(o, '')
4424 if val in (None, ''): # should check against default options instead
4424 if val in (None, ''): # should check against default options instead
4425 continue
4425 continue
4426 baseui.setconfig("web", o, val)
4426 baseui.setconfig("web", o, val)
4427 if repo and repo.ui != baseui:
4427 if repo and repo.ui != baseui:
4428 repo.ui.setconfig("web", o, val)
4428 repo.ui.setconfig("web", o, val)
4429
4429
4430 o = opts.get('web_conf') or opts.get('webdir_conf')
4430 o = opts.get('web_conf') or opts.get('webdir_conf')
4431 if not o:
4431 if not o:
4432 if not repo:
4432 if not repo:
4433 raise error.RepoError(_("There is no Mercurial repository"
4433 raise error.RepoError(_("There is no Mercurial repository"
4434 " here (.hg not found)"))
4434 " here (.hg not found)"))
4435 o = repo.root
4435 o = repo.root
4436
4436
4437 app = hgweb.hgweb(o, baseui=ui)
4437 app = hgweb.hgweb(o, baseui=ui)
4438
4438
4439 class service(object):
4439 class service(object):
4440 def init(self):
4440 def init(self):
4441 util.setsignalhandler()
4441 util.setsignalhandler()
4442 self.httpd = hgweb.server.create_server(ui, app)
4442 self.httpd = hgweb.server.create_server(ui, app)
4443
4443
4444 if opts['port'] and not ui.verbose:
4444 if opts['port'] and not ui.verbose:
4445 return
4445 return
4446
4446
4447 if self.httpd.prefix:
4447 if self.httpd.prefix:
4448 prefix = self.httpd.prefix.strip('/') + '/'
4448 prefix = self.httpd.prefix.strip('/') + '/'
4449 else:
4449 else:
4450 prefix = ''
4450 prefix = ''
4451
4451
4452 port = ':%d' % self.httpd.port
4452 port = ':%d' % self.httpd.port
4453 if port == ':80':
4453 if port == ':80':
4454 port = ''
4454 port = ''
4455
4455
4456 bindaddr = self.httpd.addr
4456 bindaddr = self.httpd.addr
4457 if bindaddr == '0.0.0.0':
4457 if bindaddr == '0.0.0.0':
4458 bindaddr = '*'
4458 bindaddr = '*'
4459 elif ':' in bindaddr: # IPv6
4459 elif ':' in bindaddr: # IPv6
4460 bindaddr = '[%s]' % bindaddr
4460 bindaddr = '[%s]' % bindaddr
4461
4461
4462 fqaddr = self.httpd.fqaddr
4462 fqaddr = self.httpd.fqaddr
4463 if ':' in fqaddr:
4463 if ':' in fqaddr:
4464 fqaddr = '[%s]' % fqaddr
4464 fqaddr = '[%s]' % fqaddr
4465 if opts['port']:
4465 if opts['port']:
4466 write = ui.status
4466 write = ui.status
4467 else:
4467 else:
4468 write = ui.write
4468 write = ui.write
4469 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4469 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4470 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4470 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4471
4471
4472 def run(self):
4472 def run(self):
4473 self.httpd.serve_forever()
4473 self.httpd.serve_forever()
4474
4474
4475 service = service()
4475 service = service()
4476
4476
4477 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4477 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4478
4478
4479 @command('showconfig|debugconfig',
4479 @command('showconfig|debugconfig',
4480 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4480 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4481 _('[-u] [NAME]...'))
4481 _('[-u] [NAME]...'))
4482 def showconfig(ui, repo, *values, **opts):
4482 def showconfig(ui, repo, *values, **opts):
4483 """show combined config settings from all hgrc files
4483 """show combined config settings from all hgrc files
4484
4484
4485 With no arguments, print names and values of all config items.
4485 With no arguments, print names and values of all config items.
4486
4486
4487 With one argument of the form section.name, print just the value
4487 With one argument of the form section.name, print just the value
4488 of that config item.
4488 of that config item.
4489
4489
4490 With multiple arguments, print names and values of all config
4490 With multiple arguments, print names and values of all config
4491 items with matching section names.
4491 items with matching section names.
4492
4492
4493 With --debug, the source (filename and line number) is printed
4493 With --debug, the source (filename and line number) is printed
4494 for each config item.
4494 for each config item.
4495
4495
4496 Returns 0 on success.
4496 Returns 0 on success.
4497 """
4497 """
4498
4498
4499 for f in scmutil.rcpath():
4499 for f in scmutil.rcpath():
4500 ui.debug(_('read config from: %s\n') % f)
4500 ui.debug(_('read config from: %s\n') % f)
4501 untrusted = bool(opts.get('untrusted'))
4501 untrusted = bool(opts.get('untrusted'))
4502 if values:
4502 if values:
4503 sections = [v for v in values if '.' not in v]
4503 sections = [v for v in values if '.' not in v]
4504 items = [v for v in values if '.' in v]
4504 items = [v for v in values if '.' in v]
4505 if len(items) > 1 or items and sections:
4505 if len(items) > 1 or items and sections:
4506 raise util.Abort(_('only one config item permitted'))
4506 raise util.Abort(_('only one config item permitted'))
4507 for section, name, value in ui.walkconfig(untrusted=untrusted):
4507 for section, name, value in ui.walkconfig(untrusted=untrusted):
4508 value = str(value).replace('\n', '\\n')
4508 value = str(value).replace('\n', '\\n')
4509 sectname = section + '.' + name
4509 sectname = section + '.' + name
4510 if values:
4510 if values:
4511 for v in values:
4511 for v in values:
4512 if v == section:
4512 if v == section:
4513 ui.debug('%s: ' %
4513 ui.debug('%s: ' %
4514 ui.configsource(section, name, untrusted))
4514 ui.configsource(section, name, untrusted))
4515 ui.write('%s=%s\n' % (sectname, value))
4515 ui.write('%s=%s\n' % (sectname, value))
4516 elif v == sectname:
4516 elif v == sectname:
4517 ui.debug('%s: ' %
4517 ui.debug('%s: ' %
4518 ui.configsource(section, name, untrusted))
4518 ui.configsource(section, name, untrusted))
4519 ui.write(value, '\n')
4519 ui.write(value, '\n')
4520 else:
4520 else:
4521 ui.debug('%s: ' %
4521 ui.debug('%s: ' %
4522 ui.configsource(section, name, untrusted))
4522 ui.configsource(section, name, untrusted))
4523 ui.write('%s=%s\n' % (sectname, value))
4523 ui.write('%s=%s\n' % (sectname, value))
4524
4524
4525 @command('^status|st',
4525 @command('^status|st',
4526 [('A', 'all', None, _('show status of all files')),
4526 [('A', 'all', None, _('show status of all files')),
4527 ('m', 'modified', None, _('show only modified files')),
4527 ('m', 'modified', None, _('show only modified files')),
4528 ('a', 'added', None, _('show only added files')),
4528 ('a', 'added', None, _('show only added files')),
4529 ('r', 'removed', None, _('show only removed files')),
4529 ('r', 'removed', None, _('show only removed files')),
4530 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4530 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4531 ('c', 'clean', None, _('show only files without changes')),
4531 ('c', 'clean', None, _('show only files without changes')),
4532 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4532 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4533 ('i', 'ignored', None, _('show only ignored files')),
4533 ('i', 'ignored', None, _('show only ignored files')),
4534 ('n', 'no-status', None, _('hide status prefix')),
4534 ('n', 'no-status', None, _('hide status prefix')),
4535 ('C', 'copies', None, _('show source of copied files')),
4535 ('C', 'copies', None, _('show source of copied files')),
4536 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4536 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4537 ('', 'rev', [], _('show difference from revision'), _('REV')),
4537 ('', 'rev', [], _('show difference from revision'), _('REV')),
4538 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4538 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4539 ] + walkopts + subrepoopts,
4539 ] + walkopts + subrepoopts,
4540 _('[OPTION]... [FILE]...'))
4540 _('[OPTION]... [FILE]...'))
4541 def status(ui, repo, *pats, **opts):
4541 def status(ui, repo, *pats, **opts):
4542 """show changed files in the working directory
4542 """show changed files in the working directory
4543
4543
4544 Show status of files in the repository. If names are given, only
4544 Show status of files in the repository. If names are given, only
4545 files that match are shown. Files that are clean or ignored or
4545 files that match are shown. Files that are clean or ignored or
4546 the source of a copy/move operation, are not listed unless
4546 the source of a copy/move operation, are not listed unless
4547 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4547 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4548 Unless options described with "show only ..." are given, the
4548 Unless options described with "show only ..." are given, the
4549 options -mardu are used.
4549 options -mardu are used.
4550
4550
4551 Option -q/--quiet hides untracked (unknown and ignored) files
4551 Option -q/--quiet hides untracked (unknown and ignored) files
4552 unless explicitly requested with -u/--unknown or -i/--ignored.
4552 unless explicitly requested with -u/--unknown or -i/--ignored.
4553
4553
4554 .. note::
4554 .. note::
4555 status may appear to disagree with diff if permissions have
4555 status may appear to disagree with diff if permissions have
4556 changed or a merge has occurred. The standard diff format does
4556 changed or a merge has occurred. The standard diff format does
4557 not report permission changes and diff only reports changes
4557 not report permission changes and diff only reports changes
4558 relative to one merge parent.
4558 relative to one merge parent.
4559
4559
4560 If one revision is given, it is used as the base revision.
4560 If one revision is given, it is used as the base revision.
4561 If two revisions are given, the differences between them are
4561 If two revisions are given, the differences between them are
4562 shown. The --change option can also be used as a shortcut to list
4562 shown. The --change option can also be used as a shortcut to list
4563 the changed files of a revision from its first parent.
4563 the changed files of a revision from its first parent.
4564
4564
4565 The codes used to show the status of files are::
4565 The codes used to show the status of files are::
4566
4566
4567 M = modified
4567 M = modified
4568 A = added
4568 A = added
4569 R = removed
4569 R = removed
4570 C = clean
4570 C = clean
4571 ! = missing (deleted by non-hg command, but still tracked)
4571 ! = missing (deleted by non-hg command, but still tracked)
4572 ? = not tracked
4572 ? = not tracked
4573 I = ignored
4573 I = ignored
4574 = origin of the previous file listed as A (added)
4574 = origin of the previous file listed as A (added)
4575
4575
4576 Returns 0 on success.
4576 Returns 0 on success.
4577 """
4577 """
4578
4578
4579 revs = opts.get('rev')
4579 revs = opts.get('rev')
4580 change = opts.get('change')
4580 change = opts.get('change')
4581
4581
4582 if revs and change:
4582 if revs and change:
4583 msg = _('cannot specify --rev and --change at the same time')
4583 msg = _('cannot specify --rev and --change at the same time')
4584 raise util.Abort(msg)
4584 raise util.Abort(msg)
4585 elif change:
4585 elif change:
4586 node2 = repo.lookup(change)
4586 node2 = repo.lookup(change)
4587 node1 = repo[node2].p1().node()
4587 node1 = repo[node2].p1().node()
4588 else:
4588 else:
4589 node1, node2 = scmutil.revpair(repo, revs)
4589 node1, node2 = scmutil.revpair(repo, revs)
4590
4590
4591 cwd = (pats and repo.getcwd()) or ''
4591 cwd = (pats and repo.getcwd()) or ''
4592 end = opts.get('print0') and '\0' or '\n'
4592 end = opts.get('print0') and '\0' or '\n'
4593 copy = {}
4593 copy = {}
4594 states = 'modified added removed deleted unknown ignored clean'.split()
4594 states = 'modified added removed deleted unknown ignored clean'.split()
4595 show = [k for k in states if opts.get(k)]
4595 show = [k for k in states if opts.get(k)]
4596 if opts.get('all'):
4596 if opts.get('all'):
4597 show += ui.quiet and (states[:4] + ['clean']) or states
4597 show += ui.quiet and (states[:4] + ['clean']) or states
4598 if not show:
4598 if not show:
4599 show = ui.quiet and states[:4] or states[:5]
4599 show = ui.quiet and states[:4] or states[:5]
4600
4600
4601 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4601 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4602 'ignored' in show, 'clean' in show, 'unknown' in show,
4602 'ignored' in show, 'clean' in show, 'unknown' in show,
4603 opts.get('subrepos'))
4603 opts.get('subrepos'))
4604 changestates = zip(states, 'MAR!?IC', stat)
4604 changestates = zip(states, 'MAR!?IC', stat)
4605
4605
4606 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4606 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4607 ctxn = repo[nullid]
4607 ctxn = repo[nullid]
4608 ctx1 = repo[node1]
4608 ctx1 = repo[node1]
4609 ctx2 = repo[node2]
4609 ctx2 = repo[node2]
4610 added = stat[1]
4610 added = stat[1]
4611 if node2 is None:
4611 if node2 is None:
4612 added = stat[0] + stat[1] # merged?
4612 added = stat[0] + stat[1] # merged?
4613
4613
4614 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4614 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4615 if k in added:
4615 if k in added:
4616 copy[k] = v
4616 copy[k] = v
4617 elif v in added:
4617 elif v in added:
4618 copy[v] = k
4618 copy[v] = k
4619
4619
4620 for state, char, files in changestates:
4620 for state, char, files in changestates:
4621 if state in show:
4621 if state in show:
4622 format = "%s %%s%s" % (char, end)
4622 format = "%s %%s%s" % (char, end)
4623 if opts.get('no_status'):
4623 if opts.get('no_status'):
4624 format = "%%s%s" % end
4624 format = "%%s%s" % end
4625
4625
4626 for f in files:
4626 for f in files:
4627 ui.write(format % repo.pathto(f, cwd),
4627 ui.write(format % repo.pathto(f, cwd),
4628 label='status.' + state)
4628 label='status.' + state)
4629 if f in copy:
4629 if f in copy:
4630 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4630 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4631 label='status.copied')
4631 label='status.copied')
4632
4632
4633 @command('^summary|sum',
4633 @command('^summary|sum',
4634 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4634 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4635 def summary(ui, repo, **opts):
4635 def summary(ui, repo, **opts):
4636 """summarize working directory state
4636 """summarize working directory state
4637
4637
4638 This generates a brief summary of the working directory state,
4638 This generates a brief summary of the working directory state,
4639 including parents, branch, commit status, and available updates.
4639 including parents, branch, commit status, and available updates.
4640
4640
4641 With the --remote option, this will check the default paths for
4641 With the --remote option, this will check the default paths for
4642 incoming and outgoing changes. This can be time-consuming.
4642 incoming and outgoing changes. This can be time-consuming.
4643
4643
4644 Returns 0 on success.
4644 Returns 0 on success.
4645 """
4645 """
4646
4646
4647 ctx = repo[None]
4647 ctx = repo[None]
4648 parents = ctx.parents()
4648 parents = ctx.parents()
4649 pnode = parents[0].node()
4649 pnode = parents[0].node()
4650
4650
4651 for p in parents:
4651 for p in parents:
4652 # label with log.changeset (instead of log.parent) since this
4652 # label with log.changeset (instead of log.parent) since this
4653 # shows a working directory parent *changeset*:
4653 # shows a working directory parent *changeset*:
4654 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4654 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4655 label='log.changeset')
4655 label='log.changeset')
4656 ui.write(' '.join(p.tags()), label='log.tag')
4656 ui.write(' '.join(p.tags()), label='log.tag')
4657 if p.bookmarks():
4657 if p.bookmarks():
4658 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4658 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4659 if p.rev() == -1:
4659 if p.rev() == -1:
4660 if not len(repo):
4660 if not len(repo):
4661 ui.write(_(' (empty repository)'))
4661 ui.write(_(' (empty repository)'))
4662 else:
4662 else:
4663 ui.write(_(' (no revision checked out)'))
4663 ui.write(_(' (no revision checked out)'))
4664 ui.write('\n')
4664 ui.write('\n')
4665 if p.description():
4665 if p.description():
4666 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4666 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4667 label='log.summary')
4667 label='log.summary')
4668
4668
4669 branch = ctx.branch()
4669 branch = ctx.branch()
4670 bheads = repo.branchheads(branch)
4670 bheads = repo.branchheads(branch)
4671 m = _('branch: %s\n') % branch
4671 m = _('branch: %s\n') % branch
4672 if branch != 'default':
4672 if branch != 'default':
4673 ui.write(m, label='log.branch')
4673 ui.write(m, label='log.branch')
4674 else:
4674 else:
4675 ui.status(m, label='log.branch')
4675 ui.status(m, label='log.branch')
4676
4676
4677 st = list(repo.status(unknown=True))[:6]
4677 st = list(repo.status(unknown=True))[:6]
4678
4678
4679 c = repo.dirstate.copies()
4679 c = repo.dirstate.copies()
4680 copied, renamed = [], []
4680 copied, renamed = [], []
4681 for d, s in c.iteritems():
4681 for d, s in c.iteritems():
4682 if s in st[2]:
4682 if s in st[2]:
4683 st[2].remove(s)
4683 st[2].remove(s)
4684 renamed.append(d)
4684 renamed.append(d)
4685 else:
4685 else:
4686 copied.append(d)
4686 copied.append(d)
4687 if d in st[1]:
4687 if d in st[1]:
4688 st[1].remove(d)
4688 st[1].remove(d)
4689 st.insert(3, renamed)
4689 st.insert(3, renamed)
4690 st.insert(4, copied)
4690 st.insert(4, copied)
4691
4691
4692 ms = mergemod.mergestate(repo)
4692 ms = mergemod.mergestate(repo)
4693 st.append([f for f in ms if ms[f] == 'u'])
4693 st.append([f for f in ms if ms[f] == 'u'])
4694
4694
4695 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4695 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4696 st.append(subs)
4696 st.append(subs)
4697
4697
4698 labels = [ui.label(_('%d modified'), 'status.modified'),
4698 labels = [ui.label(_('%d modified'), 'status.modified'),
4699 ui.label(_('%d added'), 'status.added'),
4699 ui.label(_('%d added'), 'status.added'),
4700 ui.label(_('%d removed'), 'status.removed'),
4700 ui.label(_('%d removed'), 'status.removed'),
4701 ui.label(_('%d renamed'), 'status.copied'),
4701 ui.label(_('%d renamed'), 'status.copied'),
4702 ui.label(_('%d copied'), 'status.copied'),
4702 ui.label(_('%d copied'), 'status.copied'),
4703 ui.label(_('%d deleted'), 'status.deleted'),
4703 ui.label(_('%d deleted'), 'status.deleted'),
4704 ui.label(_('%d unknown'), 'status.unknown'),
4704 ui.label(_('%d unknown'), 'status.unknown'),
4705 ui.label(_('%d ignored'), 'status.ignored'),
4705 ui.label(_('%d ignored'), 'status.ignored'),
4706 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4706 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4707 ui.label(_('%d subrepos'), 'status.modified')]
4707 ui.label(_('%d subrepos'), 'status.modified')]
4708 t = []
4708 t = []
4709 for s, l in zip(st, labels):
4709 for s, l in zip(st, labels):
4710 if s:
4710 if s:
4711 t.append(l % len(s))
4711 t.append(l % len(s))
4712
4712
4713 t = ', '.join(t)
4713 t = ', '.join(t)
4714 cleanworkdir = False
4714 cleanworkdir = False
4715
4715
4716 if len(parents) > 1:
4716 if len(parents) > 1:
4717 t += _(' (merge)')
4717 t += _(' (merge)')
4718 elif branch != parents[0].branch():
4718 elif branch != parents[0].branch():
4719 t += _(' (new branch)')
4719 t += _(' (new branch)')
4720 elif (parents[0].extra().get('close') and
4720 elif (parents[0].extra().get('close') and
4721 pnode in repo.branchheads(branch, closed=True)):
4721 pnode in repo.branchheads(branch, closed=True)):
4722 t += _(' (head closed)')
4722 t += _(' (head closed)')
4723 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4723 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4724 t += _(' (clean)')
4724 t += _(' (clean)')
4725 cleanworkdir = True
4725 cleanworkdir = True
4726 elif pnode not in bheads:
4726 elif pnode not in bheads:
4727 t += _(' (new branch head)')
4727 t += _(' (new branch head)')
4728
4728
4729 if cleanworkdir:
4729 if cleanworkdir:
4730 ui.status(_('commit: %s\n') % t.strip())
4730 ui.status(_('commit: %s\n') % t.strip())
4731 else:
4731 else:
4732 ui.write(_('commit: %s\n') % t.strip())
4732 ui.write(_('commit: %s\n') % t.strip())
4733
4733
4734 # all ancestors of branch heads - all ancestors of parent = new csets
4734 # all ancestors of branch heads - all ancestors of parent = new csets
4735 new = [0] * len(repo)
4735 new = [0] * len(repo)
4736 cl = repo.changelog
4736 cl = repo.changelog
4737 for a in [cl.rev(n) for n in bheads]:
4737 for a in [cl.rev(n) for n in bheads]:
4738 new[a] = 1
4738 new[a] = 1
4739 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4739 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4740 new[a] = 1
4740 new[a] = 1
4741 for a in [p.rev() for p in parents]:
4741 for a in [p.rev() for p in parents]:
4742 if a >= 0:
4742 if a >= 0:
4743 new[a] = 0
4743 new[a] = 0
4744 for a in cl.ancestors(*[p.rev() for p in parents]):
4744 for a in cl.ancestors(*[p.rev() for p in parents]):
4745 new[a] = 0
4745 new[a] = 0
4746 new = sum(new)
4746 new = sum(new)
4747
4747
4748 if new == 0:
4748 if new == 0:
4749 ui.status(_('update: (current)\n'))
4749 ui.status(_('update: (current)\n'))
4750 elif pnode not in bheads:
4750 elif pnode not in bheads:
4751 ui.write(_('update: %d new changesets (update)\n') % new)
4751 ui.write(_('update: %d new changesets (update)\n') % new)
4752 else:
4752 else:
4753 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4753 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4754 (new, len(bheads)))
4754 (new, len(bheads)))
4755
4755
4756 if opts.get('remote'):
4756 if opts.get('remote'):
4757 t = []
4757 t = []
4758 source, branches = hg.parseurl(ui.expandpath('default'))
4758 source, branches = hg.parseurl(ui.expandpath('default'))
4759 other = hg.repository(hg.remoteui(repo, {}), source)
4759 other = hg.repository(hg.remoteui(repo, {}), source)
4760 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4760 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4761 ui.debug('comparing with %s\n' % util.hidepassword(source))
4761 ui.debug('comparing with %s\n' % util.hidepassword(source))
4762 repo.ui.pushbuffer()
4762 repo.ui.pushbuffer()
4763 commoninc = discovery.findcommonincoming(repo, other)
4763 commoninc = discovery.findcommonincoming(repo, other)
4764 _common, incoming, _rheads = commoninc
4764 _common, incoming, _rheads = commoninc
4765 repo.ui.popbuffer()
4765 repo.ui.popbuffer()
4766 if incoming:
4766 if incoming:
4767 t.append(_('1 or more incoming'))
4767 t.append(_('1 or more incoming'))
4768
4768
4769 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4769 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4770 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4770 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4771 if source != dest:
4771 if source != dest:
4772 other = hg.repository(hg.remoteui(repo, {}), dest)
4772 other = hg.repository(hg.remoteui(repo, {}), dest)
4773 commoninc = None
4773 commoninc = None
4774 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4774 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4775 repo.ui.pushbuffer()
4775 repo.ui.pushbuffer()
4776 common, outheads = discovery.findcommonoutgoing(repo, other,
4776 common, outheads = discovery.findcommonoutgoing(repo, other,
4777 commoninc=commoninc)
4777 commoninc=commoninc)
4778 repo.ui.popbuffer()
4778 repo.ui.popbuffer()
4779 o = repo.changelog.findmissing(common=common, heads=outheads)
4779 o = repo.changelog.findmissing(common=common, heads=outheads)
4780 if o:
4780 if o:
4781 t.append(_('%d outgoing') % len(o))
4781 t.append(_('%d outgoing') % len(o))
4782 if 'bookmarks' in other.listkeys('namespaces'):
4782 if 'bookmarks' in other.listkeys('namespaces'):
4783 lmarks = repo.listkeys('bookmarks')
4783 lmarks = repo.listkeys('bookmarks')
4784 rmarks = other.listkeys('bookmarks')
4784 rmarks = other.listkeys('bookmarks')
4785 diff = set(rmarks) - set(lmarks)
4785 diff = set(rmarks) - set(lmarks)
4786 if len(diff) > 0:
4786 if len(diff) > 0:
4787 t.append(_('%d incoming bookmarks') % len(diff))
4787 t.append(_('%d incoming bookmarks') % len(diff))
4788 diff = set(lmarks) - set(rmarks)
4788 diff = set(lmarks) - set(rmarks)
4789 if len(diff) > 0:
4789 if len(diff) > 0:
4790 t.append(_('%d outgoing bookmarks') % len(diff))
4790 t.append(_('%d outgoing bookmarks') % len(diff))
4791
4791
4792 if t:
4792 if t:
4793 ui.write(_('remote: %s\n') % (', '.join(t)))
4793 ui.write(_('remote: %s\n') % (', '.join(t)))
4794 else:
4794 else:
4795 ui.status(_('remote: (synced)\n'))
4795 ui.status(_('remote: (synced)\n'))
4796
4796
4797 @command('tag',
4797 @command('tag',
4798 [('f', 'force', None, _('force tag')),
4798 [('f', 'force', None, _('force tag')),
4799 ('l', 'local', None, _('make the tag local')),
4799 ('l', 'local', None, _('make the tag local')),
4800 ('r', 'rev', '', _('revision to tag'), _('REV')),
4800 ('r', 'rev', '', _('revision to tag'), _('REV')),
4801 ('', 'remove', None, _('remove a tag')),
4801 ('', 'remove', None, _('remove a tag')),
4802 # -l/--local is already there, commitopts cannot be used
4802 # -l/--local is already there, commitopts cannot be used
4803 ('e', 'edit', None, _('edit commit message')),
4803 ('e', 'edit', None, _('edit commit message')),
4804 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4804 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4805 ] + commitopts2,
4805 ] + commitopts2,
4806 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4806 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4807 def tag(ui, repo, name1, *names, **opts):
4807 def tag(ui, repo, name1, *names, **opts):
4808 """add one or more tags for the current or given revision
4808 """add one or more tags for the current or given revision
4809
4809
4810 Name a particular revision using <name>.
4810 Name a particular revision using <name>.
4811
4811
4812 Tags are used to name particular revisions of the repository and are
4812 Tags are used to name particular revisions of the repository and are
4813 very useful to compare different revisions, to go back to significant
4813 very useful to compare different revisions, to go back to significant
4814 earlier versions or to mark branch points as releases, etc. Changing
4814 earlier versions or to mark branch points as releases, etc. Changing
4815 an existing tag is normally disallowed; use -f/--force to override.
4815 an existing tag is normally disallowed; use -f/--force to override.
4816
4816
4817 If no revision is given, the parent of the working directory is
4817 If no revision is given, the parent of the working directory is
4818 used, or tip if no revision is checked out.
4818 used, or tip if no revision is checked out.
4819
4819
4820 To facilitate version control, distribution, and merging of tags,
4820 To facilitate version control, distribution, and merging of tags,
4821 they are stored as a file named ".hgtags" which is managed similarly
4821 they are stored as a file named ".hgtags" which is managed similarly
4822 to other project files and can be hand-edited if necessary. This
4822 to other project files and can be hand-edited if necessary. This
4823 also means that tagging creates a new commit. The file
4823 also means that tagging creates a new commit. The file
4824 ".hg/localtags" is used for local tags (not shared among
4824 ".hg/localtags" is used for local tags (not shared among
4825 repositories).
4825 repositories).
4826
4826
4827 Tag commits are usually made at the head of a branch. If the parent
4827 Tag commits are usually made at the head of a branch. If the parent
4828 of the working directory is not a branch head, :hg:`tag` aborts; use
4828 of the working directory is not a branch head, :hg:`tag` aborts; use
4829 -f/--force to force the tag commit to be based on a non-head
4829 -f/--force to force the tag commit to be based on a non-head
4830 changeset.
4830 changeset.
4831
4831
4832 See :hg:`help dates` for a list of formats valid for -d/--date.
4832 See :hg:`help dates` for a list of formats valid for -d/--date.
4833
4833
4834 Since tag names have priority over branch names during revision
4834 Since tag names have priority over branch names during revision
4835 lookup, using an existing branch name as a tag name is discouraged.
4835 lookup, using an existing branch name as a tag name is discouraged.
4836
4836
4837 Returns 0 on success.
4837 Returns 0 on success.
4838 """
4838 """
4839
4839
4840 rev_ = "."
4840 rev_ = "."
4841 names = [t.strip() for t in (name1,) + names]
4841 names = [t.strip() for t in (name1,) + names]
4842 if len(names) != len(set(names)):
4842 if len(names) != len(set(names)):
4843 raise util.Abort(_('tag names must be unique'))
4843 raise util.Abort(_('tag names must be unique'))
4844 for n in names:
4844 for n in names:
4845 if n in ['tip', '.', 'null']:
4845 if n in ['tip', '.', 'null']:
4846 raise util.Abort(_("the name '%s' is reserved") % n)
4846 raise util.Abort(_("the name '%s' is reserved") % n)
4847 if not n:
4847 if not n:
4848 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4848 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4849 if opts.get('rev') and opts.get('remove'):
4849 if opts.get('rev') and opts.get('remove'):
4850 raise util.Abort(_("--rev and --remove are incompatible"))
4850 raise util.Abort(_("--rev and --remove are incompatible"))
4851 if opts.get('rev'):
4851 if opts.get('rev'):
4852 rev_ = opts['rev']
4852 rev_ = opts['rev']
4853 message = opts.get('message')
4853 message = opts.get('message')
4854 if opts.get('remove'):
4854 if opts.get('remove'):
4855 expectedtype = opts.get('local') and 'local' or 'global'
4855 expectedtype = opts.get('local') and 'local' or 'global'
4856 for n in names:
4856 for n in names:
4857 if not repo.tagtype(n):
4857 if not repo.tagtype(n):
4858 raise util.Abort(_("tag '%s' does not exist") % n)
4858 raise util.Abort(_("tag '%s' does not exist") % n)
4859 if repo.tagtype(n) != expectedtype:
4859 if repo.tagtype(n) != expectedtype:
4860 if expectedtype == 'global':
4860 if expectedtype == 'global':
4861 raise util.Abort(_("tag '%s' is not a global tag") % n)
4861 raise util.Abort(_("tag '%s' is not a global tag") % n)
4862 else:
4862 else:
4863 raise util.Abort(_("tag '%s' is not a local tag") % n)
4863 raise util.Abort(_("tag '%s' is not a local tag") % n)
4864 rev_ = nullid
4864 rev_ = nullid
4865 if not message:
4865 if not message:
4866 # we don't translate commit messages
4866 # we don't translate commit messages
4867 message = 'Removed tag %s' % ', '.join(names)
4867 message = 'Removed tag %s' % ', '.join(names)
4868 elif not opts.get('force'):
4868 elif not opts.get('force'):
4869 for n in names:
4869 for n in names:
4870 if n in repo.tags():
4870 if n in repo.tags():
4871 raise util.Abort(_("tag '%s' already exists "
4871 raise util.Abort(_("tag '%s' already exists "
4872 "(use -f to force)") % n)
4872 "(use -f to force)") % n)
4873 if not opts.get('local'):
4873 if not opts.get('local'):
4874 p1, p2 = repo.dirstate.parents()
4874 p1, p2 = repo.dirstate.parents()
4875 if p2 != nullid:
4875 if p2 != nullid:
4876 raise util.Abort(_('uncommitted merge'))
4876 raise util.Abort(_('uncommitted merge'))
4877 bheads = repo.branchheads()
4877 bheads = repo.branchheads()
4878 if not opts.get('force') and bheads and p1 not in bheads:
4878 if not opts.get('force') and bheads and p1 not in bheads:
4879 raise util.Abort(_('not at a branch head (use -f to force)'))
4879 raise util.Abort(_('not at a branch head (use -f to force)'))
4880 r = scmutil.revsingle(repo, rev_).node()
4880 r = scmutil.revsingle(repo, rev_).node()
4881
4881
4882 if not message:
4882 if not message:
4883 # we don't translate commit messages
4883 # we don't translate commit messages
4884 message = ('Added tag %s for changeset %s' %
4884 message = ('Added tag %s for changeset %s' %
4885 (', '.join(names), short(r)))
4885 (', '.join(names), short(r)))
4886
4886
4887 date = opts.get('date')
4887 date = opts.get('date')
4888 if date:
4888 if date:
4889 date = util.parsedate(date)
4889 date = util.parsedate(date)
4890
4890
4891 if opts.get('edit'):
4891 if opts.get('edit'):
4892 message = ui.edit(message, ui.username())
4892 message = ui.edit(message, ui.username())
4893
4893
4894 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4894 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4895
4895
4896 @command('tags', [], '')
4896 @command('tags', [], '')
4897 def tags(ui, repo):
4897 def tags(ui, repo):
4898 """list repository tags
4898 """list repository tags
4899
4899
4900 This lists both regular and local tags. When the -v/--verbose
4900 This lists both regular and local tags. When the -v/--verbose
4901 switch is used, a third column "local" is printed for local tags.
4901 switch is used, a third column "local" is printed for local tags.
4902
4902
4903 Returns 0 on success.
4903 Returns 0 on success.
4904 """
4904 """
4905
4905
4906 hexfunc = ui.debugflag and hex or short
4906 hexfunc = ui.debugflag and hex or short
4907 tagtype = ""
4907 tagtype = ""
4908
4908
4909 for t, n in reversed(repo.tagslist()):
4909 for t, n in reversed(repo.tagslist()):
4910 if ui.quiet:
4910 if ui.quiet:
4911 ui.write("%s\n" % t)
4911 ui.write("%s\n" % t)
4912 continue
4912 continue
4913
4913
4914 hn = hexfunc(n)
4914 hn = hexfunc(n)
4915 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4915 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4916 spaces = " " * (30 - encoding.colwidth(t))
4916 spaces = " " * (30 - encoding.colwidth(t))
4917
4917
4918 if ui.verbose:
4918 if ui.verbose:
4919 if repo.tagtype(t) == 'local':
4919 if repo.tagtype(t) == 'local':
4920 tagtype = " local"
4920 tagtype = " local"
4921 else:
4921 else:
4922 tagtype = ""
4922 tagtype = ""
4923 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4923 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4924
4924
4925 @command('tip',
4925 @command('tip',
4926 [('p', 'patch', None, _('show patch')),
4926 [('p', 'patch', None, _('show patch')),
4927 ('g', 'git', None, _('use git extended diff format')),
4927 ('g', 'git', None, _('use git extended diff format')),
4928 ] + templateopts,
4928 ] + templateopts,
4929 _('[-p] [-g]'))
4929 _('[-p] [-g]'))
4930 def tip(ui, repo, **opts):
4930 def tip(ui, repo, **opts):
4931 """show the tip revision
4931 """show the tip revision
4932
4932
4933 The tip revision (usually just called the tip) is the changeset
4933 The tip revision (usually just called the tip) is the changeset
4934 most recently added to the repository (and therefore the most
4934 most recently added to the repository (and therefore the most
4935 recently changed head).
4935 recently changed head).
4936
4936
4937 If you have just made a commit, that commit will be the tip. If
4937 If you have just made a commit, that commit will be the tip. If
4938 you have just pulled changes from another repository, the tip of
4938 you have just pulled changes from another repository, the tip of
4939 that repository becomes the current tip. The "tip" tag is special
4939 that repository becomes the current tip. The "tip" tag is special
4940 and cannot be renamed or assigned to a different changeset.
4940 and cannot be renamed or assigned to a different changeset.
4941
4941
4942 Returns 0 on success.
4942 Returns 0 on success.
4943 """
4943 """
4944 displayer = cmdutil.show_changeset(ui, repo, opts)
4944 displayer = cmdutil.show_changeset(ui, repo, opts)
4945 displayer.show(repo[len(repo) - 1])
4945 displayer.show(repo[len(repo) - 1])
4946 displayer.close()
4946 displayer.close()
4947
4947
4948 @command('unbundle',
4948 @command('unbundle',
4949 [('u', 'update', None,
4949 [('u', 'update', None,
4950 _('update to new branch head if changesets were unbundled'))],
4950 _('update to new branch head if changesets were unbundled'))],
4951 _('[-u] FILE...'))
4951 _('[-u] FILE...'))
4952 def unbundle(ui, repo, fname1, *fnames, **opts):
4952 def unbundle(ui, repo, fname1, *fnames, **opts):
4953 """apply one or more changegroup files
4953 """apply one or more changegroup files
4954
4954
4955 Apply one or more compressed changegroup files generated by the
4955 Apply one or more compressed changegroup files generated by the
4956 bundle command.
4956 bundle command.
4957
4957
4958 Returns 0 on success, 1 if an update has unresolved files.
4958 Returns 0 on success, 1 if an update has unresolved files.
4959 """
4959 """
4960 fnames = (fname1,) + fnames
4960 fnames = (fname1,) + fnames
4961
4961
4962 lock = repo.lock()
4962 lock = repo.lock()
4963 wc = repo['.']
4963 wc = repo['.']
4964 try:
4964 try:
4965 for fname in fnames:
4965 for fname in fnames:
4966 f = url.open(ui, fname)
4966 f = url.open(ui, fname)
4967 gen = changegroup.readbundle(f, fname)
4967 gen = changegroup.readbundle(f, fname)
4968 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4968 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
4969 lock=lock)
4969 lock=lock)
4970 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4970 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
4971 finally:
4971 finally:
4972 lock.release()
4972 lock.release()
4973 return postincoming(ui, repo, modheads, opts.get('update'), None)
4973 return postincoming(ui, repo, modheads, opts.get('update'), None)
4974
4974
4975 @command('^update|up|checkout|co',
4975 @command('^update|up|checkout|co',
4976 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4976 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
4977 ('c', 'check', None,
4977 ('c', 'check', None,
4978 _('update across branches if no uncommitted changes')),
4978 _('update across branches if no uncommitted changes')),
4979 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4979 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4980 ('r', 'rev', '', _('revision'), _('REV'))],
4980 ('r', 'rev', '', _('revision'), _('REV'))],
4981 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4981 _('[-c] [-C] [-d DATE] [[-r] REV]'))
4982 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4982 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
4983 """update working directory (or switch revisions)
4983 """update working directory (or switch revisions)
4984
4984
4985 Update the repository's working directory to the specified
4985 Update the repository's working directory to the specified
4986 changeset. If no changeset is specified, update to the tip of the
4986 changeset. If no changeset is specified, update to the tip of the
4987 current named branch.
4987 current named branch.
4988
4988
4989 If the changeset is not a descendant of the working directory's
4989 If the changeset is not a descendant of the working directory's
4990 parent, the update is aborted. With the -c/--check option, the
4990 parent, the update is aborted. With the -c/--check option, the
4991 working directory is checked for uncommitted changes; if none are
4991 working directory is checked for uncommitted changes; if none are
4992 found, the working directory is updated to the specified
4992 found, the working directory is updated to the specified
4993 changeset.
4993 changeset.
4994
4994
4995 The following rules apply when the working directory contains
4995 The following rules apply when the working directory contains
4996 uncommitted changes:
4996 uncommitted changes:
4997
4997
4998 1. If neither -c/--check nor -C/--clean is specified, and if
4998 1. If neither -c/--check nor -C/--clean is specified, and if
4999 the requested changeset is an ancestor or descendant of
4999 the requested changeset is an ancestor or descendant of
5000 the working directory's parent, the uncommitted changes
5000 the working directory's parent, the uncommitted changes
5001 are merged into the requested changeset and the merged
5001 are merged into the requested changeset and the merged
5002 result is left uncommitted. If the requested changeset is
5002 result is left uncommitted. If the requested changeset is
5003 not an ancestor or descendant (that is, it is on another
5003 not an ancestor or descendant (that is, it is on another
5004 branch), the update is aborted and the uncommitted changes
5004 branch), the update is aborted and the uncommitted changes
5005 are preserved.
5005 are preserved.
5006
5006
5007 2. With the -c/--check option, the update is aborted and the
5007 2. With the -c/--check option, the update is aborted and the
5008 uncommitted changes are preserved.
5008 uncommitted changes are preserved.
5009
5009
5010 3. With the -C/--clean option, uncommitted changes are discarded and
5010 3. With the -C/--clean option, uncommitted changes are discarded and
5011 the working directory is updated to the requested changeset.
5011 the working directory is updated to the requested changeset.
5012
5012
5013 Use null as the changeset to remove the working directory (like
5013 Use null as the changeset to remove the working directory (like
5014 :hg:`clone -U`).
5014 :hg:`clone -U`).
5015
5015
5016 If you want to update just one file to an older changeset, use
5016 If you want to update just one file to an older changeset, use
5017 :hg:`revert`.
5017 :hg:`revert`.
5018
5018
5019 See :hg:`help dates` for a list of formats valid for -d/--date.
5019 See :hg:`help dates` for a list of formats valid for -d/--date.
5020
5020
5021 Returns 0 on success, 1 if there are unresolved files.
5021 Returns 0 on success, 1 if there are unresolved files.
5022 """
5022 """
5023 if rev and node:
5023 if rev and node:
5024 raise util.Abort(_("please specify just one revision"))
5024 raise util.Abort(_("please specify just one revision"))
5025
5025
5026 if rev is None or rev == '':
5026 if rev is None or rev == '':
5027 rev = node
5027 rev = node
5028
5028
5029 # if we defined a bookmark, we have to remember the original bookmark name
5029 # if we defined a bookmark, we have to remember the original bookmark name
5030 brev = rev
5030 brev = rev
5031 rev = scmutil.revsingle(repo, rev, rev).rev()
5031 rev = scmutil.revsingle(repo, rev, rev).rev()
5032
5032
5033 if check and clean:
5033 if check and clean:
5034 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5034 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5035
5035
5036 if check:
5036 if check:
5037 # we could use dirty() but we can ignore merge and branch trivia
5037 # we could use dirty() but we can ignore merge and branch trivia
5038 c = repo[None]
5038 c = repo[None]
5039 if c.modified() or c.added() or c.removed():
5039 if c.modified() or c.added() or c.removed():
5040 raise util.Abort(_("uncommitted local changes"))
5040 raise util.Abort(_("uncommitted local changes"))
5041
5041
5042 if date:
5042 if date:
5043 if rev is not None:
5043 if rev is not None:
5044 raise util.Abort(_("you can't specify a revision and a date"))
5044 raise util.Abort(_("you can't specify a revision and a date"))
5045 rev = cmdutil.finddate(ui, repo, date)
5045 rev = cmdutil.finddate(ui, repo, date)
5046
5046
5047 if clean or check:
5047 if clean or check:
5048 ret = hg.clean(repo, rev)
5048 ret = hg.clean(repo, rev)
5049 else:
5049 else:
5050 ret = hg.update(repo, rev)
5050 ret = hg.update(repo, rev)
5051
5051
5052 if brev in repo._bookmarks:
5052 if brev in repo._bookmarks:
5053 bookmarks.setcurrent(repo, brev)
5053 bookmarks.setcurrent(repo, brev)
5054
5054
5055 return ret
5055 return ret
5056
5056
5057 @command('verify', [])
5057 @command('verify', [])
5058 def verify(ui, repo):
5058 def verify(ui, repo):
5059 """verify the integrity of the repository
5059 """verify the integrity of the repository
5060
5060
5061 Verify the integrity of the current repository.
5061 Verify the integrity of the current repository.
5062
5062
5063 This will perform an extensive check of the repository's
5063 This will perform an extensive check of the repository's
5064 integrity, validating the hashes and checksums of each entry in
5064 integrity, validating the hashes and checksums of each entry in
5065 the changelog, manifest, and tracked files, as well as the
5065 the changelog, manifest, and tracked files, as well as the
5066 integrity of their crosslinks and indices.
5066 integrity of their crosslinks and indices.
5067
5067
5068 Returns 0 on success, 1 if errors are encountered.
5068 Returns 0 on success, 1 if errors are encountered.
5069 """
5069 """
5070 return hg.verify(repo)
5070 return hg.verify(repo)
5071
5071
5072 @command('version', [])
5072 @command('version', [])
5073 def version_(ui):
5073 def version_(ui):
5074 """output version and copyright information"""
5074 """output version and copyright information"""
5075 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5075 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5076 % util.version())
5076 % util.version())
5077 ui.status(_(
5077 ui.status(_(
5078 "(see http://mercurial.selenic.com for more information)\n"
5078 "(see http://mercurial.selenic.com for more information)\n"
5079 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5079 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5080 "This is free software; see the source for copying conditions. "
5080 "This is free software; see the source for copying conditions. "
5081 "There is NO\nwarranty; "
5081 "There is NO\nwarranty; "
5082 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5082 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5083 ))
5083 ))
5084
5084
5085 norepo = ("clone init version help debugcommands debugcomplete"
5085 norepo = ("clone init version help debugcommands debugcomplete"
5086 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5086 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5087 " debugknown debuggetbundle debugbundle")
5087 " debugknown debuggetbundle debugbundle")
5088 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5088 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5089 " debugdata debugindex debugindexdot debugrevlog")
5089 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,436 +1,436 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 grep search for a pattern in specified files and revisions
299 grep search for a pattern in specified files and revisions
300 heads show current repository heads or show branch heads
300 heads show current repository heads or show branch heads
301 help show help for a given topic or a help overview
301 help show help for a given topic or a help overview
302 identify identify the working copy or specified revision
302 identify identify the working copy or specified revision
303 import import an ordered set of patches
303 import import an ordered set of patches
304 incoming show new changesets found in source
304 incoming show new changesets found in source
305 init create a new repository in the given directory
305 init create a new repository in the given directory
306 locate locate files matching specific patterns
306 locate locate files matching specific patterns
307 log show revision history of entire repository or files
307 log show revision history of entire repository or files
308 manifest output the current or given revision of the project manifest
308 manifest output the current or given revision of the project manifest
309 merge merge working directory with another revision
309 merge merge working directory with another revision
310 outgoing show changesets not found in the destination
310 outgoing show changesets not found in the destination
311 parents show the parents of the working directory or revision
311 parents show the parents of the working directory or revision
312 paths show aliases for remote repositories
312 paths show aliases for remote repositories
313 pull pull changes from the specified source
313 pull pull changes from the specified source
314 push push changes to the specified destination
314 push push changes to the specified destination
315 recover roll back an interrupted transaction
315 recover roll back an interrupted transaction
316 remove remove the specified files on the next commit
316 remove remove the specified files on the next commit
317 rename rename files; equivalent of copy + remove
317 rename rename files; equivalent of copy + remove
318 resolve redo merges or set/view the merge status of files
318 resolve redo merges or set/view the merge status of files
319 revert restore individual files or directories to an earlier state
319 revert restore files to their checkout state
320 rollback roll back the last transaction (dangerous)
320 rollback roll back the last transaction (dangerous)
321 root print the root (top) of the current working directory
321 root print the root (top) of the current working directory
322 serve start stand-alone webserver
322 serve start stand-alone webserver
323 showconfig show combined config settings from all hgrc files
323 showconfig show combined config settings from all hgrc files
324 status show changed files in the working directory
324 status show changed files in the working directory
325 summary summarize working directory state
325 summary summarize working directory state
326 tag add one or more tags for the current or given revision
326 tag add one or more tags for the current or given revision
327 tags list repository tags
327 tags list repository tags
328 tip show the tip revision
328 tip show the tip revision
329 unbundle apply one or more changegroup files
329 unbundle apply one or more changegroup files
330 update update working directory (or switch revisions)
330 update update working directory (or switch revisions)
331 verify verify the integrity of the repository
331 verify verify the integrity of the repository
332 version output version and copyright information
332 version output version and copyright information
333
333
334 additional help topics:
334 additional help topics:
335
335
336 config Configuration Files
336 config Configuration Files
337 dates Date Formats
337 dates Date Formats
338 diffs Diff Formats
338 diffs Diff Formats
339 environment Environment Variables
339 environment Environment Variables
340 extensions Using additional features
340 extensions Using additional features
341 glossary Glossary
341 glossary Glossary
342 hgignore syntax for Mercurial ignore files
342 hgignore syntax for Mercurial ignore files
343 hgweb Configuring hgweb
343 hgweb Configuring hgweb
344 merge-tools Merge Tools
344 merge-tools Merge Tools
345 multirevs Specifying Multiple Revisions
345 multirevs Specifying Multiple Revisions
346 patterns File Name Patterns
346 patterns File Name Patterns
347 revisions Specifying Single Revisions
347 revisions Specifying Single Revisions
348 revsets Specifying Revision Sets
348 revsets Specifying Revision Sets
349 subrepos Subrepositories
349 subrepos Subrepositories
350 templating Template Usage
350 templating Template Usage
351 urls URL Paths
351 urls URL Paths
352
352
353 use "hg -v help" to show builtin aliases and global options
353 use "hg -v help" to show builtin aliases and global options
354
354
355
355
356
356
357 $ hg --help
357 $ hg --help
358 Mercurial Distributed SCM
358 Mercurial Distributed SCM
359
359
360 list of commands:
360 list of commands:
361
361
362 add add the specified files on the next commit
362 add add the specified files on the next commit
363 addremove add all new files, delete all missing files
363 addremove add all new files, delete all missing files
364 annotate show changeset information by line for each file
364 annotate show changeset information by line for each file
365 archive create an unversioned archive of a repository revision
365 archive create an unversioned archive of a repository revision
366 backout reverse effect of earlier changeset
366 backout reverse effect of earlier changeset
367 bisect subdivision search of changesets
367 bisect subdivision search of changesets
368 bookmarks track a line of development with movable markers
368 bookmarks track a line of development with movable markers
369 branch set or show the current branch name
369 branch set or show the current branch name
370 branches list repository named branches
370 branches list repository named branches
371 bundle create a changegroup file
371 bundle create a changegroup file
372 cat output the current or given revision of files
372 cat output the current or given revision of files
373 clone make a copy of an existing repository
373 clone make a copy of an existing repository
374 commit commit the specified files or all outstanding changes
374 commit commit the specified files or all outstanding changes
375 copy mark files as copied for the next commit
375 copy mark files as copied for the next commit
376 diff diff repository (or selected files)
376 diff diff repository (or selected files)
377 export dump the header and diffs for one or more changesets
377 export dump the header and diffs for one or more changesets
378 forget forget the specified files on the next commit
378 forget forget the specified files on the next commit
379 grep search for a pattern in specified files and revisions
379 grep search for a pattern in specified files and revisions
380 heads show current repository heads or show branch heads
380 heads show current repository heads or show branch heads
381 help show help for a given topic or a help overview
381 help show help for a given topic or a help overview
382 identify identify the working copy or specified revision
382 identify identify the working copy or specified revision
383 import import an ordered set of patches
383 import import an ordered set of patches
384 incoming show new changesets found in source
384 incoming show new changesets found in source
385 init create a new repository in the given directory
385 init create a new repository in the given directory
386 locate locate files matching specific patterns
386 locate locate files matching specific patterns
387 log show revision history of entire repository or files
387 log show revision history of entire repository or files
388 manifest output the current or given revision of the project manifest
388 manifest output the current or given revision of the project manifest
389 merge merge working directory with another revision
389 merge merge working directory with another revision
390 outgoing show changesets not found in the destination
390 outgoing show changesets not found in the destination
391 parents show the parents of the working directory or revision
391 parents show the parents of the working directory or revision
392 paths show aliases for remote repositories
392 paths show aliases for remote repositories
393 pull pull changes from the specified source
393 pull pull changes from the specified source
394 push push changes to the specified destination
394 push push changes to the specified destination
395 recover roll back an interrupted transaction
395 recover roll back an interrupted transaction
396 remove remove the specified files on the next commit
396 remove remove the specified files on the next commit
397 rename rename files; equivalent of copy + remove
397 rename rename files; equivalent of copy + remove
398 resolve redo merges or set/view the merge status of files
398 resolve redo merges or set/view the merge status of files
399 revert restore individual files or directories to an earlier state
399 revert restore files to their checkout state
400 rollback roll back the last transaction (dangerous)
400 rollback roll back the last transaction (dangerous)
401 root print the root (top) of the current working directory
401 root print the root (top) of the current working directory
402 serve start stand-alone webserver
402 serve start stand-alone webserver
403 showconfig show combined config settings from all hgrc files
403 showconfig show combined config settings from all hgrc files
404 status show changed files in the working directory
404 status show changed files in the working directory
405 summary summarize working directory state
405 summary summarize working directory state
406 tag add one or more tags for the current or given revision
406 tag add one or more tags for the current or given revision
407 tags list repository tags
407 tags list repository tags
408 tip show the tip revision
408 tip show the tip revision
409 unbundle apply one or more changegroup files
409 unbundle apply one or more changegroup files
410 update update working directory (or switch revisions)
410 update update working directory (or switch revisions)
411 verify verify the integrity of the repository
411 verify verify the integrity of the repository
412 version output version and copyright information
412 version output version and copyright information
413
413
414 additional help topics:
414 additional help topics:
415
415
416 config Configuration Files
416 config Configuration Files
417 dates Date Formats
417 dates Date Formats
418 diffs Diff Formats
418 diffs Diff Formats
419 environment Environment Variables
419 environment Environment Variables
420 extensions Using additional features
420 extensions Using additional features
421 glossary Glossary
421 glossary Glossary
422 hgignore syntax for Mercurial ignore files
422 hgignore syntax for Mercurial ignore files
423 hgweb Configuring hgweb
423 hgweb Configuring hgweb
424 merge-tools Merge Tools
424 merge-tools Merge Tools
425 multirevs Specifying Multiple Revisions
425 multirevs Specifying Multiple Revisions
426 patterns File Name Patterns
426 patterns File Name Patterns
427 revisions Specifying Single Revisions
427 revisions Specifying Single Revisions
428 revsets Specifying Revision Sets
428 revsets Specifying Revision Sets
429 subrepos Subrepositories
429 subrepos Subrepositories
430 templating Template Usage
430 templating Template Usage
431 urls URL Paths
431 urls URL Paths
432
432
433 use "hg -v help" to show builtin aliases and global options
433 use "hg -v help" to show builtin aliases and global options
434
434
435 Not tested: --debugger
435 Not tested: --debugger
436
436
@@ -1,795 +1,795 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 grep search for a pattern in specified files and revisions
69 grep search for a pattern in specified files and revisions
70 heads show current repository heads or show branch heads
70 heads show current repository heads or show branch heads
71 help show help for a given topic or a help overview
71 help show help for a given topic or a help overview
72 identify identify the working copy or specified revision
72 identify identify the working copy or specified revision
73 import import an ordered set of patches
73 import import an ordered set of patches
74 incoming show new changesets found in source
74 incoming show new changesets found in source
75 init create a new repository in the given directory
75 init create a new repository in the given directory
76 locate locate files matching specific patterns
76 locate locate files matching specific patterns
77 log show revision history of entire repository or files
77 log show revision history of entire repository or files
78 manifest output the current or given revision of the project manifest
78 manifest output the current or given revision of the project manifest
79 merge merge working directory with another revision
79 merge merge working directory with another revision
80 outgoing show changesets not found in the destination
80 outgoing show changesets not found in the destination
81 parents show the parents of the working directory or revision
81 parents show the parents of the working directory or revision
82 paths show aliases for remote repositories
82 paths show aliases for remote repositories
83 pull pull changes from the specified source
83 pull pull changes from the specified source
84 push push changes to the specified destination
84 push push changes to the specified destination
85 recover roll back an interrupted transaction
85 recover roll back an interrupted transaction
86 remove remove the specified files on the next commit
86 remove remove the specified files on the next commit
87 rename rename files; equivalent of copy + remove
87 rename rename files; equivalent of copy + remove
88 resolve redo merges or set/view the merge status of files
88 resolve redo merges or set/view the merge status of files
89 revert restore individual files or directories to an earlier state
89 revert restore files to their checkout state
90 rollback roll back the last transaction (dangerous)
90 rollback roll back the last transaction (dangerous)
91 root print the root (top) of the current working directory
91 root print the root (top) of the current working directory
92 serve start stand-alone webserver
92 serve start stand-alone webserver
93 showconfig show combined config settings from all hgrc files
93 showconfig show combined config settings from all hgrc files
94 status show changed files in the working directory
94 status show changed files in the working directory
95 summary summarize working directory state
95 summary summarize working directory state
96 tag add one or more tags for the current or given revision
96 tag add one or more tags for the current or given revision
97 tags list repository tags
97 tags list repository tags
98 tip show the tip revision
98 tip show the tip revision
99 unbundle apply one or more changegroup files
99 unbundle apply one or more changegroup files
100 update update working directory (or switch revisions)
100 update update working directory (or switch revisions)
101 verify verify the integrity of the repository
101 verify verify the integrity of the repository
102 version output version and copyright information
102 version output version and copyright information
103
103
104 additional help topics:
104 additional help topics:
105
105
106 config Configuration Files
106 config Configuration Files
107 dates Date Formats
107 dates Date Formats
108 diffs Diff Formats
108 diffs Diff Formats
109 environment Environment Variables
109 environment Environment Variables
110 extensions Using additional features
110 extensions Using additional features
111 glossary Glossary
111 glossary Glossary
112 hgignore syntax for Mercurial ignore files
112 hgignore syntax for Mercurial ignore files
113 hgweb Configuring hgweb
113 hgweb Configuring hgweb
114 merge-tools Merge Tools
114 merge-tools Merge Tools
115 multirevs Specifying Multiple Revisions
115 multirevs Specifying Multiple Revisions
116 patterns File Name Patterns
116 patterns File Name Patterns
117 revisions Specifying Single Revisions
117 revisions Specifying Single Revisions
118 revsets Specifying Revision Sets
118 revsets Specifying Revision Sets
119 subrepos Subrepositories
119 subrepos Subrepositories
120 templating Template Usage
120 templating Template Usage
121 urls URL Paths
121 urls URL Paths
122
122
123 use "hg -v help" to show builtin aliases and global options
123 use "hg -v help" to show builtin aliases and global options
124
124
125 $ hg -q help
125 $ hg -q help
126 add add the specified files on the next commit
126 add add the specified files on the next commit
127 addremove add all new files, delete all missing files
127 addremove add all new files, delete all missing files
128 annotate show changeset information by line for each file
128 annotate show changeset information by line for each file
129 archive create an unversioned archive of a repository revision
129 archive create an unversioned archive of a repository revision
130 backout reverse effect of earlier changeset
130 backout reverse effect of earlier changeset
131 bisect subdivision search of changesets
131 bisect subdivision search of changesets
132 bookmarks track a line of development with movable markers
132 bookmarks track a line of development with movable markers
133 branch set or show the current branch name
133 branch set or show the current branch name
134 branches list repository named branches
134 branches list repository named branches
135 bundle create a changegroup file
135 bundle create a changegroup file
136 cat output the current or given revision of files
136 cat output the current or given revision of files
137 clone make a copy of an existing repository
137 clone make a copy of an existing repository
138 commit commit the specified files or all outstanding changes
138 commit commit the specified files or all outstanding changes
139 copy mark files as copied for the next commit
139 copy mark files as copied for the next commit
140 diff diff repository (or selected files)
140 diff diff repository (or selected files)
141 export dump the header and diffs for one or more changesets
141 export dump the header and diffs for one or more changesets
142 forget forget the specified files on the next commit
142 forget forget the specified files on the next commit
143 grep search for a pattern in specified files and revisions
143 grep search for a pattern in specified files and revisions
144 heads show current repository heads or show branch heads
144 heads show current repository heads or show branch heads
145 help show help for a given topic or a help overview
145 help show help for a given topic or a help overview
146 identify identify the working copy or specified revision
146 identify identify the working copy or specified revision
147 import import an ordered set of patches
147 import import an ordered set of patches
148 incoming show new changesets found in source
148 incoming show new changesets found in source
149 init create a new repository in the given directory
149 init create a new repository in the given directory
150 locate locate files matching specific patterns
150 locate locate files matching specific patterns
151 log show revision history of entire repository or files
151 log show revision history of entire repository or files
152 manifest output the current or given revision of the project manifest
152 manifest output the current or given revision of the project manifest
153 merge merge working directory with another revision
153 merge merge working directory with another revision
154 outgoing show changesets not found in the destination
154 outgoing show changesets not found in the destination
155 parents show the parents of the working directory or revision
155 parents show the parents of the working directory or revision
156 paths show aliases for remote repositories
156 paths show aliases for remote repositories
157 pull pull changes from the specified source
157 pull pull changes from the specified source
158 push push changes to the specified destination
158 push push changes to the specified destination
159 recover roll back an interrupted transaction
159 recover roll back an interrupted transaction
160 remove remove the specified files on the next commit
160 remove remove the specified files on the next commit
161 rename rename files; equivalent of copy + remove
161 rename rename files; equivalent of copy + remove
162 resolve redo merges or set/view the merge status of files
162 resolve redo merges or set/view the merge status of files
163 revert restore individual files or directories to an earlier state
163 revert restore files to their checkout state
164 rollback roll back the last transaction (dangerous)
164 rollback roll back the last transaction (dangerous)
165 root print the root (top) of the current working directory
165 root print the root (top) of the current working directory
166 serve start stand-alone webserver
166 serve start stand-alone webserver
167 showconfig show combined config settings from all hgrc files
167 showconfig show combined config settings from all hgrc files
168 status show changed files in the working directory
168 status show changed files in the working directory
169 summary summarize working directory state
169 summary summarize working directory state
170 tag add one or more tags for the current or given revision
170 tag add one or more tags for the current or given revision
171 tags list repository tags
171 tags list repository tags
172 tip show the tip revision
172 tip show the tip revision
173 unbundle apply one or more changegroup files
173 unbundle apply one or more changegroup files
174 update update working directory (or switch revisions)
174 update update working directory (or switch revisions)
175 verify verify the integrity of the repository
175 verify verify the integrity of the repository
176 version output version and copyright information
176 version output version and copyright information
177
177
178 additional help topics:
178 additional help topics:
179
179
180 config Configuration Files
180 config Configuration Files
181 dates Date Formats
181 dates Date Formats
182 diffs Diff Formats
182 diffs Diff Formats
183 environment Environment Variables
183 environment Environment Variables
184 extensions Using additional features
184 extensions Using additional features
185 glossary Glossary
185 glossary Glossary
186 hgignore syntax for Mercurial ignore files
186 hgignore syntax for Mercurial ignore files
187 hgweb Configuring hgweb
187 hgweb Configuring hgweb
188 merge-tools Merge Tools
188 merge-tools Merge Tools
189 multirevs Specifying Multiple Revisions
189 multirevs Specifying Multiple Revisions
190 patterns File Name Patterns
190 patterns File Name Patterns
191 revisions Specifying Single Revisions
191 revisions Specifying Single Revisions
192 revsets Specifying Revision Sets
192 revsets Specifying Revision Sets
193 subrepos Subrepositories
193 subrepos Subrepositories
194 templating Template Usage
194 templating Template Usage
195 urls URL Paths
195 urls URL Paths
196
196
197 Test short command list with verbose option
197 Test short command list with verbose option
198
198
199 $ hg -v help shortlist
199 $ hg -v help shortlist
200 Mercurial Distributed SCM (version *) (glob)
200 Mercurial Distributed SCM (version *) (glob)
201 (see http://mercurial.selenic.com for more information)
201 (see http://mercurial.selenic.com for more information)
202
202
203 Copyright (C) 2005-2011 Matt Mackall and others
203 Copyright (C) 2005-2011 Matt Mackall and others
204 This is free software; see the source for copying conditions. There is NO
204 This is free software; see the source for copying conditions. There is NO
205 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
205 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
206
206
207 basic commands:
207 basic commands:
208
208
209 add:
209 add:
210 add the specified files on the next commit
210 add the specified files on the next commit
211 annotate, blame:
211 annotate, blame:
212 show changeset information by line for each file
212 show changeset information by line for each file
213 clone:
213 clone:
214 make a copy of an existing repository
214 make a copy of an existing repository
215 commit, ci:
215 commit, ci:
216 commit the specified files or all outstanding changes
216 commit the specified files or all outstanding changes
217 diff:
217 diff:
218 diff repository (or selected files)
218 diff repository (or selected files)
219 export:
219 export:
220 dump the header and diffs for one or more changesets
220 dump the header and diffs for one or more changesets
221 forget:
221 forget:
222 forget the specified files on the next commit
222 forget the specified files on the next commit
223 init:
223 init:
224 create a new repository in the given directory
224 create a new repository in the given directory
225 log, history:
225 log, history:
226 show revision history of entire repository or files
226 show revision history of entire repository or files
227 merge:
227 merge:
228 merge working directory with another revision
228 merge working directory with another revision
229 pull:
229 pull:
230 pull changes from the specified source
230 pull changes from the specified source
231 push:
231 push:
232 push changes to the specified destination
232 push changes to the specified destination
233 remove, rm:
233 remove, rm:
234 remove the specified files on the next commit
234 remove the specified files on the next commit
235 serve:
235 serve:
236 start stand-alone webserver
236 start stand-alone webserver
237 status, st:
237 status, st:
238 show changed files in the working directory
238 show changed files in the working directory
239 summary, sum:
239 summary, sum:
240 summarize working directory state
240 summarize working directory state
241 update, up, checkout, co:
241 update, up, checkout, co:
242 update working directory (or switch revisions)
242 update working directory (or switch revisions)
243
243
244 global options:
244 global options:
245 -R --repository REPO repository root directory or name of overlay bundle
245 -R --repository REPO repository root directory or name of overlay bundle
246 file
246 file
247 --cwd DIR change working directory
247 --cwd DIR change working directory
248 -y --noninteractive do not prompt, assume 'yes' for any required answers
248 -y --noninteractive do not prompt, assume 'yes' for any required answers
249 -q --quiet suppress output
249 -q --quiet suppress output
250 -v --verbose enable additional output
250 -v --verbose enable additional output
251 --config CONFIG [+] set/override config option (use 'section.name=value')
251 --config CONFIG [+] set/override config option (use 'section.name=value')
252 --debug enable debugging output
252 --debug enable debugging output
253 --debugger start debugger
253 --debugger start debugger
254 --encoding ENCODE set the charset encoding (default: ascii)
254 --encoding ENCODE set the charset encoding (default: ascii)
255 --encodingmode MODE set the charset encoding mode (default: strict)
255 --encodingmode MODE set the charset encoding mode (default: strict)
256 --traceback always print a traceback on exception
256 --traceback always print a traceback on exception
257 --time time how long the command takes
257 --time time how long the command takes
258 --profile print command execution profile
258 --profile print command execution profile
259 --version output version information and exit
259 --version output version information and exit
260 -h --help display help and exit
260 -h --help display help and exit
261
261
262 [+] marked option can be specified multiple times
262 [+] marked option can be specified multiple times
263
263
264 use "hg help" for the full list of commands
264 use "hg help" for the full list of commands
265
265
266 $ hg add -h
266 $ hg add -h
267 hg add [OPTION]... [FILE]...
267 hg add [OPTION]... [FILE]...
268
268
269 add the specified files on the next commit
269 add the specified files on the next commit
270
270
271 Schedule files to be version controlled and added to the repository.
271 Schedule files to be version controlled and added to the repository.
272
272
273 The files will be added to the repository at the next commit. To undo an
273 The files will be added to the repository at the next commit. To undo an
274 add before that, see "hg forget".
274 add before that, see "hg forget".
275
275
276 If no names are given, add all files to the repository.
276 If no names are given, add all files to the repository.
277
277
278 Returns 0 if all files are successfully added.
278 Returns 0 if all files are successfully added.
279
279
280 use "hg -v help add" to show verbose help
280 use "hg -v help add" to show verbose help
281
281
282 options:
282 options:
283
283
284 -I --include PATTERN [+] include names matching the given patterns
284 -I --include PATTERN [+] include names matching the given patterns
285 -X --exclude PATTERN [+] exclude names matching the given patterns
285 -X --exclude PATTERN [+] exclude names matching the given patterns
286 -S --subrepos recurse into subrepositories
286 -S --subrepos recurse into subrepositories
287 -n --dry-run do not perform actions, just print output
287 -n --dry-run do not perform actions, just print output
288
288
289 [+] marked option can be specified multiple times
289 [+] marked option can be specified multiple times
290
290
291 use "hg -v help add" to show global options
291 use "hg -v help add" to show global options
292
292
293 Verbose help for add
293 Verbose help for add
294
294
295 $ hg add -hv
295 $ hg add -hv
296 hg add [OPTION]... [FILE]...
296 hg add [OPTION]... [FILE]...
297
297
298 add the specified files on the next commit
298 add the specified files on the next commit
299
299
300 Schedule files to be version controlled and added to the repository.
300 Schedule files to be version controlled and added to the repository.
301
301
302 The files will be added to the repository at the next commit. To undo an
302 The files will be added to the repository at the next commit. To undo an
303 add before that, see "hg forget".
303 add before that, see "hg forget".
304
304
305 If no names are given, add all files to the repository.
305 If no names are given, add all files to the repository.
306
306
307 An example showing how new (unknown) files are added automatically by "hg
307 An example showing how new (unknown) files are added automatically by "hg
308 add":
308 add":
309
309
310 $ ls
310 $ ls
311 foo.c
311 foo.c
312 $ hg status
312 $ hg status
313 ? foo.c
313 ? foo.c
314 $ hg add
314 $ hg add
315 adding foo.c
315 adding foo.c
316 $ hg status
316 $ hg status
317 A foo.c
317 A foo.c
318
318
319 Returns 0 if all files are successfully added.
319 Returns 0 if all files are successfully added.
320
320
321 options:
321 options:
322
322
323 -I --include PATTERN [+] include names matching the given patterns
323 -I --include PATTERN [+] include names matching the given patterns
324 -X --exclude PATTERN [+] exclude names matching the given patterns
324 -X --exclude PATTERN [+] exclude names matching the given patterns
325 -S --subrepos recurse into subrepositories
325 -S --subrepos recurse into subrepositories
326 -n --dry-run do not perform actions, just print output
326 -n --dry-run do not perform actions, just print output
327
327
328 global options:
328 global options:
329 -R --repository REPO repository root directory or name of overlay bundle
329 -R --repository REPO repository root directory or name of overlay bundle
330 file
330 file
331 --cwd DIR change working directory
331 --cwd DIR change working directory
332 -y --noninteractive do not prompt, assume 'yes' for any required
332 -y --noninteractive do not prompt, assume 'yes' for any required
333 answers
333 answers
334 -q --quiet suppress output
334 -q --quiet suppress output
335 -v --verbose enable additional output
335 -v --verbose enable additional output
336 --config CONFIG [+] set/override config option (use
336 --config CONFIG [+] set/override config option (use
337 'section.name=value')
337 'section.name=value')
338 --debug enable debugging output
338 --debug enable debugging output
339 --debugger start debugger
339 --debugger start debugger
340 --encoding ENCODE set the charset encoding (default: ascii)
340 --encoding ENCODE set the charset encoding (default: ascii)
341 --encodingmode MODE set the charset encoding mode (default: strict)
341 --encodingmode MODE set the charset encoding mode (default: strict)
342 --traceback always print a traceback on exception
342 --traceback always print a traceback on exception
343 --time time how long the command takes
343 --time time how long the command takes
344 --profile print command execution profile
344 --profile print command execution profile
345 --version output version information and exit
345 --version output version information and exit
346 -h --help display help and exit
346 -h --help display help and exit
347
347
348 [+] marked option can be specified multiple times
348 [+] marked option can be specified multiple times
349
349
350 Test help option with version option
350 Test help option with version option
351
351
352 $ hg add -h --version
352 $ hg add -h --version
353 Mercurial Distributed SCM (version *) (glob)
353 Mercurial Distributed SCM (version *) (glob)
354 (see http://mercurial.selenic.com for more information)
354 (see http://mercurial.selenic.com for more information)
355
355
356 Copyright (C) 2005-2011 Matt Mackall and others
356 Copyright (C) 2005-2011 Matt Mackall and others
357 This is free software; see the source for copying conditions. There is NO
357 This is free software; see the source for copying conditions. There is NO
358 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
358 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
359
359
360 hg add [OPTION]... [FILE]...
360 hg add [OPTION]... [FILE]...
361
361
362 add the specified files on the next commit
362 add the specified files on the next commit
363
363
364 Schedule files to be version controlled and added to the repository.
364 Schedule files to be version controlled and added to the repository.
365
365
366 The files will be added to the repository at the next commit. To undo an
366 The files will be added to the repository at the next commit. To undo an
367 add before that, see "hg forget".
367 add before that, see "hg forget".
368
368
369 If no names are given, add all files to the repository.
369 If no names are given, add all files to the repository.
370
370
371 Returns 0 if all files are successfully added.
371 Returns 0 if all files are successfully added.
372
372
373 use "hg -v help add" to show verbose help
373 use "hg -v help add" to show verbose help
374
374
375 options:
375 options:
376
376
377 -I --include PATTERN [+] include names matching the given patterns
377 -I --include PATTERN [+] include names matching the given patterns
378 -X --exclude PATTERN [+] exclude names matching the given patterns
378 -X --exclude PATTERN [+] exclude names matching the given patterns
379 -S --subrepos recurse into subrepositories
379 -S --subrepos recurse into subrepositories
380 -n --dry-run do not perform actions, just print output
380 -n --dry-run do not perform actions, just print output
381
381
382 [+] marked option can be specified multiple times
382 [+] marked option can be specified multiple times
383
383
384 use "hg -v help add" to show global options
384 use "hg -v help add" to show global options
385
385
386 $ hg add --skjdfks
386 $ hg add --skjdfks
387 hg add: option --skjdfks not recognized
387 hg add: option --skjdfks not recognized
388 hg add [OPTION]... [FILE]...
388 hg add [OPTION]... [FILE]...
389
389
390 add the specified files on the next commit
390 add the specified files on the next commit
391
391
392 options:
392 options:
393
393
394 -I --include PATTERN [+] include names matching the given patterns
394 -I --include PATTERN [+] include names matching the given patterns
395 -X --exclude PATTERN [+] exclude names matching the given patterns
395 -X --exclude PATTERN [+] exclude names matching the given patterns
396 -S --subrepos recurse into subrepositories
396 -S --subrepos recurse into subrepositories
397 -n --dry-run do not perform actions, just print output
397 -n --dry-run do not perform actions, just print output
398
398
399 [+] marked option can be specified multiple times
399 [+] marked option can be specified multiple times
400
400
401 use "hg help add" to show the full help text
401 use "hg help add" to show the full help text
402 [255]
402 [255]
403
403
404 Test ambiguous command help
404 Test ambiguous command help
405
405
406 $ hg help ad
406 $ hg help ad
407 list of commands:
407 list of commands:
408
408
409 add add the specified files on the next commit
409 add add the specified files on the next commit
410 addremove add all new files, delete all missing files
410 addremove add all new files, delete all missing files
411
411
412 use "hg -v help ad" to show builtin aliases and global options
412 use "hg -v help ad" to show builtin aliases and global options
413
413
414 Test command without options
414 Test command without options
415
415
416 $ hg help verify
416 $ hg help verify
417 hg verify
417 hg verify
418
418
419 verify the integrity of the repository
419 verify the integrity of the repository
420
420
421 Verify the integrity of the current repository.
421 Verify the integrity of the current repository.
422
422
423 This will perform an extensive check of the repository's integrity,
423 This will perform an extensive check of the repository's integrity,
424 validating the hashes and checksums of each entry in the changelog,
424 validating the hashes and checksums of each entry in the changelog,
425 manifest, and tracked files, as well as the integrity of their crosslinks
425 manifest, and tracked files, as well as the integrity of their crosslinks
426 and indices.
426 and indices.
427
427
428 Returns 0 on success, 1 if errors are encountered.
428 Returns 0 on success, 1 if errors are encountered.
429
429
430 use "hg -v help verify" to show global options
430 use "hg -v help verify" to show global options
431
431
432 $ hg help diff
432 $ hg help diff
433 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
433 hg diff [OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...
434
434
435 diff repository (or selected files)
435 diff repository (or selected files)
436
436
437 Show differences between revisions for the specified files.
437 Show differences between revisions for the specified files.
438
438
439 Differences between files are shown using the unified diff format.
439 Differences between files are shown using the unified diff format.
440
440
441 Note:
441 Note:
442 diff may generate unexpected results for merges, as it will default to
442 diff may generate unexpected results for merges, as it will default to
443 comparing against the working directory's first parent changeset if no
443 comparing against the working directory's first parent changeset if no
444 revisions are specified.
444 revisions are specified.
445
445
446 When two revision arguments are given, then changes are shown between
446 When two revision arguments are given, then changes are shown between
447 those revisions. If only one revision is specified then that revision is
447 those revisions. If only one revision is specified then that revision is
448 compared to the working directory, and, when no revisions are specified,
448 compared to the working directory, and, when no revisions are specified,
449 the working directory files are compared to its parent.
449 the working directory files are compared to its parent.
450
450
451 Alternatively you can specify -c/--change with a revision to see the
451 Alternatively you can specify -c/--change with a revision to see the
452 changes in that changeset relative to its first parent.
452 changes in that changeset relative to its first parent.
453
453
454 Without the -a/--text option, diff will avoid generating diffs of files it
454 Without the -a/--text option, diff will avoid generating diffs of files it
455 detects as binary. With -a, diff will generate a diff anyway, probably
455 detects as binary. With -a, diff will generate a diff anyway, probably
456 with undesirable results.
456 with undesirable results.
457
457
458 Use the -g/--git option to generate diffs in the git extended diff format.
458 Use the -g/--git option to generate diffs in the git extended diff format.
459 For more information, read "hg help diffs".
459 For more information, read "hg help diffs".
460
460
461 Returns 0 on success.
461 Returns 0 on success.
462
462
463 options:
463 options:
464
464
465 -r --rev REV [+] revision
465 -r --rev REV [+] revision
466 -c --change REV change made by revision
466 -c --change REV change made by revision
467 -a --text treat all files as text
467 -a --text treat all files as text
468 -g --git use git extended diff format
468 -g --git use git extended diff format
469 --nodates omit dates from diff headers
469 --nodates omit dates from diff headers
470 -p --show-function show which function each change is in
470 -p --show-function show which function each change is in
471 --reverse produce a diff that undoes the changes
471 --reverse produce a diff that undoes the changes
472 -w --ignore-all-space ignore white space when comparing lines
472 -w --ignore-all-space ignore white space when comparing lines
473 -b --ignore-space-change ignore changes in the amount of white space
473 -b --ignore-space-change ignore changes in the amount of white space
474 -B --ignore-blank-lines ignore changes whose lines are all blank
474 -B --ignore-blank-lines ignore changes whose lines are all blank
475 -U --unified NUM number of lines of context to show
475 -U --unified NUM number of lines of context to show
476 --stat output diffstat-style summary of changes
476 --stat output diffstat-style summary of changes
477 -I --include PATTERN [+] include names matching the given patterns
477 -I --include PATTERN [+] include names matching the given patterns
478 -X --exclude PATTERN [+] exclude names matching the given patterns
478 -X --exclude PATTERN [+] exclude names matching the given patterns
479 -S --subrepos recurse into subrepositories
479 -S --subrepos recurse into subrepositories
480
480
481 [+] marked option can be specified multiple times
481 [+] marked option can be specified multiple times
482
482
483 use "hg -v help diff" to show global options
483 use "hg -v help diff" to show global options
484
484
485 $ hg help status
485 $ hg help status
486 hg status [OPTION]... [FILE]...
486 hg status [OPTION]... [FILE]...
487
487
488 aliases: st
488 aliases: st
489
489
490 show changed files in the working directory
490 show changed files in the working directory
491
491
492 Show status of files in the repository. If names are given, only files
492 Show status of files in the repository. If names are given, only files
493 that match are shown. Files that are clean or ignored or the source of a
493 that match are shown. Files that are clean or ignored or the source of a
494 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
494 copy/move operation, are not listed unless -c/--clean, -i/--ignored,
495 -C/--copies or -A/--all are given. Unless options described with "show
495 -C/--copies or -A/--all are given. Unless options described with "show
496 only ..." are given, the options -mardu are used.
496 only ..." are given, the options -mardu are used.
497
497
498 Option -q/--quiet hides untracked (unknown and ignored) files unless
498 Option -q/--quiet hides untracked (unknown and ignored) files unless
499 explicitly requested with -u/--unknown or -i/--ignored.
499 explicitly requested with -u/--unknown or -i/--ignored.
500
500
501 Note:
501 Note:
502 status may appear to disagree with diff if permissions have changed or
502 status may appear to disagree with diff if permissions have changed or
503 a merge has occurred. The standard diff format does not report
503 a merge has occurred. The standard diff format does not report
504 permission changes and diff only reports changes relative to one merge
504 permission changes and diff only reports changes relative to one merge
505 parent.
505 parent.
506
506
507 If one revision is given, it is used as the base revision. If two
507 If one revision is given, it is used as the base revision. If two
508 revisions are given, the differences between them are shown. The --change
508 revisions are given, the differences between them are shown. The --change
509 option can also be used as a shortcut to list the changed files of a
509 option can also be used as a shortcut to list the changed files of a
510 revision from its first parent.
510 revision from its first parent.
511
511
512 The codes used to show the status of files are:
512 The codes used to show the status of files are:
513
513
514 M = modified
514 M = modified
515 A = added
515 A = added
516 R = removed
516 R = removed
517 C = clean
517 C = clean
518 ! = missing (deleted by non-hg command, but still tracked)
518 ! = missing (deleted by non-hg command, but still tracked)
519 ? = not tracked
519 ? = not tracked
520 I = ignored
520 I = ignored
521 = origin of the previous file listed as A (added)
521 = origin of the previous file listed as A (added)
522
522
523 Returns 0 on success.
523 Returns 0 on success.
524
524
525 options:
525 options:
526
526
527 -A --all show status of all files
527 -A --all show status of all files
528 -m --modified show only modified files
528 -m --modified show only modified files
529 -a --added show only added files
529 -a --added show only added files
530 -r --removed show only removed files
530 -r --removed show only removed files
531 -d --deleted show only deleted (but tracked) files
531 -d --deleted show only deleted (but tracked) files
532 -c --clean show only files without changes
532 -c --clean show only files without changes
533 -u --unknown show only unknown (not tracked) files
533 -u --unknown show only unknown (not tracked) files
534 -i --ignored show only ignored files
534 -i --ignored show only ignored files
535 -n --no-status hide status prefix
535 -n --no-status hide status prefix
536 -C --copies show source of copied files
536 -C --copies show source of copied files
537 -0 --print0 end filenames with NUL, for use with xargs
537 -0 --print0 end filenames with NUL, for use with xargs
538 --rev REV [+] show difference from revision
538 --rev REV [+] show difference from revision
539 --change REV list the changed files of a revision
539 --change REV list the changed files of a revision
540 -I --include PATTERN [+] include names matching the given patterns
540 -I --include PATTERN [+] include names matching the given patterns
541 -X --exclude PATTERN [+] exclude names matching the given patterns
541 -X --exclude PATTERN [+] exclude names matching the given patterns
542 -S --subrepos recurse into subrepositories
542 -S --subrepos recurse into subrepositories
543
543
544 [+] marked option can be specified multiple times
544 [+] marked option can be specified multiple times
545
545
546 use "hg -v help status" to show global options
546 use "hg -v help status" to show global options
547
547
548 $ hg -q help status
548 $ hg -q help status
549 hg status [OPTION]... [FILE]...
549 hg status [OPTION]... [FILE]...
550
550
551 show changed files in the working directory
551 show changed files in the working directory
552
552
553 $ hg help foo
553 $ hg help foo
554 hg: unknown command 'foo'
554 hg: unknown command 'foo'
555 Mercurial Distributed SCM
555 Mercurial Distributed SCM
556
556
557 basic commands:
557 basic commands:
558
558
559 add add the specified files on the next commit
559 add add the specified files on the next commit
560 annotate show changeset information by line for each file
560 annotate show changeset information by line for each file
561 clone make a copy of an existing repository
561 clone make a copy of an existing repository
562 commit commit the specified files or all outstanding changes
562 commit commit the specified files or all outstanding changes
563 diff diff repository (or selected files)
563 diff diff repository (or selected files)
564 export dump the header and diffs for one or more changesets
564 export dump the header and diffs for one or more changesets
565 forget forget the specified files on the next commit
565 forget forget the specified files on the next commit
566 init create a new repository in the given directory
566 init create a new repository in the given directory
567 log show revision history of entire repository or files
567 log show revision history of entire repository or files
568 merge merge working directory with another revision
568 merge merge working directory with another revision
569 pull pull changes from the specified source
569 pull pull changes from the specified source
570 push push changes to the specified destination
570 push push changes to the specified destination
571 remove remove the specified files on the next commit
571 remove remove the specified files on the next commit
572 serve start stand-alone webserver
572 serve start stand-alone webserver
573 status show changed files in the working directory
573 status show changed files in the working directory
574 summary summarize working directory state
574 summary summarize working directory state
575 update update working directory (or switch revisions)
575 update update working directory (or switch revisions)
576
576
577 use "hg help" for the full list of commands or "hg -v" for details
577 use "hg help" for the full list of commands or "hg -v" for details
578 [255]
578 [255]
579
579
580 $ hg skjdfks
580 $ hg skjdfks
581 hg: unknown command 'skjdfks'
581 hg: unknown command 'skjdfks'
582 Mercurial Distributed SCM
582 Mercurial Distributed SCM
583
583
584 basic commands:
584 basic commands:
585
585
586 add add the specified files on the next commit
586 add add the specified files on the next commit
587 annotate show changeset information by line for each file
587 annotate show changeset information by line for each file
588 clone make a copy of an existing repository
588 clone make a copy of an existing repository
589 commit commit the specified files or all outstanding changes
589 commit commit the specified files or all outstanding changes
590 diff diff repository (or selected files)
590 diff diff repository (or selected files)
591 export dump the header and diffs for one or more changesets
591 export dump the header and diffs for one or more changesets
592 forget forget the specified files on the next commit
592 forget forget the specified files on the next commit
593 init create a new repository in the given directory
593 init create a new repository in the given directory
594 log show revision history of entire repository or files
594 log show revision history of entire repository or files
595 merge merge working directory with another revision
595 merge merge working directory with another revision
596 pull pull changes from the specified source
596 pull pull changes from the specified source
597 push push changes to the specified destination
597 push push changes to the specified destination
598 remove remove the specified files on the next commit
598 remove remove the specified files on the next commit
599 serve start stand-alone webserver
599 serve start stand-alone webserver
600 status show changed files in the working directory
600 status show changed files in the working directory
601 summary summarize working directory state
601 summary summarize working directory state
602 update update working directory (or switch revisions)
602 update update working directory (or switch revisions)
603
603
604 use "hg help" for the full list of commands or "hg -v" for details
604 use "hg help" for the full list of commands or "hg -v" for details
605 [255]
605 [255]
606
606
607 $ cat > helpext.py <<EOF
607 $ cat > helpext.py <<EOF
608 > import os
608 > import os
609 > from mercurial import commands
609 > from mercurial import commands
610 >
610 >
611 > def nohelp(ui, *args, **kwargs):
611 > def nohelp(ui, *args, **kwargs):
612 > pass
612 > pass
613 >
613 >
614 > cmdtable = {
614 > cmdtable = {
615 > "nohelp": (nohelp, [], "hg nohelp"),
615 > "nohelp": (nohelp, [], "hg nohelp"),
616 > }
616 > }
617 >
617 >
618 > commands.norepo += ' nohelp'
618 > commands.norepo += ' nohelp'
619 > EOF
619 > EOF
620 $ echo '[extensions]' >> $HGRCPATH
620 $ echo '[extensions]' >> $HGRCPATH
621 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
621 $ echo "helpext = `pwd`/helpext.py" >> $HGRCPATH
622
622
623 Test command with no help text
623 Test command with no help text
624
624
625 $ hg help nohelp
625 $ hg help nohelp
626 hg nohelp
626 hg nohelp
627
627
628 (no help text available)
628 (no help text available)
629
629
630 use "hg -v help nohelp" to show global options
630 use "hg -v help nohelp" to show global options
631
631
632 Test that default list of commands omits extension commands
632 Test that default list of commands omits extension commands
633
633
634 $ hg help
634 $ hg help
635 Mercurial Distributed SCM
635 Mercurial Distributed SCM
636
636
637 list of commands:
637 list of commands:
638
638
639 add add the specified files on the next commit
639 add add the specified files on the next commit
640 addremove add all new files, delete all missing files
640 addremove add all new files, delete all missing files
641 annotate show changeset information by line for each file
641 annotate show changeset information by line for each file
642 archive create an unversioned archive of a repository revision
642 archive create an unversioned archive of a repository revision
643 backout reverse effect of earlier changeset
643 backout reverse effect of earlier changeset
644 bisect subdivision search of changesets
644 bisect subdivision search of changesets
645 bookmarks track a line of development with movable markers
645 bookmarks track a line of development with movable markers
646 branch set or show the current branch name
646 branch set or show the current branch name
647 branches list repository named branches
647 branches list repository named branches
648 bundle create a changegroup file
648 bundle create a changegroup file
649 cat output the current or given revision of files
649 cat output the current or given revision of files
650 clone make a copy of an existing repository
650 clone make a copy of an existing repository
651 commit commit the specified files or all outstanding changes
651 commit commit the specified files or all outstanding changes
652 copy mark files as copied for the next commit
652 copy mark files as copied for the next commit
653 diff diff repository (or selected files)
653 diff diff repository (or selected files)
654 export dump the header and diffs for one or more changesets
654 export dump the header and diffs for one or more changesets
655 forget forget the specified files on the next commit
655 forget forget the specified files on the next commit
656 grep search for a pattern in specified files and revisions
656 grep search for a pattern in specified files and revisions
657 heads show current repository heads or show branch heads
657 heads show current repository heads or show branch heads
658 help show help for a given topic or a help overview
658 help show help for a given topic or a help overview
659 identify identify the working copy or specified revision
659 identify identify the working copy or specified revision
660 import import an ordered set of patches
660 import import an ordered set of patches
661 incoming show new changesets found in source
661 incoming show new changesets found in source
662 init create a new repository in the given directory
662 init create a new repository in the given directory
663 locate locate files matching specific patterns
663 locate locate files matching specific patterns
664 log show revision history of entire repository or files
664 log show revision history of entire repository or files
665 manifest output the current or given revision of the project manifest
665 manifest output the current or given revision of the project manifest
666 merge merge working directory with another revision
666 merge merge working directory with another revision
667 outgoing show changesets not found in the destination
667 outgoing show changesets not found in the destination
668 parents show the parents of the working directory or revision
668 parents show the parents of the working directory or revision
669 paths show aliases for remote repositories
669 paths show aliases for remote repositories
670 pull pull changes from the specified source
670 pull pull changes from the specified source
671 push push changes to the specified destination
671 push push changes to the specified destination
672 recover roll back an interrupted transaction
672 recover roll back an interrupted transaction
673 remove remove the specified files on the next commit
673 remove remove the specified files on the next commit
674 rename rename files; equivalent of copy + remove
674 rename rename files; equivalent of copy + remove
675 resolve redo merges or set/view the merge status of files
675 resolve redo merges or set/view the merge status of files
676 revert restore individual files or directories to an earlier state
676 revert restore files to their checkout state
677 rollback roll back the last transaction (dangerous)
677 rollback roll back the last transaction (dangerous)
678 root print the root (top) of the current working directory
678 root print the root (top) of the current working directory
679 serve start stand-alone webserver
679 serve start stand-alone webserver
680 showconfig show combined config settings from all hgrc files
680 showconfig show combined config settings from all hgrc files
681 status show changed files in the working directory
681 status show changed files in the working directory
682 summary summarize working directory state
682 summary summarize working directory state
683 tag add one or more tags for the current or given revision
683 tag add one or more tags for the current or given revision
684 tags list repository tags
684 tags list repository tags
685 tip show the tip revision
685 tip show the tip revision
686 unbundle apply one or more changegroup files
686 unbundle apply one or more changegroup files
687 update update working directory (or switch revisions)
687 update update working directory (or switch revisions)
688 verify verify the integrity of the repository
688 verify verify the integrity of the repository
689 version output version and copyright information
689 version output version and copyright information
690
690
691 enabled extensions:
691 enabled extensions:
692
692
693 helpext (no help text available)
693 helpext (no help text available)
694
694
695 additional help topics:
695 additional help topics:
696
696
697 config Configuration Files
697 config Configuration Files
698 dates Date Formats
698 dates Date Formats
699 diffs Diff Formats
699 diffs Diff Formats
700 environment Environment Variables
700 environment Environment Variables
701 extensions Using additional features
701 extensions Using additional features
702 glossary Glossary
702 glossary Glossary
703 hgignore syntax for Mercurial ignore files
703 hgignore syntax for Mercurial ignore files
704 hgweb Configuring hgweb
704 hgweb Configuring hgweb
705 merge-tools Merge Tools
705 merge-tools Merge Tools
706 multirevs Specifying Multiple Revisions
706 multirevs Specifying Multiple Revisions
707 patterns File Name Patterns
707 patterns File Name Patterns
708 revisions Specifying Single Revisions
708 revisions Specifying Single Revisions
709 revsets Specifying Revision Sets
709 revsets Specifying Revision Sets
710 subrepos Subrepositories
710 subrepos Subrepositories
711 templating Template Usage
711 templating Template Usage
712 urls URL Paths
712 urls URL Paths
713
713
714 use "hg -v help" to show builtin aliases and global options
714 use "hg -v help" to show builtin aliases and global options
715
715
716
716
717
717
718 Test list of commands with command with no help text
718 Test list of commands with command with no help text
719
719
720 $ hg help helpext
720 $ hg help helpext
721 helpext extension - no help text available
721 helpext extension - no help text available
722
722
723 list of commands:
723 list of commands:
724
724
725 nohelp (no help text available)
725 nohelp (no help text available)
726
726
727 use "hg -v help helpext" to show builtin aliases and global options
727 use "hg -v help helpext" to show builtin aliases and global options
728
728
729 Test a help topic
729 Test a help topic
730
730
731 $ hg help revs
731 $ hg help revs
732 Specifying Single Revisions
732 Specifying Single Revisions
733
733
734 Mercurial supports several ways to specify individual revisions.
734 Mercurial supports several ways to specify individual revisions.
735
735
736 A plain integer is treated as a revision number. Negative integers are
736 A plain integer is treated as a revision number. Negative integers are
737 treated as sequential offsets from the tip, with -1 denoting the tip, -2
737 treated as sequential offsets from the tip, with -1 denoting the tip, -2
738 denoting the revision prior to the tip, and so forth.
738 denoting the revision prior to the tip, and so forth.
739
739
740 A 40-digit hexadecimal string is treated as a unique revision identifier.
740 A 40-digit hexadecimal string is treated as a unique revision identifier.
741
741
742 A hexadecimal string less than 40 characters long is treated as a unique
742 A hexadecimal string less than 40 characters long is treated as a unique
743 revision identifier and is referred to as a short-form identifier. A
743 revision identifier and is referred to as a short-form identifier. A
744 short-form identifier is only valid if it is the prefix of exactly one
744 short-form identifier is only valid if it is the prefix of exactly one
745 full-length identifier.
745 full-length identifier.
746
746
747 Any other string is treated as a tag or branch name. A tag name is a
747 Any other string is treated as a tag or branch name. A tag name is a
748 symbolic name associated with a revision identifier. A branch name denotes
748 symbolic name associated with a revision identifier. A branch name denotes
749 the tipmost revision of that branch. Tag and branch names must not contain
749 the tipmost revision of that branch. Tag and branch names must not contain
750 the ":" character.
750 the ":" character.
751
751
752 The reserved name "tip" is a special tag that always identifies the most
752 The reserved name "tip" is a special tag that always identifies the most
753 recent revision.
753 recent revision.
754
754
755 The reserved name "null" indicates the null revision. This is the revision
755 The reserved name "null" indicates the null revision. This is the revision
756 of an empty repository, and the parent of revision 0.
756 of an empty repository, and the parent of revision 0.
757
757
758 The reserved name "." indicates the working directory parent. If no
758 The reserved name "." indicates the working directory parent. If no
759 working directory is checked out, it is equivalent to null. If an
759 working directory is checked out, it is equivalent to null. If an
760 uncommitted merge is in progress, "." is the revision of the first parent.
760 uncommitted merge is in progress, "." is the revision of the first parent.
761
761
762 Test templating help
762 Test templating help
763
763
764 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
764 $ hg help templating | egrep '(desc|diffstat|firstline|nonempty) '
765 desc String. The text of the changeset description.
765 desc String. The text of the changeset description.
766 diffstat String. Statistics of changes with the following format:
766 diffstat String. Statistics of changes with the following format:
767 firstline Any text. Returns the first line of text.
767 firstline Any text. Returns the first line of text.
768 nonempty Any text. Returns '(none)' if the string is empty.
768 nonempty Any text. Returns '(none)' if the string is empty.
769
769
770 Test help hooks
770 Test help hooks
771
771
772 $ cat > helphook1.py <<EOF
772 $ cat > helphook1.py <<EOF
773 > from mercurial import help
773 > from mercurial import help
774 >
774 >
775 > def rewrite(topic, doc):
775 > def rewrite(topic, doc):
776 > return doc + '\nhelphook1\n'
776 > return doc + '\nhelphook1\n'
777 >
777 >
778 > def extsetup(ui):
778 > def extsetup(ui):
779 > help.addtopichook('revsets', rewrite)
779 > help.addtopichook('revsets', rewrite)
780 > EOF
780 > EOF
781 $ cat > helphook2.py <<EOF
781 $ cat > helphook2.py <<EOF
782 > from mercurial import help
782 > from mercurial import help
783 >
783 >
784 > def rewrite(topic, doc):
784 > def rewrite(topic, doc):
785 > return doc + '\nhelphook2\n'
785 > return doc + '\nhelphook2\n'
786 >
786 >
787 > def extsetup(ui):
787 > def extsetup(ui):
788 > help.addtopichook('revsets', rewrite)
788 > help.addtopichook('revsets', rewrite)
789 > EOF
789 > EOF
790 $ echo '[extensions]' >> $HGRCPATH
790 $ echo '[extensions]' >> $HGRCPATH
791 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
791 $ echo "helphook1 = `pwd`/helphook1.py" >> $HGRCPATH
792 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
792 $ echo "helphook2 = `pwd`/helphook2.py" >> $HGRCPATH
793 $ hg help revsets | grep helphook
793 $ hg help revsets | grep helphook
794 helphook1
794 helphook1
795 helphook2
795 helphook2
General Comments 0
You need to be logged in to leave comments. Login now