##// END OF EJS Templates
backout: deprecate/hide support for backing out merges...
Matt Mackall -
r15211:1209de02 default
parent child Browse files
Show More
@@ -1,5469 +1,5469 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, url, encoding, templatekw, discovery
13 import patch, help, url, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, hbisect
14 import archival, changegroup, cmdutil, hbisect
15 import sshserver, hgweb, hgweb.server, commandserver
15 import sshserver, hgweb, hgweb.server, commandserver
16 import merge as mergemod
16 import merge as mergemod
17 import minirst, revset, fileset
17 import minirst, revset, fileset
18 import dagparser, context, simplemerge
18 import dagparser, context, simplemerge
19 import random, setdiscovery, treediscovery, dagutil
19 import random, setdiscovery, treediscovery, dagutil
20
20
21 table = {}
21 table = {}
22
22
23 command = cmdutil.command(table)
23 command = cmdutil.command(table)
24
24
25 # common command options
25 # common command options
26
26
27 globalopts = [
27 globalopts = [
28 ('R', 'repository', '',
28 ('R', 'repository', '',
29 _('repository root directory or name of overlay bundle file'),
29 _('repository root directory or name of overlay bundle file'),
30 _('REPO')),
30 _('REPO')),
31 ('', 'cwd', '',
31 ('', 'cwd', '',
32 _('change working directory'), _('DIR')),
32 _('change working directory'), _('DIR')),
33 ('y', 'noninteractive', None,
33 ('y', 'noninteractive', None,
34 _('do not prompt, automatically pick the first choice for all prompts')),
34 _('do not prompt, automatically pick the first choice for all prompts')),
35 ('q', 'quiet', None, _('suppress output')),
35 ('q', 'quiet', None, _('suppress output')),
36 ('v', 'verbose', None, _('enable additional output')),
36 ('v', 'verbose', None, _('enable additional output')),
37 ('', 'config', [],
37 ('', 'config', [],
38 _('set/override config option (use \'section.name=value\')'),
38 _('set/override config option (use \'section.name=value\')'),
39 _('CONFIG')),
39 _('CONFIG')),
40 ('', 'debug', None, _('enable debugging output')),
40 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debugger', None, _('start debugger')),
41 ('', 'debugger', None, _('start debugger')),
42 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 _('ENCODE')),
43 _('ENCODE')),
44 ('', 'encodingmode', encoding.encodingmode,
44 ('', 'encodingmode', encoding.encodingmode,
45 _('set the charset encoding mode'), _('MODE')),
45 _('set the charset encoding mode'), _('MODE')),
46 ('', 'traceback', None, _('always print a traceback on exception')),
46 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'time', None, _('time how long the command takes')),
47 ('', 'time', None, _('time how long the command takes')),
48 ('', 'profile', None, _('print command execution profile')),
48 ('', 'profile', None, _('print command execution profile')),
49 ('', 'version', None, _('output version information and exit')),
49 ('', 'version', None, _('output version information and exit')),
50 ('h', 'help', None, _('display help and exit')),
50 ('h', 'help', None, _('display help and exit')),
51 ]
51 ]
52
52
53 dryrunopts = [('n', 'dry-run', None,
53 dryrunopts = [('n', 'dry-run', None,
54 _('do not perform actions, just print output'))]
54 _('do not perform actions, just print output'))]
55
55
56 remoteopts = [
56 remoteopts = [
57 ('e', 'ssh', '',
57 ('e', 'ssh', '',
58 _('specify ssh command to use'), _('CMD')),
58 _('specify ssh command to use'), _('CMD')),
59 ('', 'remotecmd', '',
59 ('', 'remotecmd', '',
60 _('specify hg command to run on the remote side'), _('CMD')),
60 _('specify hg command to run on the remote side'), _('CMD')),
61 ('', 'insecure', None,
61 ('', 'insecure', None,
62 _('do not verify server certificate (ignoring web.cacerts config)')),
62 _('do not verify server certificate (ignoring web.cacerts config)')),
63 ]
63 ]
64
64
65 walkopts = [
65 walkopts = [
66 ('I', 'include', [],
66 ('I', 'include', [],
67 _('include names matching the given patterns'), _('PATTERN')),
67 _('include names matching the given patterns'), _('PATTERN')),
68 ('X', 'exclude', [],
68 ('X', 'exclude', [],
69 _('exclude names matching the given patterns'), _('PATTERN')),
69 _('exclude names matching the given patterns'), _('PATTERN')),
70 ]
70 ]
71
71
72 commitopts = [
72 commitopts = [
73 ('m', 'message', '',
73 ('m', 'message', '',
74 _('use text as commit message'), _('TEXT')),
74 _('use text as commit message'), _('TEXT')),
75 ('l', 'logfile', '',
75 ('l', 'logfile', '',
76 _('read commit message from file'), _('FILE')),
76 _('read commit message from file'), _('FILE')),
77 ]
77 ]
78
78
79 commitopts2 = [
79 commitopts2 = [
80 ('d', 'date', '',
80 ('d', 'date', '',
81 _('record the specified date as commit date'), _('DATE')),
81 _('record the specified date as commit date'), _('DATE')),
82 ('u', 'user', '',
82 ('u', 'user', '',
83 _('record the specified user as committer'), _('USER')),
83 _('record the specified user as committer'), _('USER')),
84 ]
84 ]
85
85
86 templateopts = [
86 templateopts = [
87 ('', 'style', '',
87 ('', 'style', '',
88 _('display using template map file'), _('STYLE')),
88 _('display using template map file'), _('STYLE')),
89 ('', 'template', '',
89 ('', 'template', '',
90 _('display with template'), _('TEMPLATE')),
90 _('display with template'), _('TEMPLATE')),
91 ]
91 ]
92
92
93 logopts = [
93 logopts = [
94 ('p', 'patch', None, _('show patch')),
94 ('p', 'patch', None, _('show patch')),
95 ('g', 'git', None, _('use git extended diff format')),
95 ('g', 'git', None, _('use git extended diff format')),
96 ('l', 'limit', '',
96 ('l', 'limit', '',
97 _('limit number of changes displayed'), _('NUM')),
97 _('limit number of changes displayed'), _('NUM')),
98 ('M', 'no-merges', None, _('do not show merges')),
98 ('M', 'no-merges', None, _('do not show merges')),
99 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ] + templateopts
100 ] + templateopts
101
101
102 diffopts = [
102 diffopts = [
103 ('a', 'text', None, _('treat all files as text')),
103 ('a', 'text', None, _('treat all files as text')),
104 ('g', 'git', None, _('use git extended diff format')),
104 ('g', 'git', None, _('use git extended diff format')),
105 ('', 'nodates', None, _('omit dates from diff headers'))
105 ('', 'nodates', None, _('omit dates from diff headers'))
106 ]
106 ]
107
107
108 diffopts2 = [
108 diffopts2 = [
109 ('p', 'show-function', None, _('show which function each change is in')),
109 ('p', 'show-function', None, _('show which function each change is in')),
110 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 ('', 'reverse', None, _('produce a diff that undoes the changes')),
111 ('w', 'ignore-all-space', None,
111 ('w', 'ignore-all-space', None,
112 _('ignore white space when comparing lines')),
112 _('ignore white space when comparing lines')),
113 ('b', 'ignore-space-change', None,
113 ('b', 'ignore-space-change', None,
114 _('ignore changes in the amount of white space')),
114 _('ignore changes in the amount of white space')),
115 ('B', 'ignore-blank-lines', None,
115 ('B', 'ignore-blank-lines', None,
116 _('ignore changes whose lines are all blank')),
116 _('ignore changes whose lines are all blank')),
117 ('U', 'unified', '',
117 ('U', 'unified', '',
118 _('number of lines of context to show'), _('NUM')),
118 _('number of lines of context to show'), _('NUM')),
119 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ('', 'stat', None, _('output diffstat-style summary of changes')),
120 ]
120 ]
121
121
122 mergetoolopts = [
122 mergetoolopts = [
123 ('t', 'tool', '', _('specify merge tool')),
123 ('t', 'tool', '', _('specify merge tool')),
124 ]
124 ]
125
125
126 similarityopts = [
126 similarityopts = [
127 ('s', 'similarity', '',
127 ('s', 'similarity', '',
128 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
128 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
129 ]
129 ]
130
130
131 subrepoopts = [
131 subrepoopts = [
132 ('S', 'subrepos', None,
132 ('S', 'subrepos', None,
133 _('recurse into subrepositories'))
133 _('recurse into subrepositories'))
134 ]
134 ]
135
135
136 # Commands start here, listed alphabetically
136 # Commands start here, listed alphabetically
137
137
138 @command('^add',
138 @command('^add',
139 walkopts + subrepoopts + dryrunopts,
139 walkopts + subrepoopts + dryrunopts,
140 _('[OPTION]... [FILE]...'))
140 _('[OPTION]... [FILE]...'))
141 def add(ui, repo, *pats, **opts):
141 def add(ui, repo, *pats, **opts):
142 """add the specified files on the next commit
142 """add the specified files on the next commit
143
143
144 Schedule files to be version controlled and added to the
144 Schedule files to be version controlled and added to the
145 repository.
145 repository.
146
146
147 The files will be added to the repository at the next commit. To
147 The files will be added to the repository at the next commit. To
148 undo an add before that, see :hg:`forget`.
148 undo an add before that, see :hg:`forget`.
149
149
150 If no names are given, add all files to the repository.
150 If no names are given, add all files to the repository.
151
151
152 .. container:: verbose
152 .. container:: verbose
153
153
154 An example showing how new (unknown) files are added
154 An example showing how new (unknown) files are added
155 automatically by :hg:`add`::
155 automatically by :hg:`add`::
156
156
157 $ ls
157 $ ls
158 foo.c
158 foo.c
159 $ hg status
159 $ hg status
160 ? foo.c
160 ? foo.c
161 $ hg add
161 $ hg add
162 adding foo.c
162 adding foo.c
163 $ hg status
163 $ hg status
164 A foo.c
164 A foo.c
165
165
166 Returns 0 if all files are successfully added.
166 Returns 0 if all files are successfully added.
167 """
167 """
168
168
169 m = scmutil.match(repo[None], pats, opts)
169 m = scmutil.match(repo[None], pats, opts)
170 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
170 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
171 opts.get('subrepos'), prefix="")
171 opts.get('subrepos'), prefix="")
172 return rejected and 1 or 0
172 return rejected and 1 or 0
173
173
174 @command('addremove',
174 @command('addremove',
175 similarityopts + walkopts + dryrunopts,
175 similarityopts + walkopts + dryrunopts,
176 _('[OPTION]... [FILE]...'))
176 _('[OPTION]... [FILE]...'))
177 def addremove(ui, repo, *pats, **opts):
177 def addremove(ui, repo, *pats, **opts):
178 """add all new files, delete all missing files
178 """add all new files, delete all missing files
179
179
180 Add all new files and remove all missing files from the
180 Add all new files and remove all missing files from the
181 repository.
181 repository.
182
182
183 New files are ignored if they match any of the patterns in
183 New files are ignored if they match any of the patterns in
184 ``.hgignore``. As with add, these changes take effect at the next
184 ``.hgignore``. As with add, these changes take effect at the next
185 commit.
185 commit.
186
186
187 Use the -s/--similarity option to detect renamed files. With a
187 Use the -s/--similarity option to detect renamed files. With a
188 parameter greater than 0, this compares every removed file with
188 parameter greater than 0, this compares every removed file with
189 every added file and records those similar enough as renames. This
189 every added file and records those similar enough as renames. This
190 option takes a percentage between 0 (disabled) and 100 (files must
190 option takes a percentage between 0 (disabled) and 100 (files must
191 be identical) as its parameter. Detecting renamed files this way
191 be identical) as its parameter. Detecting renamed files this way
192 can be expensive. After using this option, :hg:`status -C` can be
192 can be expensive. After using this option, :hg:`status -C` can be
193 used to check which files were identified as moved or renamed.
193 used to check which files were identified as moved or renamed.
194
194
195 Returns 0 if all files are successfully added.
195 Returns 0 if all files are successfully added.
196 """
196 """
197 try:
197 try:
198 sim = float(opts.get('similarity') or 100)
198 sim = float(opts.get('similarity') or 100)
199 except ValueError:
199 except ValueError:
200 raise util.Abort(_('similarity must be a number'))
200 raise util.Abort(_('similarity must be a number'))
201 if sim < 0 or sim > 100:
201 if sim < 0 or sim > 100:
202 raise util.Abort(_('similarity must be between 0 and 100'))
202 raise util.Abort(_('similarity must be between 0 and 100'))
203 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
203 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
204
204
205 @command('^annotate|blame',
205 @command('^annotate|blame',
206 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
206 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
207 ('', 'follow', None,
207 ('', 'follow', None,
208 _('follow copies/renames and list the filename (DEPRECATED)')),
208 _('follow copies/renames and list the filename (DEPRECATED)')),
209 ('', 'no-follow', None, _("don't follow copies and renames")),
209 ('', 'no-follow', None, _("don't follow copies and renames")),
210 ('a', 'text', None, _('treat all files as text')),
210 ('a', 'text', None, _('treat all files as text')),
211 ('u', 'user', None, _('list the author (long with -v)')),
211 ('u', 'user', None, _('list the author (long with -v)')),
212 ('f', 'file', None, _('list the filename')),
212 ('f', 'file', None, _('list the filename')),
213 ('d', 'date', None, _('list the date (short with -q)')),
213 ('d', 'date', None, _('list the date (short with -q)')),
214 ('n', 'number', None, _('list the revision number (default)')),
214 ('n', 'number', None, _('list the revision number (default)')),
215 ('c', 'changeset', None, _('list the changeset')),
215 ('c', 'changeset', None, _('list the changeset')),
216 ('l', 'line-number', None, _('show line number at the first appearance'))
216 ('l', 'line-number', None, _('show line number at the first appearance'))
217 ] + walkopts,
217 ] + walkopts,
218 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
218 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
219 def annotate(ui, repo, *pats, **opts):
219 def annotate(ui, repo, *pats, **opts):
220 """show changeset information by line for each file
220 """show changeset information by line for each file
221
221
222 List changes in files, showing the revision id responsible for
222 List changes in files, showing the revision id responsible for
223 each line
223 each line
224
224
225 This command is useful for discovering when a change was made and
225 This command is useful for discovering when a change was made and
226 by whom.
226 by whom.
227
227
228 Without the -a/--text option, annotate will avoid processing files
228 Without the -a/--text option, annotate will avoid processing files
229 it detects as binary. With -a, annotate will annotate the file
229 it detects as binary. With -a, annotate will annotate the file
230 anyway, although the results will probably be neither useful
230 anyway, although the results will probably be neither useful
231 nor desirable.
231 nor desirable.
232
232
233 Returns 0 on success.
233 Returns 0 on success.
234 """
234 """
235 if opts.get('follow'):
235 if opts.get('follow'):
236 # --follow is deprecated and now just an alias for -f/--file
236 # --follow is deprecated and now just an alias for -f/--file
237 # to mimic the behavior of Mercurial before version 1.5
237 # to mimic the behavior of Mercurial before version 1.5
238 opts['file'] = True
238 opts['file'] = True
239
239
240 datefunc = ui.quiet and util.shortdate or util.datestr
240 datefunc = ui.quiet and util.shortdate or util.datestr
241 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
241 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
242
242
243 if not pats:
243 if not pats:
244 raise util.Abort(_('at least one filename or pattern is required'))
244 raise util.Abort(_('at least one filename or pattern is required'))
245
245
246 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
246 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
247 ('number', ' ', lambda x: str(x[0].rev())),
247 ('number', ' ', lambda x: str(x[0].rev())),
248 ('changeset', ' ', lambda x: short(x[0].node())),
248 ('changeset', ' ', lambda x: short(x[0].node())),
249 ('date', ' ', getdate),
249 ('date', ' ', getdate),
250 ('file', ' ', lambda x: x[0].path()),
250 ('file', ' ', lambda x: x[0].path()),
251 ('line_number', ':', lambda x: str(x[1])),
251 ('line_number', ':', lambda x: str(x[1])),
252 ]
252 ]
253
253
254 if (not opts.get('user') and not opts.get('changeset')
254 if (not opts.get('user') and not opts.get('changeset')
255 and not opts.get('date') and not opts.get('file')):
255 and not opts.get('date') and not opts.get('file')):
256 opts['number'] = True
256 opts['number'] = True
257
257
258 linenumber = opts.get('line_number') is not None
258 linenumber = opts.get('line_number') is not None
259 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
259 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
260 raise util.Abort(_('at least one of -n/-c is required for -l'))
260 raise util.Abort(_('at least one of -n/-c is required for -l'))
261
261
262 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
262 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
263 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
263 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
264
264
265 def bad(x, y):
265 def bad(x, y):
266 raise util.Abort("%s: %s" % (x, y))
266 raise util.Abort("%s: %s" % (x, y))
267
267
268 ctx = scmutil.revsingle(repo, opts.get('rev'))
268 ctx = scmutil.revsingle(repo, opts.get('rev'))
269 m = scmutil.match(ctx, pats, opts)
269 m = scmutil.match(ctx, pats, opts)
270 m.bad = bad
270 m.bad = bad
271 follow = not opts.get('no_follow')
271 follow = not opts.get('no_follow')
272 for abs in ctx.walk(m):
272 for abs in ctx.walk(m):
273 fctx = ctx[abs]
273 fctx = ctx[abs]
274 if not opts.get('text') and util.binary(fctx.data()):
274 if not opts.get('text') and util.binary(fctx.data()):
275 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
275 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
276 continue
276 continue
277
277
278 lines = fctx.annotate(follow=follow, linenumber=linenumber)
278 lines = fctx.annotate(follow=follow, linenumber=linenumber)
279 pieces = []
279 pieces = []
280
280
281 for f, sep in funcmap:
281 for f, sep in funcmap:
282 l = [f(n) for n, dummy in lines]
282 l = [f(n) for n, dummy in lines]
283 if l:
283 if l:
284 sized = [(x, encoding.colwidth(x)) for x in l]
284 sized = [(x, encoding.colwidth(x)) for x in l]
285 ml = max([w for x, w in sized])
285 ml = max([w for x, w in sized])
286 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
286 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
287 for x, w in sized])
287 for x, w in sized])
288
288
289 if pieces:
289 if pieces:
290 for p, l in zip(zip(*pieces), lines):
290 for p, l in zip(zip(*pieces), lines):
291 ui.write("%s: %s" % ("".join(p), l[1]))
291 ui.write("%s: %s" % ("".join(p), l[1]))
292
292
293 @command('archive',
293 @command('archive',
294 [('', 'no-decode', None, _('do not pass files through decoders')),
294 [('', 'no-decode', None, _('do not pass files through decoders')),
295 ('p', 'prefix', '', _('directory prefix for files in archive'),
295 ('p', 'prefix', '', _('directory prefix for files in archive'),
296 _('PREFIX')),
296 _('PREFIX')),
297 ('r', 'rev', '', _('revision to distribute'), _('REV')),
297 ('r', 'rev', '', _('revision to distribute'), _('REV')),
298 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
298 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
299 ] + subrepoopts + walkopts,
299 ] + subrepoopts + walkopts,
300 _('[OPTION]... DEST'))
300 _('[OPTION]... DEST'))
301 def archive(ui, repo, dest, **opts):
301 def archive(ui, repo, dest, **opts):
302 '''create an unversioned archive of a repository revision
302 '''create an unversioned archive of a repository revision
303
303
304 By default, the revision used is the parent of the working
304 By default, the revision used is the parent of the working
305 directory; use -r/--rev to specify a different revision.
305 directory; use -r/--rev to specify a different revision.
306
306
307 The archive type is automatically detected based on file
307 The archive type is automatically detected based on file
308 extension (or override using -t/--type).
308 extension (or override using -t/--type).
309
309
310 .. container:: verbose
310 .. container:: verbose
311
311
312 Examples:
312 Examples:
313
313
314 - create a zip file containing the 1.0 release::
314 - create a zip file containing the 1.0 release::
315
315
316 hg archive -r 1.0 project-1.0.zip
316 hg archive -r 1.0 project-1.0.zip
317
317
318 - create a tarball excluding .hg files::
318 - create a tarball excluding .hg files::
319
319
320 hg archive project.tar.gz -X ".hg*"
320 hg archive project.tar.gz -X ".hg*"
321
321
322 Valid types are:
322 Valid types are:
323
323
324 :``files``: a directory full of files (default)
324 :``files``: a directory full of files (default)
325 :``tar``: tar archive, uncompressed
325 :``tar``: tar archive, uncompressed
326 :``tbz2``: tar archive, compressed using bzip2
326 :``tbz2``: tar archive, compressed using bzip2
327 :``tgz``: tar archive, compressed using gzip
327 :``tgz``: tar archive, compressed using gzip
328 :``uzip``: zip archive, uncompressed
328 :``uzip``: zip archive, uncompressed
329 :``zip``: zip archive, compressed using deflate
329 :``zip``: zip archive, compressed using deflate
330
330
331 The exact name of the destination archive or directory is given
331 The exact name of the destination archive or directory is given
332 using a format string; see :hg:`help export` for details.
332 using a format string; see :hg:`help export` for details.
333
333
334 Each member added to an archive file has a directory prefix
334 Each member added to an archive file has a directory prefix
335 prepended. Use -p/--prefix to specify a format string for the
335 prepended. Use -p/--prefix to specify a format string for the
336 prefix. The default is the basename of the archive, with suffixes
336 prefix. The default is the basename of the archive, with suffixes
337 removed.
337 removed.
338
338
339 Returns 0 on success.
339 Returns 0 on success.
340 '''
340 '''
341
341
342 ctx = scmutil.revsingle(repo, opts.get('rev'))
342 ctx = scmutil.revsingle(repo, opts.get('rev'))
343 if not ctx:
343 if not ctx:
344 raise util.Abort(_('no working directory: please specify a revision'))
344 raise util.Abort(_('no working directory: please specify a revision'))
345 node = ctx.node()
345 node = ctx.node()
346 dest = cmdutil.makefilename(repo, dest, node)
346 dest = cmdutil.makefilename(repo, dest, node)
347 if os.path.realpath(dest) == repo.root:
347 if os.path.realpath(dest) == repo.root:
348 raise util.Abort(_('repository root cannot be destination'))
348 raise util.Abort(_('repository root cannot be destination'))
349
349
350 kind = opts.get('type') or archival.guesskind(dest) or 'files'
350 kind = opts.get('type') or archival.guesskind(dest) or 'files'
351 prefix = opts.get('prefix')
351 prefix = opts.get('prefix')
352
352
353 if dest == '-':
353 if dest == '-':
354 if kind == 'files':
354 if kind == 'files':
355 raise util.Abort(_('cannot archive plain files to stdout'))
355 raise util.Abort(_('cannot archive plain files to stdout'))
356 dest = cmdutil.makefileobj(repo, dest)
356 dest = cmdutil.makefileobj(repo, dest)
357 if not prefix:
357 if not prefix:
358 prefix = os.path.basename(repo.root) + '-%h'
358 prefix = os.path.basename(repo.root) + '-%h'
359
359
360 prefix = cmdutil.makefilename(repo, prefix, node)
360 prefix = cmdutil.makefilename(repo, prefix, node)
361 matchfn = scmutil.match(ctx, [], opts)
361 matchfn = scmutil.match(ctx, [], opts)
362 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
362 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
363 matchfn, prefix, subrepos=opts.get('subrepos'))
363 matchfn, prefix, subrepos=opts.get('subrepos'))
364
364
365 @command('backout',
365 @command('backout',
366 [('', 'merge', None, _('merge with old dirstate parent after backout')),
366 [('', 'merge', None, _('merge with old dirstate parent after backout')),
367 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
367 ('', 'parent', '',
368 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
368 ('r', 'rev', '', _('revision to backout'), _('REV')),
369 ('r', 'rev', '', _('revision to backout'), _('REV')),
369 ] + mergetoolopts + walkopts + commitopts + commitopts2,
370 ] + mergetoolopts + walkopts + commitopts + commitopts2,
370 _('[OPTION]... [-r] REV'))
371 _('[OPTION]... [-r] REV'))
371 def backout(ui, repo, node=None, rev=None, **opts):
372 def backout(ui, repo, node=None, rev=None, **opts):
372 '''reverse effect of earlier changeset
373 '''reverse effect of earlier changeset
373
374
374 Prepare a new changeset with the effect of REV undone in the
375 Prepare a new changeset with the effect of REV undone in the
375 current working directory.
376 current working directory.
376
377
377 If REV is the parent of the working directory, then this new changeset
378 If REV is the parent of the working directory, then this new changeset
378 is committed automatically. Otherwise, hg needs to merge the
379 is committed automatically. Otherwise, hg needs to merge the
379 changes and the merged result is left uncommitted.
380 changes and the merged result is left uncommitted.
380
381
381 .. note::
382 .. note::
382 backout cannot be used to fix either an unwanted or
383 backout cannot be used to fix either an unwanted or
383 incorrect merge.
384 incorrect merge.
384
385
385 .. container:: verbose
386 .. container:: verbose
386
387
387 By default, the pending changeset will have one parent,
388 By default, the pending changeset will have one parent,
388 maintaining a linear history. With --merge, the pending
389 maintaining a linear history. With --merge, the pending
389 changeset will instead have two parents: the old parent of the
390 changeset will instead have two parents: the old parent of the
390 working directory and a new child of REV that simply undoes REV.
391 working directory and a new child of REV that simply undoes REV.
391
392
392 Before version 1.7, the behavior without --merge was equivalent
393 Before version 1.7, the behavior without --merge was equivalent
393 to specifying --merge followed by :hg:`update --clean .` to
394 to specifying --merge followed by :hg:`update --clean .` to
394 cancel the merge and leave the child of REV as a head to be
395 cancel the merge and leave the child of REV as a head to be
395 merged separately.
396 merged separately.
396
397
397 See :hg:`help dates` for a list of formats valid for -d/--date.
398 See :hg:`help dates` for a list of formats valid for -d/--date.
398
399
399 Returns 0 on success.
400 Returns 0 on success.
400 '''
401 '''
401 if rev and node:
402 if rev and node:
402 raise util.Abort(_("please specify just one revision"))
403 raise util.Abort(_("please specify just one revision"))
403
404
404 if not rev:
405 if not rev:
405 rev = node
406 rev = node
406
407
407 if not rev:
408 if not rev:
408 raise util.Abort(_("please specify a revision to backout"))
409 raise util.Abort(_("please specify a revision to backout"))
409
410
410 date = opts.get('date')
411 date = opts.get('date')
411 if date:
412 if date:
412 opts['date'] = util.parsedate(date)
413 opts['date'] = util.parsedate(date)
413
414
414 cmdutil.bailifchanged(repo)
415 cmdutil.bailifchanged(repo)
415 node = scmutil.revsingle(repo, rev).node()
416 node = scmutil.revsingle(repo, rev).node()
416
417
417 op1, op2 = repo.dirstate.parents()
418 op1, op2 = repo.dirstate.parents()
418 a = repo.changelog.ancestor(op1, node)
419 a = repo.changelog.ancestor(op1, node)
419 if a != node:
420 if a != node:
420 raise util.Abort(_('cannot backout change on a different branch'))
421 raise util.Abort(_('cannot backout change on a different branch'))
421
422
422 p1, p2 = repo.changelog.parents(node)
423 p1, p2 = repo.changelog.parents(node)
423 if p1 == nullid:
424 if p1 == nullid:
424 raise util.Abort(_('cannot backout a change with no parents'))
425 raise util.Abort(_('cannot backout a change with no parents'))
425 if p2 != nullid:
426 if p2 != nullid:
426 if not opts.get('parent'):
427 if not opts.get('parent'):
427 raise util.Abort(_('cannot backout a merge changeset without '
428 raise util.Abort(_('cannot backout a merge changeset'))
428 '--parent'))
429 p = repo.lookup(opts['parent'])
429 p = repo.lookup(opts['parent'])
430 if p not in (p1, p2):
430 if p not in (p1, p2):
431 raise util.Abort(_('%s is not a parent of %s') %
431 raise util.Abort(_('%s is not a parent of %s') %
432 (short(p), short(node)))
432 (short(p), short(node)))
433 parent = p
433 parent = p
434 else:
434 else:
435 if opts.get('parent'):
435 if opts.get('parent'):
436 raise util.Abort(_('cannot use --parent on non-merge changeset'))
436 raise util.Abort(_('cannot use --parent on non-merge changeset'))
437 parent = p1
437 parent = p1
438
438
439 # the backout should appear on the same branch
439 # the backout should appear on the same branch
440 branch = repo.dirstate.branch()
440 branch = repo.dirstate.branch()
441 hg.clean(repo, node, show_stats=False)
441 hg.clean(repo, node, show_stats=False)
442 repo.dirstate.setbranch(branch)
442 repo.dirstate.setbranch(branch)
443 revert_opts = opts.copy()
443 revert_opts = opts.copy()
444 revert_opts['date'] = None
444 revert_opts['date'] = None
445 revert_opts['all'] = True
445 revert_opts['all'] = True
446 revert_opts['rev'] = hex(parent)
446 revert_opts['rev'] = hex(parent)
447 revert_opts['no_backup'] = None
447 revert_opts['no_backup'] = None
448 revert(ui, repo, **revert_opts)
448 revert(ui, repo, **revert_opts)
449 if not opts.get('merge') and op1 != node:
449 if not opts.get('merge') and op1 != node:
450 try:
450 try:
451 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
452 return hg.update(repo, op1)
452 return hg.update(repo, op1)
453 finally:
453 finally:
454 ui.setconfig('ui', 'forcemerge', '')
454 ui.setconfig('ui', 'forcemerge', '')
455
455
456 commit_opts = opts.copy()
456 commit_opts = opts.copy()
457 commit_opts['addremove'] = False
457 commit_opts['addremove'] = False
458 if not commit_opts['message'] and not commit_opts['logfile']:
458 if not commit_opts['message'] and not commit_opts['logfile']:
459 # we don't translate commit messages
459 # we don't translate commit messages
460 commit_opts['message'] = "Backed out changeset %s" % short(node)
460 commit_opts['message'] = "Backed out changeset %s" % short(node)
461 commit_opts['force_editor'] = True
461 commit_opts['force_editor'] = True
462 commit(ui, repo, **commit_opts)
462 commit(ui, repo, **commit_opts)
463 def nice(node):
463 def nice(node):
464 return '%d:%s' % (repo.changelog.rev(node), short(node))
464 return '%d:%s' % (repo.changelog.rev(node), short(node))
465 ui.status(_('changeset %s backs out changeset %s\n') %
465 ui.status(_('changeset %s backs out changeset %s\n') %
466 (nice(repo.changelog.tip()), nice(node)))
466 (nice(repo.changelog.tip()), nice(node)))
467 if opts.get('merge') and op1 != node:
467 if opts.get('merge') and op1 != node:
468 hg.clean(repo, op1, show_stats=False)
468 hg.clean(repo, op1, show_stats=False)
469 ui.status(_('merging with changeset %s\n')
469 ui.status(_('merging with changeset %s\n')
470 % nice(repo.changelog.tip()))
470 % nice(repo.changelog.tip()))
471 try:
471 try:
472 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
472 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
473 return hg.merge(repo, hex(repo.changelog.tip()))
473 return hg.merge(repo, hex(repo.changelog.tip()))
474 finally:
474 finally:
475 ui.setconfig('ui', 'forcemerge', '')
475 ui.setconfig('ui', 'forcemerge', '')
476 return 0
476 return 0
477
477
478 @command('bisect',
478 @command('bisect',
479 [('r', 'reset', False, _('reset bisect state')),
479 [('r', 'reset', False, _('reset bisect state')),
480 ('g', 'good', False, _('mark changeset good')),
480 ('g', 'good', False, _('mark changeset good')),
481 ('b', 'bad', False, _('mark changeset bad')),
481 ('b', 'bad', False, _('mark changeset bad')),
482 ('s', 'skip', False, _('skip testing changeset')),
482 ('s', 'skip', False, _('skip testing changeset')),
483 ('e', 'extend', False, _('extend the bisect range')),
483 ('e', 'extend', False, _('extend the bisect range')),
484 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
484 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
485 ('U', 'noupdate', False, _('do not update to target'))],
485 ('U', 'noupdate', False, _('do not update to target'))],
486 _("[-gbsr] [-U] [-c CMD] [REV]"))
486 _("[-gbsr] [-U] [-c CMD] [REV]"))
487 def bisect(ui, repo, rev=None, extra=None, command=None,
487 def bisect(ui, repo, rev=None, extra=None, command=None,
488 reset=None, good=None, bad=None, skip=None, extend=None,
488 reset=None, good=None, bad=None, skip=None, extend=None,
489 noupdate=None):
489 noupdate=None):
490 """subdivision search of changesets
490 """subdivision search of changesets
491
491
492 This command helps to find changesets which introduce problems. To
492 This command helps to find changesets which introduce problems. To
493 use, mark the earliest changeset you know exhibits the problem as
493 use, mark the earliest changeset you know exhibits the problem as
494 bad, then mark the latest changeset which is free from the problem
494 bad, then mark the latest changeset which is free from the problem
495 as good. Bisect will update your working directory to a revision
495 as good. Bisect will update your working directory to a revision
496 for testing (unless the -U/--noupdate option is specified). Once
496 for testing (unless the -U/--noupdate option is specified). Once
497 you have performed tests, mark the working directory as good or
497 you have performed tests, mark the working directory as good or
498 bad, and bisect will either update to another candidate changeset
498 bad, and bisect will either update to another candidate changeset
499 or announce that it has found the bad revision.
499 or announce that it has found the bad revision.
500
500
501 As a shortcut, you can also use the revision argument to mark a
501 As a shortcut, you can also use the revision argument to mark a
502 revision as good or bad without checking it out first.
502 revision as good or bad without checking it out first.
503
503
504 If you supply a command, it will be used for automatic bisection.
504 If you supply a command, it will be used for automatic bisection.
505 Its exit status will be used to mark revisions as good or bad:
505 Its exit status will be used to mark revisions as good or bad:
506 status 0 means good, 125 means to skip the revision, 127
506 status 0 means good, 125 means to skip the revision, 127
507 (command not found) will abort the bisection, and any other
507 (command not found) will abort the bisection, and any other
508 non-zero exit status means the revision is bad.
508 non-zero exit status means the revision is bad.
509
509
510 .. container:: verbose
510 .. container:: verbose
511
511
512 Some examples:
512 Some examples:
513
513
514 - start a bisection with known bad revision 12, and good revision 34::
514 - start a bisection with known bad revision 12, and good revision 34::
515
515
516 hg bisect --bad 34
516 hg bisect --bad 34
517 hg bisect --good 12
517 hg bisect --good 12
518
518
519 - advance the current bisection by marking current revision as good or
519 - advance the current bisection by marking current revision as good or
520 bad::
520 bad::
521
521
522 hg bisect --good
522 hg bisect --good
523 hg bisect --bad
523 hg bisect --bad
524
524
525 - mark the current revision, or a known revision, to be skipped (eg. if
525 - mark the current revision, or a known revision, to be skipped (eg. if
526 that revision is not usable because of another issue)::
526 that revision is not usable because of another issue)::
527
527
528 hg bisect --skip
528 hg bisect --skip
529 hg bisect --skip 23
529 hg bisect --skip 23
530
530
531 - forget the current bisection::
531 - forget the current bisection::
532
532
533 hg bisect --reset
533 hg bisect --reset
534
534
535 - use 'make && make tests' to automatically find the first broken
535 - use 'make && make tests' to automatically find the first broken
536 revision::
536 revision::
537
537
538 hg bisect --reset
538 hg bisect --reset
539 hg bisect --bad 34
539 hg bisect --bad 34
540 hg bisect --good 12
540 hg bisect --good 12
541 hg bisect --command 'make && make tests'
541 hg bisect --command 'make && make tests'
542
542
543 - see all changesets whose states are already known in the current
543 - see all changesets whose states are already known in the current
544 bisection::
544 bisection::
545
545
546 hg log -r "bisect(pruned)"
546 hg log -r "bisect(pruned)"
547
547
548 - see all changesets that took part in the current bisection::
548 - see all changesets that took part in the current bisection::
549
549
550 hg log -r "bisect(range)"
550 hg log -r "bisect(range)"
551
551
552 - with the graphlog extension, you can even get a nice graph::
552 - with the graphlog extension, you can even get a nice graph::
553
553
554 hg log --graph -r "bisect(range)"
554 hg log --graph -r "bisect(range)"
555
555
556 See :hg:`help revsets` for more about the `bisect()` keyword.
556 See :hg:`help revsets` for more about the `bisect()` keyword.
557
557
558 Returns 0 on success.
558 Returns 0 on success.
559 """
559 """
560 def extendbisectrange(nodes, good):
560 def extendbisectrange(nodes, good):
561 # bisect is incomplete when it ends on a merge node and
561 # bisect is incomplete when it ends on a merge node and
562 # one of the parent was not checked.
562 # one of the parent was not checked.
563 parents = repo[nodes[0]].parents()
563 parents = repo[nodes[0]].parents()
564 if len(parents) > 1:
564 if len(parents) > 1:
565 side = good and state['bad'] or state['good']
565 side = good and state['bad'] or state['good']
566 num = len(set(i.node() for i in parents) & set(side))
566 num = len(set(i.node() for i in parents) & set(side))
567 if num == 1:
567 if num == 1:
568 return parents[0].ancestor(parents[1])
568 return parents[0].ancestor(parents[1])
569 return None
569 return None
570
570
571 def print_result(nodes, good):
571 def print_result(nodes, good):
572 displayer = cmdutil.show_changeset(ui, repo, {})
572 displayer = cmdutil.show_changeset(ui, repo, {})
573 if len(nodes) == 1:
573 if len(nodes) == 1:
574 # narrowed it down to a single revision
574 # narrowed it down to a single revision
575 if good:
575 if good:
576 ui.write(_("The first good revision is:\n"))
576 ui.write(_("The first good revision is:\n"))
577 else:
577 else:
578 ui.write(_("The first bad revision is:\n"))
578 ui.write(_("The first bad revision is:\n"))
579 displayer.show(repo[nodes[0]])
579 displayer.show(repo[nodes[0]])
580 extendnode = extendbisectrange(nodes, good)
580 extendnode = extendbisectrange(nodes, good)
581 if extendnode is not None:
581 if extendnode is not None:
582 ui.write(_('Not all ancestors of this changeset have been'
582 ui.write(_('Not all ancestors of this changeset have been'
583 ' checked.\nUse bisect --extend to continue the '
583 ' checked.\nUse bisect --extend to continue the '
584 'bisection from\nthe common ancestor, %s.\n')
584 'bisection from\nthe common ancestor, %s.\n')
585 % extendnode)
585 % extendnode)
586 else:
586 else:
587 # multiple possible revisions
587 # multiple possible revisions
588 if good:
588 if good:
589 ui.write(_("Due to skipped revisions, the first "
589 ui.write(_("Due to skipped revisions, the first "
590 "good revision could be any of:\n"))
590 "good revision could be any of:\n"))
591 else:
591 else:
592 ui.write(_("Due to skipped revisions, the first "
592 ui.write(_("Due to skipped revisions, the first "
593 "bad revision could be any of:\n"))
593 "bad revision could be any of:\n"))
594 for n in nodes:
594 for n in nodes:
595 displayer.show(repo[n])
595 displayer.show(repo[n])
596 displayer.close()
596 displayer.close()
597
597
598 def check_state(state, interactive=True):
598 def check_state(state, interactive=True):
599 if not state['good'] or not state['bad']:
599 if not state['good'] or not state['bad']:
600 if (good or bad or skip or reset) and interactive:
600 if (good or bad or skip or reset) and interactive:
601 return
601 return
602 if not state['good']:
602 if not state['good']:
603 raise util.Abort(_('cannot bisect (no known good revisions)'))
603 raise util.Abort(_('cannot bisect (no known good revisions)'))
604 else:
604 else:
605 raise util.Abort(_('cannot bisect (no known bad revisions)'))
605 raise util.Abort(_('cannot bisect (no known bad revisions)'))
606 return True
606 return True
607
607
608 # backward compatibility
608 # backward compatibility
609 if rev in "good bad reset init".split():
609 if rev in "good bad reset init".split():
610 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
610 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
611 cmd, rev, extra = rev, extra, None
611 cmd, rev, extra = rev, extra, None
612 if cmd == "good":
612 if cmd == "good":
613 good = True
613 good = True
614 elif cmd == "bad":
614 elif cmd == "bad":
615 bad = True
615 bad = True
616 else:
616 else:
617 reset = True
617 reset = True
618 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
618 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
619 raise util.Abort(_('incompatible arguments'))
619 raise util.Abort(_('incompatible arguments'))
620
620
621 if reset:
621 if reset:
622 p = repo.join("bisect.state")
622 p = repo.join("bisect.state")
623 if os.path.exists(p):
623 if os.path.exists(p):
624 os.unlink(p)
624 os.unlink(p)
625 return
625 return
626
626
627 state = hbisect.load_state(repo)
627 state = hbisect.load_state(repo)
628
628
629 if command:
629 if command:
630 changesets = 1
630 changesets = 1
631 try:
631 try:
632 while changesets:
632 while changesets:
633 # update state
633 # update state
634 status = util.system(command, out=ui.fout)
634 status = util.system(command, out=ui.fout)
635 if status == 125:
635 if status == 125:
636 transition = "skip"
636 transition = "skip"
637 elif status == 0:
637 elif status == 0:
638 transition = "good"
638 transition = "good"
639 # status < 0 means process was killed
639 # status < 0 means process was killed
640 elif status == 127:
640 elif status == 127:
641 raise util.Abort(_("failed to execute %s") % command)
641 raise util.Abort(_("failed to execute %s") % command)
642 elif status < 0:
642 elif status < 0:
643 raise util.Abort(_("%s killed") % command)
643 raise util.Abort(_("%s killed") % command)
644 else:
644 else:
645 transition = "bad"
645 transition = "bad"
646 ctx = scmutil.revsingle(repo, rev)
646 ctx = scmutil.revsingle(repo, rev)
647 rev = None # clear for future iterations
647 rev = None # clear for future iterations
648 state[transition].append(ctx.node())
648 state[transition].append(ctx.node())
649 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
649 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
650 check_state(state, interactive=False)
650 check_state(state, interactive=False)
651 # bisect
651 # bisect
652 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
652 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
653 # update to next check
653 # update to next check
654 cmdutil.bailifchanged(repo)
654 cmdutil.bailifchanged(repo)
655 hg.clean(repo, nodes[0], show_stats=False)
655 hg.clean(repo, nodes[0], show_stats=False)
656 finally:
656 finally:
657 hbisect.save_state(repo, state)
657 hbisect.save_state(repo, state)
658 print_result(nodes, good)
658 print_result(nodes, good)
659 return
659 return
660
660
661 # update state
661 # update state
662
662
663 if rev:
663 if rev:
664 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
664 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
665 else:
665 else:
666 nodes = [repo.lookup('.')]
666 nodes = [repo.lookup('.')]
667
667
668 if good or bad or skip:
668 if good or bad or skip:
669 if good:
669 if good:
670 state['good'] += nodes
670 state['good'] += nodes
671 elif bad:
671 elif bad:
672 state['bad'] += nodes
672 state['bad'] += nodes
673 elif skip:
673 elif skip:
674 state['skip'] += nodes
674 state['skip'] += nodes
675 hbisect.save_state(repo, state)
675 hbisect.save_state(repo, state)
676
676
677 if not check_state(state):
677 if not check_state(state):
678 return
678 return
679
679
680 # actually bisect
680 # actually bisect
681 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
681 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
682 if extend:
682 if extend:
683 if not changesets:
683 if not changesets:
684 extendnode = extendbisectrange(nodes, good)
684 extendnode = extendbisectrange(nodes, good)
685 if extendnode is not None:
685 if extendnode is not None:
686 ui.write(_("Extending search to changeset %d:%s\n"
686 ui.write(_("Extending search to changeset %d:%s\n"
687 % (extendnode.rev(), extendnode)))
687 % (extendnode.rev(), extendnode)))
688 if noupdate:
688 if noupdate:
689 return
689 return
690 cmdutil.bailifchanged(repo)
690 cmdutil.bailifchanged(repo)
691 return hg.clean(repo, extendnode.node())
691 return hg.clean(repo, extendnode.node())
692 raise util.Abort(_("nothing to extend"))
692 raise util.Abort(_("nothing to extend"))
693
693
694 if changesets == 0:
694 if changesets == 0:
695 print_result(nodes, good)
695 print_result(nodes, good)
696 else:
696 else:
697 assert len(nodes) == 1 # only a single node can be tested next
697 assert len(nodes) == 1 # only a single node can be tested next
698 node = nodes[0]
698 node = nodes[0]
699 # compute the approximate number of remaining tests
699 # compute the approximate number of remaining tests
700 tests, size = 0, 2
700 tests, size = 0, 2
701 while size <= changesets:
701 while size <= changesets:
702 tests, size = tests + 1, size * 2
702 tests, size = tests + 1, size * 2
703 rev = repo.changelog.rev(node)
703 rev = repo.changelog.rev(node)
704 ui.write(_("Testing changeset %d:%s "
704 ui.write(_("Testing changeset %d:%s "
705 "(%d changesets remaining, ~%d tests)\n")
705 "(%d changesets remaining, ~%d tests)\n")
706 % (rev, short(node), changesets, tests))
706 % (rev, short(node), changesets, tests))
707 if not noupdate:
707 if not noupdate:
708 cmdutil.bailifchanged(repo)
708 cmdutil.bailifchanged(repo)
709 return hg.clean(repo, node)
709 return hg.clean(repo, node)
710
710
711 @command('bookmarks',
711 @command('bookmarks',
712 [('f', 'force', False, _('force')),
712 [('f', 'force', False, _('force')),
713 ('r', 'rev', '', _('revision'), _('REV')),
713 ('r', 'rev', '', _('revision'), _('REV')),
714 ('d', 'delete', False, _('delete a given bookmark')),
714 ('d', 'delete', False, _('delete a given bookmark')),
715 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
715 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
716 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
716 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
717 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
717 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
718 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
718 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
719 rename=None, inactive=False):
719 rename=None, inactive=False):
720 '''track a line of development with movable markers
720 '''track a line of development with movable markers
721
721
722 Bookmarks are pointers to certain commits that move when
722 Bookmarks are pointers to certain commits that move when
723 committing. Bookmarks are local. They can be renamed, copied and
723 committing. Bookmarks are local. They can be renamed, copied and
724 deleted. It is possible to use bookmark names in :hg:`merge` and
724 deleted. It is possible to use bookmark names in :hg:`merge` and
725 :hg:`update` to merge and update respectively to a given bookmark.
725 :hg:`update` to merge and update respectively to a given bookmark.
726
726
727 You can use :hg:`bookmark NAME` to set a bookmark on the working
727 You can use :hg:`bookmark NAME` to set a bookmark on the working
728 directory's parent revision with the given name. If you specify
728 directory's parent revision with the given name. If you specify
729 a revision using -r REV (where REV may be an existing bookmark),
729 a revision using -r REV (where REV may be an existing bookmark),
730 the bookmark is assigned to that revision.
730 the bookmark is assigned to that revision.
731
731
732 Bookmarks can be pushed and pulled between repositories (see :hg:`help
732 Bookmarks can be pushed and pulled between repositories (see :hg:`help
733 push` and :hg:`help pull`). This requires both the local and remote
733 push` and :hg:`help pull`). This requires both the local and remote
734 repositories to support bookmarks. For versions prior to 1.8, this means
734 repositories to support bookmarks. For versions prior to 1.8, this means
735 the bookmarks extension must be enabled.
735 the bookmarks extension must be enabled.
736 '''
736 '''
737 hexfn = ui.debugflag and hex or short
737 hexfn = ui.debugflag and hex or short
738 marks = repo._bookmarks
738 marks = repo._bookmarks
739 cur = repo.changectx('.').node()
739 cur = repo.changectx('.').node()
740
740
741 if rename:
741 if rename:
742 if rename not in marks:
742 if rename not in marks:
743 raise util.Abort(_("bookmark '%s' does not exist") % rename)
743 raise util.Abort(_("bookmark '%s' does not exist") % rename)
744 if mark in marks and not force:
744 if mark in marks and not force:
745 raise util.Abort(_("bookmark '%s' already exists "
745 raise util.Abort(_("bookmark '%s' already exists "
746 "(use -f to force)") % mark)
746 "(use -f to force)") % mark)
747 if mark is None:
747 if mark is None:
748 raise util.Abort(_("new bookmark name required"))
748 raise util.Abort(_("new bookmark name required"))
749 marks[mark] = marks[rename]
749 marks[mark] = marks[rename]
750 if repo._bookmarkcurrent == rename and not inactive:
750 if repo._bookmarkcurrent == rename and not inactive:
751 bookmarks.setcurrent(repo, mark)
751 bookmarks.setcurrent(repo, mark)
752 del marks[rename]
752 del marks[rename]
753 bookmarks.write(repo)
753 bookmarks.write(repo)
754 return
754 return
755
755
756 if delete:
756 if delete:
757 if mark is None:
757 if mark is None:
758 raise util.Abort(_("bookmark name required"))
758 raise util.Abort(_("bookmark name required"))
759 if mark not in marks:
759 if mark not in marks:
760 raise util.Abort(_("bookmark '%s' does not exist") % mark)
760 raise util.Abort(_("bookmark '%s' does not exist") % mark)
761 if mark == repo._bookmarkcurrent:
761 if mark == repo._bookmarkcurrent:
762 bookmarks.setcurrent(repo, None)
762 bookmarks.setcurrent(repo, None)
763 del marks[mark]
763 del marks[mark]
764 bookmarks.write(repo)
764 bookmarks.write(repo)
765 return
765 return
766
766
767 if mark is not None:
767 if mark is not None:
768 if "\n" in mark:
768 if "\n" in mark:
769 raise util.Abort(_("bookmark name cannot contain newlines"))
769 raise util.Abort(_("bookmark name cannot contain newlines"))
770 mark = mark.strip()
770 mark = mark.strip()
771 if not mark:
771 if not mark:
772 raise util.Abort(_("bookmark names cannot consist entirely of "
772 raise util.Abort(_("bookmark names cannot consist entirely of "
773 "whitespace"))
773 "whitespace"))
774 if inactive and mark == repo._bookmarkcurrent:
774 if inactive and mark == repo._bookmarkcurrent:
775 bookmarks.setcurrent(repo, None)
775 bookmarks.setcurrent(repo, None)
776 return
776 return
777 if mark in marks and not force:
777 if mark in marks and not force:
778 raise util.Abort(_("bookmark '%s' already exists "
778 raise util.Abort(_("bookmark '%s' already exists "
779 "(use -f to force)") % mark)
779 "(use -f to force)") % mark)
780 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
780 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
781 and not force):
781 and not force):
782 raise util.Abort(
782 raise util.Abort(
783 _("a bookmark cannot have the name of an existing branch"))
783 _("a bookmark cannot have the name of an existing branch"))
784 if rev:
784 if rev:
785 marks[mark] = repo.lookup(rev)
785 marks[mark] = repo.lookup(rev)
786 else:
786 else:
787 marks[mark] = repo.changectx('.').node()
787 marks[mark] = repo.changectx('.').node()
788 if not inactive and repo.changectx('.').node() == marks[mark]:
788 if not inactive and repo.changectx('.').node() == marks[mark]:
789 bookmarks.setcurrent(repo, mark)
789 bookmarks.setcurrent(repo, mark)
790 bookmarks.write(repo)
790 bookmarks.write(repo)
791 return
791 return
792
792
793 if mark is None:
793 if mark is None:
794 if rev:
794 if rev:
795 raise util.Abort(_("bookmark name required"))
795 raise util.Abort(_("bookmark name required"))
796 if len(marks) == 0:
796 if len(marks) == 0:
797 ui.status(_("no bookmarks set\n"))
797 ui.status(_("no bookmarks set\n"))
798 else:
798 else:
799 for bmark, n in sorted(marks.iteritems()):
799 for bmark, n in sorted(marks.iteritems()):
800 current = repo._bookmarkcurrent
800 current = repo._bookmarkcurrent
801 if bmark == current and n == cur:
801 if bmark == current and n == cur:
802 prefix, label = '*', 'bookmarks.current'
802 prefix, label = '*', 'bookmarks.current'
803 else:
803 else:
804 prefix, label = ' ', ''
804 prefix, label = ' ', ''
805
805
806 if ui.quiet:
806 if ui.quiet:
807 ui.write("%s\n" % bmark, label=label)
807 ui.write("%s\n" % bmark, label=label)
808 else:
808 else:
809 ui.write(" %s %-25s %d:%s\n" % (
809 ui.write(" %s %-25s %d:%s\n" % (
810 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
810 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
811 label=label)
811 label=label)
812 return
812 return
813
813
814 @command('branch',
814 @command('branch',
815 [('f', 'force', None,
815 [('f', 'force', None,
816 _('set branch name even if it shadows an existing branch')),
816 _('set branch name even if it shadows an existing branch')),
817 ('C', 'clean', None, _('reset branch name to parent branch name'))],
817 ('C', 'clean', None, _('reset branch name to parent branch name'))],
818 _('[-fC] [NAME]'))
818 _('[-fC] [NAME]'))
819 def branch(ui, repo, label=None, **opts):
819 def branch(ui, repo, label=None, **opts):
820 """set or show the current branch name
820 """set or show the current branch name
821
821
822 With no argument, show the current branch name. With one argument,
822 With no argument, show the current branch name. With one argument,
823 set the working directory branch name (the branch will not exist
823 set the working directory branch name (the branch will not exist
824 in the repository until the next commit). Standard practice
824 in the repository until the next commit). Standard practice
825 recommends that primary development take place on the 'default'
825 recommends that primary development take place on the 'default'
826 branch.
826 branch.
827
827
828 Unless -f/--force is specified, branch will not let you set a
828 Unless -f/--force is specified, branch will not let you set a
829 branch name that already exists, even if it's inactive.
829 branch name that already exists, even if it's inactive.
830
830
831 Use -C/--clean to reset the working directory branch to that of
831 Use -C/--clean to reset the working directory branch to that of
832 the parent of the working directory, negating a previous branch
832 the parent of the working directory, negating a previous branch
833 change.
833 change.
834
834
835 Use the command :hg:`update` to switch to an existing branch. Use
835 Use the command :hg:`update` to switch to an existing branch. Use
836 :hg:`commit --close-branch` to mark this branch as closed.
836 :hg:`commit --close-branch` to mark this branch as closed.
837
837
838 .. note::
838 .. note::
839
839
840 Branch names are permanent. Use :hg:`bookmark` to create a
840 Branch names are permanent. Use :hg:`bookmark` to create a
841 light-weight bookmark instead. See :hg:`help glossary` for more
841 light-weight bookmark instead. See :hg:`help glossary` for more
842 information about named branches and bookmarks.
842 information about named branches and bookmarks.
843
843
844 Returns 0 on success.
844 Returns 0 on success.
845 """
845 """
846
846
847 if opts.get('clean'):
847 if opts.get('clean'):
848 label = repo[None].p1().branch()
848 label = repo[None].p1().branch()
849 repo.dirstate.setbranch(label)
849 repo.dirstate.setbranch(label)
850 ui.status(_('reset working directory to branch %s\n') % label)
850 ui.status(_('reset working directory to branch %s\n') % label)
851 elif label:
851 elif label:
852 if not opts.get('force') and label in repo.branchtags():
852 if not opts.get('force') and label in repo.branchtags():
853 if label not in [p.branch() for p in repo.parents()]:
853 if label not in [p.branch() for p in repo.parents()]:
854 raise util.Abort(_('a branch of the same name already exists'),
854 raise util.Abort(_('a branch of the same name already exists'),
855 # i18n: "it" refers to an existing branch
855 # i18n: "it" refers to an existing branch
856 hint=_("use 'hg update' to switch to it"))
856 hint=_("use 'hg update' to switch to it"))
857 repo.dirstate.setbranch(label)
857 repo.dirstate.setbranch(label)
858 ui.status(_('marked working directory as branch %s\n') % label)
858 ui.status(_('marked working directory as branch %s\n') % label)
859 else:
859 else:
860 ui.write("%s\n" % repo.dirstate.branch())
860 ui.write("%s\n" % repo.dirstate.branch())
861
861
862 @command('branches',
862 @command('branches',
863 [('a', 'active', False, _('show only branches that have unmerged heads')),
863 [('a', 'active', False, _('show only branches that have unmerged heads')),
864 ('c', 'closed', False, _('show normal and closed branches'))],
864 ('c', 'closed', False, _('show normal and closed branches'))],
865 _('[-ac]'))
865 _('[-ac]'))
866 def branches(ui, repo, active=False, closed=False):
866 def branches(ui, repo, active=False, closed=False):
867 """list repository named branches
867 """list repository named branches
868
868
869 List the repository's named branches, indicating which ones are
869 List the repository's named branches, indicating which ones are
870 inactive. If -c/--closed is specified, also list branches which have
870 inactive. If -c/--closed is specified, also list branches which have
871 been marked closed (see :hg:`commit --close-branch`).
871 been marked closed (see :hg:`commit --close-branch`).
872
872
873 If -a/--active is specified, only show active branches. A branch
873 If -a/--active is specified, only show active branches. A branch
874 is considered active if it contains repository heads.
874 is considered active if it contains repository heads.
875
875
876 Use the command :hg:`update` to switch to an existing branch.
876 Use the command :hg:`update` to switch to an existing branch.
877
877
878 Returns 0.
878 Returns 0.
879 """
879 """
880
880
881 hexfunc = ui.debugflag and hex or short
881 hexfunc = ui.debugflag and hex or short
882 activebranches = [repo[n].branch() for n in repo.heads()]
882 activebranches = [repo[n].branch() for n in repo.heads()]
883 def testactive(tag, node):
883 def testactive(tag, node):
884 realhead = tag in activebranches
884 realhead = tag in activebranches
885 open = node in repo.branchheads(tag, closed=False)
885 open = node in repo.branchheads(tag, closed=False)
886 return realhead and open
886 return realhead and open
887 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
887 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
888 for tag, node in repo.branchtags().items()],
888 for tag, node in repo.branchtags().items()],
889 reverse=True)
889 reverse=True)
890
890
891 for isactive, node, tag in branches:
891 for isactive, node, tag in branches:
892 if (not active) or isactive:
892 if (not active) or isactive:
893 if ui.quiet:
893 if ui.quiet:
894 ui.write("%s\n" % tag)
894 ui.write("%s\n" % tag)
895 else:
895 else:
896 hn = repo.lookup(node)
896 hn = repo.lookup(node)
897 if isactive:
897 if isactive:
898 label = 'branches.active'
898 label = 'branches.active'
899 notice = ''
899 notice = ''
900 elif hn not in repo.branchheads(tag, closed=False):
900 elif hn not in repo.branchheads(tag, closed=False):
901 if not closed:
901 if not closed:
902 continue
902 continue
903 label = 'branches.closed'
903 label = 'branches.closed'
904 notice = _(' (closed)')
904 notice = _(' (closed)')
905 else:
905 else:
906 label = 'branches.inactive'
906 label = 'branches.inactive'
907 notice = _(' (inactive)')
907 notice = _(' (inactive)')
908 if tag == repo.dirstate.branch():
908 if tag == repo.dirstate.branch():
909 label = 'branches.current'
909 label = 'branches.current'
910 rev = str(node).rjust(31 - encoding.colwidth(tag))
910 rev = str(node).rjust(31 - encoding.colwidth(tag))
911 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
911 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
912 tag = ui.label(tag, label)
912 tag = ui.label(tag, label)
913 ui.write("%s %s%s\n" % (tag, rev, notice))
913 ui.write("%s %s%s\n" % (tag, rev, notice))
914
914
915 @command('bundle',
915 @command('bundle',
916 [('f', 'force', None, _('run even when the destination is unrelated')),
916 [('f', 'force', None, _('run even when the destination is unrelated')),
917 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
917 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
918 _('REV')),
918 _('REV')),
919 ('b', 'branch', [], _('a specific branch you would like to bundle'),
919 ('b', 'branch', [], _('a specific branch you would like to bundle'),
920 _('BRANCH')),
920 _('BRANCH')),
921 ('', 'base', [],
921 ('', 'base', [],
922 _('a base changeset assumed to be available at the destination'),
922 _('a base changeset assumed to be available at the destination'),
923 _('REV')),
923 _('REV')),
924 ('a', 'all', None, _('bundle all changesets in the repository')),
924 ('a', 'all', None, _('bundle all changesets in the repository')),
925 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
925 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
926 ] + remoteopts,
926 ] + remoteopts,
927 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
927 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
928 def bundle(ui, repo, fname, dest=None, **opts):
928 def bundle(ui, repo, fname, dest=None, **opts):
929 """create a changegroup file
929 """create a changegroup file
930
930
931 Generate a compressed changegroup file collecting changesets not
931 Generate a compressed changegroup file collecting changesets not
932 known to be in another repository.
932 known to be in another repository.
933
933
934 If you omit the destination repository, then hg assumes the
934 If you omit the destination repository, then hg assumes the
935 destination will have all the nodes you specify with --base
935 destination will have all the nodes you specify with --base
936 parameters. To create a bundle containing all changesets, use
936 parameters. To create a bundle containing all changesets, use
937 -a/--all (or --base null).
937 -a/--all (or --base null).
938
938
939 You can change compression method with the -t/--type option.
939 You can change compression method with the -t/--type option.
940 The available compression methods are: none, bzip2, and
940 The available compression methods are: none, bzip2, and
941 gzip (by default, bundles are compressed using bzip2).
941 gzip (by default, bundles are compressed using bzip2).
942
942
943 The bundle file can then be transferred using conventional means
943 The bundle file can then be transferred using conventional means
944 and applied to another repository with the unbundle or pull
944 and applied to another repository with the unbundle or pull
945 command. This is useful when direct push and pull are not
945 command. This is useful when direct push and pull are not
946 available or when exporting an entire repository is undesirable.
946 available or when exporting an entire repository is undesirable.
947
947
948 Applying bundles preserves all changeset contents including
948 Applying bundles preserves all changeset contents including
949 permissions, copy/rename information, and revision history.
949 permissions, copy/rename information, and revision history.
950
950
951 Returns 0 on success, 1 if no changes found.
951 Returns 0 on success, 1 if no changes found.
952 """
952 """
953 revs = None
953 revs = None
954 if 'rev' in opts:
954 if 'rev' in opts:
955 revs = scmutil.revrange(repo, opts['rev'])
955 revs = scmutil.revrange(repo, opts['rev'])
956
956
957 if opts.get('all'):
957 if opts.get('all'):
958 base = ['null']
958 base = ['null']
959 else:
959 else:
960 base = scmutil.revrange(repo, opts.get('base'))
960 base = scmutil.revrange(repo, opts.get('base'))
961 if base:
961 if base:
962 if dest:
962 if dest:
963 raise util.Abort(_("--base is incompatible with specifying "
963 raise util.Abort(_("--base is incompatible with specifying "
964 "a destination"))
964 "a destination"))
965 common = [repo.lookup(rev) for rev in base]
965 common = [repo.lookup(rev) for rev in base]
966 heads = revs and map(repo.lookup, revs) or revs
966 heads = revs and map(repo.lookup, revs) or revs
967 else:
967 else:
968 dest = ui.expandpath(dest or 'default-push', dest or 'default')
968 dest = ui.expandpath(dest or 'default-push', dest or 'default')
969 dest, branches = hg.parseurl(dest, opts.get('branch'))
969 dest, branches = hg.parseurl(dest, opts.get('branch'))
970 other = hg.peer(repo, opts, dest)
970 other = hg.peer(repo, opts, dest)
971 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
971 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
972 heads = revs and map(repo.lookup, revs) or revs
972 heads = revs and map(repo.lookup, revs) or revs
973 common, outheads = discovery.findcommonoutgoing(repo, other,
973 common, outheads = discovery.findcommonoutgoing(repo, other,
974 onlyheads=heads,
974 onlyheads=heads,
975 force=opts.get('force'))
975 force=opts.get('force'))
976
976
977 cg = repo.getbundle('bundle', common=common, heads=heads)
977 cg = repo.getbundle('bundle', common=common, heads=heads)
978 if not cg:
978 if not cg:
979 ui.status(_("no changes found\n"))
979 ui.status(_("no changes found\n"))
980 return 1
980 return 1
981
981
982 bundletype = opts.get('type', 'bzip2').lower()
982 bundletype = opts.get('type', 'bzip2').lower()
983 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
983 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
984 bundletype = btypes.get(bundletype)
984 bundletype = btypes.get(bundletype)
985 if bundletype not in changegroup.bundletypes:
985 if bundletype not in changegroup.bundletypes:
986 raise util.Abort(_('unknown bundle type specified with --type'))
986 raise util.Abort(_('unknown bundle type specified with --type'))
987
987
988 changegroup.writebundle(cg, fname, bundletype)
988 changegroup.writebundle(cg, fname, bundletype)
989
989
990 @command('cat',
990 @command('cat',
991 [('o', 'output', '',
991 [('o', 'output', '',
992 _('print output to file with formatted name'), _('FORMAT')),
992 _('print output to file with formatted name'), _('FORMAT')),
993 ('r', 'rev', '', _('print the given revision'), _('REV')),
993 ('r', 'rev', '', _('print the given revision'), _('REV')),
994 ('', 'decode', None, _('apply any matching decode filter')),
994 ('', 'decode', None, _('apply any matching decode filter')),
995 ] + walkopts,
995 ] + walkopts,
996 _('[OPTION]... FILE...'))
996 _('[OPTION]... FILE...'))
997 def cat(ui, repo, file1, *pats, **opts):
997 def cat(ui, repo, file1, *pats, **opts):
998 """output the current or given revision of files
998 """output the current or given revision of files
999
999
1000 Print the specified files as they were at the given revision. If
1000 Print the specified files as they were at the given revision. If
1001 no revision is given, the parent of the working directory is used,
1001 no revision is given, the parent of the working directory is used,
1002 or tip if no revision is checked out.
1002 or tip if no revision is checked out.
1003
1003
1004 Output may be to a file, in which case the name of the file is
1004 Output may be to a file, in which case the name of the file is
1005 given using a format string. The formatting rules are the same as
1005 given using a format string. The formatting rules are the same as
1006 for the export command, with the following additions:
1006 for the export command, with the following additions:
1007
1007
1008 :``%s``: basename of file being printed
1008 :``%s``: basename of file being printed
1009 :``%d``: dirname of file being printed, or '.' if in repository root
1009 :``%d``: dirname of file being printed, or '.' if in repository root
1010 :``%p``: root-relative path name of file being printed
1010 :``%p``: root-relative path name of file being printed
1011
1011
1012 Returns 0 on success.
1012 Returns 0 on success.
1013 """
1013 """
1014 ctx = scmutil.revsingle(repo, opts.get('rev'))
1014 ctx = scmutil.revsingle(repo, opts.get('rev'))
1015 err = 1
1015 err = 1
1016 m = scmutil.match(ctx, (file1,) + pats, opts)
1016 m = scmutil.match(ctx, (file1,) + pats, opts)
1017 for abs in ctx.walk(m):
1017 for abs in ctx.walk(m):
1018 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1018 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1019 pathname=abs)
1019 pathname=abs)
1020 data = ctx[abs].data()
1020 data = ctx[abs].data()
1021 if opts.get('decode'):
1021 if opts.get('decode'):
1022 data = repo.wwritedata(abs, data)
1022 data = repo.wwritedata(abs, data)
1023 fp.write(data)
1023 fp.write(data)
1024 fp.close()
1024 fp.close()
1025 err = 0
1025 err = 0
1026 return err
1026 return err
1027
1027
1028 @command('^clone',
1028 @command('^clone',
1029 [('U', 'noupdate', None,
1029 [('U', 'noupdate', None,
1030 _('the clone will include an empty working copy (only a repository)')),
1030 _('the clone will include an empty working copy (only a repository)')),
1031 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1031 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1032 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1032 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1033 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1033 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1034 ('', 'pull', None, _('use pull protocol to copy metadata')),
1034 ('', 'pull', None, _('use pull protocol to copy metadata')),
1035 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1035 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1036 ] + remoteopts,
1036 ] + remoteopts,
1037 _('[OPTION]... SOURCE [DEST]'))
1037 _('[OPTION]... SOURCE [DEST]'))
1038 def clone(ui, source, dest=None, **opts):
1038 def clone(ui, source, dest=None, **opts):
1039 """make a copy of an existing repository
1039 """make a copy of an existing repository
1040
1040
1041 Create a copy of an existing repository in a new directory.
1041 Create a copy of an existing repository in a new directory.
1042
1042
1043 If no destination directory name is specified, it defaults to the
1043 If no destination directory name is specified, it defaults to the
1044 basename of the source.
1044 basename of the source.
1045
1045
1046 The location of the source is added to the new repository's
1046 The location of the source is added to the new repository's
1047 ``.hg/hgrc`` file, as the default to be used for future pulls.
1047 ``.hg/hgrc`` file, as the default to be used for future pulls.
1048
1048
1049 Only local paths and ``ssh://`` URLs are supported as
1049 Only local paths and ``ssh://`` URLs are supported as
1050 destinations. For ``ssh://`` destinations, no working directory or
1050 destinations. For ``ssh://`` destinations, no working directory or
1051 ``.hg/hgrc`` will be created on the remote side.
1051 ``.hg/hgrc`` will be created on the remote side.
1052
1052
1053 To pull only a subset of changesets, specify one or more revisions
1053 To pull only a subset of changesets, specify one or more revisions
1054 identifiers with -r/--rev or branches with -b/--branch. The
1054 identifiers with -r/--rev or branches with -b/--branch. The
1055 resulting clone will contain only the specified changesets and
1055 resulting clone will contain only the specified changesets and
1056 their ancestors. These options (or 'clone src#rev dest') imply
1056 their ancestors. These options (or 'clone src#rev dest') imply
1057 --pull, even for local source repositories. Note that specifying a
1057 --pull, even for local source repositories. Note that specifying a
1058 tag will include the tagged changeset but not the changeset
1058 tag will include the tagged changeset but not the changeset
1059 containing the tag.
1059 containing the tag.
1060
1060
1061 To check out a particular version, use -u/--update, or
1061 To check out a particular version, use -u/--update, or
1062 -U/--noupdate to create a clone with no working directory.
1062 -U/--noupdate to create a clone with no working directory.
1063
1063
1064 .. container:: verbose
1064 .. container:: verbose
1065
1065
1066 For efficiency, hardlinks are used for cloning whenever the
1066 For efficiency, hardlinks are used for cloning whenever the
1067 source and destination are on the same filesystem (note this
1067 source and destination are on the same filesystem (note this
1068 applies only to the repository data, not to the working
1068 applies only to the repository data, not to the working
1069 directory). Some filesystems, such as AFS, implement hardlinking
1069 directory). Some filesystems, such as AFS, implement hardlinking
1070 incorrectly, but do not report errors. In these cases, use the
1070 incorrectly, but do not report errors. In these cases, use the
1071 --pull option to avoid hardlinking.
1071 --pull option to avoid hardlinking.
1072
1072
1073 In some cases, you can clone repositories and the working
1073 In some cases, you can clone repositories and the working
1074 directory using full hardlinks with ::
1074 directory using full hardlinks with ::
1075
1075
1076 $ cp -al REPO REPOCLONE
1076 $ cp -al REPO REPOCLONE
1077
1077
1078 This is the fastest way to clone, but it is not always safe. The
1078 This is the fastest way to clone, but it is not always safe. The
1079 operation is not atomic (making sure REPO is not modified during
1079 operation is not atomic (making sure REPO is not modified during
1080 the operation is up to you) and you have to make sure your
1080 the operation is up to you) and you have to make sure your
1081 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1081 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1082 so). Also, this is not compatible with certain extensions that
1082 so). Also, this is not compatible with certain extensions that
1083 place their metadata under the .hg directory, such as mq.
1083 place their metadata under the .hg directory, such as mq.
1084
1084
1085 Mercurial will update the working directory to the first applicable
1085 Mercurial will update the working directory to the first applicable
1086 revision from this list:
1086 revision from this list:
1087
1087
1088 a) null if -U or the source repository has no changesets
1088 a) null if -U or the source repository has no changesets
1089 b) if -u . and the source repository is local, the first parent of
1089 b) if -u . and the source repository is local, the first parent of
1090 the source repository's working directory
1090 the source repository's working directory
1091 c) the changeset specified with -u (if a branch name, this means the
1091 c) the changeset specified with -u (if a branch name, this means the
1092 latest head of that branch)
1092 latest head of that branch)
1093 d) the changeset specified with -r
1093 d) the changeset specified with -r
1094 e) the tipmost head specified with -b
1094 e) the tipmost head specified with -b
1095 f) the tipmost head specified with the url#branch source syntax
1095 f) the tipmost head specified with the url#branch source syntax
1096 g) the tipmost head of the default branch
1096 g) the tipmost head of the default branch
1097 h) tip
1097 h) tip
1098
1098
1099 Examples:
1099 Examples:
1100
1100
1101 - clone a remote repository to a new directory named hg/::
1101 - clone a remote repository to a new directory named hg/::
1102
1102
1103 hg clone http://selenic.com/hg
1103 hg clone http://selenic.com/hg
1104
1104
1105 - create a lightweight local clone::
1105 - create a lightweight local clone::
1106
1106
1107 hg clone project/ project-feature/
1107 hg clone project/ project-feature/
1108
1108
1109 - clone from an absolute path on an ssh server (note double-slash)::
1109 - clone from an absolute path on an ssh server (note double-slash)::
1110
1110
1111 hg clone ssh://user@server//home/projects/alpha/
1111 hg clone ssh://user@server//home/projects/alpha/
1112
1112
1113 - do a high-speed clone over a LAN while checking out a
1113 - do a high-speed clone over a LAN while checking out a
1114 specified version::
1114 specified version::
1115
1115
1116 hg clone --uncompressed http://server/repo -u 1.5
1116 hg clone --uncompressed http://server/repo -u 1.5
1117
1117
1118 - create a repository without changesets after a particular revision::
1118 - create a repository without changesets after a particular revision::
1119
1119
1120 hg clone -r 04e544 experimental/ good/
1120 hg clone -r 04e544 experimental/ good/
1121
1121
1122 - clone (and track) a particular named branch::
1122 - clone (and track) a particular named branch::
1123
1123
1124 hg clone http://selenic.com/hg#stable
1124 hg clone http://selenic.com/hg#stable
1125
1125
1126 See :hg:`help urls` for details on specifying URLs.
1126 See :hg:`help urls` for details on specifying URLs.
1127
1127
1128 Returns 0 on success.
1128 Returns 0 on success.
1129 """
1129 """
1130 if opts.get('noupdate') and opts.get('updaterev'):
1130 if opts.get('noupdate') and opts.get('updaterev'):
1131 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1131 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1132
1132
1133 r = hg.clone(ui, opts, source, dest,
1133 r = hg.clone(ui, opts, source, dest,
1134 pull=opts.get('pull'),
1134 pull=opts.get('pull'),
1135 stream=opts.get('uncompressed'),
1135 stream=opts.get('uncompressed'),
1136 rev=opts.get('rev'),
1136 rev=opts.get('rev'),
1137 update=opts.get('updaterev') or not opts.get('noupdate'),
1137 update=opts.get('updaterev') or not opts.get('noupdate'),
1138 branch=opts.get('branch'))
1138 branch=opts.get('branch'))
1139
1139
1140 return r is None
1140 return r is None
1141
1141
1142 @command('^commit|ci',
1142 @command('^commit|ci',
1143 [('A', 'addremove', None,
1143 [('A', 'addremove', None,
1144 _('mark new/missing files as added/removed before committing')),
1144 _('mark new/missing files as added/removed before committing')),
1145 ('', 'close-branch', None,
1145 ('', 'close-branch', None,
1146 _('mark a branch as closed, hiding it from the branch list')),
1146 _('mark a branch as closed, hiding it from the branch list')),
1147 ] + walkopts + commitopts + commitopts2,
1147 ] + walkopts + commitopts + commitopts2,
1148 _('[OPTION]... [FILE]...'))
1148 _('[OPTION]... [FILE]...'))
1149 def commit(ui, repo, *pats, **opts):
1149 def commit(ui, repo, *pats, **opts):
1150 """commit the specified files or all outstanding changes
1150 """commit the specified files or all outstanding changes
1151
1151
1152 Commit changes to the given files into the repository. Unlike a
1152 Commit changes to the given files into the repository. Unlike a
1153 centralized SCM, this operation is a local operation. See
1153 centralized SCM, this operation is a local operation. See
1154 :hg:`push` for a way to actively distribute your changes.
1154 :hg:`push` for a way to actively distribute your changes.
1155
1155
1156 If a list of files is omitted, all changes reported by :hg:`status`
1156 If a list of files is omitted, all changes reported by :hg:`status`
1157 will be committed.
1157 will be committed.
1158
1158
1159 If you are committing the result of a merge, do not provide any
1159 If you are committing the result of a merge, do not provide any
1160 filenames or -I/-X filters.
1160 filenames or -I/-X filters.
1161
1161
1162 If no commit message is specified, Mercurial starts your
1162 If no commit message is specified, Mercurial starts your
1163 configured editor where you can enter a message. In case your
1163 configured editor where you can enter a message. In case your
1164 commit fails, you will find a backup of your message in
1164 commit fails, you will find a backup of your message in
1165 ``.hg/last-message.txt``.
1165 ``.hg/last-message.txt``.
1166
1166
1167 See :hg:`help dates` for a list of formats valid for -d/--date.
1167 See :hg:`help dates` for a list of formats valid for -d/--date.
1168
1168
1169 Returns 0 on success, 1 if nothing changed.
1169 Returns 0 on success, 1 if nothing changed.
1170 """
1170 """
1171 extra = {}
1171 extra = {}
1172 if opts.get('close_branch'):
1172 if opts.get('close_branch'):
1173 if repo['.'].node() not in repo.branchheads():
1173 if repo['.'].node() not in repo.branchheads():
1174 # The topo heads set is included in the branch heads set of the
1174 # The topo heads set is included in the branch heads set of the
1175 # current branch, so it's sufficient to test branchheads
1175 # current branch, so it's sufficient to test branchheads
1176 raise util.Abort(_('can only close branch heads'))
1176 raise util.Abort(_('can only close branch heads'))
1177 extra['close'] = 1
1177 extra['close'] = 1
1178 e = cmdutil.commiteditor
1178 e = cmdutil.commiteditor
1179 if opts.get('force_editor'):
1179 if opts.get('force_editor'):
1180 e = cmdutil.commitforceeditor
1180 e = cmdutil.commitforceeditor
1181
1181
1182 def commitfunc(ui, repo, message, match, opts):
1182 def commitfunc(ui, repo, message, match, opts):
1183 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1183 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1184 editor=e, extra=extra)
1184 editor=e, extra=extra)
1185
1185
1186 branch = repo[None].branch()
1186 branch = repo[None].branch()
1187 bheads = repo.branchheads(branch)
1187 bheads = repo.branchheads(branch)
1188
1188
1189 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1189 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1190 if not node:
1190 if not node:
1191 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1191 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1192 if stat[3]:
1192 if stat[3]:
1193 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1193 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1194 % len(stat[3]))
1194 % len(stat[3]))
1195 else:
1195 else:
1196 ui.status(_("nothing changed\n"))
1196 ui.status(_("nothing changed\n"))
1197 return 1
1197 return 1
1198
1198
1199 ctx = repo[node]
1199 ctx = repo[node]
1200 parents = ctx.parents()
1200 parents = ctx.parents()
1201
1201
1202 if (bheads and node not in bheads and not
1202 if (bheads and node not in bheads and not
1203 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1203 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1204 ui.status(_('created new head\n'))
1204 ui.status(_('created new head\n'))
1205 # The message is not printed for initial roots. For the other
1205 # The message is not printed for initial roots. For the other
1206 # changesets, it is printed in the following situations:
1206 # changesets, it is printed in the following situations:
1207 #
1207 #
1208 # Par column: for the 2 parents with ...
1208 # Par column: for the 2 parents with ...
1209 # N: null or no parent
1209 # N: null or no parent
1210 # B: parent is on another named branch
1210 # B: parent is on another named branch
1211 # C: parent is a regular non head changeset
1211 # C: parent is a regular non head changeset
1212 # H: parent was a branch head of the current branch
1212 # H: parent was a branch head of the current branch
1213 # Msg column: whether we print "created new head" message
1213 # Msg column: whether we print "created new head" message
1214 # In the following, it is assumed that there already exists some
1214 # In the following, it is assumed that there already exists some
1215 # initial branch heads of the current branch, otherwise nothing is
1215 # initial branch heads of the current branch, otherwise nothing is
1216 # printed anyway.
1216 # printed anyway.
1217 #
1217 #
1218 # Par Msg Comment
1218 # Par Msg Comment
1219 # NN y additional topo root
1219 # NN y additional topo root
1220 #
1220 #
1221 # BN y additional branch root
1221 # BN y additional branch root
1222 # CN y additional topo head
1222 # CN y additional topo head
1223 # HN n usual case
1223 # HN n usual case
1224 #
1224 #
1225 # BB y weird additional branch root
1225 # BB y weird additional branch root
1226 # CB y branch merge
1226 # CB y branch merge
1227 # HB n merge with named branch
1227 # HB n merge with named branch
1228 #
1228 #
1229 # CC y additional head from merge
1229 # CC y additional head from merge
1230 # CH n merge with a head
1230 # CH n merge with a head
1231 #
1231 #
1232 # HH n head merge: head count decreases
1232 # HH n head merge: head count decreases
1233
1233
1234 if not opts.get('close_branch'):
1234 if not opts.get('close_branch'):
1235 for r in parents:
1235 for r in parents:
1236 if r.extra().get('close') and r.branch() == branch:
1236 if r.extra().get('close') and r.branch() == branch:
1237 ui.status(_('reopening closed branch head %d\n') % r)
1237 ui.status(_('reopening closed branch head %d\n') % r)
1238
1238
1239 if ui.debugflag:
1239 if ui.debugflag:
1240 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1240 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1241 elif ui.verbose:
1241 elif ui.verbose:
1242 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1242 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1243
1243
1244 @command('copy|cp',
1244 @command('copy|cp',
1245 [('A', 'after', None, _('record a copy that has already occurred')),
1245 [('A', 'after', None, _('record a copy that has already occurred')),
1246 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1246 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1247 ] + walkopts + dryrunopts,
1247 ] + walkopts + dryrunopts,
1248 _('[OPTION]... [SOURCE]... DEST'))
1248 _('[OPTION]... [SOURCE]... DEST'))
1249 def copy(ui, repo, *pats, **opts):
1249 def copy(ui, repo, *pats, **opts):
1250 """mark files as copied for the next commit
1250 """mark files as copied for the next commit
1251
1251
1252 Mark dest as having copies of source files. If dest is a
1252 Mark dest as having copies of source files. If dest is a
1253 directory, copies are put in that directory. If dest is a file,
1253 directory, copies are put in that directory. If dest is a file,
1254 the source must be a single file.
1254 the source must be a single file.
1255
1255
1256 By default, this command copies the contents of files as they
1256 By default, this command copies the contents of files as they
1257 exist in the working directory. If invoked with -A/--after, the
1257 exist in the working directory. If invoked with -A/--after, the
1258 operation is recorded, but no copying is performed.
1258 operation is recorded, but no copying is performed.
1259
1259
1260 This command takes effect with the next commit. To undo a copy
1260 This command takes effect with the next commit. To undo a copy
1261 before that, see :hg:`revert`.
1261 before that, see :hg:`revert`.
1262
1262
1263 Returns 0 on success, 1 if errors are encountered.
1263 Returns 0 on success, 1 if errors are encountered.
1264 """
1264 """
1265 wlock = repo.wlock(False)
1265 wlock = repo.wlock(False)
1266 try:
1266 try:
1267 return cmdutil.copy(ui, repo, pats, opts)
1267 return cmdutil.copy(ui, repo, pats, opts)
1268 finally:
1268 finally:
1269 wlock.release()
1269 wlock.release()
1270
1270
1271 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1271 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1272 def debugancestor(ui, repo, *args):
1272 def debugancestor(ui, repo, *args):
1273 """find the ancestor revision of two revisions in a given index"""
1273 """find the ancestor revision of two revisions in a given index"""
1274 if len(args) == 3:
1274 if len(args) == 3:
1275 index, rev1, rev2 = args
1275 index, rev1, rev2 = args
1276 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1276 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1277 lookup = r.lookup
1277 lookup = r.lookup
1278 elif len(args) == 2:
1278 elif len(args) == 2:
1279 if not repo:
1279 if not repo:
1280 raise util.Abort(_("there is no Mercurial repository here "
1280 raise util.Abort(_("there is no Mercurial repository here "
1281 "(.hg not found)"))
1281 "(.hg not found)"))
1282 rev1, rev2 = args
1282 rev1, rev2 = args
1283 r = repo.changelog
1283 r = repo.changelog
1284 lookup = repo.lookup
1284 lookup = repo.lookup
1285 else:
1285 else:
1286 raise util.Abort(_('either two or three arguments required'))
1286 raise util.Abort(_('either two or three arguments required'))
1287 a = r.ancestor(lookup(rev1), lookup(rev2))
1287 a = r.ancestor(lookup(rev1), lookup(rev2))
1288 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1288 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1289
1289
1290 @command('debugbuilddag',
1290 @command('debugbuilddag',
1291 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1291 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1292 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1292 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1293 ('n', 'new-file', None, _('add new file at each rev'))],
1293 ('n', 'new-file', None, _('add new file at each rev'))],
1294 _('[OPTION]... [TEXT]'))
1294 _('[OPTION]... [TEXT]'))
1295 def debugbuilddag(ui, repo, text=None,
1295 def debugbuilddag(ui, repo, text=None,
1296 mergeable_file=False,
1296 mergeable_file=False,
1297 overwritten_file=False,
1297 overwritten_file=False,
1298 new_file=False):
1298 new_file=False):
1299 """builds a repo with a given DAG from scratch in the current empty repo
1299 """builds a repo with a given DAG from scratch in the current empty repo
1300
1300
1301 The description of the DAG is read from stdin if not given on the
1301 The description of the DAG is read from stdin if not given on the
1302 command line.
1302 command line.
1303
1303
1304 Elements:
1304 Elements:
1305
1305
1306 - "+n" is a linear run of n nodes based on the current default parent
1306 - "+n" is a linear run of n nodes based on the current default parent
1307 - "." is a single node based on the current default parent
1307 - "." is a single node based on the current default parent
1308 - "$" resets the default parent to null (implied at the start);
1308 - "$" resets the default parent to null (implied at the start);
1309 otherwise the default parent is always the last node created
1309 otherwise the default parent is always the last node created
1310 - "<p" sets the default parent to the backref p
1310 - "<p" sets the default parent to the backref p
1311 - "*p" is a fork at parent p, which is a backref
1311 - "*p" is a fork at parent p, which is a backref
1312 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1312 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1313 - "/p2" is a merge of the preceding node and p2
1313 - "/p2" is a merge of the preceding node and p2
1314 - ":tag" defines a local tag for the preceding node
1314 - ":tag" defines a local tag for the preceding node
1315 - "@branch" sets the named branch for subsequent nodes
1315 - "@branch" sets the named branch for subsequent nodes
1316 - "#...\\n" is a comment up to the end of the line
1316 - "#...\\n" is a comment up to the end of the line
1317
1317
1318 Whitespace between the above elements is ignored.
1318 Whitespace between the above elements is ignored.
1319
1319
1320 A backref is either
1320 A backref is either
1321
1321
1322 - a number n, which references the node curr-n, where curr is the current
1322 - a number n, which references the node curr-n, where curr is the current
1323 node, or
1323 node, or
1324 - the name of a local tag you placed earlier using ":tag", or
1324 - the name of a local tag you placed earlier using ":tag", or
1325 - empty to denote the default parent.
1325 - empty to denote the default parent.
1326
1326
1327 All string valued-elements are either strictly alphanumeric, or must
1327 All string valued-elements are either strictly alphanumeric, or must
1328 be enclosed in double quotes ("..."), with "\\" as escape character.
1328 be enclosed in double quotes ("..."), with "\\" as escape character.
1329 """
1329 """
1330
1330
1331 if text is None:
1331 if text is None:
1332 ui.status(_("reading DAG from stdin\n"))
1332 ui.status(_("reading DAG from stdin\n"))
1333 text = ui.fin.read()
1333 text = ui.fin.read()
1334
1334
1335 cl = repo.changelog
1335 cl = repo.changelog
1336 if len(cl) > 0:
1336 if len(cl) > 0:
1337 raise util.Abort(_('repository is not empty'))
1337 raise util.Abort(_('repository is not empty'))
1338
1338
1339 # determine number of revs in DAG
1339 # determine number of revs in DAG
1340 total = 0
1340 total = 0
1341 for type, data in dagparser.parsedag(text):
1341 for type, data in dagparser.parsedag(text):
1342 if type == 'n':
1342 if type == 'n':
1343 total += 1
1343 total += 1
1344
1344
1345 if mergeable_file:
1345 if mergeable_file:
1346 linesperrev = 2
1346 linesperrev = 2
1347 # make a file with k lines per rev
1347 # make a file with k lines per rev
1348 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1348 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1349 initialmergedlines.append("")
1349 initialmergedlines.append("")
1350
1350
1351 tags = []
1351 tags = []
1352
1352
1353 tr = repo.transaction("builddag")
1353 tr = repo.transaction("builddag")
1354 try:
1354 try:
1355
1355
1356 at = -1
1356 at = -1
1357 atbranch = 'default'
1357 atbranch = 'default'
1358 nodeids = []
1358 nodeids = []
1359 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1359 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1360 for type, data in dagparser.parsedag(text):
1360 for type, data in dagparser.parsedag(text):
1361 if type == 'n':
1361 if type == 'n':
1362 ui.note('node %s\n' % str(data))
1362 ui.note('node %s\n' % str(data))
1363 id, ps = data
1363 id, ps = data
1364
1364
1365 files = []
1365 files = []
1366 fctxs = {}
1366 fctxs = {}
1367
1367
1368 p2 = None
1368 p2 = None
1369 if mergeable_file:
1369 if mergeable_file:
1370 fn = "mf"
1370 fn = "mf"
1371 p1 = repo[ps[0]]
1371 p1 = repo[ps[0]]
1372 if len(ps) > 1:
1372 if len(ps) > 1:
1373 p2 = repo[ps[1]]
1373 p2 = repo[ps[1]]
1374 pa = p1.ancestor(p2)
1374 pa = p1.ancestor(p2)
1375 base, local, other = [x[fn].data() for x in pa, p1, p2]
1375 base, local, other = [x[fn].data() for x in pa, p1, p2]
1376 m3 = simplemerge.Merge3Text(base, local, other)
1376 m3 = simplemerge.Merge3Text(base, local, other)
1377 ml = [l.strip() for l in m3.merge_lines()]
1377 ml = [l.strip() for l in m3.merge_lines()]
1378 ml.append("")
1378 ml.append("")
1379 elif at > 0:
1379 elif at > 0:
1380 ml = p1[fn].data().split("\n")
1380 ml = p1[fn].data().split("\n")
1381 else:
1381 else:
1382 ml = initialmergedlines
1382 ml = initialmergedlines
1383 ml[id * linesperrev] += " r%i" % id
1383 ml[id * linesperrev] += " r%i" % id
1384 mergedtext = "\n".join(ml)
1384 mergedtext = "\n".join(ml)
1385 files.append(fn)
1385 files.append(fn)
1386 fctxs[fn] = context.memfilectx(fn, mergedtext)
1386 fctxs[fn] = context.memfilectx(fn, mergedtext)
1387
1387
1388 if overwritten_file:
1388 if overwritten_file:
1389 fn = "of"
1389 fn = "of"
1390 files.append(fn)
1390 files.append(fn)
1391 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1391 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1392
1392
1393 if new_file:
1393 if new_file:
1394 fn = "nf%i" % id
1394 fn = "nf%i" % id
1395 files.append(fn)
1395 files.append(fn)
1396 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1396 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1397 if len(ps) > 1:
1397 if len(ps) > 1:
1398 if not p2:
1398 if not p2:
1399 p2 = repo[ps[1]]
1399 p2 = repo[ps[1]]
1400 for fn in p2:
1400 for fn in p2:
1401 if fn.startswith("nf"):
1401 if fn.startswith("nf"):
1402 files.append(fn)
1402 files.append(fn)
1403 fctxs[fn] = p2[fn]
1403 fctxs[fn] = p2[fn]
1404
1404
1405 def fctxfn(repo, cx, path):
1405 def fctxfn(repo, cx, path):
1406 return fctxs.get(path)
1406 return fctxs.get(path)
1407
1407
1408 if len(ps) == 0 or ps[0] < 0:
1408 if len(ps) == 0 or ps[0] < 0:
1409 pars = [None, None]
1409 pars = [None, None]
1410 elif len(ps) == 1:
1410 elif len(ps) == 1:
1411 pars = [nodeids[ps[0]], None]
1411 pars = [nodeids[ps[0]], None]
1412 else:
1412 else:
1413 pars = [nodeids[p] for p in ps]
1413 pars = [nodeids[p] for p in ps]
1414 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1414 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1415 date=(id, 0),
1415 date=(id, 0),
1416 user="debugbuilddag",
1416 user="debugbuilddag",
1417 extra={'branch': atbranch})
1417 extra={'branch': atbranch})
1418 nodeid = repo.commitctx(cx)
1418 nodeid = repo.commitctx(cx)
1419 nodeids.append(nodeid)
1419 nodeids.append(nodeid)
1420 at = id
1420 at = id
1421 elif type == 'l':
1421 elif type == 'l':
1422 id, name = data
1422 id, name = data
1423 ui.note('tag %s\n' % name)
1423 ui.note('tag %s\n' % name)
1424 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1424 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1425 elif type == 'a':
1425 elif type == 'a':
1426 ui.note('branch %s\n' % data)
1426 ui.note('branch %s\n' % data)
1427 atbranch = data
1427 atbranch = data
1428 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1428 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1429 tr.close()
1429 tr.close()
1430 finally:
1430 finally:
1431 ui.progress(_('building'), None)
1431 ui.progress(_('building'), None)
1432 tr.release()
1432 tr.release()
1433
1433
1434 if tags:
1434 if tags:
1435 repo.opener.write("localtags", "".join(tags))
1435 repo.opener.write("localtags", "".join(tags))
1436
1436
1437 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1437 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1438 def debugbundle(ui, bundlepath, all=None, **opts):
1438 def debugbundle(ui, bundlepath, all=None, **opts):
1439 """lists the contents of a bundle"""
1439 """lists the contents of a bundle"""
1440 f = url.open(ui, bundlepath)
1440 f = url.open(ui, bundlepath)
1441 try:
1441 try:
1442 gen = changegroup.readbundle(f, bundlepath)
1442 gen = changegroup.readbundle(f, bundlepath)
1443 if all:
1443 if all:
1444 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1444 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1445
1445
1446 def showchunks(named):
1446 def showchunks(named):
1447 ui.write("\n%s\n" % named)
1447 ui.write("\n%s\n" % named)
1448 chain = None
1448 chain = None
1449 while True:
1449 while True:
1450 chunkdata = gen.deltachunk(chain)
1450 chunkdata = gen.deltachunk(chain)
1451 if not chunkdata:
1451 if not chunkdata:
1452 break
1452 break
1453 node = chunkdata['node']
1453 node = chunkdata['node']
1454 p1 = chunkdata['p1']
1454 p1 = chunkdata['p1']
1455 p2 = chunkdata['p2']
1455 p2 = chunkdata['p2']
1456 cs = chunkdata['cs']
1456 cs = chunkdata['cs']
1457 deltabase = chunkdata['deltabase']
1457 deltabase = chunkdata['deltabase']
1458 delta = chunkdata['delta']
1458 delta = chunkdata['delta']
1459 ui.write("%s %s %s %s %s %s\n" %
1459 ui.write("%s %s %s %s %s %s\n" %
1460 (hex(node), hex(p1), hex(p2),
1460 (hex(node), hex(p1), hex(p2),
1461 hex(cs), hex(deltabase), len(delta)))
1461 hex(cs), hex(deltabase), len(delta)))
1462 chain = node
1462 chain = node
1463
1463
1464 chunkdata = gen.changelogheader()
1464 chunkdata = gen.changelogheader()
1465 showchunks("changelog")
1465 showchunks("changelog")
1466 chunkdata = gen.manifestheader()
1466 chunkdata = gen.manifestheader()
1467 showchunks("manifest")
1467 showchunks("manifest")
1468 while True:
1468 while True:
1469 chunkdata = gen.filelogheader()
1469 chunkdata = gen.filelogheader()
1470 if not chunkdata:
1470 if not chunkdata:
1471 break
1471 break
1472 fname = chunkdata['filename']
1472 fname = chunkdata['filename']
1473 showchunks(fname)
1473 showchunks(fname)
1474 else:
1474 else:
1475 chunkdata = gen.changelogheader()
1475 chunkdata = gen.changelogheader()
1476 chain = None
1476 chain = None
1477 while True:
1477 while True:
1478 chunkdata = gen.deltachunk(chain)
1478 chunkdata = gen.deltachunk(chain)
1479 if not chunkdata:
1479 if not chunkdata:
1480 break
1480 break
1481 node = chunkdata['node']
1481 node = chunkdata['node']
1482 ui.write("%s\n" % hex(node))
1482 ui.write("%s\n" % hex(node))
1483 chain = node
1483 chain = node
1484 finally:
1484 finally:
1485 f.close()
1485 f.close()
1486
1486
1487 @command('debugcheckstate', [], '')
1487 @command('debugcheckstate', [], '')
1488 def debugcheckstate(ui, repo):
1488 def debugcheckstate(ui, repo):
1489 """validate the correctness of the current dirstate"""
1489 """validate the correctness of the current dirstate"""
1490 parent1, parent2 = repo.dirstate.parents()
1490 parent1, parent2 = repo.dirstate.parents()
1491 m1 = repo[parent1].manifest()
1491 m1 = repo[parent1].manifest()
1492 m2 = repo[parent2].manifest()
1492 m2 = repo[parent2].manifest()
1493 errors = 0
1493 errors = 0
1494 for f in repo.dirstate:
1494 for f in repo.dirstate:
1495 state = repo.dirstate[f]
1495 state = repo.dirstate[f]
1496 if state in "nr" and f not in m1:
1496 if state in "nr" and f not in m1:
1497 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1497 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1498 errors += 1
1498 errors += 1
1499 if state in "a" and f in m1:
1499 if state in "a" and f in m1:
1500 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1500 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1501 errors += 1
1501 errors += 1
1502 if state in "m" and f not in m1 and f not in m2:
1502 if state in "m" and f not in m1 and f not in m2:
1503 ui.warn(_("%s in state %s, but not in either manifest\n") %
1503 ui.warn(_("%s in state %s, but not in either manifest\n") %
1504 (f, state))
1504 (f, state))
1505 errors += 1
1505 errors += 1
1506 for f in m1:
1506 for f in m1:
1507 state = repo.dirstate[f]
1507 state = repo.dirstate[f]
1508 if state not in "nrm":
1508 if state not in "nrm":
1509 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1509 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1510 errors += 1
1510 errors += 1
1511 if errors:
1511 if errors:
1512 error = _(".hg/dirstate inconsistent with current parent's manifest")
1512 error = _(".hg/dirstate inconsistent with current parent's manifest")
1513 raise util.Abort(error)
1513 raise util.Abort(error)
1514
1514
1515 @command('debugcommands', [], _('[COMMAND]'))
1515 @command('debugcommands', [], _('[COMMAND]'))
1516 def debugcommands(ui, cmd='', *args):
1516 def debugcommands(ui, cmd='', *args):
1517 """list all available commands and options"""
1517 """list all available commands and options"""
1518 for cmd, vals in sorted(table.iteritems()):
1518 for cmd, vals in sorted(table.iteritems()):
1519 cmd = cmd.split('|')[0].strip('^')
1519 cmd = cmd.split('|')[0].strip('^')
1520 opts = ', '.join([i[1] for i in vals[1]])
1520 opts = ', '.join([i[1] for i in vals[1]])
1521 ui.write('%s: %s\n' % (cmd, opts))
1521 ui.write('%s: %s\n' % (cmd, opts))
1522
1522
1523 @command('debugcomplete',
1523 @command('debugcomplete',
1524 [('o', 'options', None, _('show the command options'))],
1524 [('o', 'options', None, _('show the command options'))],
1525 _('[-o] CMD'))
1525 _('[-o] CMD'))
1526 def debugcomplete(ui, cmd='', **opts):
1526 def debugcomplete(ui, cmd='', **opts):
1527 """returns the completion list associated with the given command"""
1527 """returns the completion list associated with the given command"""
1528
1528
1529 if opts.get('options'):
1529 if opts.get('options'):
1530 options = []
1530 options = []
1531 otables = [globalopts]
1531 otables = [globalopts]
1532 if cmd:
1532 if cmd:
1533 aliases, entry = cmdutil.findcmd(cmd, table, False)
1533 aliases, entry = cmdutil.findcmd(cmd, table, False)
1534 otables.append(entry[1])
1534 otables.append(entry[1])
1535 for t in otables:
1535 for t in otables:
1536 for o in t:
1536 for o in t:
1537 if "(DEPRECATED)" in o[3]:
1537 if "(DEPRECATED)" in o[3]:
1538 continue
1538 continue
1539 if o[0]:
1539 if o[0]:
1540 options.append('-%s' % o[0])
1540 options.append('-%s' % o[0])
1541 options.append('--%s' % o[1])
1541 options.append('--%s' % o[1])
1542 ui.write("%s\n" % "\n".join(options))
1542 ui.write("%s\n" % "\n".join(options))
1543 return
1543 return
1544
1544
1545 cmdlist = cmdutil.findpossible(cmd, table)
1545 cmdlist = cmdutil.findpossible(cmd, table)
1546 if ui.verbose:
1546 if ui.verbose:
1547 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1547 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1548 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1548 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1549
1549
1550 @command('debugdag',
1550 @command('debugdag',
1551 [('t', 'tags', None, _('use tags as labels')),
1551 [('t', 'tags', None, _('use tags as labels')),
1552 ('b', 'branches', None, _('annotate with branch names')),
1552 ('b', 'branches', None, _('annotate with branch names')),
1553 ('', 'dots', None, _('use dots for runs')),
1553 ('', 'dots', None, _('use dots for runs')),
1554 ('s', 'spaces', None, _('separate elements by spaces'))],
1554 ('s', 'spaces', None, _('separate elements by spaces'))],
1555 _('[OPTION]... [FILE [REV]...]'))
1555 _('[OPTION]... [FILE [REV]...]'))
1556 def debugdag(ui, repo, file_=None, *revs, **opts):
1556 def debugdag(ui, repo, file_=None, *revs, **opts):
1557 """format the changelog or an index DAG as a concise textual description
1557 """format the changelog or an index DAG as a concise textual description
1558
1558
1559 If you pass a revlog index, the revlog's DAG is emitted. If you list
1559 If you pass a revlog index, the revlog's DAG is emitted. If you list
1560 revision numbers, they get labelled in the output as rN.
1560 revision numbers, they get labelled in the output as rN.
1561
1561
1562 Otherwise, the changelog DAG of the current repo is emitted.
1562 Otherwise, the changelog DAG of the current repo is emitted.
1563 """
1563 """
1564 spaces = opts.get('spaces')
1564 spaces = opts.get('spaces')
1565 dots = opts.get('dots')
1565 dots = opts.get('dots')
1566 if file_:
1566 if file_:
1567 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1567 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1568 revs = set((int(r) for r in revs))
1568 revs = set((int(r) for r in revs))
1569 def events():
1569 def events():
1570 for r in rlog:
1570 for r in rlog:
1571 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1571 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1572 if r in revs:
1572 if r in revs:
1573 yield 'l', (r, "r%i" % r)
1573 yield 'l', (r, "r%i" % r)
1574 elif repo:
1574 elif repo:
1575 cl = repo.changelog
1575 cl = repo.changelog
1576 tags = opts.get('tags')
1576 tags = opts.get('tags')
1577 branches = opts.get('branches')
1577 branches = opts.get('branches')
1578 if tags:
1578 if tags:
1579 labels = {}
1579 labels = {}
1580 for l, n in repo.tags().items():
1580 for l, n in repo.tags().items():
1581 labels.setdefault(cl.rev(n), []).append(l)
1581 labels.setdefault(cl.rev(n), []).append(l)
1582 def events():
1582 def events():
1583 b = "default"
1583 b = "default"
1584 for r in cl:
1584 for r in cl:
1585 if branches:
1585 if branches:
1586 newb = cl.read(cl.node(r))[5]['branch']
1586 newb = cl.read(cl.node(r))[5]['branch']
1587 if newb != b:
1587 if newb != b:
1588 yield 'a', newb
1588 yield 'a', newb
1589 b = newb
1589 b = newb
1590 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1590 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1591 if tags:
1591 if tags:
1592 ls = labels.get(r)
1592 ls = labels.get(r)
1593 if ls:
1593 if ls:
1594 for l in ls:
1594 for l in ls:
1595 yield 'l', (r, l)
1595 yield 'l', (r, l)
1596 else:
1596 else:
1597 raise util.Abort(_('need repo for changelog dag'))
1597 raise util.Abort(_('need repo for changelog dag'))
1598
1598
1599 for line in dagparser.dagtextlines(events(),
1599 for line in dagparser.dagtextlines(events(),
1600 addspaces=spaces,
1600 addspaces=spaces,
1601 wraplabels=True,
1601 wraplabels=True,
1602 wrapannotations=True,
1602 wrapannotations=True,
1603 wrapnonlinear=dots,
1603 wrapnonlinear=dots,
1604 usedots=dots,
1604 usedots=dots,
1605 maxlinewidth=70):
1605 maxlinewidth=70):
1606 ui.write(line)
1606 ui.write(line)
1607 ui.write("\n")
1607 ui.write("\n")
1608
1608
1609 @command('debugdata',
1609 @command('debugdata',
1610 [('c', 'changelog', False, _('open changelog')),
1610 [('c', 'changelog', False, _('open changelog')),
1611 ('m', 'manifest', False, _('open manifest'))],
1611 ('m', 'manifest', False, _('open manifest'))],
1612 _('-c|-m|FILE REV'))
1612 _('-c|-m|FILE REV'))
1613 def debugdata(ui, repo, file_, rev = None, **opts):
1613 def debugdata(ui, repo, file_, rev = None, **opts):
1614 """dump the contents of a data file revision"""
1614 """dump the contents of a data file revision"""
1615 if opts.get('changelog') or opts.get('manifest'):
1615 if opts.get('changelog') or opts.get('manifest'):
1616 file_, rev = None, file_
1616 file_, rev = None, file_
1617 elif rev is None:
1617 elif rev is None:
1618 raise error.CommandError('debugdata', _('invalid arguments'))
1618 raise error.CommandError('debugdata', _('invalid arguments'))
1619 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1619 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1620 try:
1620 try:
1621 ui.write(r.revision(r.lookup(rev)))
1621 ui.write(r.revision(r.lookup(rev)))
1622 except KeyError:
1622 except KeyError:
1623 raise util.Abort(_('invalid revision identifier %s') % rev)
1623 raise util.Abort(_('invalid revision identifier %s') % rev)
1624
1624
1625 @command('debugdate',
1625 @command('debugdate',
1626 [('e', 'extended', None, _('try extended date formats'))],
1626 [('e', 'extended', None, _('try extended date formats'))],
1627 _('[-e] DATE [RANGE]'))
1627 _('[-e] DATE [RANGE]'))
1628 def debugdate(ui, date, range=None, **opts):
1628 def debugdate(ui, date, range=None, **opts):
1629 """parse and display a date"""
1629 """parse and display a date"""
1630 if opts["extended"]:
1630 if opts["extended"]:
1631 d = util.parsedate(date, util.extendeddateformats)
1631 d = util.parsedate(date, util.extendeddateformats)
1632 else:
1632 else:
1633 d = util.parsedate(date)
1633 d = util.parsedate(date)
1634 ui.write("internal: %s %s\n" % d)
1634 ui.write("internal: %s %s\n" % d)
1635 ui.write("standard: %s\n" % util.datestr(d))
1635 ui.write("standard: %s\n" % util.datestr(d))
1636 if range:
1636 if range:
1637 m = util.matchdate(range)
1637 m = util.matchdate(range)
1638 ui.write("match: %s\n" % m(d[0]))
1638 ui.write("match: %s\n" % m(d[0]))
1639
1639
1640 @command('debugdiscovery',
1640 @command('debugdiscovery',
1641 [('', 'old', None, _('use old-style discovery')),
1641 [('', 'old', None, _('use old-style discovery')),
1642 ('', 'nonheads', None,
1642 ('', 'nonheads', None,
1643 _('use old-style discovery with non-heads included')),
1643 _('use old-style discovery with non-heads included')),
1644 ] + remoteopts,
1644 ] + remoteopts,
1645 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1645 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1646 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1646 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1647 """runs the changeset discovery protocol in isolation"""
1647 """runs the changeset discovery protocol in isolation"""
1648 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1648 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1649 remote = hg.peer(repo, opts, remoteurl)
1649 remote = hg.peer(repo, opts, remoteurl)
1650 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1650 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1651
1651
1652 # make sure tests are repeatable
1652 # make sure tests are repeatable
1653 random.seed(12323)
1653 random.seed(12323)
1654
1654
1655 def doit(localheads, remoteheads):
1655 def doit(localheads, remoteheads):
1656 if opts.get('old'):
1656 if opts.get('old'):
1657 if localheads:
1657 if localheads:
1658 raise util.Abort('cannot use localheads with old style discovery')
1658 raise util.Abort('cannot use localheads with old style discovery')
1659 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1659 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1660 force=True)
1660 force=True)
1661 common = set(common)
1661 common = set(common)
1662 if not opts.get('nonheads'):
1662 if not opts.get('nonheads'):
1663 ui.write("unpruned common: %s\n" % " ".join([short(n)
1663 ui.write("unpruned common: %s\n" % " ".join([short(n)
1664 for n in common]))
1664 for n in common]))
1665 dag = dagutil.revlogdag(repo.changelog)
1665 dag = dagutil.revlogdag(repo.changelog)
1666 all = dag.ancestorset(dag.internalizeall(common))
1666 all = dag.ancestorset(dag.internalizeall(common))
1667 common = dag.externalizeall(dag.headsetofconnecteds(all))
1667 common = dag.externalizeall(dag.headsetofconnecteds(all))
1668 else:
1668 else:
1669 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1669 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1670 common = set(common)
1670 common = set(common)
1671 rheads = set(hds)
1671 rheads = set(hds)
1672 lheads = set(repo.heads())
1672 lheads = set(repo.heads())
1673 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1673 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1674 if lheads <= common:
1674 if lheads <= common:
1675 ui.write("local is subset\n")
1675 ui.write("local is subset\n")
1676 elif rheads <= common:
1676 elif rheads <= common:
1677 ui.write("remote is subset\n")
1677 ui.write("remote is subset\n")
1678
1678
1679 serverlogs = opts.get('serverlog')
1679 serverlogs = opts.get('serverlog')
1680 if serverlogs:
1680 if serverlogs:
1681 for filename in serverlogs:
1681 for filename in serverlogs:
1682 logfile = open(filename, 'r')
1682 logfile = open(filename, 'r')
1683 try:
1683 try:
1684 line = logfile.readline()
1684 line = logfile.readline()
1685 while line:
1685 while line:
1686 parts = line.strip().split(';')
1686 parts = line.strip().split(';')
1687 op = parts[1]
1687 op = parts[1]
1688 if op == 'cg':
1688 if op == 'cg':
1689 pass
1689 pass
1690 elif op == 'cgss':
1690 elif op == 'cgss':
1691 doit(parts[2].split(' '), parts[3].split(' '))
1691 doit(parts[2].split(' '), parts[3].split(' '))
1692 elif op == 'unb':
1692 elif op == 'unb':
1693 doit(parts[3].split(' '), parts[2].split(' '))
1693 doit(parts[3].split(' '), parts[2].split(' '))
1694 line = logfile.readline()
1694 line = logfile.readline()
1695 finally:
1695 finally:
1696 logfile.close()
1696 logfile.close()
1697
1697
1698 else:
1698 else:
1699 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1699 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1700 opts.get('remote_head'))
1700 opts.get('remote_head'))
1701 localrevs = opts.get('local_head')
1701 localrevs = opts.get('local_head')
1702 doit(localrevs, remoterevs)
1702 doit(localrevs, remoterevs)
1703
1703
1704 @command('debugfileset', [], ('REVSPEC'))
1704 @command('debugfileset', [], ('REVSPEC'))
1705 def debugfileset(ui, repo, expr):
1705 def debugfileset(ui, repo, expr):
1706 '''parse and apply a fileset specification'''
1706 '''parse and apply a fileset specification'''
1707 if ui.verbose:
1707 if ui.verbose:
1708 tree = fileset.parse(expr)[0]
1708 tree = fileset.parse(expr)[0]
1709 ui.note(tree, "\n")
1709 ui.note(tree, "\n")
1710
1710
1711 for f in fileset.getfileset(repo[None], expr):
1711 for f in fileset.getfileset(repo[None], expr):
1712 ui.write("%s\n" % f)
1712 ui.write("%s\n" % f)
1713
1713
1714 @command('debugfsinfo', [], _('[PATH]'))
1714 @command('debugfsinfo', [], _('[PATH]'))
1715 def debugfsinfo(ui, path = "."):
1715 def debugfsinfo(ui, path = "."):
1716 """show information detected about current filesystem"""
1716 """show information detected about current filesystem"""
1717 util.writefile('.debugfsinfo', '')
1717 util.writefile('.debugfsinfo', '')
1718 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1718 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1719 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1719 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1720 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1720 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1721 and 'yes' or 'no'))
1721 and 'yes' or 'no'))
1722 os.unlink('.debugfsinfo')
1722 os.unlink('.debugfsinfo')
1723
1723
1724 @command('debuggetbundle',
1724 @command('debuggetbundle',
1725 [('H', 'head', [], _('id of head node'), _('ID')),
1725 [('H', 'head', [], _('id of head node'), _('ID')),
1726 ('C', 'common', [], _('id of common node'), _('ID')),
1726 ('C', 'common', [], _('id of common node'), _('ID')),
1727 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1727 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1728 _('REPO FILE [-H|-C ID]...'))
1728 _('REPO FILE [-H|-C ID]...'))
1729 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1729 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1730 """retrieves a bundle from a repo
1730 """retrieves a bundle from a repo
1731
1731
1732 Every ID must be a full-length hex node id string. Saves the bundle to the
1732 Every ID must be a full-length hex node id string. Saves the bundle to the
1733 given file.
1733 given file.
1734 """
1734 """
1735 repo = hg.peer(ui, opts, repopath)
1735 repo = hg.peer(ui, opts, repopath)
1736 if not repo.capable('getbundle'):
1736 if not repo.capable('getbundle'):
1737 raise util.Abort("getbundle() not supported by target repository")
1737 raise util.Abort("getbundle() not supported by target repository")
1738 args = {}
1738 args = {}
1739 if common:
1739 if common:
1740 args['common'] = [bin(s) for s in common]
1740 args['common'] = [bin(s) for s in common]
1741 if head:
1741 if head:
1742 args['heads'] = [bin(s) for s in head]
1742 args['heads'] = [bin(s) for s in head]
1743 bundle = repo.getbundle('debug', **args)
1743 bundle = repo.getbundle('debug', **args)
1744
1744
1745 bundletype = opts.get('type', 'bzip2').lower()
1745 bundletype = opts.get('type', 'bzip2').lower()
1746 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1746 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1747 bundletype = btypes.get(bundletype)
1747 bundletype = btypes.get(bundletype)
1748 if bundletype not in changegroup.bundletypes:
1748 if bundletype not in changegroup.bundletypes:
1749 raise util.Abort(_('unknown bundle type specified with --type'))
1749 raise util.Abort(_('unknown bundle type specified with --type'))
1750 changegroup.writebundle(bundle, bundlepath, bundletype)
1750 changegroup.writebundle(bundle, bundlepath, bundletype)
1751
1751
1752 @command('debugignore', [], '')
1752 @command('debugignore', [], '')
1753 def debugignore(ui, repo, *values, **opts):
1753 def debugignore(ui, repo, *values, **opts):
1754 """display the combined ignore pattern"""
1754 """display the combined ignore pattern"""
1755 ignore = repo.dirstate._ignore
1755 ignore = repo.dirstate._ignore
1756 includepat = getattr(ignore, 'includepat', None)
1756 includepat = getattr(ignore, 'includepat', None)
1757 if includepat is not None:
1757 if includepat is not None:
1758 ui.write("%s\n" % includepat)
1758 ui.write("%s\n" % includepat)
1759 else:
1759 else:
1760 raise util.Abort(_("no ignore patterns found"))
1760 raise util.Abort(_("no ignore patterns found"))
1761
1761
1762 @command('debugindex',
1762 @command('debugindex',
1763 [('c', 'changelog', False, _('open changelog')),
1763 [('c', 'changelog', False, _('open changelog')),
1764 ('m', 'manifest', False, _('open manifest')),
1764 ('m', 'manifest', False, _('open manifest')),
1765 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1765 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1766 _('[-f FORMAT] -c|-m|FILE'))
1766 _('[-f FORMAT] -c|-m|FILE'))
1767 def debugindex(ui, repo, file_ = None, **opts):
1767 def debugindex(ui, repo, file_ = None, **opts):
1768 """dump the contents of an index file"""
1768 """dump the contents of an index file"""
1769 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1769 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1770 format = opts.get('format', 0)
1770 format = opts.get('format', 0)
1771 if format not in (0, 1):
1771 if format not in (0, 1):
1772 raise util.Abort(_("unknown format %d") % format)
1772 raise util.Abort(_("unknown format %d") % format)
1773
1773
1774 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1774 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1775 if generaldelta:
1775 if generaldelta:
1776 basehdr = ' delta'
1776 basehdr = ' delta'
1777 else:
1777 else:
1778 basehdr = ' base'
1778 basehdr = ' base'
1779
1779
1780 if format == 0:
1780 if format == 0:
1781 ui.write(" rev offset length " + basehdr + " linkrev"
1781 ui.write(" rev offset length " + basehdr + " linkrev"
1782 " nodeid p1 p2\n")
1782 " nodeid p1 p2\n")
1783 elif format == 1:
1783 elif format == 1:
1784 ui.write(" rev flag offset length"
1784 ui.write(" rev flag offset length"
1785 " size " + basehdr + " link p1 p2 nodeid\n")
1785 " size " + basehdr + " link p1 p2 nodeid\n")
1786
1786
1787 for i in r:
1787 for i in r:
1788 node = r.node(i)
1788 node = r.node(i)
1789 if generaldelta:
1789 if generaldelta:
1790 base = r.deltaparent(i)
1790 base = r.deltaparent(i)
1791 else:
1791 else:
1792 base = r.chainbase(i)
1792 base = r.chainbase(i)
1793 if format == 0:
1793 if format == 0:
1794 try:
1794 try:
1795 pp = r.parents(node)
1795 pp = r.parents(node)
1796 except:
1796 except:
1797 pp = [nullid, nullid]
1797 pp = [nullid, nullid]
1798 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1798 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1799 i, r.start(i), r.length(i), base, r.linkrev(i),
1799 i, r.start(i), r.length(i), base, r.linkrev(i),
1800 short(node), short(pp[0]), short(pp[1])))
1800 short(node), short(pp[0]), short(pp[1])))
1801 elif format == 1:
1801 elif format == 1:
1802 pr = r.parentrevs(i)
1802 pr = r.parentrevs(i)
1803 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1803 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1804 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1804 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1805 base, r.linkrev(i), pr[0], pr[1], short(node)))
1805 base, r.linkrev(i), pr[0], pr[1], short(node)))
1806
1806
1807 @command('debugindexdot', [], _('FILE'))
1807 @command('debugindexdot', [], _('FILE'))
1808 def debugindexdot(ui, repo, file_):
1808 def debugindexdot(ui, repo, file_):
1809 """dump an index DAG as a graphviz dot file"""
1809 """dump an index DAG as a graphviz dot file"""
1810 r = None
1810 r = None
1811 if repo:
1811 if repo:
1812 filelog = repo.file(file_)
1812 filelog = repo.file(file_)
1813 if len(filelog):
1813 if len(filelog):
1814 r = filelog
1814 r = filelog
1815 if not r:
1815 if not r:
1816 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1816 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1817 ui.write("digraph G {\n")
1817 ui.write("digraph G {\n")
1818 for i in r:
1818 for i in r:
1819 node = r.node(i)
1819 node = r.node(i)
1820 pp = r.parents(node)
1820 pp = r.parents(node)
1821 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1821 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1822 if pp[1] != nullid:
1822 if pp[1] != nullid:
1823 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1823 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1824 ui.write("}\n")
1824 ui.write("}\n")
1825
1825
1826 @command('debuginstall', [], '')
1826 @command('debuginstall', [], '')
1827 def debuginstall(ui):
1827 def debuginstall(ui):
1828 '''test Mercurial installation
1828 '''test Mercurial installation
1829
1829
1830 Returns 0 on success.
1830 Returns 0 on success.
1831 '''
1831 '''
1832
1832
1833 def writetemp(contents):
1833 def writetemp(contents):
1834 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1834 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1835 f = os.fdopen(fd, "wb")
1835 f = os.fdopen(fd, "wb")
1836 f.write(contents)
1836 f.write(contents)
1837 f.close()
1837 f.close()
1838 return name
1838 return name
1839
1839
1840 problems = 0
1840 problems = 0
1841
1841
1842 # encoding
1842 # encoding
1843 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1843 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1844 try:
1844 try:
1845 encoding.fromlocal("test")
1845 encoding.fromlocal("test")
1846 except util.Abort, inst:
1846 except util.Abort, inst:
1847 ui.write(" %s\n" % inst)
1847 ui.write(" %s\n" % inst)
1848 ui.write(_(" (check that your locale is properly set)\n"))
1848 ui.write(_(" (check that your locale is properly set)\n"))
1849 problems += 1
1849 problems += 1
1850
1850
1851 # compiled modules
1851 # compiled modules
1852 ui.status(_("Checking installed modules (%s)...\n")
1852 ui.status(_("Checking installed modules (%s)...\n")
1853 % os.path.dirname(__file__))
1853 % os.path.dirname(__file__))
1854 try:
1854 try:
1855 import bdiff, mpatch, base85, osutil
1855 import bdiff, mpatch, base85, osutil
1856 except Exception, inst:
1856 except Exception, inst:
1857 ui.write(" %s\n" % inst)
1857 ui.write(" %s\n" % inst)
1858 ui.write(_(" One or more extensions could not be found"))
1858 ui.write(_(" One or more extensions could not be found"))
1859 ui.write(_(" (check that you compiled the extensions)\n"))
1859 ui.write(_(" (check that you compiled the extensions)\n"))
1860 problems += 1
1860 problems += 1
1861
1861
1862 # templates
1862 # templates
1863 import templater
1863 import templater
1864 p = templater.templatepath()
1864 p = templater.templatepath()
1865 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1865 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1866 try:
1866 try:
1867 templater.templater(templater.templatepath("map-cmdline.default"))
1867 templater.templater(templater.templatepath("map-cmdline.default"))
1868 except Exception, inst:
1868 except Exception, inst:
1869 ui.write(" %s\n" % inst)
1869 ui.write(" %s\n" % inst)
1870 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1870 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1871 problems += 1
1871 problems += 1
1872
1872
1873 # editor
1873 # editor
1874 ui.status(_("Checking commit editor...\n"))
1874 ui.status(_("Checking commit editor...\n"))
1875 editor = ui.geteditor()
1875 editor = ui.geteditor()
1876 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1876 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1877 if not cmdpath:
1877 if not cmdpath:
1878 if editor == 'vi':
1878 if editor == 'vi':
1879 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1879 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1880 ui.write(_(" (specify a commit editor in your configuration"
1880 ui.write(_(" (specify a commit editor in your configuration"
1881 " file)\n"))
1881 " file)\n"))
1882 else:
1882 else:
1883 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1883 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1884 ui.write(_(" (specify a commit editor in your configuration"
1884 ui.write(_(" (specify a commit editor in your configuration"
1885 " file)\n"))
1885 " file)\n"))
1886 problems += 1
1886 problems += 1
1887
1887
1888 # check username
1888 # check username
1889 ui.status(_("Checking username...\n"))
1889 ui.status(_("Checking username...\n"))
1890 try:
1890 try:
1891 ui.username()
1891 ui.username()
1892 except util.Abort, e:
1892 except util.Abort, e:
1893 ui.write(" %s\n" % e)
1893 ui.write(" %s\n" % e)
1894 ui.write(_(" (specify a username in your configuration file)\n"))
1894 ui.write(_(" (specify a username in your configuration file)\n"))
1895 problems += 1
1895 problems += 1
1896
1896
1897 if not problems:
1897 if not problems:
1898 ui.status(_("No problems detected\n"))
1898 ui.status(_("No problems detected\n"))
1899 else:
1899 else:
1900 ui.write(_("%s problems detected,"
1900 ui.write(_("%s problems detected,"
1901 " please check your install!\n") % problems)
1901 " please check your install!\n") % problems)
1902
1902
1903 return problems
1903 return problems
1904
1904
1905 @command('debugknown', [], _('REPO ID...'))
1905 @command('debugknown', [], _('REPO ID...'))
1906 def debugknown(ui, repopath, *ids, **opts):
1906 def debugknown(ui, repopath, *ids, **opts):
1907 """test whether node ids are known to a repo
1907 """test whether node ids are known to a repo
1908
1908
1909 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1909 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1910 indicating unknown/known.
1910 indicating unknown/known.
1911 """
1911 """
1912 repo = hg.peer(ui, opts, repopath)
1912 repo = hg.peer(ui, opts, repopath)
1913 if not repo.capable('known'):
1913 if not repo.capable('known'):
1914 raise util.Abort("known() not supported by target repository")
1914 raise util.Abort("known() not supported by target repository")
1915 flags = repo.known([bin(s) for s in ids])
1915 flags = repo.known([bin(s) for s in ids])
1916 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1916 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1917
1917
1918 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1918 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1919 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1919 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1920 '''access the pushkey key/value protocol
1920 '''access the pushkey key/value protocol
1921
1921
1922 With two args, list the keys in the given namespace.
1922 With two args, list the keys in the given namespace.
1923
1923
1924 With five args, set a key to new if it currently is set to old.
1924 With five args, set a key to new if it currently is set to old.
1925 Reports success or failure.
1925 Reports success or failure.
1926 '''
1926 '''
1927
1927
1928 target = hg.peer(ui, {}, repopath)
1928 target = hg.peer(ui, {}, repopath)
1929 if keyinfo:
1929 if keyinfo:
1930 key, old, new = keyinfo
1930 key, old, new = keyinfo
1931 r = target.pushkey(namespace, key, old, new)
1931 r = target.pushkey(namespace, key, old, new)
1932 ui.status(str(r) + '\n')
1932 ui.status(str(r) + '\n')
1933 return not r
1933 return not r
1934 else:
1934 else:
1935 for k, v in target.listkeys(namespace).iteritems():
1935 for k, v in target.listkeys(namespace).iteritems():
1936 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1936 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1937 v.encode('string-escape')))
1937 v.encode('string-escape')))
1938
1938
1939 @command('debugrebuildstate',
1939 @command('debugrebuildstate',
1940 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1940 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1941 _('[-r REV] [REV]'))
1941 _('[-r REV] [REV]'))
1942 def debugrebuildstate(ui, repo, rev="tip"):
1942 def debugrebuildstate(ui, repo, rev="tip"):
1943 """rebuild the dirstate as it would look like for the given revision"""
1943 """rebuild the dirstate as it would look like for the given revision"""
1944 ctx = scmutil.revsingle(repo, rev)
1944 ctx = scmutil.revsingle(repo, rev)
1945 wlock = repo.wlock()
1945 wlock = repo.wlock()
1946 try:
1946 try:
1947 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1947 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1948 finally:
1948 finally:
1949 wlock.release()
1949 wlock.release()
1950
1950
1951 @command('debugrename',
1951 @command('debugrename',
1952 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1952 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1953 _('[-r REV] FILE'))
1953 _('[-r REV] FILE'))
1954 def debugrename(ui, repo, file1, *pats, **opts):
1954 def debugrename(ui, repo, file1, *pats, **opts):
1955 """dump rename information"""
1955 """dump rename information"""
1956
1956
1957 ctx = scmutil.revsingle(repo, opts.get('rev'))
1957 ctx = scmutil.revsingle(repo, opts.get('rev'))
1958 m = scmutil.match(ctx, (file1,) + pats, opts)
1958 m = scmutil.match(ctx, (file1,) + pats, opts)
1959 for abs in ctx.walk(m):
1959 for abs in ctx.walk(m):
1960 fctx = ctx[abs]
1960 fctx = ctx[abs]
1961 o = fctx.filelog().renamed(fctx.filenode())
1961 o = fctx.filelog().renamed(fctx.filenode())
1962 rel = m.rel(abs)
1962 rel = m.rel(abs)
1963 if o:
1963 if o:
1964 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1964 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1965 else:
1965 else:
1966 ui.write(_("%s not renamed\n") % rel)
1966 ui.write(_("%s not renamed\n") % rel)
1967
1967
1968 @command('debugrevlog',
1968 @command('debugrevlog',
1969 [('c', 'changelog', False, _('open changelog')),
1969 [('c', 'changelog', False, _('open changelog')),
1970 ('m', 'manifest', False, _('open manifest')),
1970 ('m', 'manifest', False, _('open manifest')),
1971 ('d', 'dump', False, _('dump index data'))],
1971 ('d', 'dump', False, _('dump index data'))],
1972 _('-c|-m|FILE'))
1972 _('-c|-m|FILE'))
1973 def debugrevlog(ui, repo, file_ = None, **opts):
1973 def debugrevlog(ui, repo, file_ = None, **opts):
1974 """show data and statistics about a revlog"""
1974 """show data and statistics about a revlog"""
1975 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1975 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1976
1976
1977 if opts.get("dump"):
1977 if opts.get("dump"):
1978 numrevs = len(r)
1978 numrevs = len(r)
1979 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1979 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1980 " rawsize totalsize compression heads\n")
1980 " rawsize totalsize compression heads\n")
1981 ts = 0
1981 ts = 0
1982 heads = set()
1982 heads = set()
1983 for rev in xrange(numrevs):
1983 for rev in xrange(numrevs):
1984 dbase = r.deltaparent(rev)
1984 dbase = r.deltaparent(rev)
1985 if dbase == -1:
1985 if dbase == -1:
1986 dbase = rev
1986 dbase = rev
1987 cbase = r.chainbase(rev)
1987 cbase = r.chainbase(rev)
1988 p1, p2 = r.parentrevs(rev)
1988 p1, p2 = r.parentrevs(rev)
1989 rs = r.rawsize(rev)
1989 rs = r.rawsize(rev)
1990 ts = ts + rs
1990 ts = ts + rs
1991 heads -= set(r.parentrevs(rev))
1991 heads -= set(r.parentrevs(rev))
1992 heads.add(rev)
1992 heads.add(rev)
1993 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1993 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1994 (rev, p1, p2, r.start(rev), r.end(rev),
1994 (rev, p1, p2, r.start(rev), r.end(rev),
1995 r.start(dbase), r.start(cbase),
1995 r.start(dbase), r.start(cbase),
1996 r.start(p1), r.start(p2),
1996 r.start(p1), r.start(p2),
1997 rs, ts, ts / r.end(rev), len(heads)))
1997 rs, ts, ts / r.end(rev), len(heads)))
1998 return 0
1998 return 0
1999
1999
2000 v = r.version
2000 v = r.version
2001 format = v & 0xFFFF
2001 format = v & 0xFFFF
2002 flags = []
2002 flags = []
2003 gdelta = False
2003 gdelta = False
2004 if v & revlog.REVLOGNGINLINEDATA:
2004 if v & revlog.REVLOGNGINLINEDATA:
2005 flags.append('inline')
2005 flags.append('inline')
2006 if v & revlog.REVLOGGENERALDELTA:
2006 if v & revlog.REVLOGGENERALDELTA:
2007 gdelta = True
2007 gdelta = True
2008 flags.append('generaldelta')
2008 flags.append('generaldelta')
2009 if not flags:
2009 if not flags:
2010 flags = ['(none)']
2010 flags = ['(none)']
2011
2011
2012 nummerges = 0
2012 nummerges = 0
2013 numfull = 0
2013 numfull = 0
2014 numprev = 0
2014 numprev = 0
2015 nump1 = 0
2015 nump1 = 0
2016 nump2 = 0
2016 nump2 = 0
2017 numother = 0
2017 numother = 0
2018 nump1prev = 0
2018 nump1prev = 0
2019 nump2prev = 0
2019 nump2prev = 0
2020 chainlengths = []
2020 chainlengths = []
2021
2021
2022 datasize = [None, 0, 0L]
2022 datasize = [None, 0, 0L]
2023 fullsize = [None, 0, 0L]
2023 fullsize = [None, 0, 0L]
2024 deltasize = [None, 0, 0L]
2024 deltasize = [None, 0, 0L]
2025
2025
2026 def addsize(size, l):
2026 def addsize(size, l):
2027 if l[0] is None or size < l[0]:
2027 if l[0] is None or size < l[0]:
2028 l[0] = size
2028 l[0] = size
2029 if size > l[1]:
2029 if size > l[1]:
2030 l[1] = size
2030 l[1] = size
2031 l[2] += size
2031 l[2] += size
2032
2032
2033 numrevs = len(r)
2033 numrevs = len(r)
2034 for rev in xrange(numrevs):
2034 for rev in xrange(numrevs):
2035 p1, p2 = r.parentrevs(rev)
2035 p1, p2 = r.parentrevs(rev)
2036 delta = r.deltaparent(rev)
2036 delta = r.deltaparent(rev)
2037 if format > 0:
2037 if format > 0:
2038 addsize(r.rawsize(rev), datasize)
2038 addsize(r.rawsize(rev), datasize)
2039 if p2 != nullrev:
2039 if p2 != nullrev:
2040 nummerges += 1
2040 nummerges += 1
2041 size = r.length(rev)
2041 size = r.length(rev)
2042 if delta == nullrev:
2042 if delta == nullrev:
2043 chainlengths.append(0)
2043 chainlengths.append(0)
2044 numfull += 1
2044 numfull += 1
2045 addsize(size, fullsize)
2045 addsize(size, fullsize)
2046 else:
2046 else:
2047 chainlengths.append(chainlengths[delta] + 1)
2047 chainlengths.append(chainlengths[delta] + 1)
2048 addsize(size, deltasize)
2048 addsize(size, deltasize)
2049 if delta == rev - 1:
2049 if delta == rev - 1:
2050 numprev += 1
2050 numprev += 1
2051 if delta == p1:
2051 if delta == p1:
2052 nump1prev += 1
2052 nump1prev += 1
2053 elif delta == p2:
2053 elif delta == p2:
2054 nump2prev += 1
2054 nump2prev += 1
2055 elif delta == p1:
2055 elif delta == p1:
2056 nump1 += 1
2056 nump1 += 1
2057 elif delta == p2:
2057 elif delta == p2:
2058 nump2 += 1
2058 nump2 += 1
2059 elif delta != nullrev:
2059 elif delta != nullrev:
2060 numother += 1
2060 numother += 1
2061
2061
2062 numdeltas = numrevs - numfull
2062 numdeltas = numrevs - numfull
2063 numoprev = numprev - nump1prev - nump2prev
2063 numoprev = numprev - nump1prev - nump2prev
2064 totalrawsize = datasize[2]
2064 totalrawsize = datasize[2]
2065 datasize[2] /= numrevs
2065 datasize[2] /= numrevs
2066 fulltotal = fullsize[2]
2066 fulltotal = fullsize[2]
2067 fullsize[2] /= numfull
2067 fullsize[2] /= numfull
2068 deltatotal = deltasize[2]
2068 deltatotal = deltasize[2]
2069 deltasize[2] /= numrevs - numfull
2069 deltasize[2] /= numrevs - numfull
2070 totalsize = fulltotal + deltatotal
2070 totalsize = fulltotal + deltatotal
2071 avgchainlen = sum(chainlengths) / numrevs
2071 avgchainlen = sum(chainlengths) / numrevs
2072 compratio = totalrawsize / totalsize
2072 compratio = totalrawsize / totalsize
2073
2073
2074 basedfmtstr = '%%%dd\n'
2074 basedfmtstr = '%%%dd\n'
2075 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2075 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2076
2076
2077 def dfmtstr(max):
2077 def dfmtstr(max):
2078 return basedfmtstr % len(str(max))
2078 return basedfmtstr % len(str(max))
2079 def pcfmtstr(max, padding=0):
2079 def pcfmtstr(max, padding=0):
2080 return basepcfmtstr % (len(str(max)), ' ' * padding)
2080 return basepcfmtstr % (len(str(max)), ' ' * padding)
2081
2081
2082 def pcfmt(value, total):
2082 def pcfmt(value, total):
2083 return (value, 100 * float(value) / total)
2083 return (value, 100 * float(value) / total)
2084
2084
2085 ui.write('format : %d\n' % format)
2085 ui.write('format : %d\n' % format)
2086 ui.write('flags : %s\n' % ', '.join(flags))
2086 ui.write('flags : %s\n' % ', '.join(flags))
2087
2087
2088 ui.write('\n')
2088 ui.write('\n')
2089 fmt = pcfmtstr(totalsize)
2089 fmt = pcfmtstr(totalsize)
2090 fmt2 = dfmtstr(totalsize)
2090 fmt2 = dfmtstr(totalsize)
2091 ui.write('revisions : ' + fmt2 % numrevs)
2091 ui.write('revisions : ' + fmt2 % numrevs)
2092 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2092 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2093 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2093 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2094 ui.write('revisions : ' + fmt2 % numrevs)
2094 ui.write('revisions : ' + fmt2 % numrevs)
2095 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2095 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2096 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2096 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2097 ui.write('revision size : ' + fmt2 % totalsize)
2097 ui.write('revision size : ' + fmt2 % totalsize)
2098 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2098 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2099 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2099 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2100
2100
2101 ui.write('\n')
2101 ui.write('\n')
2102 fmt = dfmtstr(max(avgchainlen, compratio))
2102 fmt = dfmtstr(max(avgchainlen, compratio))
2103 ui.write('avg chain length : ' + fmt % avgchainlen)
2103 ui.write('avg chain length : ' + fmt % avgchainlen)
2104 ui.write('compression ratio : ' + fmt % compratio)
2104 ui.write('compression ratio : ' + fmt % compratio)
2105
2105
2106 if format > 0:
2106 if format > 0:
2107 ui.write('\n')
2107 ui.write('\n')
2108 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2108 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2109 % tuple(datasize))
2109 % tuple(datasize))
2110 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2110 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2111 % tuple(fullsize))
2111 % tuple(fullsize))
2112 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2112 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2113 % tuple(deltasize))
2113 % tuple(deltasize))
2114
2114
2115 if numdeltas > 0:
2115 if numdeltas > 0:
2116 ui.write('\n')
2116 ui.write('\n')
2117 fmt = pcfmtstr(numdeltas)
2117 fmt = pcfmtstr(numdeltas)
2118 fmt2 = pcfmtstr(numdeltas, 4)
2118 fmt2 = pcfmtstr(numdeltas, 4)
2119 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2119 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2120 if numprev > 0:
2120 if numprev > 0:
2121 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2121 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2122 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2122 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2123 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2123 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2124 if gdelta:
2124 if gdelta:
2125 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2125 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2126 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2126 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2127 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2127 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2128
2128
2129 @command('debugrevspec', [], ('REVSPEC'))
2129 @command('debugrevspec', [], ('REVSPEC'))
2130 def debugrevspec(ui, repo, expr):
2130 def debugrevspec(ui, repo, expr):
2131 '''parse and apply a revision specification'''
2131 '''parse and apply a revision specification'''
2132 if ui.verbose:
2132 if ui.verbose:
2133 tree = revset.parse(expr)[0]
2133 tree = revset.parse(expr)[0]
2134 ui.note(tree, "\n")
2134 ui.note(tree, "\n")
2135 newtree = revset.findaliases(ui, tree)
2135 newtree = revset.findaliases(ui, tree)
2136 if newtree != tree:
2136 if newtree != tree:
2137 ui.note(newtree, "\n")
2137 ui.note(newtree, "\n")
2138 func = revset.match(ui, expr)
2138 func = revset.match(ui, expr)
2139 for c in func(repo, range(len(repo))):
2139 for c in func(repo, range(len(repo))):
2140 ui.write("%s\n" % c)
2140 ui.write("%s\n" % c)
2141
2141
2142 @command('debugsetparents', [], _('REV1 [REV2]'))
2142 @command('debugsetparents', [], _('REV1 [REV2]'))
2143 def debugsetparents(ui, repo, rev1, rev2=None):
2143 def debugsetparents(ui, repo, rev1, rev2=None):
2144 """manually set the parents of the current working directory
2144 """manually set the parents of the current working directory
2145
2145
2146 This is useful for writing repository conversion tools, but should
2146 This is useful for writing repository conversion tools, but should
2147 be used with care.
2147 be used with care.
2148
2148
2149 Returns 0 on success.
2149 Returns 0 on success.
2150 """
2150 """
2151
2151
2152 r1 = scmutil.revsingle(repo, rev1).node()
2152 r1 = scmutil.revsingle(repo, rev1).node()
2153 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2153 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2154
2154
2155 wlock = repo.wlock()
2155 wlock = repo.wlock()
2156 try:
2156 try:
2157 repo.dirstate.setparents(r1, r2)
2157 repo.dirstate.setparents(r1, r2)
2158 finally:
2158 finally:
2159 wlock.release()
2159 wlock.release()
2160
2160
2161 @command('debugstate',
2161 @command('debugstate',
2162 [('', 'nodates', None, _('do not display the saved mtime')),
2162 [('', 'nodates', None, _('do not display the saved mtime')),
2163 ('', 'datesort', None, _('sort by saved mtime'))],
2163 ('', 'datesort', None, _('sort by saved mtime'))],
2164 _('[OPTION]...'))
2164 _('[OPTION]...'))
2165 def debugstate(ui, repo, nodates=None, datesort=None):
2165 def debugstate(ui, repo, nodates=None, datesort=None):
2166 """show the contents of the current dirstate"""
2166 """show the contents of the current dirstate"""
2167 timestr = ""
2167 timestr = ""
2168 showdate = not nodates
2168 showdate = not nodates
2169 if datesort:
2169 if datesort:
2170 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2170 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2171 else:
2171 else:
2172 keyfunc = None # sort by filename
2172 keyfunc = None # sort by filename
2173 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2173 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2174 if showdate:
2174 if showdate:
2175 if ent[3] == -1:
2175 if ent[3] == -1:
2176 # Pad or slice to locale representation
2176 # Pad or slice to locale representation
2177 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2177 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2178 time.localtime(0)))
2178 time.localtime(0)))
2179 timestr = 'unset'
2179 timestr = 'unset'
2180 timestr = (timestr[:locale_len] +
2180 timestr = (timestr[:locale_len] +
2181 ' ' * (locale_len - len(timestr)))
2181 ' ' * (locale_len - len(timestr)))
2182 else:
2182 else:
2183 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2183 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2184 time.localtime(ent[3]))
2184 time.localtime(ent[3]))
2185 if ent[1] & 020000:
2185 if ent[1] & 020000:
2186 mode = 'lnk'
2186 mode = 'lnk'
2187 else:
2187 else:
2188 mode = '%3o' % (ent[1] & 0777)
2188 mode = '%3o' % (ent[1] & 0777)
2189 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2189 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2190 for f in repo.dirstate.copies():
2190 for f in repo.dirstate.copies():
2191 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2191 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2192
2192
2193 @command('debugsub',
2193 @command('debugsub',
2194 [('r', 'rev', '',
2194 [('r', 'rev', '',
2195 _('revision to check'), _('REV'))],
2195 _('revision to check'), _('REV'))],
2196 _('[-r REV] [REV]'))
2196 _('[-r REV] [REV]'))
2197 def debugsub(ui, repo, rev=None):
2197 def debugsub(ui, repo, rev=None):
2198 ctx = scmutil.revsingle(repo, rev, None)
2198 ctx = scmutil.revsingle(repo, rev, None)
2199 for k, v in sorted(ctx.substate.items()):
2199 for k, v in sorted(ctx.substate.items()):
2200 ui.write('path %s\n' % k)
2200 ui.write('path %s\n' % k)
2201 ui.write(' source %s\n' % v[0])
2201 ui.write(' source %s\n' % v[0])
2202 ui.write(' revision %s\n' % v[1])
2202 ui.write(' revision %s\n' % v[1])
2203
2203
2204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2205 def debugwalk(ui, repo, *pats, **opts):
2205 def debugwalk(ui, repo, *pats, **opts):
2206 """show how files match on given patterns"""
2206 """show how files match on given patterns"""
2207 m = scmutil.match(repo[None], pats, opts)
2207 m = scmutil.match(repo[None], pats, opts)
2208 items = list(repo.walk(m))
2208 items = list(repo.walk(m))
2209 if not items:
2209 if not items:
2210 return
2210 return
2211 fmt = 'f %%-%ds %%-%ds %%s' % (
2211 fmt = 'f %%-%ds %%-%ds %%s' % (
2212 max([len(abs) for abs in items]),
2212 max([len(abs) for abs in items]),
2213 max([len(m.rel(abs)) for abs in items]))
2213 max([len(m.rel(abs)) for abs in items]))
2214 for abs in items:
2214 for abs in items:
2215 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2215 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2216 ui.write("%s\n" % line.rstrip())
2216 ui.write("%s\n" % line.rstrip())
2217
2217
2218 @command('debugwireargs',
2218 @command('debugwireargs',
2219 [('', 'three', '', 'three'),
2219 [('', 'three', '', 'three'),
2220 ('', 'four', '', 'four'),
2220 ('', 'four', '', 'four'),
2221 ('', 'five', '', 'five'),
2221 ('', 'five', '', 'five'),
2222 ] + remoteopts,
2222 ] + remoteopts,
2223 _('REPO [OPTIONS]... [ONE [TWO]]'))
2223 _('REPO [OPTIONS]... [ONE [TWO]]'))
2224 def debugwireargs(ui, repopath, *vals, **opts):
2224 def debugwireargs(ui, repopath, *vals, **opts):
2225 repo = hg.peer(ui, opts, repopath)
2225 repo = hg.peer(ui, opts, repopath)
2226 for opt in remoteopts:
2226 for opt in remoteopts:
2227 del opts[opt[1]]
2227 del opts[opt[1]]
2228 args = {}
2228 args = {}
2229 for k, v in opts.iteritems():
2229 for k, v in opts.iteritems():
2230 if v:
2230 if v:
2231 args[k] = v
2231 args[k] = v
2232 # run twice to check that we don't mess up the stream for the next command
2232 # run twice to check that we don't mess up the stream for the next command
2233 res1 = repo.debugwireargs(*vals, **args)
2233 res1 = repo.debugwireargs(*vals, **args)
2234 res2 = repo.debugwireargs(*vals, **args)
2234 res2 = repo.debugwireargs(*vals, **args)
2235 ui.write("%s\n" % res1)
2235 ui.write("%s\n" % res1)
2236 if res1 != res2:
2236 if res1 != res2:
2237 ui.warn("%s\n" % res2)
2237 ui.warn("%s\n" % res2)
2238
2238
2239 @command('^diff',
2239 @command('^diff',
2240 [('r', 'rev', [], _('revision'), _('REV')),
2240 [('r', 'rev', [], _('revision'), _('REV')),
2241 ('c', 'change', '', _('change made by revision'), _('REV'))
2241 ('c', 'change', '', _('change made by revision'), _('REV'))
2242 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2242 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2243 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2243 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2244 def diff(ui, repo, *pats, **opts):
2244 def diff(ui, repo, *pats, **opts):
2245 """diff repository (or selected files)
2245 """diff repository (or selected files)
2246
2246
2247 Show differences between revisions for the specified files.
2247 Show differences between revisions for the specified files.
2248
2248
2249 Differences between files are shown using the unified diff format.
2249 Differences between files are shown using the unified diff format.
2250
2250
2251 .. note::
2251 .. note::
2252 diff may generate unexpected results for merges, as it will
2252 diff may generate unexpected results for merges, as it will
2253 default to comparing against the working directory's first
2253 default to comparing against the working directory's first
2254 parent changeset if no revisions are specified.
2254 parent changeset if no revisions are specified.
2255
2255
2256 When two revision arguments are given, then changes are shown
2256 When two revision arguments are given, then changes are shown
2257 between those revisions. If only one revision is specified then
2257 between those revisions. If only one revision is specified then
2258 that revision is compared to the working directory, and, when no
2258 that revision is compared to the working directory, and, when no
2259 revisions are specified, the working directory files are compared
2259 revisions are specified, the working directory files are compared
2260 to its parent.
2260 to its parent.
2261
2261
2262 Alternatively you can specify -c/--change with a revision to see
2262 Alternatively you can specify -c/--change with a revision to see
2263 the changes in that changeset relative to its first parent.
2263 the changes in that changeset relative to its first parent.
2264
2264
2265 Without the -a/--text option, diff will avoid generating diffs of
2265 Without the -a/--text option, diff will avoid generating diffs of
2266 files it detects as binary. With -a, diff will generate a diff
2266 files it detects as binary. With -a, diff will generate a diff
2267 anyway, probably with undesirable results.
2267 anyway, probably with undesirable results.
2268
2268
2269 Use the -g/--git option to generate diffs in the git extended diff
2269 Use the -g/--git option to generate diffs in the git extended diff
2270 format. For more information, read :hg:`help diffs`.
2270 format. For more information, read :hg:`help diffs`.
2271
2271
2272 .. container:: verbose
2272 .. container:: verbose
2273
2273
2274 Examples:
2274 Examples:
2275
2275
2276 - compare a file in the current working directory to its parent::
2276 - compare a file in the current working directory to its parent::
2277
2277
2278 hg diff foo.c
2278 hg diff foo.c
2279
2279
2280 - compare two historical versions of a directory, with rename info::
2280 - compare two historical versions of a directory, with rename info::
2281
2281
2282 hg diff --git -r 1.0:1.2 lib/
2282 hg diff --git -r 1.0:1.2 lib/
2283
2283
2284 - get change stats relative to the last change on some date::
2284 - get change stats relative to the last change on some date::
2285
2285
2286 hg diff --stat -r "date('may 2')"
2286 hg diff --stat -r "date('may 2')"
2287
2287
2288 - diff all newly-added files that contain a keyword::
2288 - diff all newly-added files that contain a keyword::
2289
2289
2290 hg diff "set:added() and grep(GNU)"
2290 hg diff "set:added() and grep(GNU)"
2291
2291
2292 - compare a revision and its parents::
2292 - compare a revision and its parents::
2293
2293
2294 hg diff -c 9353 # compare against first parent
2294 hg diff -c 9353 # compare against first parent
2295 hg diff -r 9353^:9353 # same using revset syntax
2295 hg diff -r 9353^:9353 # same using revset syntax
2296 hg diff -r 9353^2:9353 # compare against the second parent
2296 hg diff -r 9353^2:9353 # compare against the second parent
2297
2297
2298 Returns 0 on success.
2298 Returns 0 on success.
2299 """
2299 """
2300
2300
2301 revs = opts.get('rev')
2301 revs = opts.get('rev')
2302 change = opts.get('change')
2302 change = opts.get('change')
2303 stat = opts.get('stat')
2303 stat = opts.get('stat')
2304 reverse = opts.get('reverse')
2304 reverse = opts.get('reverse')
2305
2305
2306 if revs and change:
2306 if revs and change:
2307 msg = _('cannot specify --rev and --change at the same time')
2307 msg = _('cannot specify --rev and --change at the same time')
2308 raise util.Abort(msg)
2308 raise util.Abort(msg)
2309 elif change:
2309 elif change:
2310 node2 = scmutil.revsingle(repo, change, None).node()
2310 node2 = scmutil.revsingle(repo, change, None).node()
2311 node1 = repo[node2].p1().node()
2311 node1 = repo[node2].p1().node()
2312 else:
2312 else:
2313 node1, node2 = scmutil.revpair(repo, revs)
2313 node1, node2 = scmutil.revpair(repo, revs)
2314
2314
2315 if reverse:
2315 if reverse:
2316 node1, node2 = node2, node1
2316 node1, node2 = node2, node1
2317
2317
2318 diffopts = patch.diffopts(ui, opts)
2318 diffopts = patch.diffopts(ui, opts)
2319 m = scmutil.match(repo[node2], pats, opts)
2319 m = scmutil.match(repo[node2], pats, opts)
2320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2321 listsubrepos=opts.get('subrepos'))
2321 listsubrepos=opts.get('subrepos'))
2322
2322
2323 @command('^export',
2323 @command('^export',
2324 [('o', 'output', '',
2324 [('o', 'output', '',
2325 _('print output to file with formatted name'), _('FORMAT')),
2325 _('print output to file with formatted name'), _('FORMAT')),
2326 ('', 'switch-parent', None, _('diff against the second parent')),
2326 ('', 'switch-parent', None, _('diff against the second parent')),
2327 ('r', 'rev', [], _('revisions to export'), _('REV')),
2327 ('r', 'rev', [], _('revisions to export'), _('REV')),
2328 ] + diffopts,
2328 ] + diffopts,
2329 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2329 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2330 def export(ui, repo, *changesets, **opts):
2330 def export(ui, repo, *changesets, **opts):
2331 """dump the header and diffs for one or more changesets
2331 """dump the header and diffs for one or more changesets
2332
2332
2333 Print the changeset header and diffs for one or more revisions.
2333 Print the changeset header and diffs for one or more revisions.
2334
2334
2335 The information shown in the changeset header is: author, date,
2335 The information shown in the changeset header is: author, date,
2336 branch name (if non-default), changeset hash, parent(s) and commit
2336 branch name (if non-default), changeset hash, parent(s) and commit
2337 comment.
2337 comment.
2338
2338
2339 .. note::
2339 .. note::
2340 export may generate unexpected diff output for merge
2340 export may generate unexpected diff output for merge
2341 changesets, as it will compare the merge changeset against its
2341 changesets, as it will compare the merge changeset against its
2342 first parent only.
2342 first parent only.
2343
2343
2344 Output may be to a file, in which case the name of the file is
2344 Output may be to a file, in which case the name of the file is
2345 given using a format string. The formatting rules are as follows:
2345 given using a format string. The formatting rules are as follows:
2346
2346
2347 :``%%``: literal "%" character
2347 :``%%``: literal "%" character
2348 :``%H``: changeset hash (40 hexadecimal digits)
2348 :``%H``: changeset hash (40 hexadecimal digits)
2349 :``%N``: number of patches being generated
2349 :``%N``: number of patches being generated
2350 :``%R``: changeset revision number
2350 :``%R``: changeset revision number
2351 :``%b``: basename of the exporting repository
2351 :``%b``: basename of the exporting repository
2352 :``%h``: short-form changeset hash (12 hexadecimal digits)
2352 :``%h``: short-form changeset hash (12 hexadecimal digits)
2353 :``%m``: first line of the commit message (only alphanumeric characters)
2353 :``%m``: first line of the commit message (only alphanumeric characters)
2354 :``%n``: zero-padded sequence number, starting at 1
2354 :``%n``: zero-padded sequence number, starting at 1
2355 :``%r``: zero-padded changeset revision number
2355 :``%r``: zero-padded changeset revision number
2356
2356
2357 Without the -a/--text option, export will avoid generating diffs
2357 Without the -a/--text option, export will avoid generating diffs
2358 of files it detects as binary. With -a, export will generate a
2358 of files it detects as binary. With -a, export will generate a
2359 diff anyway, probably with undesirable results.
2359 diff anyway, probably with undesirable results.
2360
2360
2361 Use the -g/--git option to generate diffs in the git extended diff
2361 Use the -g/--git option to generate diffs in the git extended diff
2362 format. See :hg:`help diffs` for more information.
2362 format. See :hg:`help diffs` for more information.
2363
2363
2364 With the --switch-parent option, the diff will be against the
2364 With the --switch-parent option, the diff will be against the
2365 second parent. It can be useful to review a merge.
2365 second parent. It can be useful to review a merge.
2366
2366
2367 .. container:: verbose
2367 .. container:: verbose
2368
2368
2369 Examples:
2369 Examples:
2370
2370
2371 - use export and import to transplant a bugfix to the current
2371 - use export and import to transplant a bugfix to the current
2372 branch::
2372 branch::
2373
2373
2374 hg export -r 9353 | hg import -
2374 hg export -r 9353 | hg import -
2375
2375
2376 - export all the changesets between two revisions to a file with
2376 - export all the changesets between two revisions to a file with
2377 rename information::
2377 rename information::
2378
2378
2379 hg export --git -r 123:150 > changes.txt
2379 hg export --git -r 123:150 > changes.txt
2380
2380
2381 - split outgoing changes into a series of patches with
2381 - split outgoing changes into a series of patches with
2382 descriptive names::
2382 descriptive names::
2383
2383
2384 hg export -r "outgoing()" -o "%n-%m.patch"
2384 hg export -r "outgoing()" -o "%n-%m.patch"
2385
2385
2386 Returns 0 on success.
2386 Returns 0 on success.
2387 """
2387 """
2388 changesets += tuple(opts.get('rev', []))
2388 changesets += tuple(opts.get('rev', []))
2389 if not changesets:
2389 if not changesets:
2390 raise util.Abort(_("export requires at least one changeset"))
2390 raise util.Abort(_("export requires at least one changeset"))
2391 revs = scmutil.revrange(repo, changesets)
2391 revs = scmutil.revrange(repo, changesets)
2392 if len(revs) > 1:
2392 if len(revs) > 1:
2393 ui.note(_('exporting patches:\n'))
2393 ui.note(_('exporting patches:\n'))
2394 else:
2394 else:
2395 ui.note(_('exporting patch:\n'))
2395 ui.note(_('exporting patch:\n'))
2396 cmdutil.export(repo, revs, template=opts.get('output'),
2396 cmdutil.export(repo, revs, template=opts.get('output'),
2397 switch_parent=opts.get('switch_parent'),
2397 switch_parent=opts.get('switch_parent'),
2398 opts=patch.diffopts(ui, opts))
2398 opts=patch.diffopts(ui, opts))
2399
2399
2400 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2400 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2401 def forget(ui, repo, *pats, **opts):
2401 def forget(ui, repo, *pats, **opts):
2402 """forget the specified files on the next commit
2402 """forget the specified files on the next commit
2403
2403
2404 Mark the specified files so they will no longer be tracked
2404 Mark the specified files so they will no longer be tracked
2405 after the next commit.
2405 after the next commit.
2406
2406
2407 This only removes files from the current branch, not from the
2407 This only removes files from the current branch, not from the
2408 entire project history, and it does not delete them from the
2408 entire project history, and it does not delete them from the
2409 working directory.
2409 working directory.
2410
2410
2411 To undo a forget before the next commit, see :hg:`add`.
2411 To undo a forget before the next commit, see :hg:`add`.
2412
2412
2413 .. container:: verbose
2413 .. container:: verbose
2414
2414
2415 Examples:
2415 Examples:
2416
2416
2417 - forget newly-added binary files::
2417 - forget newly-added binary files::
2418
2418
2419 hg forget "set:added() and binary()"
2419 hg forget "set:added() and binary()"
2420
2420
2421 - forget files that would be excluded by .hgignore::
2421 - forget files that would be excluded by .hgignore::
2422
2422
2423 hg forget "set:hgignore()"
2423 hg forget "set:hgignore()"
2424
2424
2425 Returns 0 on success.
2425 Returns 0 on success.
2426 """
2426 """
2427
2427
2428 if not pats:
2428 if not pats:
2429 raise util.Abort(_('no files specified'))
2429 raise util.Abort(_('no files specified'))
2430
2430
2431 m = scmutil.match(repo[None], pats, opts)
2431 m = scmutil.match(repo[None], pats, opts)
2432 s = repo.status(match=m, clean=True)
2432 s = repo.status(match=m, clean=True)
2433 forget = sorted(s[0] + s[1] + s[3] + s[6])
2433 forget = sorted(s[0] + s[1] + s[3] + s[6])
2434 errs = 0
2434 errs = 0
2435
2435
2436 for f in m.files():
2436 for f in m.files():
2437 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2437 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2438 if os.path.exists(m.rel(f)):
2438 if os.path.exists(m.rel(f)):
2439 ui.warn(_('not removing %s: file is already untracked\n')
2439 ui.warn(_('not removing %s: file is already untracked\n')
2440 % m.rel(f))
2440 % m.rel(f))
2441 errs = 1
2441 errs = 1
2442
2442
2443 for f in forget:
2443 for f in forget:
2444 if ui.verbose or not m.exact(f):
2444 if ui.verbose or not m.exact(f):
2445 ui.status(_('removing %s\n') % m.rel(f))
2445 ui.status(_('removing %s\n') % m.rel(f))
2446
2446
2447 repo[None].forget(forget)
2447 repo[None].forget(forget)
2448 return errs
2448 return errs
2449
2449
2450 @command('grep',
2450 @command('grep',
2451 [('0', 'print0', None, _('end fields with NUL')),
2451 [('0', 'print0', None, _('end fields with NUL')),
2452 ('', 'all', None, _('print all revisions that match')),
2452 ('', 'all', None, _('print all revisions that match')),
2453 ('a', 'text', None, _('treat all files as text')),
2453 ('a', 'text', None, _('treat all files as text')),
2454 ('f', 'follow', None,
2454 ('f', 'follow', None,
2455 _('follow changeset history,'
2455 _('follow changeset history,'
2456 ' or file history across copies and renames')),
2456 ' or file history across copies and renames')),
2457 ('i', 'ignore-case', None, _('ignore case when matching')),
2457 ('i', 'ignore-case', None, _('ignore case when matching')),
2458 ('l', 'files-with-matches', None,
2458 ('l', 'files-with-matches', None,
2459 _('print only filenames and revisions that match')),
2459 _('print only filenames and revisions that match')),
2460 ('n', 'line-number', None, _('print matching line numbers')),
2460 ('n', 'line-number', None, _('print matching line numbers')),
2461 ('r', 'rev', [],
2461 ('r', 'rev', [],
2462 _('only search files changed within revision range'), _('REV')),
2462 _('only search files changed within revision range'), _('REV')),
2463 ('u', 'user', None, _('list the author (long with -v)')),
2463 ('u', 'user', None, _('list the author (long with -v)')),
2464 ('d', 'date', None, _('list the date (short with -q)')),
2464 ('d', 'date', None, _('list the date (short with -q)')),
2465 ] + walkopts,
2465 ] + walkopts,
2466 _('[OPTION]... PATTERN [FILE]...'))
2466 _('[OPTION]... PATTERN [FILE]...'))
2467 def grep(ui, repo, pattern, *pats, **opts):
2467 def grep(ui, repo, pattern, *pats, **opts):
2468 """search for a pattern in specified files and revisions
2468 """search for a pattern in specified files and revisions
2469
2469
2470 Search revisions of files for a regular expression.
2470 Search revisions of files for a regular expression.
2471
2471
2472 This command behaves differently than Unix grep. It only accepts
2472 This command behaves differently than Unix grep. It only accepts
2473 Python/Perl regexps. It searches repository history, not the
2473 Python/Perl regexps. It searches repository history, not the
2474 working directory. It always prints the revision number in which a
2474 working directory. It always prints the revision number in which a
2475 match appears.
2475 match appears.
2476
2476
2477 By default, grep only prints output for the first revision of a
2477 By default, grep only prints output for the first revision of a
2478 file in which it finds a match. To get it to print every revision
2478 file in which it finds a match. To get it to print every revision
2479 that contains a change in match status ("-" for a match that
2479 that contains a change in match status ("-" for a match that
2480 becomes a non-match, or "+" for a non-match that becomes a match),
2480 becomes a non-match, or "+" for a non-match that becomes a match),
2481 use the --all flag.
2481 use the --all flag.
2482
2482
2483 Returns 0 if a match is found, 1 otherwise.
2483 Returns 0 if a match is found, 1 otherwise.
2484 """
2484 """
2485 reflags = 0
2485 reflags = 0
2486 if opts.get('ignore_case'):
2486 if opts.get('ignore_case'):
2487 reflags |= re.I
2487 reflags |= re.I
2488 try:
2488 try:
2489 regexp = re.compile(pattern, reflags)
2489 regexp = re.compile(pattern, reflags)
2490 except re.error, inst:
2490 except re.error, inst:
2491 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2491 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2492 return 1
2492 return 1
2493 sep, eol = ':', '\n'
2493 sep, eol = ':', '\n'
2494 if opts.get('print0'):
2494 if opts.get('print0'):
2495 sep = eol = '\0'
2495 sep = eol = '\0'
2496
2496
2497 getfile = util.lrucachefunc(repo.file)
2497 getfile = util.lrucachefunc(repo.file)
2498
2498
2499 def matchlines(body):
2499 def matchlines(body):
2500 begin = 0
2500 begin = 0
2501 linenum = 0
2501 linenum = 0
2502 while True:
2502 while True:
2503 match = regexp.search(body, begin)
2503 match = regexp.search(body, begin)
2504 if not match:
2504 if not match:
2505 break
2505 break
2506 mstart, mend = match.span()
2506 mstart, mend = match.span()
2507 linenum += body.count('\n', begin, mstart) + 1
2507 linenum += body.count('\n', begin, mstart) + 1
2508 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2508 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2509 begin = body.find('\n', mend) + 1 or len(body)
2509 begin = body.find('\n', mend) + 1 or len(body)
2510 lend = begin - 1
2510 lend = begin - 1
2511 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2511 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2512
2512
2513 class linestate(object):
2513 class linestate(object):
2514 def __init__(self, line, linenum, colstart, colend):
2514 def __init__(self, line, linenum, colstart, colend):
2515 self.line = line
2515 self.line = line
2516 self.linenum = linenum
2516 self.linenum = linenum
2517 self.colstart = colstart
2517 self.colstart = colstart
2518 self.colend = colend
2518 self.colend = colend
2519
2519
2520 def __hash__(self):
2520 def __hash__(self):
2521 return hash((self.linenum, self.line))
2521 return hash((self.linenum, self.line))
2522
2522
2523 def __eq__(self, other):
2523 def __eq__(self, other):
2524 return self.line == other.line
2524 return self.line == other.line
2525
2525
2526 matches = {}
2526 matches = {}
2527 copies = {}
2527 copies = {}
2528 def grepbody(fn, rev, body):
2528 def grepbody(fn, rev, body):
2529 matches[rev].setdefault(fn, [])
2529 matches[rev].setdefault(fn, [])
2530 m = matches[rev][fn]
2530 m = matches[rev][fn]
2531 for lnum, cstart, cend, line in matchlines(body):
2531 for lnum, cstart, cend, line in matchlines(body):
2532 s = linestate(line, lnum, cstart, cend)
2532 s = linestate(line, lnum, cstart, cend)
2533 m.append(s)
2533 m.append(s)
2534
2534
2535 def difflinestates(a, b):
2535 def difflinestates(a, b):
2536 sm = difflib.SequenceMatcher(None, a, b)
2536 sm = difflib.SequenceMatcher(None, a, b)
2537 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2537 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2538 if tag == 'insert':
2538 if tag == 'insert':
2539 for i in xrange(blo, bhi):
2539 for i in xrange(blo, bhi):
2540 yield ('+', b[i])
2540 yield ('+', b[i])
2541 elif tag == 'delete':
2541 elif tag == 'delete':
2542 for i in xrange(alo, ahi):
2542 for i in xrange(alo, ahi):
2543 yield ('-', a[i])
2543 yield ('-', a[i])
2544 elif tag == 'replace':
2544 elif tag == 'replace':
2545 for i in xrange(alo, ahi):
2545 for i in xrange(alo, ahi):
2546 yield ('-', a[i])
2546 yield ('-', a[i])
2547 for i in xrange(blo, bhi):
2547 for i in xrange(blo, bhi):
2548 yield ('+', b[i])
2548 yield ('+', b[i])
2549
2549
2550 def display(fn, ctx, pstates, states):
2550 def display(fn, ctx, pstates, states):
2551 rev = ctx.rev()
2551 rev = ctx.rev()
2552 datefunc = ui.quiet and util.shortdate or util.datestr
2552 datefunc = ui.quiet and util.shortdate or util.datestr
2553 found = False
2553 found = False
2554 filerevmatches = {}
2554 filerevmatches = {}
2555 def binary():
2555 def binary():
2556 flog = getfile(fn)
2556 flog = getfile(fn)
2557 return util.binary(flog.read(ctx.filenode(fn)))
2557 return util.binary(flog.read(ctx.filenode(fn)))
2558
2558
2559 if opts.get('all'):
2559 if opts.get('all'):
2560 iter = difflinestates(pstates, states)
2560 iter = difflinestates(pstates, states)
2561 else:
2561 else:
2562 iter = [('', l) for l in states]
2562 iter = [('', l) for l in states]
2563 for change, l in iter:
2563 for change, l in iter:
2564 cols = [fn, str(rev)]
2564 cols = [fn, str(rev)]
2565 before, match, after = None, None, None
2565 before, match, after = None, None, None
2566 if opts.get('line_number'):
2566 if opts.get('line_number'):
2567 cols.append(str(l.linenum))
2567 cols.append(str(l.linenum))
2568 if opts.get('all'):
2568 if opts.get('all'):
2569 cols.append(change)
2569 cols.append(change)
2570 if opts.get('user'):
2570 if opts.get('user'):
2571 cols.append(ui.shortuser(ctx.user()))
2571 cols.append(ui.shortuser(ctx.user()))
2572 if opts.get('date'):
2572 if opts.get('date'):
2573 cols.append(datefunc(ctx.date()))
2573 cols.append(datefunc(ctx.date()))
2574 if opts.get('files_with_matches'):
2574 if opts.get('files_with_matches'):
2575 c = (fn, rev)
2575 c = (fn, rev)
2576 if c in filerevmatches:
2576 if c in filerevmatches:
2577 continue
2577 continue
2578 filerevmatches[c] = 1
2578 filerevmatches[c] = 1
2579 else:
2579 else:
2580 before = l.line[:l.colstart]
2580 before = l.line[:l.colstart]
2581 match = l.line[l.colstart:l.colend]
2581 match = l.line[l.colstart:l.colend]
2582 after = l.line[l.colend:]
2582 after = l.line[l.colend:]
2583 ui.write(sep.join(cols))
2583 ui.write(sep.join(cols))
2584 if before is not None:
2584 if before is not None:
2585 if not opts.get('text') and binary():
2585 if not opts.get('text') and binary():
2586 ui.write(sep + " Binary file matches")
2586 ui.write(sep + " Binary file matches")
2587 else:
2587 else:
2588 ui.write(sep + before)
2588 ui.write(sep + before)
2589 ui.write(match, label='grep.match')
2589 ui.write(match, label='grep.match')
2590 ui.write(after)
2590 ui.write(after)
2591 ui.write(eol)
2591 ui.write(eol)
2592 found = True
2592 found = True
2593 return found
2593 return found
2594
2594
2595 skip = {}
2595 skip = {}
2596 revfiles = {}
2596 revfiles = {}
2597 matchfn = scmutil.match(repo[None], pats, opts)
2597 matchfn = scmutil.match(repo[None], pats, opts)
2598 found = False
2598 found = False
2599 follow = opts.get('follow')
2599 follow = opts.get('follow')
2600
2600
2601 def prep(ctx, fns):
2601 def prep(ctx, fns):
2602 rev = ctx.rev()
2602 rev = ctx.rev()
2603 pctx = ctx.p1()
2603 pctx = ctx.p1()
2604 parent = pctx.rev()
2604 parent = pctx.rev()
2605 matches.setdefault(rev, {})
2605 matches.setdefault(rev, {})
2606 matches.setdefault(parent, {})
2606 matches.setdefault(parent, {})
2607 files = revfiles.setdefault(rev, [])
2607 files = revfiles.setdefault(rev, [])
2608 for fn in fns:
2608 for fn in fns:
2609 flog = getfile(fn)
2609 flog = getfile(fn)
2610 try:
2610 try:
2611 fnode = ctx.filenode(fn)
2611 fnode = ctx.filenode(fn)
2612 except error.LookupError:
2612 except error.LookupError:
2613 continue
2613 continue
2614
2614
2615 copied = flog.renamed(fnode)
2615 copied = flog.renamed(fnode)
2616 copy = follow and copied and copied[0]
2616 copy = follow and copied and copied[0]
2617 if copy:
2617 if copy:
2618 copies.setdefault(rev, {})[fn] = copy
2618 copies.setdefault(rev, {})[fn] = copy
2619 if fn in skip:
2619 if fn in skip:
2620 if copy:
2620 if copy:
2621 skip[copy] = True
2621 skip[copy] = True
2622 continue
2622 continue
2623 files.append(fn)
2623 files.append(fn)
2624
2624
2625 if fn not in matches[rev]:
2625 if fn not in matches[rev]:
2626 grepbody(fn, rev, flog.read(fnode))
2626 grepbody(fn, rev, flog.read(fnode))
2627
2627
2628 pfn = copy or fn
2628 pfn = copy or fn
2629 if pfn not in matches[parent]:
2629 if pfn not in matches[parent]:
2630 try:
2630 try:
2631 fnode = pctx.filenode(pfn)
2631 fnode = pctx.filenode(pfn)
2632 grepbody(pfn, parent, flog.read(fnode))
2632 grepbody(pfn, parent, flog.read(fnode))
2633 except error.LookupError:
2633 except error.LookupError:
2634 pass
2634 pass
2635
2635
2636 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2636 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2637 rev = ctx.rev()
2637 rev = ctx.rev()
2638 parent = ctx.p1().rev()
2638 parent = ctx.p1().rev()
2639 for fn in sorted(revfiles.get(rev, [])):
2639 for fn in sorted(revfiles.get(rev, [])):
2640 states = matches[rev][fn]
2640 states = matches[rev][fn]
2641 copy = copies.get(rev, {}).get(fn)
2641 copy = copies.get(rev, {}).get(fn)
2642 if fn in skip:
2642 if fn in skip:
2643 if copy:
2643 if copy:
2644 skip[copy] = True
2644 skip[copy] = True
2645 continue
2645 continue
2646 pstates = matches.get(parent, {}).get(copy or fn, [])
2646 pstates = matches.get(parent, {}).get(copy or fn, [])
2647 if pstates or states:
2647 if pstates or states:
2648 r = display(fn, ctx, pstates, states)
2648 r = display(fn, ctx, pstates, states)
2649 found = found or r
2649 found = found or r
2650 if r and not opts.get('all'):
2650 if r and not opts.get('all'):
2651 skip[fn] = True
2651 skip[fn] = True
2652 if copy:
2652 if copy:
2653 skip[copy] = True
2653 skip[copy] = True
2654 del matches[rev]
2654 del matches[rev]
2655 del revfiles[rev]
2655 del revfiles[rev]
2656
2656
2657 return not found
2657 return not found
2658
2658
2659 @command('heads',
2659 @command('heads',
2660 [('r', 'rev', '',
2660 [('r', 'rev', '',
2661 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2661 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2662 ('t', 'topo', False, _('show topological heads only')),
2662 ('t', 'topo', False, _('show topological heads only')),
2663 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2663 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2664 ('c', 'closed', False, _('show normal and closed branch heads')),
2664 ('c', 'closed', False, _('show normal and closed branch heads')),
2665 ] + templateopts,
2665 ] + templateopts,
2666 _('[-ac] [-r STARTREV] [REV]...'))
2666 _('[-ac] [-r STARTREV] [REV]...'))
2667 def heads(ui, repo, *branchrevs, **opts):
2667 def heads(ui, repo, *branchrevs, **opts):
2668 """show current repository heads or show branch heads
2668 """show current repository heads or show branch heads
2669
2669
2670 With no arguments, show all repository branch heads.
2670 With no arguments, show all repository branch heads.
2671
2671
2672 Repository "heads" are changesets with no child changesets. They are
2672 Repository "heads" are changesets with no child changesets. They are
2673 where development generally takes place and are the usual targets
2673 where development generally takes place and are the usual targets
2674 for update and merge operations. Branch heads are changesets that have
2674 for update and merge operations. Branch heads are changesets that have
2675 no child changeset on the same branch.
2675 no child changeset on the same branch.
2676
2676
2677 If one or more REVs are given, only branch heads on the branches
2677 If one or more REVs are given, only branch heads on the branches
2678 associated with the specified changesets are shown. This means
2678 associated with the specified changesets are shown. This means
2679 that you can use :hg:`heads foo` to see the heads on a branch
2679 that you can use :hg:`heads foo` to see the heads on a branch
2680 named ``foo``.
2680 named ``foo``.
2681
2681
2682 If -c/--closed is specified, also show branch heads marked closed
2682 If -c/--closed is specified, also show branch heads marked closed
2683 (see :hg:`commit --close-branch`).
2683 (see :hg:`commit --close-branch`).
2684
2684
2685 If STARTREV is specified, only those heads that are descendants of
2685 If STARTREV is specified, only those heads that are descendants of
2686 STARTREV will be displayed.
2686 STARTREV will be displayed.
2687
2687
2688 If -t/--topo is specified, named branch mechanics will be ignored and only
2688 If -t/--topo is specified, named branch mechanics will be ignored and only
2689 changesets without children will be shown.
2689 changesets without children will be shown.
2690
2690
2691 Returns 0 if matching heads are found, 1 if not.
2691 Returns 0 if matching heads are found, 1 if not.
2692 """
2692 """
2693
2693
2694 start = None
2694 start = None
2695 if 'rev' in opts:
2695 if 'rev' in opts:
2696 start = scmutil.revsingle(repo, opts['rev'], None).node()
2696 start = scmutil.revsingle(repo, opts['rev'], None).node()
2697
2697
2698 if opts.get('topo'):
2698 if opts.get('topo'):
2699 heads = [repo[h] for h in repo.heads(start)]
2699 heads = [repo[h] for h in repo.heads(start)]
2700 else:
2700 else:
2701 heads = []
2701 heads = []
2702 for branch in repo.branchmap():
2702 for branch in repo.branchmap():
2703 heads += repo.branchheads(branch, start, opts.get('closed'))
2703 heads += repo.branchheads(branch, start, opts.get('closed'))
2704 heads = [repo[h] for h in heads]
2704 heads = [repo[h] for h in heads]
2705
2705
2706 if branchrevs:
2706 if branchrevs:
2707 branches = set(repo[br].branch() for br in branchrevs)
2707 branches = set(repo[br].branch() for br in branchrevs)
2708 heads = [h for h in heads if h.branch() in branches]
2708 heads = [h for h in heads if h.branch() in branches]
2709
2709
2710 if opts.get('active') and branchrevs:
2710 if opts.get('active') and branchrevs:
2711 dagheads = repo.heads(start)
2711 dagheads = repo.heads(start)
2712 heads = [h for h in heads if h.node() in dagheads]
2712 heads = [h for h in heads if h.node() in dagheads]
2713
2713
2714 if branchrevs:
2714 if branchrevs:
2715 haveheads = set(h.branch() for h in heads)
2715 haveheads = set(h.branch() for h in heads)
2716 if branches - haveheads:
2716 if branches - haveheads:
2717 headless = ', '.join(b for b in branches - haveheads)
2717 headless = ', '.join(b for b in branches - haveheads)
2718 msg = _('no open branch heads found on branches %s')
2718 msg = _('no open branch heads found on branches %s')
2719 if opts.get('rev'):
2719 if opts.get('rev'):
2720 msg += _(' (started at %s)' % opts['rev'])
2720 msg += _(' (started at %s)' % opts['rev'])
2721 ui.warn((msg + '\n') % headless)
2721 ui.warn((msg + '\n') % headless)
2722
2722
2723 if not heads:
2723 if not heads:
2724 return 1
2724 return 1
2725
2725
2726 heads = sorted(heads, key=lambda x: -x.rev())
2726 heads = sorted(heads, key=lambda x: -x.rev())
2727 displayer = cmdutil.show_changeset(ui, repo, opts)
2727 displayer = cmdutil.show_changeset(ui, repo, opts)
2728 for ctx in heads:
2728 for ctx in heads:
2729 displayer.show(ctx)
2729 displayer.show(ctx)
2730 displayer.close()
2730 displayer.close()
2731
2731
2732 @command('help',
2732 @command('help',
2733 [('e', 'extension', None, _('show only help for extensions')),
2733 [('e', 'extension', None, _('show only help for extensions')),
2734 ('c', 'command', None, _('show only help for commands'))],
2734 ('c', 'command', None, _('show only help for commands'))],
2735 _('[-ec] [TOPIC]'))
2735 _('[-ec] [TOPIC]'))
2736 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2736 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
2737 """show help for a given topic or a help overview
2737 """show help for a given topic or a help overview
2738
2738
2739 With no arguments, print a list of commands with short help messages.
2739 With no arguments, print a list of commands with short help messages.
2740
2740
2741 Given a topic, extension, or command name, print help for that
2741 Given a topic, extension, or command name, print help for that
2742 topic.
2742 topic.
2743
2743
2744 Returns 0 if successful.
2744 Returns 0 if successful.
2745 """
2745 """
2746
2746
2747 textwidth = min(ui.termwidth(), 80) - 2
2747 textwidth = min(ui.termwidth(), 80) - 2
2748
2748
2749 def optrst(options):
2749 def optrst(options):
2750 data = []
2750 data = []
2751 multioccur = False
2751 multioccur = False
2752 for option in options:
2752 for option in options:
2753 if len(option) == 5:
2753 if len(option) == 5:
2754 shortopt, longopt, default, desc, optlabel = option
2754 shortopt, longopt, default, desc, optlabel = option
2755 else:
2755 else:
2756 shortopt, longopt, default, desc = option
2756 shortopt, longopt, default, desc = option
2757 optlabel = _("VALUE") # default label
2757 optlabel = _("VALUE") # default label
2758
2758
2759 if _("DEPRECATED") in desc and not ui.verbose:
2759 if _("DEPRECATED") in desc and not ui.verbose:
2760 continue
2760 continue
2761
2761
2762 so = ''
2762 so = ''
2763 if shortopt:
2763 if shortopt:
2764 so = '-' + shortopt
2764 so = '-' + shortopt
2765 lo = '--' + longopt
2765 lo = '--' + longopt
2766 if default:
2766 if default:
2767 desc += _(" (default: %s)") % default
2767 desc += _(" (default: %s)") % default
2768
2768
2769 if isinstance(default, list):
2769 if isinstance(default, list):
2770 lo += " %s [+]" % optlabel
2770 lo += " %s [+]" % optlabel
2771 multioccur = True
2771 multioccur = True
2772 elif (default is not None) and not isinstance(default, bool):
2772 elif (default is not None) and not isinstance(default, bool):
2773 lo += " %s" % optlabel
2773 lo += " %s" % optlabel
2774
2774
2775 data.append((so, lo, desc))
2775 data.append((so, lo, desc))
2776
2776
2777 rst = minirst.maketable(data, 1)
2777 rst = minirst.maketable(data, 1)
2778
2778
2779 if multioccur:
2779 if multioccur:
2780 rst += _("\n[+] marked option can be specified multiple times\n")
2780 rst += _("\n[+] marked option can be specified multiple times\n")
2781
2781
2782 return rst
2782 return rst
2783
2783
2784 # list all option lists
2784 # list all option lists
2785 def opttext(optlist, width):
2785 def opttext(optlist, width):
2786 rst = ''
2786 rst = ''
2787 if not optlist:
2787 if not optlist:
2788 return ''
2788 return ''
2789
2789
2790 for title, options in optlist:
2790 for title, options in optlist:
2791 rst += '\n%s\n' % title
2791 rst += '\n%s\n' % title
2792 if options:
2792 if options:
2793 rst += "\n"
2793 rst += "\n"
2794 rst += optrst(options)
2794 rst += optrst(options)
2795 rst += '\n'
2795 rst += '\n'
2796
2796
2797 return '\n' + minirst.format(rst, width)
2797 return '\n' + minirst.format(rst, width)
2798
2798
2799 def addglobalopts(optlist, aliases):
2799 def addglobalopts(optlist, aliases):
2800 if ui.quiet:
2800 if ui.quiet:
2801 return []
2801 return []
2802
2802
2803 if ui.verbose:
2803 if ui.verbose:
2804 optlist.append((_("global options:"), globalopts))
2804 optlist.append((_("global options:"), globalopts))
2805 if name == 'shortlist':
2805 if name == 'shortlist':
2806 optlist.append((_('use "hg help" for the full list '
2806 optlist.append((_('use "hg help" for the full list '
2807 'of commands'), ()))
2807 'of commands'), ()))
2808 else:
2808 else:
2809 if name == 'shortlist':
2809 if name == 'shortlist':
2810 msg = _('use "hg help" for the full list of commands '
2810 msg = _('use "hg help" for the full list of commands '
2811 'or "hg -v" for details')
2811 'or "hg -v" for details')
2812 elif name and not full:
2812 elif name and not full:
2813 msg = _('use "hg help %s" to show the full help text' % name)
2813 msg = _('use "hg help %s" to show the full help text' % name)
2814 elif aliases:
2814 elif aliases:
2815 msg = _('use "hg -v help%s" to show builtin aliases and '
2815 msg = _('use "hg -v help%s" to show builtin aliases and '
2816 'global options') % (name and " " + name or "")
2816 'global options') % (name and " " + name or "")
2817 else:
2817 else:
2818 msg = _('use "hg -v help %s" to show more info') % name
2818 msg = _('use "hg -v help %s" to show more info') % name
2819 optlist.append((msg, ()))
2819 optlist.append((msg, ()))
2820
2820
2821 def helpcmd(name):
2821 def helpcmd(name):
2822 try:
2822 try:
2823 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2823 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2824 except error.AmbiguousCommand, inst:
2824 except error.AmbiguousCommand, inst:
2825 # py3k fix: except vars can't be used outside the scope of the
2825 # py3k fix: except vars can't be used outside the scope of the
2826 # except block, nor can be used inside a lambda. python issue4617
2826 # except block, nor can be used inside a lambda. python issue4617
2827 prefix = inst.args[0]
2827 prefix = inst.args[0]
2828 select = lambda c: c.lstrip('^').startswith(prefix)
2828 select = lambda c: c.lstrip('^').startswith(prefix)
2829 helplist(select)
2829 helplist(select)
2830 return
2830 return
2831
2831
2832 # check if it's an invalid alias and display its error if it is
2832 # check if it's an invalid alias and display its error if it is
2833 if getattr(entry[0], 'badalias', False):
2833 if getattr(entry[0], 'badalias', False):
2834 if not unknowncmd:
2834 if not unknowncmd:
2835 entry[0](ui)
2835 entry[0](ui)
2836 return
2836 return
2837
2837
2838 rst = ""
2838 rst = ""
2839
2839
2840 # synopsis
2840 # synopsis
2841 if len(entry) > 2:
2841 if len(entry) > 2:
2842 if entry[2].startswith('hg'):
2842 if entry[2].startswith('hg'):
2843 rst += "%s\n" % entry[2]
2843 rst += "%s\n" % entry[2]
2844 else:
2844 else:
2845 rst += 'hg %s %s\n' % (aliases[0], entry[2])
2845 rst += 'hg %s %s\n' % (aliases[0], entry[2])
2846 else:
2846 else:
2847 rst += 'hg %s\n' % aliases[0]
2847 rst += 'hg %s\n' % aliases[0]
2848
2848
2849 # aliases
2849 # aliases
2850 if full and not ui.quiet and len(aliases) > 1:
2850 if full and not ui.quiet and len(aliases) > 1:
2851 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
2851 rst += _("\naliases: %s\n") % ', '.join(aliases[1:])
2852
2852
2853 # description
2853 # description
2854 doc = gettext(entry[0].__doc__)
2854 doc = gettext(entry[0].__doc__)
2855 if not doc:
2855 if not doc:
2856 doc = _("(no help text available)")
2856 doc = _("(no help text available)")
2857 if util.safehasattr(entry[0], 'definition'): # aliased command
2857 if util.safehasattr(entry[0], 'definition'): # aliased command
2858 if entry[0].definition.startswith('!'): # shell alias
2858 if entry[0].definition.startswith('!'): # shell alias
2859 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2859 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2860 else:
2860 else:
2861 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2861 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2862 if ui.quiet or not full:
2862 if ui.quiet or not full:
2863 doc = doc.splitlines()[0]
2863 doc = doc.splitlines()[0]
2864 rst += "\n" + doc + "\n"
2864 rst += "\n" + doc + "\n"
2865
2865
2866 # check if this command shadows a non-trivial (multi-line)
2866 # check if this command shadows a non-trivial (multi-line)
2867 # extension help text
2867 # extension help text
2868 try:
2868 try:
2869 mod = extensions.find(name)
2869 mod = extensions.find(name)
2870 doc = gettext(mod.__doc__) or ''
2870 doc = gettext(mod.__doc__) or ''
2871 if '\n' in doc.strip():
2871 if '\n' in doc.strip():
2872 msg = _('use "hg help -e %s" to show help for '
2872 msg = _('use "hg help -e %s" to show help for '
2873 'the %s extension') % (name, name)
2873 'the %s extension') % (name, name)
2874 rst += '\n%s\n' % msg
2874 rst += '\n%s\n' % msg
2875 except KeyError:
2875 except KeyError:
2876 pass
2876 pass
2877
2877
2878 # options
2878 # options
2879 if not ui.quiet and entry[1]:
2879 if not ui.quiet and entry[1]:
2880 rst += '\noptions:\n\n'
2880 rst += '\noptions:\n\n'
2881 rst += optrst(entry[1])
2881 rst += optrst(entry[1])
2882
2882
2883 if ui.verbose:
2883 if ui.verbose:
2884 rst += '\nglobal options:\n\n'
2884 rst += '\nglobal options:\n\n'
2885 rst += optrst(globalopts)
2885 rst += optrst(globalopts)
2886
2886
2887 keep = ui.verbose and ['verbose'] or []
2887 keep = ui.verbose and ['verbose'] or []
2888 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
2888 formatted, pruned = minirst.format(rst, textwidth, keep=keep)
2889 ui.write(formatted)
2889 ui.write(formatted)
2890
2890
2891 if not ui.verbose:
2891 if not ui.verbose:
2892 if not full:
2892 if not full:
2893 ui.write(_('\nuse "hg help %s" to show the full help text\n')
2893 ui.write(_('\nuse "hg help %s" to show the full help text\n')
2894 % name)
2894 % name)
2895 elif not ui.quiet:
2895 elif not ui.quiet:
2896 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
2896 ui.write(_('\nuse "hg -v help %s" to show more info\n') % name)
2897
2897
2898
2898
2899 def helplist(select=None):
2899 def helplist(select=None):
2900 # list of commands
2900 # list of commands
2901 if name == "shortlist":
2901 if name == "shortlist":
2902 header = _('basic commands:\n\n')
2902 header = _('basic commands:\n\n')
2903 else:
2903 else:
2904 header = _('list of commands:\n\n')
2904 header = _('list of commands:\n\n')
2905
2905
2906 h = {}
2906 h = {}
2907 cmds = {}
2907 cmds = {}
2908 for c, e in table.iteritems():
2908 for c, e in table.iteritems():
2909 f = c.split("|", 1)[0]
2909 f = c.split("|", 1)[0]
2910 if select and not select(f):
2910 if select and not select(f):
2911 continue
2911 continue
2912 if (not select and name != 'shortlist' and
2912 if (not select and name != 'shortlist' and
2913 e[0].__module__ != __name__):
2913 e[0].__module__ != __name__):
2914 continue
2914 continue
2915 if name == "shortlist" and not f.startswith("^"):
2915 if name == "shortlist" and not f.startswith("^"):
2916 continue
2916 continue
2917 f = f.lstrip("^")
2917 f = f.lstrip("^")
2918 if not ui.debugflag and f.startswith("debug"):
2918 if not ui.debugflag and f.startswith("debug"):
2919 continue
2919 continue
2920 doc = e[0].__doc__
2920 doc = e[0].__doc__
2921 if doc and 'DEPRECATED' in doc and not ui.verbose:
2921 if doc and 'DEPRECATED' in doc and not ui.verbose:
2922 continue
2922 continue
2923 doc = gettext(doc)
2923 doc = gettext(doc)
2924 if not doc:
2924 if not doc:
2925 doc = _("(no help text available)")
2925 doc = _("(no help text available)")
2926 h[f] = doc.splitlines()[0].rstrip()
2926 h[f] = doc.splitlines()[0].rstrip()
2927 cmds[f] = c.lstrip("^")
2927 cmds[f] = c.lstrip("^")
2928
2928
2929 if not h:
2929 if not h:
2930 ui.status(_('no commands defined\n'))
2930 ui.status(_('no commands defined\n'))
2931 return
2931 return
2932
2932
2933 ui.status(header)
2933 ui.status(header)
2934 fns = sorted(h)
2934 fns = sorted(h)
2935 m = max(map(len, fns))
2935 m = max(map(len, fns))
2936 for f in fns:
2936 for f in fns:
2937 if ui.verbose:
2937 if ui.verbose:
2938 commands = cmds[f].replace("|",", ")
2938 commands = cmds[f].replace("|",", ")
2939 ui.write(" %s:\n %s\n"%(commands, h[f]))
2939 ui.write(" %s:\n %s\n"%(commands, h[f]))
2940 else:
2940 else:
2941 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2941 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2942 initindent=' %-*s ' % (m, f),
2942 initindent=' %-*s ' % (m, f),
2943 hangindent=' ' * (m + 4))))
2943 hangindent=' ' * (m + 4))))
2944
2944
2945 if not name:
2945 if not name:
2946 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2946 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2947 if text:
2947 if text:
2948 ui.write("\n%s" % minirst.format(text, textwidth))
2948 ui.write("\n%s" % minirst.format(text, textwidth))
2949
2949
2950 ui.write(_("\nadditional help topics:\n\n"))
2950 ui.write(_("\nadditional help topics:\n\n"))
2951 topics = []
2951 topics = []
2952 for names, header, doc in help.helptable:
2952 for names, header, doc in help.helptable:
2953 topics.append((sorted(names, key=len, reverse=True)[0], header))
2953 topics.append((sorted(names, key=len, reverse=True)[0], header))
2954 topics_len = max([len(s[0]) for s in topics])
2954 topics_len = max([len(s[0]) for s in topics])
2955 for t, desc in topics:
2955 for t, desc in topics:
2956 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2956 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2957
2957
2958 optlist = []
2958 optlist = []
2959 addglobalopts(optlist, True)
2959 addglobalopts(optlist, True)
2960 ui.write(opttext(optlist, textwidth))
2960 ui.write(opttext(optlist, textwidth))
2961
2961
2962 def helptopic(name):
2962 def helptopic(name):
2963 for names, header, doc in help.helptable:
2963 for names, header, doc in help.helptable:
2964 if name in names:
2964 if name in names:
2965 break
2965 break
2966 else:
2966 else:
2967 raise error.UnknownCommand(name)
2967 raise error.UnknownCommand(name)
2968
2968
2969 # description
2969 # description
2970 if not doc:
2970 if not doc:
2971 doc = _("(no help text available)")
2971 doc = _("(no help text available)")
2972 if util.safehasattr(doc, '__call__'):
2972 if util.safehasattr(doc, '__call__'):
2973 doc = doc()
2973 doc = doc()
2974
2974
2975 ui.write("%s\n\n" % header)
2975 ui.write("%s\n\n" % header)
2976 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
2976 ui.write("%s" % minirst.format(doc, textwidth, indent=4))
2977 try:
2977 try:
2978 cmdutil.findcmd(name, table)
2978 cmdutil.findcmd(name, table)
2979 ui.write(_('\nuse "hg help -c %s" to see help for '
2979 ui.write(_('\nuse "hg help -c %s" to see help for '
2980 'the %s command\n') % (name, name))
2980 'the %s command\n') % (name, name))
2981 except error.UnknownCommand:
2981 except error.UnknownCommand:
2982 pass
2982 pass
2983
2983
2984 def helpext(name):
2984 def helpext(name):
2985 try:
2985 try:
2986 mod = extensions.find(name)
2986 mod = extensions.find(name)
2987 doc = gettext(mod.__doc__) or _('no help text available')
2987 doc = gettext(mod.__doc__) or _('no help text available')
2988 except KeyError:
2988 except KeyError:
2989 mod = None
2989 mod = None
2990 doc = extensions.disabledext(name)
2990 doc = extensions.disabledext(name)
2991 if not doc:
2991 if not doc:
2992 raise error.UnknownCommand(name)
2992 raise error.UnknownCommand(name)
2993
2993
2994 if '\n' not in doc:
2994 if '\n' not in doc:
2995 head, tail = doc, ""
2995 head, tail = doc, ""
2996 else:
2996 else:
2997 head, tail = doc.split('\n', 1)
2997 head, tail = doc.split('\n', 1)
2998 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2998 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2999 if tail:
2999 if tail:
3000 ui.write(minirst.format(tail, textwidth))
3000 ui.write(minirst.format(tail, textwidth))
3001 ui.status('\n')
3001 ui.status('\n')
3002
3002
3003 if mod:
3003 if mod:
3004 try:
3004 try:
3005 ct = mod.cmdtable
3005 ct = mod.cmdtable
3006 except AttributeError:
3006 except AttributeError:
3007 ct = {}
3007 ct = {}
3008 modcmds = set([c.split('|', 1)[0] for c in ct])
3008 modcmds = set([c.split('|', 1)[0] for c in ct])
3009 helplist(modcmds.__contains__)
3009 helplist(modcmds.__contains__)
3010 else:
3010 else:
3011 ui.write(_('use "hg help extensions" for information on enabling '
3011 ui.write(_('use "hg help extensions" for information on enabling '
3012 'extensions\n'))
3012 'extensions\n'))
3013
3013
3014 def helpextcmd(name):
3014 def helpextcmd(name):
3015 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3015 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
3016 doc = gettext(mod.__doc__).splitlines()[0]
3016 doc = gettext(mod.__doc__).splitlines()[0]
3017
3017
3018 msg = help.listexts(_("'%s' is provided by the following "
3018 msg = help.listexts(_("'%s' is provided by the following "
3019 "extension:") % cmd, {ext: doc}, indent=4)
3019 "extension:") % cmd, {ext: doc}, indent=4)
3020 ui.write(minirst.format(msg, textwidth))
3020 ui.write(minirst.format(msg, textwidth))
3021 ui.write('\n')
3021 ui.write('\n')
3022 ui.write(_('use "hg help extensions" for information on enabling '
3022 ui.write(_('use "hg help extensions" for information on enabling '
3023 'extensions\n'))
3023 'extensions\n'))
3024
3024
3025 if name and name != 'shortlist':
3025 if name and name != 'shortlist':
3026 i = None
3026 i = None
3027 if unknowncmd:
3027 if unknowncmd:
3028 queries = (helpextcmd,)
3028 queries = (helpextcmd,)
3029 elif opts.get('extension'):
3029 elif opts.get('extension'):
3030 queries = (helpext,)
3030 queries = (helpext,)
3031 elif opts.get('command'):
3031 elif opts.get('command'):
3032 queries = (helpcmd,)
3032 queries = (helpcmd,)
3033 else:
3033 else:
3034 queries = (helptopic, helpcmd, helpext, helpextcmd)
3034 queries = (helptopic, helpcmd, helpext, helpextcmd)
3035 for f in queries:
3035 for f in queries:
3036 try:
3036 try:
3037 f(name)
3037 f(name)
3038 i = None
3038 i = None
3039 break
3039 break
3040 except error.UnknownCommand, inst:
3040 except error.UnknownCommand, inst:
3041 i = inst
3041 i = inst
3042 if i:
3042 if i:
3043 raise i
3043 raise i
3044 else:
3044 else:
3045 # program name
3045 # program name
3046 ui.status(_("Mercurial Distributed SCM\n"))
3046 ui.status(_("Mercurial Distributed SCM\n"))
3047 ui.status('\n')
3047 ui.status('\n')
3048 helplist()
3048 helplist()
3049
3049
3050
3050
3051 @command('identify|id',
3051 @command('identify|id',
3052 [('r', 'rev', '',
3052 [('r', 'rev', '',
3053 _('identify the specified revision'), _('REV')),
3053 _('identify the specified revision'), _('REV')),
3054 ('n', 'num', None, _('show local revision number')),
3054 ('n', 'num', None, _('show local revision number')),
3055 ('i', 'id', None, _('show global revision id')),
3055 ('i', 'id', None, _('show global revision id')),
3056 ('b', 'branch', None, _('show branch')),
3056 ('b', 'branch', None, _('show branch')),
3057 ('t', 'tags', None, _('show tags')),
3057 ('t', 'tags', None, _('show tags')),
3058 ('B', 'bookmarks', None, _('show bookmarks'))],
3058 ('B', 'bookmarks', None, _('show bookmarks'))],
3059 _('[-nibtB] [-r REV] [SOURCE]'))
3059 _('[-nibtB] [-r REV] [SOURCE]'))
3060 def identify(ui, repo, source=None, rev=None,
3060 def identify(ui, repo, source=None, rev=None,
3061 num=None, id=None, branch=None, tags=None, bookmarks=None):
3061 num=None, id=None, branch=None, tags=None, bookmarks=None):
3062 """identify the working copy or specified revision
3062 """identify the working copy or specified revision
3063
3063
3064 Print a summary identifying the repository state at REV using one or
3064 Print a summary identifying the repository state at REV using one or
3065 two parent hash identifiers, followed by a "+" if the working
3065 two parent hash identifiers, followed by a "+" if the working
3066 directory has uncommitted changes, the branch name (if not default),
3066 directory has uncommitted changes, the branch name (if not default),
3067 a list of tags, and a list of bookmarks.
3067 a list of tags, and a list of bookmarks.
3068
3068
3069 When REV is not given, print a summary of the current state of the
3069 When REV is not given, print a summary of the current state of the
3070 repository.
3070 repository.
3071
3071
3072 Specifying a path to a repository root or Mercurial bundle will
3072 Specifying a path to a repository root or Mercurial bundle will
3073 cause lookup to operate on that repository/bundle.
3073 cause lookup to operate on that repository/bundle.
3074
3074
3075 .. container:: verbose
3075 .. container:: verbose
3076
3076
3077 Examples:
3077 Examples:
3078
3078
3079 - generate a build identifier for the working directory::
3079 - generate a build identifier for the working directory::
3080
3080
3081 hg id --id > build-id.dat
3081 hg id --id > build-id.dat
3082
3082
3083 - find the revision corresponding to a tag::
3083 - find the revision corresponding to a tag::
3084
3084
3085 hg id -n -r 1.3
3085 hg id -n -r 1.3
3086
3086
3087 - check the most recent revision of a remote repository::
3087 - check the most recent revision of a remote repository::
3088
3088
3089 hg id -r tip http://selenic.com/hg/
3089 hg id -r tip http://selenic.com/hg/
3090
3090
3091 Returns 0 if successful.
3091 Returns 0 if successful.
3092 """
3092 """
3093
3093
3094 if not repo and not source:
3094 if not repo and not source:
3095 raise util.Abort(_("there is no Mercurial repository here "
3095 raise util.Abort(_("there is no Mercurial repository here "
3096 "(.hg not found)"))
3096 "(.hg not found)"))
3097
3097
3098 hexfunc = ui.debugflag and hex or short
3098 hexfunc = ui.debugflag and hex or short
3099 default = not (num or id or branch or tags or bookmarks)
3099 default = not (num or id or branch or tags or bookmarks)
3100 output = []
3100 output = []
3101 revs = []
3101 revs = []
3102
3102
3103 if source:
3103 if source:
3104 source, branches = hg.parseurl(ui.expandpath(source))
3104 source, branches = hg.parseurl(ui.expandpath(source))
3105 repo = hg.peer(ui, {}, source)
3105 repo = hg.peer(ui, {}, source)
3106 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3106 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3107
3107
3108 if not repo.local():
3108 if not repo.local():
3109 if num or branch or tags:
3109 if num or branch or tags:
3110 raise util.Abort(
3110 raise util.Abort(
3111 _("can't query remote revision number, branch, or tags"))
3111 _("can't query remote revision number, branch, or tags"))
3112 if not rev and revs:
3112 if not rev and revs:
3113 rev = revs[0]
3113 rev = revs[0]
3114 if not rev:
3114 if not rev:
3115 rev = "tip"
3115 rev = "tip"
3116
3116
3117 remoterev = repo.lookup(rev)
3117 remoterev = repo.lookup(rev)
3118 if default or id:
3118 if default or id:
3119 output = [hexfunc(remoterev)]
3119 output = [hexfunc(remoterev)]
3120
3120
3121 def getbms():
3121 def getbms():
3122 bms = []
3122 bms = []
3123
3123
3124 if 'bookmarks' in repo.listkeys('namespaces'):
3124 if 'bookmarks' in repo.listkeys('namespaces'):
3125 hexremoterev = hex(remoterev)
3125 hexremoterev = hex(remoterev)
3126 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3126 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
3127 if bmr == hexremoterev]
3127 if bmr == hexremoterev]
3128
3128
3129 return bms
3129 return bms
3130
3130
3131 if bookmarks:
3131 if bookmarks:
3132 output.extend(getbms())
3132 output.extend(getbms())
3133 elif default and not ui.quiet:
3133 elif default and not ui.quiet:
3134 # multiple bookmarks for a single parent separated by '/'
3134 # multiple bookmarks for a single parent separated by '/'
3135 bm = '/'.join(getbms())
3135 bm = '/'.join(getbms())
3136 if bm:
3136 if bm:
3137 output.append(bm)
3137 output.append(bm)
3138 else:
3138 else:
3139 if not rev:
3139 if not rev:
3140 ctx = repo[None]
3140 ctx = repo[None]
3141 parents = ctx.parents()
3141 parents = ctx.parents()
3142 changed = ""
3142 changed = ""
3143 if default or id or num:
3143 if default or id or num:
3144 changed = util.any(repo.status()) and "+" or ""
3144 changed = util.any(repo.status()) and "+" or ""
3145 if default or id:
3145 if default or id:
3146 output = ["%s%s" %
3146 output = ["%s%s" %
3147 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3147 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3148 if num:
3148 if num:
3149 output.append("%s%s" %
3149 output.append("%s%s" %
3150 ('+'.join([str(p.rev()) for p in parents]), changed))
3150 ('+'.join([str(p.rev()) for p in parents]), changed))
3151 else:
3151 else:
3152 ctx = scmutil.revsingle(repo, rev)
3152 ctx = scmutil.revsingle(repo, rev)
3153 if default or id:
3153 if default or id:
3154 output = [hexfunc(ctx.node())]
3154 output = [hexfunc(ctx.node())]
3155 if num:
3155 if num:
3156 output.append(str(ctx.rev()))
3156 output.append(str(ctx.rev()))
3157
3157
3158 if default and not ui.quiet:
3158 if default and not ui.quiet:
3159 b = ctx.branch()
3159 b = ctx.branch()
3160 if b != 'default':
3160 if b != 'default':
3161 output.append("(%s)" % b)
3161 output.append("(%s)" % b)
3162
3162
3163 # multiple tags for a single parent separated by '/'
3163 # multiple tags for a single parent separated by '/'
3164 t = '/'.join(ctx.tags())
3164 t = '/'.join(ctx.tags())
3165 if t:
3165 if t:
3166 output.append(t)
3166 output.append(t)
3167
3167
3168 # multiple bookmarks for a single parent separated by '/'
3168 # multiple bookmarks for a single parent separated by '/'
3169 bm = '/'.join(ctx.bookmarks())
3169 bm = '/'.join(ctx.bookmarks())
3170 if bm:
3170 if bm:
3171 output.append(bm)
3171 output.append(bm)
3172 else:
3172 else:
3173 if branch:
3173 if branch:
3174 output.append(ctx.branch())
3174 output.append(ctx.branch())
3175
3175
3176 if tags:
3176 if tags:
3177 output.extend(ctx.tags())
3177 output.extend(ctx.tags())
3178
3178
3179 if bookmarks:
3179 if bookmarks:
3180 output.extend(ctx.bookmarks())
3180 output.extend(ctx.bookmarks())
3181
3181
3182 ui.write("%s\n" % ' '.join(output))
3182 ui.write("%s\n" % ' '.join(output))
3183
3183
3184 @command('import|patch',
3184 @command('import|patch',
3185 [('p', 'strip', 1,
3185 [('p', 'strip', 1,
3186 _('directory strip option for patch. This has the same '
3186 _('directory strip option for patch. This has the same '
3187 'meaning as the corresponding patch option'), _('NUM')),
3187 'meaning as the corresponding patch option'), _('NUM')),
3188 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3188 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3189 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3189 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3190 ('', 'no-commit', None,
3190 ('', 'no-commit', None,
3191 _("don't commit, just update the working directory")),
3191 _("don't commit, just update the working directory")),
3192 ('', 'bypass', None,
3192 ('', 'bypass', None,
3193 _("apply patch without touching the working directory")),
3193 _("apply patch without touching the working directory")),
3194 ('', 'exact', None,
3194 ('', 'exact', None,
3195 _('apply patch to the nodes from which it was generated')),
3195 _('apply patch to the nodes from which it was generated')),
3196 ('', 'import-branch', None,
3196 ('', 'import-branch', None,
3197 _('use any branch information in patch (implied by --exact)'))] +
3197 _('use any branch information in patch (implied by --exact)'))] +
3198 commitopts + commitopts2 + similarityopts,
3198 commitopts + commitopts2 + similarityopts,
3199 _('[OPTION]... PATCH...'))
3199 _('[OPTION]... PATCH...'))
3200 def import_(ui, repo, patch1, *patches, **opts):
3200 def import_(ui, repo, patch1, *patches, **opts):
3201 """import an ordered set of patches
3201 """import an ordered set of patches
3202
3202
3203 Import a list of patches and commit them individually (unless
3203 Import a list of patches and commit them individually (unless
3204 --no-commit is specified).
3204 --no-commit is specified).
3205
3205
3206 If there are outstanding changes in the working directory, import
3206 If there are outstanding changes in the working directory, import
3207 will abort unless given the -f/--force flag.
3207 will abort unless given the -f/--force flag.
3208
3208
3209 You can import a patch straight from a mail message. Even patches
3209 You can import a patch straight from a mail message. Even patches
3210 as attachments work (to use the body part, it must have type
3210 as attachments work (to use the body part, it must have type
3211 text/plain or text/x-patch). From and Subject headers of email
3211 text/plain or text/x-patch). From and Subject headers of email
3212 message are used as default committer and commit message. All
3212 message are used as default committer and commit message. All
3213 text/plain body parts before first diff are added to commit
3213 text/plain body parts before first diff are added to commit
3214 message.
3214 message.
3215
3215
3216 If the imported patch was generated by :hg:`export`, user and
3216 If the imported patch was generated by :hg:`export`, user and
3217 description from patch override values from message headers and
3217 description from patch override values from message headers and
3218 body. Values given on command line with -m/--message and -u/--user
3218 body. Values given on command line with -m/--message and -u/--user
3219 override these.
3219 override these.
3220
3220
3221 If --exact is specified, import will set the working directory to
3221 If --exact is specified, import will set the working directory to
3222 the parent of each patch before applying it, and will abort if the
3222 the parent of each patch before applying it, and will abort if the
3223 resulting changeset has a different ID than the one recorded in
3223 resulting changeset has a different ID than the one recorded in
3224 the patch. This may happen due to character set problems or other
3224 the patch. This may happen due to character set problems or other
3225 deficiencies in the text patch format.
3225 deficiencies in the text patch format.
3226
3226
3227 Use --bypass to apply and commit patches directly to the
3227 Use --bypass to apply and commit patches directly to the
3228 repository, not touching the working directory. Without --exact,
3228 repository, not touching the working directory. Without --exact,
3229 patches will be applied on top of the working directory parent
3229 patches will be applied on top of the working directory parent
3230 revision.
3230 revision.
3231
3231
3232 With -s/--similarity, hg will attempt to discover renames and
3232 With -s/--similarity, hg will attempt to discover renames and
3233 copies in the patch in the same way as 'addremove'.
3233 copies in the patch in the same way as 'addremove'.
3234
3234
3235 To read a patch from standard input, use "-" as the patch name. If
3235 To read a patch from standard input, use "-" as the patch name. If
3236 a URL is specified, the patch will be downloaded from it.
3236 a URL is specified, the patch will be downloaded from it.
3237 See :hg:`help dates` for a list of formats valid for -d/--date.
3237 See :hg:`help dates` for a list of formats valid for -d/--date.
3238
3238
3239 .. container:: verbose
3239 .. container:: verbose
3240
3240
3241 Examples:
3241 Examples:
3242
3242
3243 - import a traditional patch from a website and detect renames::
3243 - import a traditional patch from a website and detect renames::
3244
3244
3245 hg import -s 80 http://example.com/bugfix.patch
3245 hg import -s 80 http://example.com/bugfix.patch
3246
3246
3247 - import a changeset from an hgweb server::
3247 - import a changeset from an hgweb server::
3248
3248
3249 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3249 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3250
3250
3251 - import all the patches in an Unix-style mbox::
3251 - import all the patches in an Unix-style mbox::
3252
3252
3253 hg import incoming-patches.mbox
3253 hg import incoming-patches.mbox
3254
3254
3255 - attempt to exactly restore an exported changeset (not always
3255 - attempt to exactly restore an exported changeset (not always
3256 possible)::
3256 possible)::
3257
3257
3258 hg import --exact proposed-fix.patch
3258 hg import --exact proposed-fix.patch
3259
3259
3260 Returns 0 on success.
3260 Returns 0 on success.
3261 """
3261 """
3262 patches = (patch1,) + patches
3262 patches = (patch1,) + patches
3263
3263
3264 date = opts.get('date')
3264 date = opts.get('date')
3265 if date:
3265 if date:
3266 opts['date'] = util.parsedate(date)
3266 opts['date'] = util.parsedate(date)
3267
3267
3268 update = not opts.get('bypass')
3268 update = not opts.get('bypass')
3269 if not update and opts.get('no_commit'):
3269 if not update and opts.get('no_commit'):
3270 raise util.Abort(_('cannot use --no-commit with --bypass'))
3270 raise util.Abort(_('cannot use --no-commit with --bypass'))
3271 try:
3271 try:
3272 sim = float(opts.get('similarity') or 0)
3272 sim = float(opts.get('similarity') or 0)
3273 except ValueError:
3273 except ValueError:
3274 raise util.Abort(_('similarity must be a number'))
3274 raise util.Abort(_('similarity must be a number'))
3275 if sim < 0 or sim > 100:
3275 if sim < 0 or sim > 100:
3276 raise util.Abort(_('similarity must be between 0 and 100'))
3276 raise util.Abort(_('similarity must be between 0 and 100'))
3277 if sim and not update:
3277 if sim and not update:
3278 raise util.Abort(_('cannot use --similarity with --bypass'))
3278 raise util.Abort(_('cannot use --similarity with --bypass'))
3279
3279
3280 if (opts.get('exact') or not opts.get('force')) and update:
3280 if (opts.get('exact') or not opts.get('force')) and update:
3281 cmdutil.bailifchanged(repo)
3281 cmdutil.bailifchanged(repo)
3282
3282
3283 base = opts["base"]
3283 base = opts["base"]
3284 strip = opts["strip"]
3284 strip = opts["strip"]
3285 wlock = lock = tr = None
3285 wlock = lock = tr = None
3286 msgs = []
3286 msgs = []
3287
3287
3288 def checkexact(repo, n, nodeid):
3288 def checkexact(repo, n, nodeid):
3289 if opts.get('exact') and hex(n) != nodeid:
3289 if opts.get('exact') and hex(n) != nodeid:
3290 repo.rollback()
3290 repo.rollback()
3291 raise util.Abort(_('patch is damaged or loses information'))
3291 raise util.Abort(_('patch is damaged or loses information'))
3292
3292
3293 def tryone(ui, hunk, parents):
3293 def tryone(ui, hunk, parents):
3294 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3294 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3295 patch.extract(ui, hunk)
3295 patch.extract(ui, hunk)
3296
3296
3297 if not tmpname:
3297 if not tmpname:
3298 return (None, None)
3298 return (None, None)
3299 msg = _('applied to working directory')
3299 msg = _('applied to working directory')
3300
3300
3301 try:
3301 try:
3302 cmdline_message = cmdutil.logmessage(ui, opts)
3302 cmdline_message = cmdutil.logmessage(ui, opts)
3303 if cmdline_message:
3303 if cmdline_message:
3304 # pickup the cmdline msg
3304 # pickup the cmdline msg
3305 message = cmdline_message
3305 message = cmdline_message
3306 elif message:
3306 elif message:
3307 # pickup the patch msg
3307 # pickup the patch msg
3308 message = message.strip()
3308 message = message.strip()
3309 else:
3309 else:
3310 # launch the editor
3310 # launch the editor
3311 message = None
3311 message = None
3312 ui.debug('message:\n%s\n' % message)
3312 ui.debug('message:\n%s\n' % message)
3313
3313
3314 if len(parents) == 1:
3314 if len(parents) == 1:
3315 parents.append(repo[nullid])
3315 parents.append(repo[nullid])
3316 if opts.get('exact'):
3316 if opts.get('exact'):
3317 if not nodeid or not p1:
3317 if not nodeid or not p1:
3318 raise util.Abort(_('not a Mercurial patch'))
3318 raise util.Abort(_('not a Mercurial patch'))
3319 p1 = repo[p1]
3319 p1 = repo[p1]
3320 p2 = repo[p2 or nullid]
3320 p2 = repo[p2 or nullid]
3321 elif p2:
3321 elif p2:
3322 try:
3322 try:
3323 p1 = repo[p1]
3323 p1 = repo[p1]
3324 p2 = repo[p2]
3324 p2 = repo[p2]
3325 except error.RepoError:
3325 except error.RepoError:
3326 p1, p2 = parents
3326 p1, p2 = parents
3327 else:
3327 else:
3328 p1, p2 = parents
3328 p1, p2 = parents
3329
3329
3330 n = None
3330 n = None
3331 if update:
3331 if update:
3332 if opts.get('exact') and p1 != parents[0]:
3332 if opts.get('exact') and p1 != parents[0]:
3333 hg.clean(repo, p1.node())
3333 hg.clean(repo, p1.node())
3334 if p1 != parents[0] and p2 != parents[1]:
3334 if p1 != parents[0] and p2 != parents[1]:
3335 repo.dirstate.setparents(p1.node(), p2.node())
3335 repo.dirstate.setparents(p1.node(), p2.node())
3336
3336
3337 if opts.get('exact') or opts.get('import_branch'):
3337 if opts.get('exact') or opts.get('import_branch'):
3338 repo.dirstate.setbranch(branch or 'default')
3338 repo.dirstate.setbranch(branch or 'default')
3339
3339
3340 files = set()
3340 files = set()
3341 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3341 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3342 eolmode=None, similarity=sim / 100.0)
3342 eolmode=None, similarity=sim / 100.0)
3343 files = list(files)
3343 files = list(files)
3344 if opts.get('no_commit'):
3344 if opts.get('no_commit'):
3345 if message:
3345 if message:
3346 msgs.append(message)
3346 msgs.append(message)
3347 else:
3347 else:
3348 if opts.get('exact'):
3348 if opts.get('exact'):
3349 m = None
3349 m = None
3350 else:
3350 else:
3351 m = scmutil.matchfiles(repo, files or [])
3351 m = scmutil.matchfiles(repo, files or [])
3352 n = repo.commit(message, opts.get('user') or user,
3352 n = repo.commit(message, opts.get('user') or user,
3353 opts.get('date') or date, match=m,
3353 opts.get('date') or date, match=m,
3354 editor=cmdutil.commiteditor)
3354 editor=cmdutil.commiteditor)
3355 checkexact(repo, n, nodeid)
3355 checkexact(repo, n, nodeid)
3356 else:
3356 else:
3357 if opts.get('exact') or opts.get('import_branch'):
3357 if opts.get('exact') or opts.get('import_branch'):
3358 branch = branch or 'default'
3358 branch = branch or 'default'
3359 else:
3359 else:
3360 branch = p1.branch()
3360 branch = p1.branch()
3361 store = patch.filestore()
3361 store = patch.filestore()
3362 try:
3362 try:
3363 files = set()
3363 files = set()
3364 try:
3364 try:
3365 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3365 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3366 files, eolmode=None)
3366 files, eolmode=None)
3367 except patch.PatchError, e:
3367 except patch.PatchError, e:
3368 raise util.Abort(str(e))
3368 raise util.Abort(str(e))
3369 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3369 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3370 message,
3370 message,
3371 opts.get('user') or user,
3371 opts.get('user') or user,
3372 opts.get('date') or date,
3372 opts.get('date') or date,
3373 branch, files, store,
3373 branch, files, store,
3374 editor=cmdutil.commiteditor)
3374 editor=cmdutil.commiteditor)
3375 repo.savecommitmessage(memctx.description())
3375 repo.savecommitmessage(memctx.description())
3376 n = memctx.commit()
3376 n = memctx.commit()
3377 checkexact(repo, n, nodeid)
3377 checkexact(repo, n, nodeid)
3378 finally:
3378 finally:
3379 store.close()
3379 store.close()
3380 if n:
3380 if n:
3381 msg = _('created %s') % short(n)
3381 msg = _('created %s') % short(n)
3382 return (msg, n)
3382 return (msg, n)
3383 finally:
3383 finally:
3384 os.unlink(tmpname)
3384 os.unlink(tmpname)
3385
3385
3386 try:
3386 try:
3387 wlock = repo.wlock()
3387 wlock = repo.wlock()
3388 lock = repo.lock()
3388 lock = repo.lock()
3389 tr = repo.transaction('import')
3389 tr = repo.transaction('import')
3390 parents = repo.parents()
3390 parents = repo.parents()
3391 for patchurl in patches:
3391 for patchurl in patches:
3392 if patchurl == '-':
3392 if patchurl == '-':
3393 ui.status(_('applying patch from stdin\n'))
3393 ui.status(_('applying patch from stdin\n'))
3394 patchfile = ui.fin
3394 patchfile = ui.fin
3395 patchurl = 'stdin' # for error message
3395 patchurl = 'stdin' # for error message
3396 else:
3396 else:
3397 patchurl = os.path.join(base, patchurl)
3397 patchurl = os.path.join(base, patchurl)
3398 ui.status(_('applying %s\n') % patchurl)
3398 ui.status(_('applying %s\n') % patchurl)
3399 patchfile = url.open(ui, patchurl)
3399 patchfile = url.open(ui, patchurl)
3400
3400
3401 haspatch = False
3401 haspatch = False
3402 for hunk in patch.split(patchfile):
3402 for hunk in patch.split(patchfile):
3403 (msg, node) = tryone(ui, hunk, parents)
3403 (msg, node) = tryone(ui, hunk, parents)
3404 if msg:
3404 if msg:
3405 haspatch = True
3405 haspatch = True
3406 ui.note(msg + '\n')
3406 ui.note(msg + '\n')
3407 if update or opts.get('exact'):
3407 if update or opts.get('exact'):
3408 parents = repo.parents()
3408 parents = repo.parents()
3409 else:
3409 else:
3410 parents = [repo[node]]
3410 parents = [repo[node]]
3411
3411
3412 if not haspatch:
3412 if not haspatch:
3413 raise util.Abort(_('%s: no diffs found') % patchurl)
3413 raise util.Abort(_('%s: no diffs found') % patchurl)
3414
3414
3415 tr.close()
3415 tr.close()
3416 if msgs:
3416 if msgs:
3417 repo.savecommitmessage('\n* * *\n'.join(msgs))
3417 repo.savecommitmessage('\n* * *\n'.join(msgs))
3418 except:
3418 except:
3419 # wlock.release() indirectly calls dirstate.write(): since
3419 # wlock.release() indirectly calls dirstate.write(): since
3420 # we're crashing, we do not want to change the working dir
3420 # we're crashing, we do not want to change the working dir
3421 # parent after all, so make sure it writes nothing
3421 # parent after all, so make sure it writes nothing
3422 repo.dirstate.invalidate()
3422 repo.dirstate.invalidate()
3423 raise
3423 raise
3424 finally:
3424 finally:
3425 if tr:
3425 if tr:
3426 tr.release()
3426 tr.release()
3427 release(lock, wlock)
3427 release(lock, wlock)
3428
3428
3429 @command('incoming|in',
3429 @command('incoming|in',
3430 [('f', 'force', None,
3430 [('f', 'force', None,
3431 _('run even if remote repository is unrelated')),
3431 _('run even if remote repository is unrelated')),
3432 ('n', 'newest-first', None, _('show newest record first')),
3432 ('n', 'newest-first', None, _('show newest record first')),
3433 ('', 'bundle', '',
3433 ('', 'bundle', '',
3434 _('file to store the bundles into'), _('FILE')),
3434 _('file to store the bundles into'), _('FILE')),
3435 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3435 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3436 ('B', 'bookmarks', False, _("compare bookmarks")),
3436 ('B', 'bookmarks', False, _("compare bookmarks")),
3437 ('b', 'branch', [],
3437 ('b', 'branch', [],
3438 _('a specific branch you would like to pull'), _('BRANCH')),
3438 _('a specific branch you would like to pull'), _('BRANCH')),
3439 ] + logopts + remoteopts + subrepoopts,
3439 ] + logopts + remoteopts + subrepoopts,
3440 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3440 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3441 def incoming(ui, repo, source="default", **opts):
3441 def incoming(ui, repo, source="default", **opts):
3442 """show new changesets found in source
3442 """show new changesets found in source
3443
3443
3444 Show new changesets found in the specified path/URL or the default
3444 Show new changesets found in the specified path/URL or the default
3445 pull location. These are the changesets that would have been pulled
3445 pull location. These are the changesets that would have been pulled
3446 if a pull at the time you issued this command.
3446 if a pull at the time you issued this command.
3447
3447
3448 For remote repository, using --bundle avoids downloading the
3448 For remote repository, using --bundle avoids downloading the
3449 changesets twice if the incoming is followed by a pull.
3449 changesets twice if the incoming is followed by a pull.
3450
3450
3451 See pull for valid source format details.
3451 See pull for valid source format details.
3452
3452
3453 Returns 0 if there are incoming changes, 1 otherwise.
3453 Returns 0 if there are incoming changes, 1 otherwise.
3454 """
3454 """
3455 if opts.get('bundle') and opts.get('subrepos'):
3455 if opts.get('bundle') and opts.get('subrepos'):
3456 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3456 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3457
3457
3458 if opts.get('bookmarks'):
3458 if opts.get('bookmarks'):
3459 source, branches = hg.parseurl(ui.expandpath(source),
3459 source, branches = hg.parseurl(ui.expandpath(source),
3460 opts.get('branch'))
3460 opts.get('branch'))
3461 other = hg.peer(repo, opts, source)
3461 other = hg.peer(repo, opts, source)
3462 if 'bookmarks' not in other.listkeys('namespaces'):
3462 if 'bookmarks' not in other.listkeys('namespaces'):
3463 ui.warn(_("remote doesn't support bookmarks\n"))
3463 ui.warn(_("remote doesn't support bookmarks\n"))
3464 return 0
3464 return 0
3465 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3465 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3466 return bookmarks.diff(ui, repo, other)
3466 return bookmarks.diff(ui, repo, other)
3467
3467
3468 repo._subtoppath = ui.expandpath(source)
3468 repo._subtoppath = ui.expandpath(source)
3469 try:
3469 try:
3470 return hg.incoming(ui, repo, source, opts)
3470 return hg.incoming(ui, repo, source, opts)
3471 finally:
3471 finally:
3472 del repo._subtoppath
3472 del repo._subtoppath
3473
3473
3474
3474
3475 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3475 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3476 def init(ui, dest=".", **opts):
3476 def init(ui, dest=".", **opts):
3477 """create a new repository in the given directory
3477 """create a new repository in the given directory
3478
3478
3479 Initialize a new repository in the given directory. If the given
3479 Initialize a new repository in the given directory. If the given
3480 directory does not exist, it will be created.
3480 directory does not exist, it will be created.
3481
3481
3482 If no directory is given, the current directory is used.
3482 If no directory is given, the current directory is used.
3483
3483
3484 It is possible to specify an ``ssh://`` URL as the destination.
3484 It is possible to specify an ``ssh://`` URL as the destination.
3485 See :hg:`help urls` for more information.
3485 See :hg:`help urls` for more information.
3486
3486
3487 Returns 0 on success.
3487 Returns 0 on success.
3488 """
3488 """
3489 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3489 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3490
3490
3491 @command('locate',
3491 @command('locate',
3492 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3492 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3493 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3493 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3494 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3494 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3495 ] + walkopts,
3495 ] + walkopts,
3496 _('[OPTION]... [PATTERN]...'))
3496 _('[OPTION]... [PATTERN]...'))
3497 def locate(ui, repo, *pats, **opts):
3497 def locate(ui, repo, *pats, **opts):
3498 """locate files matching specific patterns
3498 """locate files matching specific patterns
3499
3499
3500 Print files under Mercurial control in the working directory whose
3500 Print files under Mercurial control in the working directory whose
3501 names match the given patterns.
3501 names match the given patterns.
3502
3502
3503 By default, this command searches all directories in the working
3503 By default, this command searches all directories in the working
3504 directory. To search just the current directory and its
3504 directory. To search just the current directory and its
3505 subdirectories, use "--include .".
3505 subdirectories, use "--include .".
3506
3506
3507 If no patterns are given to match, this command prints the names
3507 If no patterns are given to match, this command prints the names
3508 of all files under Mercurial control in the working directory.
3508 of all files under Mercurial control in the working directory.
3509
3509
3510 If you want to feed the output of this command into the "xargs"
3510 If you want to feed the output of this command into the "xargs"
3511 command, use the -0 option to both this command and "xargs". This
3511 command, use the -0 option to both this command and "xargs". This
3512 will avoid the problem of "xargs" treating single filenames that
3512 will avoid the problem of "xargs" treating single filenames that
3513 contain whitespace as multiple filenames.
3513 contain whitespace as multiple filenames.
3514
3514
3515 Returns 0 if a match is found, 1 otherwise.
3515 Returns 0 if a match is found, 1 otherwise.
3516 """
3516 """
3517 end = opts.get('print0') and '\0' or '\n'
3517 end = opts.get('print0') and '\0' or '\n'
3518 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3518 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3519
3519
3520 ret = 1
3520 ret = 1
3521 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3521 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3522 m.bad = lambda x, y: False
3522 m.bad = lambda x, y: False
3523 for abs in repo[rev].walk(m):
3523 for abs in repo[rev].walk(m):
3524 if not rev and abs not in repo.dirstate:
3524 if not rev and abs not in repo.dirstate:
3525 continue
3525 continue
3526 if opts.get('fullpath'):
3526 if opts.get('fullpath'):
3527 ui.write(repo.wjoin(abs), end)
3527 ui.write(repo.wjoin(abs), end)
3528 else:
3528 else:
3529 ui.write(((pats and m.rel(abs)) or abs), end)
3529 ui.write(((pats and m.rel(abs)) or abs), end)
3530 ret = 0
3530 ret = 0
3531
3531
3532 return ret
3532 return ret
3533
3533
3534 @command('^log|history',
3534 @command('^log|history',
3535 [('f', 'follow', None,
3535 [('f', 'follow', None,
3536 _('follow changeset history, or file history across copies and renames')),
3536 _('follow changeset history, or file history across copies and renames')),
3537 ('', 'follow-first', None,
3537 ('', 'follow-first', None,
3538 _('only follow the first parent of merge changesets')),
3538 _('only follow the first parent of merge changesets')),
3539 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3539 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3540 ('C', 'copies', None, _('show copied files')),
3540 ('C', 'copies', None, _('show copied files')),
3541 ('k', 'keyword', [],
3541 ('k', 'keyword', [],
3542 _('do case-insensitive search for a given text'), _('TEXT')),
3542 _('do case-insensitive search for a given text'), _('TEXT')),
3543 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3543 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3544 ('', 'removed', None, _('include revisions where files were removed')),
3544 ('', 'removed', None, _('include revisions where files were removed')),
3545 ('m', 'only-merges', None, _('show only merges')),
3545 ('m', 'only-merges', None, _('show only merges')),
3546 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3546 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3547 ('', 'only-branch', [],
3547 ('', 'only-branch', [],
3548 _('show only changesets within the given named branch (DEPRECATED)'),
3548 _('show only changesets within the given named branch (DEPRECATED)'),
3549 _('BRANCH')),
3549 _('BRANCH')),
3550 ('b', 'branch', [],
3550 ('b', 'branch', [],
3551 _('show changesets within the given named branch'), _('BRANCH')),
3551 _('show changesets within the given named branch'), _('BRANCH')),
3552 ('P', 'prune', [],
3552 ('P', 'prune', [],
3553 _('do not display revision or any of its ancestors'), _('REV')),
3553 _('do not display revision or any of its ancestors'), _('REV')),
3554 ('', 'hidden', False, _('show hidden changesets')),
3554 ('', 'hidden', False, _('show hidden changesets')),
3555 ] + logopts + walkopts,
3555 ] + logopts + walkopts,
3556 _('[OPTION]... [FILE]'))
3556 _('[OPTION]... [FILE]'))
3557 def log(ui, repo, *pats, **opts):
3557 def log(ui, repo, *pats, **opts):
3558 """show revision history of entire repository or files
3558 """show revision history of entire repository or files
3559
3559
3560 Print the revision history of the specified files or the entire
3560 Print the revision history of the specified files or the entire
3561 project.
3561 project.
3562
3562
3563 If no revision range is specified, the default is ``tip:0`` unless
3563 If no revision range is specified, the default is ``tip:0`` unless
3564 --follow is set, in which case the working directory parent is
3564 --follow is set, in which case the working directory parent is
3565 used as the starting revision.
3565 used as the starting revision.
3566
3566
3567 File history is shown without following rename or copy history of
3567 File history is shown without following rename or copy history of
3568 files. Use -f/--follow with a filename to follow history across
3568 files. Use -f/--follow with a filename to follow history across
3569 renames and copies. --follow without a filename will only show
3569 renames and copies. --follow without a filename will only show
3570 ancestors or descendants of the starting revision.
3570 ancestors or descendants of the starting revision.
3571
3571
3572 By default this command prints revision number and changeset id,
3572 By default this command prints revision number and changeset id,
3573 tags, non-trivial parents, user, date and time, and a summary for
3573 tags, non-trivial parents, user, date and time, and a summary for
3574 each commit. When the -v/--verbose switch is used, the list of
3574 each commit. When the -v/--verbose switch is used, the list of
3575 changed files and full commit message are shown.
3575 changed files and full commit message are shown.
3576
3576
3577 .. note::
3577 .. note::
3578 log -p/--patch may generate unexpected diff output for merge
3578 log -p/--patch may generate unexpected diff output for merge
3579 changesets, as it will only compare the merge changeset against
3579 changesets, as it will only compare the merge changeset against
3580 its first parent. Also, only files different from BOTH parents
3580 its first parent. Also, only files different from BOTH parents
3581 will appear in files:.
3581 will appear in files:.
3582
3582
3583 .. note::
3583 .. note::
3584 for performance reasons, log FILE may omit duplicate changes
3584 for performance reasons, log FILE may omit duplicate changes
3585 made on branches and will not show deletions. To see all
3585 made on branches and will not show deletions. To see all
3586 changes including duplicates and deletions, use the --removed
3586 changes including duplicates and deletions, use the --removed
3587 switch.
3587 switch.
3588
3588
3589 .. container:: verbose
3589 .. container:: verbose
3590
3590
3591 Some examples:
3591 Some examples:
3592
3592
3593 - changesets with full descriptions and file lists::
3593 - changesets with full descriptions and file lists::
3594
3594
3595 hg log -v
3595 hg log -v
3596
3596
3597 - changesets ancestral to the working directory::
3597 - changesets ancestral to the working directory::
3598
3598
3599 hg log -f
3599 hg log -f
3600
3600
3601 - last 10 commits on the current branch::
3601 - last 10 commits on the current branch::
3602
3602
3603 hg log -l 10 -b .
3603 hg log -l 10 -b .
3604
3604
3605 - changesets showing all modifications of a file, including removals::
3605 - changesets showing all modifications of a file, including removals::
3606
3606
3607 hg log --removed file.c
3607 hg log --removed file.c
3608
3608
3609 - all changesets that touch a directory, with diffs, excluding merges::
3609 - all changesets that touch a directory, with diffs, excluding merges::
3610
3610
3611 hg log -Mp lib/
3611 hg log -Mp lib/
3612
3612
3613 - all revision numbers that match a keyword::
3613 - all revision numbers that match a keyword::
3614
3614
3615 hg log -k bug --template "{rev}\\n"
3615 hg log -k bug --template "{rev}\\n"
3616
3616
3617 - check if a given changeset is included is a tagged release::
3617 - check if a given changeset is included is a tagged release::
3618
3618
3619 hg log -r "a21ccf and ancestor(1.9)"
3619 hg log -r "a21ccf and ancestor(1.9)"
3620
3620
3621 - find all changesets by some user in a date range::
3621 - find all changesets by some user in a date range::
3622
3622
3623 hg log -k alice -d "may 2008 to jul 2008"
3623 hg log -k alice -d "may 2008 to jul 2008"
3624
3624
3625 - summary of all changesets after the last tag::
3625 - summary of all changesets after the last tag::
3626
3626
3627 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3627 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3628
3628
3629 See :hg:`help dates` for a list of formats valid for -d/--date.
3629 See :hg:`help dates` for a list of formats valid for -d/--date.
3630
3630
3631 See :hg:`help revisions` and :hg:`help revsets` for more about
3631 See :hg:`help revisions` and :hg:`help revsets` for more about
3632 specifying revisions.
3632 specifying revisions.
3633
3633
3634 Returns 0 on success.
3634 Returns 0 on success.
3635 """
3635 """
3636
3636
3637 matchfn = scmutil.match(repo[None], pats, opts)
3637 matchfn = scmutil.match(repo[None], pats, opts)
3638 limit = cmdutil.loglimit(opts)
3638 limit = cmdutil.loglimit(opts)
3639 count = 0
3639 count = 0
3640
3640
3641 endrev = None
3641 endrev = None
3642 if opts.get('copies') and opts.get('rev'):
3642 if opts.get('copies') and opts.get('rev'):
3643 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3643 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3644
3644
3645 df = False
3645 df = False
3646 if opts["date"]:
3646 if opts["date"]:
3647 df = util.matchdate(opts["date"])
3647 df = util.matchdate(opts["date"])
3648
3648
3649 branches = opts.get('branch', []) + opts.get('only_branch', [])
3649 branches = opts.get('branch', []) + opts.get('only_branch', [])
3650 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3650 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3651
3651
3652 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3652 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3653 def prep(ctx, fns):
3653 def prep(ctx, fns):
3654 rev = ctx.rev()
3654 rev = ctx.rev()
3655 parents = [p for p in repo.changelog.parentrevs(rev)
3655 parents = [p for p in repo.changelog.parentrevs(rev)
3656 if p != nullrev]
3656 if p != nullrev]
3657 if opts.get('no_merges') and len(parents) == 2:
3657 if opts.get('no_merges') and len(parents) == 2:
3658 return
3658 return
3659 if opts.get('only_merges') and len(parents) != 2:
3659 if opts.get('only_merges') and len(parents) != 2:
3660 return
3660 return
3661 if opts.get('branch') and ctx.branch() not in opts['branch']:
3661 if opts.get('branch') and ctx.branch() not in opts['branch']:
3662 return
3662 return
3663 if not opts.get('hidden') and ctx.hidden():
3663 if not opts.get('hidden') and ctx.hidden():
3664 return
3664 return
3665 if df and not df(ctx.date()[0]):
3665 if df and not df(ctx.date()[0]):
3666 return
3666 return
3667 if opts['user'] and not [k for k in opts['user']
3667 if opts['user'] and not [k for k in opts['user']
3668 if k.lower() in ctx.user().lower()]:
3668 if k.lower() in ctx.user().lower()]:
3669 return
3669 return
3670 if opts.get('keyword'):
3670 if opts.get('keyword'):
3671 for k in [kw.lower() for kw in opts['keyword']]:
3671 for k in [kw.lower() for kw in opts['keyword']]:
3672 if (k in ctx.user().lower() or
3672 if (k in ctx.user().lower() or
3673 k in ctx.description().lower() or
3673 k in ctx.description().lower() or
3674 k in " ".join(ctx.files()).lower()):
3674 k in " ".join(ctx.files()).lower()):
3675 break
3675 break
3676 else:
3676 else:
3677 return
3677 return
3678
3678
3679 copies = None
3679 copies = None
3680 if opts.get('copies') and rev:
3680 if opts.get('copies') and rev:
3681 copies = []
3681 copies = []
3682 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3682 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3683 for fn in ctx.files():
3683 for fn in ctx.files():
3684 rename = getrenamed(fn, rev)
3684 rename = getrenamed(fn, rev)
3685 if rename:
3685 if rename:
3686 copies.append((fn, rename[0]))
3686 copies.append((fn, rename[0]))
3687
3687
3688 revmatchfn = None
3688 revmatchfn = None
3689 if opts.get('patch') or opts.get('stat'):
3689 if opts.get('patch') or opts.get('stat'):
3690 if opts.get('follow') or opts.get('follow_first'):
3690 if opts.get('follow') or opts.get('follow_first'):
3691 # note: this might be wrong when following through merges
3691 # note: this might be wrong when following through merges
3692 revmatchfn = scmutil.match(repo[None], fns, default='path')
3692 revmatchfn = scmutil.match(repo[None], fns, default='path')
3693 else:
3693 else:
3694 revmatchfn = matchfn
3694 revmatchfn = matchfn
3695
3695
3696 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3696 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3697
3697
3698 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3698 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3699 if count == limit:
3699 if count == limit:
3700 break
3700 break
3701 if displayer.flush(ctx.rev()):
3701 if displayer.flush(ctx.rev()):
3702 count += 1
3702 count += 1
3703 displayer.close()
3703 displayer.close()
3704
3704
3705 @command('manifest',
3705 @command('manifest',
3706 [('r', 'rev', '', _('revision to display'), _('REV')),
3706 [('r', 'rev', '', _('revision to display'), _('REV')),
3707 ('', 'all', False, _("list files from all revisions"))],
3707 ('', 'all', False, _("list files from all revisions"))],
3708 _('[-r REV]'))
3708 _('[-r REV]'))
3709 def manifest(ui, repo, node=None, rev=None, **opts):
3709 def manifest(ui, repo, node=None, rev=None, **opts):
3710 """output the current or given revision of the project manifest
3710 """output the current or given revision of the project manifest
3711
3711
3712 Print a list of version controlled files for the given revision.
3712 Print a list of version controlled files for the given revision.
3713 If no revision is given, the first parent of the working directory
3713 If no revision is given, the first parent of the working directory
3714 is used, or the null revision if no revision is checked out.
3714 is used, or the null revision if no revision is checked out.
3715
3715
3716 With -v, print file permissions, symlink and executable bits.
3716 With -v, print file permissions, symlink and executable bits.
3717 With --debug, print file revision hashes.
3717 With --debug, print file revision hashes.
3718
3718
3719 If option --all is specified, the list of all files from all revisions
3719 If option --all is specified, the list of all files from all revisions
3720 is printed. This includes deleted and renamed files.
3720 is printed. This includes deleted and renamed files.
3721
3721
3722 Returns 0 on success.
3722 Returns 0 on success.
3723 """
3723 """
3724 if opts.get('all'):
3724 if opts.get('all'):
3725 if rev or node:
3725 if rev or node:
3726 raise util.Abort(_("can't specify a revision with --all"))
3726 raise util.Abort(_("can't specify a revision with --all"))
3727
3727
3728 res = []
3728 res = []
3729 prefix = "data/"
3729 prefix = "data/"
3730 suffix = ".i"
3730 suffix = ".i"
3731 plen = len(prefix)
3731 plen = len(prefix)
3732 slen = len(suffix)
3732 slen = len(suffix)
3733 lock = repo.lock()
3733 lock = repo.lock()
3734 try:
3734 try:
3735 for fn, b, size in repo.store.datafiles():
3735 for fn, b, size in repo.store.datafiles():
3736 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3736 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3737 res.append(fn[plen:-slen])
3737 res.append(fn[plen:-slen])
3738 finally:
3738 finally:
3739 lock.release()
3739 lock.release()
3740 for f in sorted(res):
3740 for f in sorted(res):
3741 ui.write("%s\n" % f)
3741 ui.write("%s\n" % f)
3742 return
3742 return
3743
3743
3744 if rev and node:
3744 if rev and node:
3745 raise util.Abort(_("please specify just one revision"))
3745 raise util.Abort(_("please specify just one revision"))
3746
3746
3747 if not node:
3747 if not node:
3748 node = rev
3748 node = rev
3749
3749
3750 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3750 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3751 ctx = scmutil.revsingle(repo, node)
3751 ctx = scmutil.revsingle(repo, node)
3752 for f in ctx:
3752 for f in ctx:
3753 if ui.debugflag:
3753 if ui.debugflag:
3754 ui.write("%40s " % hex(ctx.manifest()[f]))
3754 ui.write("%40s " % hex(ctx.manifest()[f]))
3755 if ui.verbose:
3755 if ui.verbose:
3756 ui.write(decor[ctx.flags(f)])
3756 ui.write(decor[ctx.flags(f)])
3757 ui.write("%s\n" % f)
3757 ui.write("%s\n" % f)
3758
3758
3759 @command('^merge',
3759 @command('^merge',
3760 [('f', 'force', None, _('force a merge with outstanding changes')),
3760 [('f', 'force', None, _('force a merge with outstanding changes')),
3761 ('r', 'rev', '', _('revision to merge'), _('REV')),
3761 ('r', 'rev', '', _('revision to merge'), _('REV')),
3762 ('P', 'preview', None,
3762 ('P', 'preview', None,
3763 _('review revisions to merge (no merge is performed)'))
3763 _('review revisions to merge (no merge is performed)'))
3764 ] + mergetoolopts,
3764 ] + mergetoolopts,
3765 _('[-P] [-f] [[-r] REV]'))
3765 _('[-P] [-f] [[-r] REV]'))
3766 def merge(ui, repo, node=None, **opts):
3766 def merge(ui, repo, node=None, **opts):
3767 """merge working directory with another revision
3767 """merge working directory with another revision
3768
3768
3769 The current working directory is updated with all changes made in
3769 The current working directory is updated with all changes made in
3770 the requested revision since the last common predecessor revision.
3770 the requested revision since the last common predecessor revision.
3771
3771
3772 Files that changed between either parent are marked as changed for
3772 Files that changed between either parent are marked as changed for
3773 the next commit and a commit must be performed before any further
3773 the next commit and a commit must be performed before any further
3774 updates to the repository are allowed. The next commit will have
3774 updates to the repository are allowed. The next commit will have
3775 two parents.
3775 two parents.
3776
3776
3777 ``--tool`` can be used to specify the merge tool used for file
3777 ``--tool`` can be used to specify the merge tool used for file
3778 merges. It overrides the HGMERGE environment variable and your
3778 merges. It overrides the HGMERGE environment variable and your
3779 configuration files. See :hg:`help merge-tools` for options.
3779 configuration files. See :hg:`help merge-tools` for options.
3780
3780
3781 If no revision is specified, the working directory's parent is a
3781 If no revision is specified, the working directory's parent is a
3782 head revision, and the current branch contains exactly one other
3782 head revision, and the current branch contains exactly one other
3783 head, the other head is merged with by default. Otherwise, an
3783 head, the other head is merged with by default. Otherwise, an
3784 explicit revision with which to merge with must be provided.
3784 explicit revision with which to merge with must be provided.
3785
3785
3786 :hg:`resolve` must be used to resolve unresolved files.
3786 :hg:`resolve` must be used to resolve unresolved files.
3787
3787
3788 To undo an uncommitted merge, use :hg:`update --clean .` which
3788 To undo an uncommitted merge, use :hg:`update --clean .` which
3789 will check out a clean copy of the original merge parent, losing
3789 will check out a clean copy of the original merge parent, losing
3790 all changes.
3790 all changes.
3791
3791
3792 Returns 0 on success, 1 if there are unresolved files.
3792 Returns 0 on success, 1 if there are unresolved files.
3793 """
3793 """
3794
3794
3795 if opts.get('rev') and node:
3795 if opts.get('rev') and node:
3796 raise util.Abort(_("please specify just one revision"))
3796 raise util.Abort(_("please specify just one revision"))
3797 if not node:
3797 if not node:
3798 node = opts.get('rev')
3798 node = opts.get('rev')
3799
3799
3800 if not node:
3800 if not node:
3801 branch = repo[None].branch()
3801 branch = repo[None].branch()
3802 bheads = repo.branchheads(branch)
3802 bheads = repo.branchheads(branch)
3803 if len(bheads) > 2:
3803 if len(bheads) > 2:
3804 raise util.Abort(_("branch '%s' has %d heads - "
3804 raise util.Abort(_("branch '%s' has %d heads - "
3805 "please merge with an explicit rev")
3805 "please merge with an explicit rev")
3806 % (branch, len(bheads)),
3806 % (branch, len(bheads)),
3807 hint=_("run 'hg heads .' to see heads"))
3807 hint=_("run 'hg heads .' to see heads"))
3808
3808
3809 parent = repo.dirstate.p1()
3809 parent = repo.dirstate.p1()
3810 if len(bheads) == 1:
3810 if len(bheads) == 1:
3811 if len(repo.heads()) > 1:
3811 if len(repo.heads()) > 1:
3812 raise util.Abort(_("branch '%s' has one head - "
3812 raise util.Abort(_("branch '%s' has one head - "
3813 "please merge with an explicit rev")
3813 "please merge with an explicit rev")
3814 % branch,
3814 % branch,
3815 hint=_("run 'hg heads' to see all heads"))
3815 hint=_("run 'hg heads' to see all heads"))
3816 msg = _('there is nothing to merge')
3816 msg = _('there is nothing to merge')
3817 if parent != repo.lookup(repo[None].branch()):
3817 if parent != repo.lookup(repo[None].branch()):
3818 msg = _('%s - use "hg update" instead') % msg
3818 msg = _('%s - use "hg update" instead') % msg
3819 raise util.Abort(msg)
3819 raise util.Abort(msg)
3820
3820
3821 if parent not in bheads:
3821 if parent not in bheads:
3822 raise util.Abort(_('working directory not at a head revision'),
3822 raise util.Abort(_('working directory not at a head revision'),
3823 hint=_("use 'hg update' or merge with an "
3823 hint=_("use 'hg update' or merge with an "
3824 "explicit revision"))
3824 "explicit revision"))
3825 node = parent == bheads[0] and bheads[-1] or bheads[0]
3825 node = parent == bheads[0] and bheads[-1] or bheads[0]
3826 else:
3826 else:
3827 node = scmutil.revsingle(repo, node).node()
3827 node = scmutil.revsingle(repo, node).node()
3828
3828
3829 if opts.get('preview'):
3829 if opts.get('preview'):
3830 # find nodes that are ancestors of p2 but not of p1
3830 # find nodes that are ancestors of p2 but not of p1
3831 p1 = repo.lookup('.')
3831 p1 = repo.lookup('.')
3832 p2 = repo.lookup(node)
3832 p2 = repo.lookup(node)
3833 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3833 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3834
3834
3835 displayer = cmdutil.show_changeset(ui, repo, opts)
3835 displayer = cmdutil.show_changeset(ui, repo, opts)
3836 for node in nodes:
3836 for node in nodes:
3837 displayer.show(repo[node])
3837 displayer.show(repo[node])
3838 displayer.close()
3838 displayer.close()
3839 return 0
3839 return 0
3840
3840
3841 try:
3841 try:
3842 # ui.forcemerge is an internal variable, do not document
3842 # ui.forcemerge is an internal variable, do not document
3843 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3843 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3844 return hg.merge(repo, node, force=opts.get('force'))
3844 return hg.merge(repo, node, force=opts.get('force'))
3845 finally:
3845 finally:
3846 ui.setconfig('ui', 'forcemerge', '')
3846 ui.setconfig('ui', 'forcemerge', '')
3847
3847
3848 @command('outgoing|out',
3848 @command('outgoing|out',
3849 [('f', 'force', None, _('run even when the destination is unrelated')),
3849 [('f', 'force', None, _('run even when the destination is unrelated')),
3850 ('r', 'rev', [],
3850 ('r', 'rev', [],
3851 _('a changeset intended to be included in the destination'), _('REV')),
3851 _('a changeset intended to be included in the destination'), _('REV')),
3852 ('n', 'newest-first', None, _('show newest record first')),
3852 ('n', 'newest-first', None, _('show newest record first')),
3853 ('B', 'bookmarks', False, _('compare bookmarks')),
3853 ('B', 'bookmarks', False, _('compare bookmarks')),
3854 ('b', 'branch', [], _('a specific branch you would like to push'),
3854 ('b', 'branch', [], _('a specific branch you would like to push'),
3855 _('BRANCH')),
3855 _('BRANCH')),
3856 ] + logopts + remoteopts + subrepoopts,
3856 ] + logopts + remoteopts + subrepoopts,
3857 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3857 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3858 def outgoing(ui, repo, dest=None, **opts):
3858 def outgoing(ui, repo, dest=None, **opts):
3859 """show changesets not found in the destination
3859 """show changesets not found in the destination
3860
3860
3861 Show changesets not found in the specified destination repository
3861 Show changesets not found in the specified destination repository
3862 or the default push location. These are the changesets that would
3862 or the default push location. These are the changesets that would
3863 be pushed if a push was requested.
3863 be pushed if a push was requested.
3864
3864
3865 See pull for details of valid destination formats.
3865 See pull for details of valid destination formats.
3866
3866
3867 Returns 0 if there are outgoing changes, 1 otherwise.
3867 Returns 0 if there are outgoing changes, 1 otherwise.
3868 """
3868 """
3869
3869
3870 if opts.get('bookmarks'):
3870 if opts.get('bookmarks'):
3871 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3871 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3872 dest, branches = hg.parseurl(dest, opts.get('branch'))
3872 dest, branches = hg.parseurl(dest, opts.get('branch'))
3873 other = hg.peer(repo, opts, dest)
3873 other = hg.peer(repo, opts, dest)
3874 if 'bookmarks' not in other.listkeys('namespaces'):
3874 if 'bookmarks' not in other.listkeys('namespaces'):
3875 ui.warn(_("remote doesn't support bookmarks\n"))
3875 ui.warn(_("remote doesn't support bookmarks\n"))
3876 return 0
3876 return 0
3877 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3877 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3878 return bookmarks.diff(ui, other, repo)
3878 return bookmarks.diff(ui, other, repo)
3879
3879
3880 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3880 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3881 try:
3881 try:
3882 return hg.outgoing(ui, repo, dest, opts)
3882 return hg.outgoing(ui, repo, dest, opts)
3883 finally:
3883 finally:
3884 del repo._subtoppath
3884 del repo._subtoppath
3885
3885
3886 @command('parents',
3886 @command('parents',
3887 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3887 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3888 ] + templateopts,
3888 ] + templateopts,
3889 _('[-r REV] [FILE]'))
3889 _('[-r REV] [FILE]'))
3890 def parents(ui, repo, file_=None, **opts):
3890 def parents(ui, repo, file_=None, **opts):
3891 """show the parents of the working directory or revision
3891 """show the parents of the working directory or revision
3892
3892
3893 Print the working directory's parent revisions. If a revision is
3893 Print the working directory's parent revisions. If a revision is
3894 given via -r/--rev, the parent of that revision will be printed.
3894 given via -r/--rev, the parent of that revision will be printed.
3895 If a file argument is given, the revision in which the file was
3895 If a file argument is given, the revision in which the file was
3896 last changed (before the working directory revision or the
3896 last changed (before the working directory revision or the
3897 argument to --rev if given) is printed.
3897 argument to --rev if given) is printed.
3898
3898
3899 Returns 0 on success.
3899 Returns 0 on success.
3900 """
3900 """
3901
3901
3902 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3902 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3903
3903
3904 if file_:
3904 if file_:
3905 m = scmutil.match(ctx, (file_,), opts)
3905 m = scmutil.match(ctx, (file_,), opts)
3906 if m.anypats() or len(m.files()) != 1:
3906 if m.anypats() or len(m.files()) != 1:
3907 raise util.Abort(_('can only specify an explicit filename'))
3907 raise util.Abort(_('can only specify an explicit filename'))
3908 file_ = m.files()[0]
3908 file_ = m.files()[0]
3909 filenodes = []
3909 filenodes = []
3910 for cp in ctx.parents():
3910 for cp in ctx.parents():
3911 if not cp:
3911 if not cp:
3912 continue
3912 continue
3913 try:
3913 try:
3914 filenodes.append(cp.filenode(file_))
3914 filenodes.append(cp.filenode(file_))
3915 except error.LookupError:
3915 except error.LookupError:
3916 pass
3916 pass
3917 if not filenodes:
3917 if not filenodes:
3918 raise util.Abort(_("'%s' not found in manifest!") % file_)
3918 raise util.Abort(_("'%s' not found in manifest!") % file_)
3919 fl = repo.file(file_)
3919 fl = repo.file(file_)
3920 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3920 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3921 else:
3921 else:
3922 p = [cp.node() for cp in ctx.parents()]
3922 p = [cp.node() for cp in ctx.parents()]
3923
3923
3924 displayer = cmdutil.show_changeset(ui, repo, opts)
3924 displayer = cmdutil.show_changeset(ui, repo, opts)
3925 for n in p:
3925 for n in p:
3926 if n != nullid:
3926 if n != nullid:
3927 displayer.show(repo[n])
3927 displayer.show(repo[n])
3928 displayer.close()
3928 displayer.close()
3929
3929
3930 @command('paths', [], _('[NAME]'))
3930 @command('paths', [], _('[NAME]'))
3931 def paths(ui, repo, search=None):
3931 def paths(ui, repo, search=None):
3932 """show aliases for remote repositories
3932 """show aliases for remote repositories
3933
3933
3934 Show definition of symbolic path name NAME. If no name is given,
3934 Show definition of symbolic path name NAME. If no name is given,
3935 show definition of all available names.
3935 show definition of all available names.
3936
3936
3937 Option -q/--quiet suppresses all output when searching for NAME
3937 Option -q/--quiet suppresses all output when searching for NAME
3938 and shows only the path names when listing all definitions.
3938 and shows only the path names when listing all definitions.
3939
3939
3940 Path names are defined in the [paths] section of your
3940 Path names are defined in the [paths] section of your
3941 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3941 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3942 repository, ``.hg/hgrc`` is used, too.
3942 repository, ``.hg/hgrc`` is used, too.
3943
3943
3944 The path names ``default`` and ``default-push`` have a special
3944 The path names ``default`` and ``default-push`` have a special
3945 meaning. When performing a push or pull operation, they are used
3945 meaning. When performing a push or pull operation, they are used
3946 as fallbacks if no location is specified on the command-line.
3946 as fallbacks if no location is specified on the command-line.
3947 When ``default-push`` is set, it will be used for push and
3947 When ``default-push`` is set, it will be used for push and
3948 ``default`` will be used for pull; otherwise ``default`` is used
3948 ``default`` will be used for pull; otherwise ``default`` is used
3949 as the fallback for both. When cloning a repository, the clone
3949 as the fallback for both. When cloning a repository, the clone
3950 source is written as ``default`` in ``.hg/hgrc``. Note that
3950 source is written as ``default`` in ``.hg/hgrc``. Note that
3951 ``default`` and ``default-push`` apply to all inbound (e.g.
3951 ``default`` and ``default-push`` apply to all inbound (e.g.
3952 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3952 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3953 :hg:`bundle`) operations.
3953 :hg:`bundle`) operations.
3954
3954
3955 See :hg:`help urls` for more information.
3955 See :hg:`help urls` for more information.
3956
3956
3957 Returns 0 on success.
3957 Returns 0 on success.
3958 """
3958 """
3959 if search:
3959 if search:
3960 for name, path in ui.configitems("paths"):
3960 for name, path in ui.configitems("paths"):
3961 if name == search:
3961 if name == search:
3962 ui.status("%s\n" % util.hidepassword(path))
3962 ui.status("%s\n" % util.hidepassword(path))
3963 return
3963 return
3964 if not ui.quiet:
3964 if not ui.quiet:
3965 ui.warn(_("not found!\n"))
3965 ui.warn(_("not found!\n"))
3966 return 1
3966 return 1
3967 else:
3967 else:
3968 for name, path in ui.configitems("paths"):
3968 for name, path in ui.configitems("paths"):
3969 if ui.quiet:
3969 if ui.quiet:
3970 ui.write("%s\n" % name)
3970 ui.write("%s\n" % name)
3971 else:
3971 else:
3972 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3972 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3973
3973
3974 def postincoming(ui, repo, modheads, optupdate, checkout):
3974 def postincoming(ui, repo, modheads, optupdate, checkout):
3975 if modheads == 0:
3975 if modheads == 0:
3976 return
3976 return
3977 if optupdate:
3977 if optupdate:
3978 try:
3978 try:
3979 return hg.update(repo, checkout)
3979 return hg.update(repo, checkout)
3980 except util.Abort, inst:
3980 except util.Abort, inst:
3981 ui.warn(_("not updating: %s\n" % str(inst)))
3981 ui.warn(_("not updating: %s\n" % str(inst)))
3982 return 0
3982 return 0
3983 if modheads > 1:
3983 if modheads > 1:
3984 currentbranchheads = len(repo.branchheads())
3984 currentbranchheads = len(repo.branchheads())
3985 if currentbranchheads == modheads:
3985 if currentbranchheads == modheads:
3986 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3986 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3987 elif currentbranchheads > 1:
3987 elif currentbranchheads > 1:
3988 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3988 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3989 else:
3989 else:
3990 ui.status(_("(run 'hg heads' to see heads)\n"))
3990 ui.status(_("(run 'hg heads' to see heads)\n"))
3991 else:
3991 else:
3992 ui.status(_("(run 'hg update' to get a working copy)\n"))
3992 ui.status(_("(run 'hg update' to get a working copy)\n"))
3993
3993
3994 @command('^pull',
3994 @command('^pull',
3995 [('u', 'update', None,
3995 [('u', 'update', None,
3996 _('update to new branch head if changesets were pulled')),
3996 _('update to new branch head if changesets were pulled')),
3997 ('f', 'force', None, _('run even when remote repository is unrelated')),
3997 ('f', 'force', None, _('run even when remote repository is unrelated')),
3998 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3998 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3999 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3999 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4000 ('b', 'branch', [], _('a specific branch you would like to pull'),
4000 ('b', 'branch', [], _('a specific branch you would like to pull'),
4001 _('BRANCH')),
4001 _('BRANCH')),
4002 ] + remoteopts,
4002 ] + remoteopts,
4003 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4003 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4004 def pull(ui, repo, source="default", **opts):
4004 def pull(ui, repo, source="default", **opts):
4005 """pull changes from the specified source
4005 """pull changes from the specified source
4006
4006
4007 Pull changes from a remote repository to a local one.
4007 Pull changes from a remote repository to a local one.
4008
4008
4009 This finds all changes from the repository at the specified path
4009 This finds all changes from the repository at the specified path
4010 or URL and adds them to a local repository (the current one unless
4010 or URL and adds them to a local repository (the current one unless
4011 -R is specified). By default, this does not update the copy of the
4011 -R is specified). By default, this does not update the copy of the
4012 project in the working directory.
4012 project in the working directory.
4013
4013
4014 Use :hg:`incoming` if you want to see what would have been added
4014 Use :hg:`incoming` if you want to see what would have been added
4015 by a pull at the time you issued this command. If you then decide
4015 by a pull at the time you issued this command. If you then decide
4016 to add those changes to the repository, you should use :hg:`pull
4016 to add those changes to the repository, you should use :hg:`pull
4017 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4017 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4018
4018
4019 If SOURCE is omitted, the 'default' path will be used.
4019 If SOURCE is omitted, the 'default' path will be used.
4020 See :hg:`help urls` for more information.
4020 See :hg:`help urls` for more information.
4021
4021
4022 Returns 0 on success, 1 if an update had unresolved files.
4022 Returns 0 on success, 1 if an update had unresolved files.
4023 """
4023 """
4024 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4024 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4025 other = hg.peer(repo, opts, source)
4025 other = hg.peer(repo, opts, source)
4026 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4026 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4027 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4027 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4028
4028
4029 if opts.get('bookmark'):
4029 if opts.get('bookmark'):
4030 if not revs:
4030 if not revs:
4031 revs = []
4031 revs = []
4032 rb = other.listkeys('bookmarks')
4032 rb = other.listkeys('bookmarks')
4033 for b in opts['bookmark']:
4033 for b in opts['bookmark']:
4034 if b not in rb:
4034 if b not in rb:
4035 raise util.Abort(_('remote bookmark %s not found!') % b)
4035 raise util.Abort(_('remote bookmark %s not found!') % b)
4036 revs.append(rb[b])
4036 revs.append(rb[b])
4037
4037
4038 if revs:
4038 if revs:
4039 try:
4039 try:
4040 revs = [other.lookup(rev) for rev in revs]
4040 revs = [other.lookup(rev) for rev in revs]
4041 except error.CapabilityError:
4041 except error.CapabilityError:
4042 err = _("other repository doesn't support revision lookup, "
4042 err = _("other repository doesn't support revision lookup, "
4043 "so a rev cannot be specified.")
4043 "so a rev cannot be specified.")
4044 raise util.Abort(err)
4044 raise util.Abort(err)
4045
4045
4046 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4046 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4047 bookmarks.updatefromremote(ui, repo, other)
4047 bookmarks.updatefromremote(ui, repo, other)
4048 if checkout:
4048 if checkout:
4049 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4049 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4050 repo._subtoppath = source
4050 repo._subtoppath = source
4051 try:
4051 try:
4052 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4052 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4053
4053
4054 finally:
4054 finally:
4055 del repo._subtoppath
4055 del repo._subtoppath
4056
4056
4057 # update specified bookmarks
4057 # update specified bookmarks
4058 if opts.get('bookmark'):
4058 if opts.get('bookmark'):
4059 for b in opts['bookmark']:
4059 for b in opts['bookmark']:
4060 # explicit pull overrides local bookmark if any
4060 # explicit pull overrides local bookmark if any
4061 ui.status(_("importing bookmark %s\n") % b)
4061 ui.status(_("importing bookmark %s\n") % b)
4062 repo._bookmarks[b] = repo[rb[b]].node()
4062 repo._bookmarks[b] = repo[rb[b]].node()
4063 bookmarks.write(repo)
4063 bookmarks.write(repo)
4064
4064
4065 return ret
4065 return ret
4066
4066
4067 @command('^push',
4067 @command('^push',
4068 [('f', 'force', None, _('force push')),
4068 [('f', 'force', None, _('force push')),
4069 ('r', 'rev', [],
4069 ('r', 'rev', [],
4070 _('a changeset intended to be included in the destination'),
4070 _('a changeset intended to be included in the destination'),
4071 _('REV')),
4071 _('REV')),
4072 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4072 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4073 ('b', 'branch', [],
4073 ('b', 'branch', [],
4074 _('a specific branch you would like to push'), _('BRANCH')),
4074 _('a specific branch you would like to push'), _('BRANCH')),
4075 ('', 'new-branch', False, _('allow pushing a new branch')),
4075 ('', 'new-branch', False, _('allow pushing a new branch')),
4076 ] + remoteopts,
4076 ] + remoteopts,
4077 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4077 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4078 def push(ui, repo, dest=None, **opts):
4078 def push(ui, repo, dest=None, **opts):
4079 """push changes to the specified destination
4079 """push changes to the specified destination
4080
4080
4081 Push changesets from the local repository to the specified
4081 Push changesets from the local repository to the specified
4082 destination.
4082 destination.
4083
4083
4084 This operation is symmetrical to pull: it is identical to a pull
4084 This operation is symmetrical to pull: it is identical to a pull
4085 in the destination repository from the current one.
4085 in the destination repository from the current one.
4086
4086
4087 By default, push will not allow creation of new heads at the
4087 By default, push will not allow creation of new heads at the
4088 destination, since multiple heads would make it unclear which head
4088 destination, since multiple heads would make it unclear which head
4089 to use. In this situation, it is recommended to pull and merge
4089 to use. In this situation, it is recommended to pull and merge
4090 before pushing.
4090 before pushing.
4091
4091
4092 Use --new-branch if you want to allow push to create a new named
4092 Use --new-branch if you want to allow push to create a new named
4093 branch that is not present at the destination. This allows you to
4093 branch that is not present at the destination. This allows you to
4094 only create a new branch without forcing other changes.
4094 only create a new branch without forcing other changes.
4095
4095
4096 Use -f/--force to override the default behavior and push all
4096 Use -f/--force to override the default behavior and push all
4097 changesets on all branches.
4097 changesets on all branches.
4098
4098
4099 If -r/--rev is used, the specified revision and all its ancestors
4099 If -r/--rev is used, the specified revision and all its ancestors
4100 will be pushed to the remote repository.
4100 will be pushed to the remote repository.
4101
4101
4102 Please see :hg:`help urls` for important details about ``ssh://``
4102 Please see :hg:`help urls` for important details about ``ssh://``
4103 URLs. If DESTINATION is omitted, a default path will be used.
4103 URLs. If DESTINATION is omitted, a default path will be used.
4104
4104
4105 Returns 0 if push was successful, 1 if nothing to push.
4105 Returns 0 if push was successful, 1 if nothing to push.
4106 """
4106 """
4107
4107
4108 if opts.get('bookmark'):
4108 if opts.get('bookmark'):
4109 for b in opts['bookmark']:
4109 for b in opts['bookmark']:
4110 # translate -B options to -r so changesets get pushed
4110 # translate -B options to -r so changesets get pushed
4111 if b in repo._bookmarks:
4111 if b in repo._bookmarks:
4112 opts.setdefault('rev', []).append(b)
4112 opts.setdefault('rev', []).append(b)
4113 else:
4113 else:
4114 # if we try to push a deleted bookmark, translate it to null
4114 # if we try to push a deleted bookmark, translate it to null
4115 # this lets simultaneous -r, -b options continue working
4115 # this lets simultaneous -r, -b options continue working
4116 opts.setdefault('rev', []).append("null")
4116 opts.setdefault('rev', []).append("null")
4117
4117
4118 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4118 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4119 dest, branches = hg.parseurl(dest, opts.get('branch'))
4119 dest, branches = hg.parseurl(dest, opts.get('branch'))
4120 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4120 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4121 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4121 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4122 other = hg.peer(repo, opts, dest)
4122 other = hg.peer(repo, opts, dest)
4123 if revs:
4123 if revs:
4124 revs = [repo.lookup(rev) for rev in revs]
4124 revs = [repo.lookup(rev) for rev in revs]
4125
4125
4126 repo._subtoppath = dest
4126 repo._subtoppath = dest
4127 try:
4127 try:
4128 # push subrepos depth-first for coherent ordering
4128 # push subrepos depth-first for coherent ordering
4129 c = repo['']
4129 c = repo['']
4130 subs = c.substate # only repos that are committed
4130 subs = c.substate # only repos that are committed
4131 for s in sorted(subs):
4131 for s in sorted(subs):
4132 if not c.sub(s).push(opts.get('force')):
4132 if not c.sub(s).push(opts.get('force')):
4133 return False
4133 return False
4134 finally:
4134 finally:
4135 del repo._subtoppath
4135 del repo._subtoppath
4136 result = repo.push(other, opts.get('force'), revs=revs,
4136 result = repo.push(other, opts.get('force'), revs=revs,
4137 newbranch=opts.get('new_branch'))
4137 newbranch=opts.get('new_branch'))
4138
4138
4139 result = (result == 0)
4139 result = (result == 0)
4140
4140
4141 if opts.get('bookmark'):
4141 if opts.get('bookmark'):
4142 rb = other.listkeys('bookmarks')
4142 rb = other.listkeys('bookmarks')
4143 for b in opts['bookmark']:
4143 for b in opts['bookmark']:
4144 # explicit push overrides remote bookmark if any
4144 # explicit push overrides remote bookmark if any
4145 if b in repo._bookmarks:
4145 if b in repo._bookmarks:
4146 ui.status(_("exporting bookmark %s\n") % b)
4146 ui.status(_("exporting bookmark %s\n") % b)
4147 new = repo[b].hex()
4147 new = repo[b].hex()
4148 elif b in rb:
4148 elif b in rb:
4149 ui.status(_("deleting remote bookmark %s\n") % b)
4149 ui.status(_("deleting remote bookmark %s\n") % b)
4150 new = '' # delete
4150 new = '' # delete
4151 else:
4151 else:
4152 ui.warn(_('bookmark %s does not exist on the local '
4152 ui.warn(_('bookmark %s does not exist on the local '
4153 'or remote repository!\n') % b)
4153 'or remote repository!\n') % b)
4154 return 2
4154 return 2
4155 old = rb.get(b, '')
4155 old = rb.get(b, '')
4156 r = other.pushkey('bookmarks', b, old, new)
4156 r = other.pushkey('bookmarks', b, old, new)
4157 if not r:
4157 if not r:
4158 ui.warn(_('updating bookmark %s failed!\n') % b)
4158 ui.warn(_('updating bookmark %s failed!\n') % b)
4159 if not result:
4159 if not result:
4160 result = 2
4160 result = 2
4161
4161
4162 return result
4162 return result
4163
4163
4164 @command('recover', [])
4164 @command('recover', [])
4165 def recover(ui, repo):
4165 def recover(ui, repo):
4166 """roll back an interrupted transaction
4166 """roll back an interrupted transaction
4167
4167
4168 Recover from an interrupted commit or pull.
4168 Recover from an interrupted commit or pull.
4169
4169
4170 This command tries to fix the repository status after an
4170 This command tries to fix the repository status after an
4171 interrupted operation. It should only be necessary when Mercurial
4171 interrupted operation. It should only be necessary when Mercurial
4172 suggests it.
4172 suggests it.
4173
4173
4174 Returns 0 if successful, 1 if nothing to recover or verify fails.
4174 Returns 0 if successful, 1 if nothing to recover or verify fails.
4175 """
4175 """
4176 if repo.recover():
4176 if repo.recover():
4177 return hg.verify(repo)
4177 return hg.verify(repo)
4178 return 1
4178 return 1
4179
4179
4180 @command('^remove|rm',
4180 @command('^remove|rm',
4181 [('A', 'after', None, _('record delete for missing files')),
4181 [('A', 'after', None, _('record delete for missing files')),
4182 ('f', 'force', None,
4182 ('f', 'force', None,
4183 _('remove (and delete) file even if added or modified')),
4183 _('remove (and delete) file even if added or modified')),
4184 ] + walkopts,
4184 ] + walkopts,
4185 _('[OPTION]... FILE...'))
4185 _('[OPTION]... FILE...'))
4186 def remove(ui, repo, *pats, **opts):
4186 def remove(ui, repo, *pats, **opts):
4187 """remove the specified files on the next commit
4187 """remove the specified files on the next commit
4188
4188
4189 Schedule the indicated files for removal from the current branch.
4189 Schedule the indicated files for removal from the current branch.
4190
4190
4191 This command schedules the files to be removed at the next commit.
4191 This command schedules the files to be removed at the next commit.
4192 To undo a remove before that, see :hg:`revert`. To undo added
4192 To undo a remove before that, see :hg:`revert`. To undo added
4193 files, see :hg:`forget`.
4193 files, see :hg:`forget`.
4194
4194
4195 .. container:: verbose
4195 .. container:: verbose
4196
4196
4197 -A/--after can be used to remove only files that have already
4197 -A/--after can be used to remove only files that have already
4198 been deleted, -f/--force can be used to force deletion, and -Af
4198 been deleted, -f/--force can be used to force deletion, and -Af
4199 can be used to remove files from the next revision without
4199 can be used to remove files from the next revision without
4200 deleting them from the working directory.
4200 deleting them from the working directory.
4201
4201
4202 The following table details the behavior of remove for different
4202 The following table details the behavior of remove for different
4203 file states (columns) and option combinations (rows). The file
4203 file states (columns) and option combinations (rows). The file
4204 states are Added [A], Clean [C], Modified [M] and Missing [!]
4204 states are Added [A], Clean [C], Modified [M] and Missing [!]
4205 (as reported by :hg:`status`). The actions are Warn, Remove
4205 (as reported by :hg:`status`). The actions are Warn, Remove
4206 (from branch) and Delete (from disk):
4206 (from branch) and Delete (from disk):
4207
4207
4208 ======= == == == ==
4208 ======= == == == ==
4209 A C M !
4209 A C M !
4210 ======= == == == ==
4210 ======= == == == ==
4211 none W RD W R
4211 none W RD W R
4212 -f R RD RD R
4212 -f R RD RD R
4213 -A W W W R
4213 -A W W W R
4214 -Af R R R R
4214 -Af R R R R
4215 ======= == == == ==
4215 ======= == == == ==
4216
4216
4217 Note that remove never deletes files in Added [A] state from the
4217 Note that remove never deletes files in Added [A] state from the
4218 working directory, not even if option --force is specified.
4218 working directory, not even if option --force is specified.
4219
4219
4220 Returns 0 on success, 1 if any warnings encountered.
4220 Returns 0 on success, 1 if any warnings encountered.
4221 """
4221 """
4222
4222
4223 ret = 0
4223 ret = 0
4224 after, force = opts.get('after'), opts.get('force')
4224 after, force = opts.get('after'), opts.get('force')
4225 if not pats and not after:
4225 if not pats and not after:
4226 raise util.Abort(_('no files specified'))
4226 raise util.Abort(_('no files specified'))
4227
4227
4228 m = scmutil.match(repo[None], pats, opts)
4228 m = scmutil.match(repo[None], pats, opts)
4229 s = repo.status(match=m, clean=True)
4229 s = repo.status(match=m, clean=True)
4230 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4230 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4231
4231
4232 for f in m.files():
4232 for f in m.files():
4233 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4233 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4234 if os.path.exists(m.rel(f)):
4234 if os.path.exists(m.rel(f)):
4235 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4235 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4236 ret = 1
4236 ret = 1
4237
4237
4238 if force:
4238 if force:
4239 list = modified + deleted + clean + added
4239 list = modified + deleted + clean + added
4240 elif after:
4240 elif after:
4241 list = deleted
4241 list = deleted
4242 for f in modified + added + clean:
4242 for f in modified + added + clean:
4243 ui.warn(_('not removing %s: file still exists (use -f'
4243 ui.warn(_('not removing %s: file still exists (use -f'
4244 ' to force removal)\n') % m.rel(f))
4244 ' to force removal)\n') % m.rel(f))
4245 ret = 1
4245 ret = 1
4246 else:
4246 else:
4247 list = deleted + clean
4247 list = deleted + clean
4248 for f in modified:
4248 for f in modified:
4249 ui.warn(_('not removing %s: file is modified (use -f'
4249 ui.warn(_('not removing %s: file is modified (use -f'
4250 ' to force removal)\n') % m.rel(f))
4250 ' to force removal)\n') % m.rel(f))
4251 ret = 1
4251 ret = 1
4252 for f in added:
4252 for f in added:
4253 ui.warn(_('not removing %s: file has been marked for add'
4253 ui.warn(_('not removing %s: file has been marked for add'
4254 ' (use forget to undo)\n') % m.rel(f))
4254 ' (use forget to undo)\n') % m.rel(f))
4255 ret = 1
4255 ret = 1
4256
4256
4257 for f in sorted(list):
4257 for f in sorted(list):
4258 if ui.verbose or not m.exact(f):
4258 if ui.verbose or not m.exact(f):
4259 ui.status(_('removing %s\n') % m.rel(f))
4259 ui.status(_('removing %s\n') % m.rel(f))
4260
4260
4261 wlock = repo.wlock()
4261 wlock = repo.wlock()
4262 try:
4262 try:
4263 if not after:
4263 if not after:
4264 for f in list:
4264 for f in list:
4265 if f in added:
4265 if f in added:
4266 continue # we never unlink added files on remove
4266 continue # we never unlink added files on remove
4267 try:
4267 try:
4268 util.unlinkpath(repo.wjoin(f))
4268 util.unlinkpath(repo.wjoin(f))
4269 except OSError, inst:
4269 except OSError, inst:
4270 if inst.errno != errno.ENOENT:
4270 if inst.errno != errno.ENOENT:
4271 raise
4271 raise
4272 repo[None].forget(list)
4272 repo[None].forget(list)
4273 finally:
4273 finally:
4274 wlock.release()
4274 wlock.release()
4275
4275
4276 return ret
4276 return ret
4277
4277
4278 @command('rename|move|mv',
4278 @command('rename|move|mv',
4279 [('A', 'after', None, _('record a rename that has already occurred')),
4279 [('A', 'after', None, _('record a rename that has already occurred')),
4280 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4280 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4281 ] + walkopts + dryrunopts,
4281 ] + walkopts + dryrunopts,
4282 _('[OPTION]... SOURCE... DEST'))
4282 _('[OPTION]... SOURCE... DEST'))
4283 def rename(ui, repo, *pats, **opts):
4283 def rename(ui, repo, *pats, **opts):
4284 """rename files; equivalent of copy + remove
4284 """rename files; equivalent of copy + remove
4285
4285
4286 Mark dest as copies of sources; mark sources for deletion. If dest
4286 Mark dest as copies of sources; mark sources for deletion. If dest
4287 is a directory, copies are put in that directory. If dest is a
4287 is a directory, copies are put in that directory. If dest is a
4288 file, there can only be one source.
4288 file, there can only be one source.
4289
4289
4290 By default, this command copies the contents of files as they
4290 By default, this command copies the contents of files as they
4291 exist in the working directory. If invoked with -A/--after, the
4291 exist in the working directory. If invoked with -A/--after, the
4292 operation is recorded, but no copying is performed.
4292 operation is recorded, but no copying is performed.
4293
4293
4294 This command takes effect at the next commit. To undo a rename
4294 This command takes effect at the next commit. To undo a rename
4295 before that, see :hg:`revert`.
4295 before that, see :hg:`revert`.
4296
4296
4297 Returns 0 on success, 1 if errors are encountered.
4297 Returns 0 on success, 1 if errors are encountered.
4298 """
4298 """
4299 wlock = repo.wlock(False)
4299 wlock = repo.wlock(False)
4300 try:
4300 try:
4301 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4301 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4302 finally:
4302 finally:
4303 wlock.release()
4303 wlock.release()
4304
4304
4305 @command('resolve',
4305 @command('resolve',
4306 [('a', 'all', None, _('select all unresolved files')),
4306 [('a', 'all', None, _('select all unresolved files')),
4307 ('l', 'list', None, _('list state of files needing merge')),
4307 ('l', 'list', None, _('list state of files needing merge')),
4308 ('m', 'mark', None, _('mark files as resolved')),
4308 ('m', 'mark', None, _('mark files as resolved')),
4309 ('u', 'unmark', None, _('mark files as unresolved')),
4309 ('u', 'unmark', None, _('mark files as unresolved')),
4310 ('n', 'no-status', None, _('hide status prefix'))]
4310 ('n', 'no-status', None, _('hide status prefix'))]
4311 + mergetoolopts + walkopts,
4311 + mergetoolopts + walkopts,
4312 _('[OPTION]... [FILE]...'))
4312 _('[OPTION]... [FILE]...'))
4313 def resolve(ui, repo, *pats, **opts):
4313 def resolve(ui, repo, *pats, **opts):
4314 """redo merges or set/view the merge status of files
4314 """redo merges or set/view the merge status of files
4315
4315
4316 Merges with unresolved conflicts are often the result of
4316 Merges with unresolved conflicts are often the result of
4317 non-interactive merging using the ``internal:merge`` configuration
4317 non-interactive merging using the ``internal:merge`` configuration
4318 setting, or a command-line merge tool like ``diff3``. The resolve
4318 setting, or a command-line merge tool like ``diff3``. The resolve
4319 command is used to manage the files involved in a merge, after
4319 command is used to manage the files involved in a merge, after
4320 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4320 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4321 working directory must have two parents).
4321 working directory must have two parents).
4322
4322
4323 The resolve command can be used in the following ways:
4323 The resolve command can be used in the following ways:
4324
4324
4325 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4325 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4326 files, discarding any previous merge attempts. Re-merging is not
4326 files, discarding any previous merge attempts. Re-merging is not
4327 performed for files already marked as resolved. Use ``--all/-a``
4327 performed for files already marked as resolved. Use ``--all/-a``
4328 to select all unresolved files. ``--tool`` can be used to specify
4328 to select all unresolved files. ``--tool`` can be used to specify
4329 the merge tool used for the given files. It overrides the HGMERGE
4329 the merge tool used for the given files. It overrides the HGMERGE
4330 environment variable and your configuration files.
4330 environment variable and your configuration files.
4331
4331
4332 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4332 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4333 (e.g. after having manually fixed-up the files). The default is
4333 (e.g. after having manually fixed-up the files). The default is
4334 to mark all unresolved files.
4334 to mark all unresolved files.
4335
4335
4336 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4336 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4337 default is to mark all resolved files.
4337 default is to mark all resolved files.
4338
4338
4339 - :hg:`resolve -l`: list files which had or still have conflicts.
4339 - :hg:`resolve -l`: list files which had or still have conflicts.
4340 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4340 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4341
4341
4342 Note that Mercurial will not let you commit files with unresolved
4342 Note that Mercurial will not let you commit files with unresolved
4343 merge conflicts. You must use :hg:`resolve -m ...` before you can
4343 merge conflicts. You must use :hg:`resolve -m ...` before you can
4344 commit after a conflicting merge.
4344 commit after a conflicting merge.
4345
4345
4346 Returns 0 on success, 1 if any files fail a resolve attempt.
4346 Returns 0 on success, 1 if any files fail a resolve attempt.
4347 """
4347 """
4348
4348
4349 all, mark, unmark, show, nostatus = \
4349 all, mark, unmark, show, nostatus = \
4350 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4350 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4351
4351
4352 if (show and (mark or unmark)) or (mark and unmark):
4352 if (show and (mark or unmark)) or (mark and unmark):
4353 raise util.Abort(_("too many options specified"))
4353 raise util.Abort(_("too many options specified"))
4354 if pats and all:
4354 if pats and all:
4355 raise util.Abort(_("can't specify --all and patterns"))
4355 raise util.Abort(_("can't specify --all and patterns"))
4356 if not (all or pats or show or mark or unmark):
4356 if not (all or pats or show or mark or unmark):
4357 raise util.Abort(_('no files or directories specified; '
4357 raise util.Abort(_('no files or directories specified; '
4358 'use --all to remerge all files'))
4358 'use --all to remerge all files'))
4359
4359
4360 ms = mergemod.mergestate(repo)
4360 ms = mergemod.mergestate(repo)
4361 m = scmutil.match(repo[None], pats, opts)
4361 m = scmutil.match(repo[None], pats, opts)
4362 ret = 0
4362 ret = 0
4363
4363
4364 for f in ms:
4364 for f in ms:
4365 if m(f):
4365 if m(f):
4366 if show:
4366 if show:
4367 if nostatus:
4367 if nostatus:
4368 ui.write("%s\n" % f)
4368 ui.write("%s\n" % f)
4369 else:
4369 else:
4370 ui.write("%s %s\n" % (ms[f].upper(), f),
4370 ui.write("%s %s\n" % (ms[f].upper(), f),
4371 label='resolve.' +
4371 label='resolve.' +
4372 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4372 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4373 elif mark:
4373 elif mark:
4374 ms.mark(f, "r")
4374 ms.mark(f, "r")
4375 elif unmark:
4375 elif unmark:
4376 ms.mark(f, "u")
4376 ms.mark(f, "u")
4377 else:
4377 else:
4378 wctx = repo[None]
4378 wctx = repo[None]
4379 mctx = wctx.parents()[-1]
4379 mctx = wctx.parents()[-1]
4380
4380
4381 # backup pre-resolve (merge uses .orig for its own purposes)
4381 # backup pre-resolve (merge uses .orig for its own purposes)
4382 a = repo.wjoin(f)
4382 a = repo.wjoin(f)
4383 util.copyfile(a, a + ".resolve")
4383 util.copyfile(a, a + ".resolve")
4384
4384
4385 try:
4385 try:
4386 # resolve file
4386 # resolve file
4387 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4387 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4388 if ms.resolve(f, wctx, mctx):
4388 if ms.resolve(f, wctx, mctx):
4389 ret = 1
4389 ret = 1
4390 finally:
4390 finally:
4391 ui.setconfig('ui', 'forcemerge', '')
4391 ui.setconfig('ui', 'forcemerge', '')
4392
4392
4393 # replace filemerge's .orig file with our resolve file
4393 # replace filemerge's .orig file with our resolve file
4394 util.rename(a + ".resolve", a + ".orig")
4394 util.rename(a + ".resolve", a + ".orig")
4395
4395
4396 ms.commit()
4396 ms.commit()
4397 return ret
4397 return ret
4398
4398
4399 @command('revert',
4399 @command('revert',
4400 [('a', 'all', None, _('revert all changes when no arguments given')),
4400 [('a', 'all', None, _('revert all changes when no arguments given')),
4401 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4401 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4402 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4402 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4403 ('C', 'no-backup', None, _('do not save backup copies of files')),
4403 ('C', 'no-backup', None, _('do not save backup copies of files')),
4404 ] + walkopts + dryrunopts,
4404 ] + walkopts + dryrunopts,
4405 _('[OPTION]... [-r REV] [NAME]...'))
4405 _('[OPTION]... [-r REV] [NAME]...'))
4406 def revert(ui, repo, *pats, **opts):
4406 def revert(ui, repo, *pats, **opts):
4407 """restore files to their checkout state
4407 """restore files to their checkout state
4408
4408
4409 .. note::
4409 .. note::
4410 To check out earlier revisions, you should use :hg:`update REV`.
4410 To check out earlier revisions, you should use :hg:`update REV`.
4411 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4411 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4412
4412
4413 With no revision specified, revert the specified files or directories
4413 With no revision specified, revert the specified files or directories
4414 to the contents they had in the parent of the working directory.
4414 to the contents they had in the parent of the working directory.
4415 This restores the contents of files to an unmodified
4415 This restores the contents of files to an unmodified
4416 state and unschedules adds, removes, copies, and renames. If the
4416 state and unschedules adds, removes, copies, and renames. If the
4417 working directory has two parents, you must explicitly specify a
4417 working directory has two parents, you must explicitly specify a
4418 revision.
4418 revision.
4419
4419
4420 Using the -r/--rev or -d/--date options, revert the given files or
4420 Using the -r/--rev or -d/--date options, revert the given files or
4421 directories to their states as of a specific revision. Because
4421 directories to their states as of a specific revision. Because
4422 revert does not change the working directory parents, this will
4422 revert does not change the working directory parents, this will
4423 cause these files to appear modified. This can be helpful to "back
4423 cause these files to appear modified. This can be helpful to "back
4424 out" some or all of an earlier change. See :hg:`backout` for a
4424 out" some or all of an earlier change. See :hg:`backout` for a
4425 related method.
4425 related method.
4426
4426
4427 Modified files are saved with a .orig suffix before reverting.
4427 Modified files are saved with a .orig suffix before reverting.
4428 To disable these backups, use --no-backup.
4428 To disable these backups, use --no-backup.
4429
4429
4430 See :hg:`help dates` for a list of formats valid for -d/--date.
4430 See :hg:`help dates` for a list of formats valid for -d/--date.
4431
4431
4432 Returns 0 on success.
4432 Returns 0 on success.
4433 """
4433 """
4434
4434
4435 if opts.get("date"):
4435 if opts.get("date"):
4436 if opts.get("rev"):
4436 if opts.get("rev"):
4437 raise util.Abort(_("you can't specify a revision and a date"))
4437 raise util.Abort(_("you can't specify a revision and a date"))
4438 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4438 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4439
4439
4440 parent, p2 = repo.dirstate.parents()
4440 parent, p2 = repo.dirstate.parents()
4441 if not opts.get('rev') and p2 != nullid:
4441 if not opts.get('rev') and p2 != nullid:
4442 # revert after merge is a trap for new users (issue2915)
4442 # revert after merge is a trap for new users (issue2915)
4443 raise util.Abort(_('uncommitted merge with no revision specified'),
4443 raise util.Abort(_('uncommitted merge with no revision specified'),
4444 hint=_('use "hg update" or see "hg help revert"'))
4444 hint=_('use "hg update" or see "hg help revert"'))
4445
4445
4446 ctx = scmutil.revsingle(repo, opts.get('rev'))
4446 ctx = scmutil.revsingle(repo, opts.get('rev'))
4447 node = ctx.node()
4447 node = ctx.node()
4448
4448
4449 if not pats and not opts.get('all'):
4449 if not pats and not opts.get('all'):
4450 msg = _("no files or directories specified")
4450 msg = _("no files or directories specified")
4451 if p2 != nullid:
4451 if p2 != nullid:
4452 hint = _("uncommitted merge, use --all to discard all changes,"
4452 hint = _("uncommitted merge, use --all to discard all changes,"
4453 " or 'hg update -C .' to abort the merge")
4453 " or 'hg update -C .' to abort the merge")
4454 raise util.Abort(msg, hint=hint)
4454 raise util.Abort(msg, hint=hint)
4455 dirty = util.any(repo.status())
4455 dirty = util.any(repo.status())
4456 if node != parent:
4456 if node != parent:
4457 if dirty:
4457 if dirty:
4458 hint = _("uncommitted changes, use --all to discard all"
4458 hint = _("uncommitted changes, use --all to discard all"
4459 " changes, or 'hg update %s' to update") % ctx.rev()
4459 " changes, or 'hg update %s' to update") % ctx.rev()
4460 else:
4460 else:
4461 hint = _("use --all to revert all files,"
4461 hint = _("use --all to revert all files,"
4462 " or 'hg update %s' to update") % ctx.rev()
4462 " or 'hg update %s' to update") % ctx.rev()
4463 elif dirty:
4463 elif dirty:
4464 hint = _("uncommitted changes, use --all to discard all changes")
4464 hint = _("uncommitted changes, use --all to discard all changes")
4465 else:
4465 else:
4466 hint = _("use --all to revert all files")
4466 hint = _("use --all to revert all files")
4467 raise util.Abort(msg, hint=hint)
4467 raise util.Abort(msg, hint=hint)
4468
4468
4469 mf = ctx.manifest()
4469 mf = ctx.manifest()
4470 if node == parent:
4470 if node == parent:
4471 pmf = mf
4471 pmf = mf
4472 else:
4472 else:
4473 pmf = None
4473 pmf = None
4474
4474
4475 # need all matching names in dirstate and manifest of target rev,
4475 # need all matching names in dirstate and manifest of target rev,
4476 # so have to walk both. do not print errors if files exist in one
4476 # so have to walk both. do not print errors if files exist in one
4477 # but not other.
4477 # but not other.
4478
4478
4479 names = {}
4479 names = {}
4480
4480
4481 wlock = repo.wlock()
4481 wlock = repo.wlock()
4482 try:
4482 try:
4483 # walk dirstate.
4483 # walk dirstate.
4484
4484
4485 m = scmutil.match(repo[None], pats, opts)
4485 m = scmutil.match(repo[None], pats, opts)
4486 m.bad = lambda x, y: False
4486 m.bad = lambda x, y: False
4487 for abs in repo.walk(m):
4487 for abs in repo.walk(m):
4488 names[abs] = m.rel(abs), m.exact(abs)
4488 names[abs] = m.rel(abs), m.exact(abs)
4489
4489
4490 # walk target manifest.
4490 # walk target manifest.
4491
4491
4492 def badfn(path, msg):
4492 def badfn(path, msg):
4493 if path in names:
4493 if path in names:
4494 return
4494 return
4495 path_ = path + '/'
4495 path_ = path + '/'
4496 for f in names:
4496 for f in names:
4497 if f.startswith(path_):
4497 if f.startswith(path_):
4498 return
4498 return
4499 ui.warn("%s: %s\n" % (m.rel(path), msg))
4499 ui.warn("%s: %s\n" % (m.rel(path), msg))
4500
4500
4501 m = scmutil.match(repo[node], pats, opts)
4501 m = scmutil.match(repo[node], pats, opts)
4502 m.bad = badfn
4502 m.bad = badfn
4503 for abs in repo[node].walk(m):
4503 for abs in repo[node].walk(m):
4504 if abs not in names:
4504 if abs not in names:
4505 names[abs] = m.rel(abs), m.exact(abs)
4505 names[abs] = m.rel(abs), m.exact(abs)
4506
4506
4507 m = scmutil.matchfiles(repo, names)
4507 m = scmutil.matchfiles(repo, names)
4508 changes = repo.status(match=m)[:4]
4508 changes = repo.status(match=m)[:4]
4509 modified, added, removed, deleted = map(set, changes)
4509 modified, added, removed, deleted = map(set, changes)
4510
4510
4511 # if f is a rename, also revert the source
4511 # if f is a rename, also revert the source
4512 cwd = repo.getcwd()
4512 cwd = repo.getcwd()
4513 for f in added:
4513 for f in added:
4514 src = repo.dirstate.copied(f)
4514 src = repo.dirstate.copied(f)
4515 if src and src not in names and repo.dirstate[src] == 'r':
4515 if src and src not in names and repo.dirstate[src] == 'r':
4516 removed.add(src)
4516 removed.add(src)
4517 names[src] = (repo.pathto(src, cwd), True)
4517 names[src] = (repo.pathto(src, cwd), True)
4518
4518
4519 def removeforget(abs):
4519 def removeforget(abs):
4520 if repo.dirstate[abs] == 'a':
4520 if repo.dirstate[abs] == 'a':
4521 return _('forgetting %s\n')
4521 return _('forgetting %s\n')
4522 return _('removing %s\n')
4522 return _('removing %s\n')
4523
4523
4524 revert = ([], _('reverting %s\n'))
4524 revert = ([], _('reverting %s\n'))
4525 add = ([], _('adding %s\n'))
4525 add = ([], _('adding %s\n'))
4526 remove = ([], removeforget)
4526 remove = ([], removeforget)
4527 undelete = ([], _('undeleting %s\n'))
4527 undelete = ([], _('undeleting %s\n'))
4528
4528
4529 disptable = (
4529 disptable = (
4530 # dispatch table:
4530 # dispatch table:
4531 # file state
4531 # file state
4532 # action if in target manifest
4532 # action if in target manifest
4533 # action if not in target manifest
4533 # action if not in target manifest
4534 # make backup if in target manifest
4534 # make backup if in target manifest
4535 # make backup if not in target manifest
4535 # make backup if not in target manifest
4536 (modified, revert, remove, True, True),
4536 (modified, revert, remove, True, True),
4537 (added, revert, remove, True, False),
4537 (added, revert, remove, True, False),
4538 (removed, undelete, None, False, False),
4538 (removed, undelete, None, False, False),
4539 (deleted, revert, remove, False, False),
4539 (deleted, revert, remove, False, False),
4540 )
4540 )
4541
4541
4542 for abs, (rel, exact) in sorted(names.items()):
4542 for abs, (rel, exact) in sorted(names.items()):
4543 mfentry = mf.get(abs)
4543 mfentry = mf.get(abs)
4544 target = repo.wjoin(abs)
4544 target = repo.wjoin(abs)
4545 def handle(xlist, dobackup):
4545 def handle(xlist, dobackup):
4546 xlist[0].append(abs)
4546 xlist[0].append(abs)
4547 if (dobackup and not opts.get('no_backup') and
4547 if (dobackup and not opts.get('no_backup') and
4548 os.path.lexists(target)):
4548 os.path.lexists(target)):
4549 bakname = "%s.orig" % rel
4549 bakname = "%s.orig" % rel
4550 ui.note(_('saving current version of %s as %s\n') %
4550 ui.note(_('saving current version of %s as %s\n') %
4551 (rel, bakname))
4551 (rel, bakname))
4552 if not opts.get('dry_run'):
4552 if not opts.get('dry_run'):
4553 util.rename(target, bakname)
4553 util.rename(target, bakname)
4554 if ui.verbose or not exact:
4554 if ui.verbose or not exact:
4555 msg = xlist[1]
4555 msg = xlist[1]
4556 if not isinstance(msg, basestring):
4556 if not isinstance(msg, basestring):
4557 msg = msg(abs)
4557 msg = msg(abs)
4558 ui.status(msg % rel)
4558 ui.status(msg % rel)
4559 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4559 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4560 if abs not in table:
4560 if abs not in table:
4561 continue
4561 continue
4562 # file has changed in dirstate
4562 # file has changed in dirstate
4563 if mfentry:
4563 if mfentry:
4564 handle(hitlist, backuphit)
4564 handle(hitlist, backuphit)
4565 elif misslist is not None:
4565 elif misslist is not None:
4566 handle(misslist, backupmiss)
4566 handle(misslist, backupmiss)
4567 break
4567 break
4568 else:
4568 else:
4569 if abs not in repo.dirstate:
4569 if abs not in repo.dirstate:
4570 if mfentry:
4570 if mfentry:
4571 handle(add, True)
4571 handle(add, True)
4572 elif exact:
4572 elif exact:
4573 ui.warn(_('file not managed: %s\n') % rel)
4573 ui.warn(_('file not managed: %s\n') % rel)
4574 continue
4574 continue
4575 # file has not changed in dirstate
4575 # file has not changed in dirstate
4576 if node == parent:
4576 if node == parent:
4577 if exact:
4577 if exact:
4578 ui.warn(_('no changes needed to %s\n') % rel)
4578 ui.warn(_('no changes needed to %s\n') % rel)
4579 continue
4579 continue
4580 if pmf is None:
4580 if pmf is None:
4581 # only need parent manifest in this unlikely case,
4581 # only need parent manifest in this unlikely case,
4582 # so do not read by default
4582 # so do not read by default
4583 pmf = repo[parent].manifest()
4583 pmf = repo[parent].manifest()
4584 if abs in pmf:
4584 if abs in pmf:
4585 if mfentry:
4585 if mfentry:
4586 # if version of file is same in parent and target
4586 # if version of file is same in parent and target
4587 # manifests, do nothing
4587 # manifests, do nothing
4588 if (pmf[abs] != mfentry or
4588 if (pmf[abs] != mfentry or
4589 pmf.flags(abs) != mf.flags(abs)):
4589 pmf.flags(abs) != mf.flags(abs)):
4590 handle(revert, False)
4590 handle(revert, False)
4591 else:
4591 else:
4592 handle(remove, False)
4592 handle(remove, False)
4593
4593
4594 if not opts.get('dry_run'):
4594 if not opts.get('dry_run'):
4595 def checkout(f):
4595 def checkout(f):
4596 fc = ctx[f]
4596 fc = ctx[f]
4597 repo.wwrite(f, fc.data(), fc.flags())
4597 repo.wwrite(f, fc.data(), fc.flags())
4598
4598
4599 audit_path = scmutil.pathauditor(repo.root)
4599 audit_path = scmutil.pathauditor(repo.root)
4600 for f in remove[0]:
4600 for f in remove[0]:
4601 if repo.dirstate[f] == 'a':
4601 if repo.dirstate[f] == 'a':
4602 repo.dirstate.drop(f)
4602 repo.dirstate.drop(f)
4603 continue
4603 continue
4604 audit_path(f)
4604 audit_path(f)
4605 try:
4605 try:
4606 util.unlinkpath(repo.wjoin(f))
4606 util.unlinkpath(repo.wjoin(f))
4607 except OSError:
4607 except OSError:
4608 pass
4608 pass
4609 repo.dirstate.remove(f)
4609 repo.dirstate.remove(f)
4610
4610
4611 normal = None
4611 normal = None
4612 if node == parent:
4612 if node == parent:
4613 # We're reverting to our parent. If possible, we'd like status
4613 # We're reverting to our parent. If possible, we'd like status
4614 # to report the file as clean. We have to use normallookup for
4614 # to report the file as clean. We have to use normallookup for
4615 # merges to avoid losing information about merged/dirty files.
4615 # merges to avoid losing information about merged/dirty files.
4616 if p2 != nullid:
4616 if p2 != nullid:
4617 normal = repo.dirstate.normallookup
4617 normal = repo.dirstate.normallookup
4618 else:
4618 else:
4619 normal = repo.dirstate.normal
4619 normal = repo.dirstate.normal
4620 for f in revert[0]:
4620 for f in revert[0]:
4621 checkout(f)
4621 checkout(f)
4622 if normal:
4622 if normal:
4623 normal(f)
4623 normal(f)
4624
4624
4625 for f in add[0]:
4625 for f in add[0]:
4626 checkout(f)
4626 checkout(f)
4627 repo.dirstate.add(f)
4627 repo.dirstate.add(f)
4628
4628
4629 normal = repo.dirstate.normallookup
4629 normal = repo.dirstate.normallookup
4630 if node == parent and p2 == nullid:
4630 if node == parent and p2 == nullid:
4631 normal = repo.dirstate.normal
4631 normal = repo.dirstate.normal
4632 for f in undelete[0]:
4632 for f in undelete[0]:
4633 checkout(f)
4633 checkout(f)
4634 normal(f)
4634 normal(f)
4635
4635
4636 finally:
4636 finally:
4637 wlock.release()
4637 wlock.release()
4638
4638
4639 @command('rollback', dryrunopts +
4639 @command('rollback', dryrunopts +
4640 [('f', 'force', False, _('ignore safety measures'))])
4640 [('f', 'force', False, _('ignore safety measures'))])
4641 def rollback(ui, repo, **opts):
4641 def rollback(ui, repo, **opts):
4642 """roll back the last transaction (dangerous)
4642 """roll back the last transaction (dangerous)
4643
4643
4644 This command should be used with care. There is only one level of
4644 This command should be used with care. There is only one level of
4645 rollback, and there is no way to undo a rollback. It will also
4645 rollback, and there is no way to undo a rollback. It will also
4646 restore the dirstate at the time of the last transaction, losing
4646 restore the dirstate at the time of the last transaction, losing
4647 any dirstate changes since that time. This command does not alter
4647 any dirstate changes since that time. This command does not alter
4648 the working directory.
4648 the working directory.
4649
4649
4650 Transactions are used to encapsulate the effects of all commands
4650 Transactions are used to encapsulate the effects of all commands
4651 that create new changesets or propagate existing changesets into a
4651 that create new changesets or propagate existing changesets into a
4652 repository. For example, the following commands are transactional,
4652 repository. For example, the following commands are transactional,
4653 and their effects can be rolled back:
4653 and their effects can be rolled back:
4654
4654
4655 - commit
4655 - commit
4656 - import
4656 - import
4657 - pull
4657 - pull
4658 - push (with this repository as the destination)
4658 - push (with this repository as the destination)
4659 - unbundle
4659 - unbundle
4660
4660
4661 It's possible to lose data with rollback: commit, update back to
4661 It's possible to lose data with rollback: commit, update back to
4662 an older changeset, and then rollback. The update removes the
4662 an older changeset, and then rollback. The update removes the
4663 changes you committed from the working directory, and rollback
4663 changes you committed from the working directory, and rollback
4664 removes them from history. To avoid data loss, you must pass
4664 removes them from history. To avoid data loss, you must pass
4665 --force in this case.
4665 --force in this case.
4666
4666
4667 This command is not intended for use on public repositories. Once
4667 This command is not intended for use on public repositories. Once
4668 changes are visible for pull by other users, rolling a transaction
4668 changes are visible for pull by other users, rolling a transaction
4669 back locally is ineffective (someone else may already have pulled
4669 back locally is ineffective (someone else may already have pulled
4670 the changes). Furthermore, a race is possible with readers of the
4670 the changes). Furthermore, a race is possible with readers of the
4671 repository; for example an in-progress pull from the repository
4671 repository; for example an in-progress pull from the repository
4672 may fail if a rollback is performed.
4672 may fail if a rollback is performed.
4673
4673
4674 Returns 0 on success, 1 if no rollback data is available.
4674 Returns 0 on success, 1 if no rollback data is available.
4675 """
4675 """
4676 return repo.rollback(dryrun=opts.get('dry_run'),
4676 return repo.rollback(dryrun=opts.get('dry_run'),
4677 force=opts.get('force'))
4677 force=opts.get('force'))
4678
4678
4679 @command('root', [])
4679 @command('root', [])
4680 def root(ui, repo):
4680 def root(ui, repo):
4681 """print the root (top) of the current working directory
4681 """print the root (top) of the current working directory
4682
4682
4683 Print the root directory of the current repository.
4683 Print the root directory of the current repository.
4684
4684
4685 Returns 0 on success.
4685 Returns 0 on success.
4686 """
4686 """
4687 ui.write(repo.root + "\n")
4687 ui.write(repo.root + "\n")
4688
4688
4689 @command('^serve',
4689 @command('^serve',
4690 [('A', 'accesslog', '', _('name of access log file to write to'),
4690 [('A', 'accesslog', '', _('name of access log file to write to'),
4691 _('FILE')),
4691 _('FILE')),
4692 ('d', 'daemon', None, _('run server in background')),
4692 ('d', 'daemon', None, _('run server in background')),
4693 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4693 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4694 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4694 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4695 # use string type, then we can check if something was passed
4695 # use string type, then we can check if something was passed
4696 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4696 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4697 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4697 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4698 _('ADDR')),
4698 _('ADDR')),
4699 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4699 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4700 _('PREFIX')),
4700 _('PREFIX')),
4701 ('n', 'name', '',
4701 ('n', 'name', '',
4702 _('name to show in web pages (default: working directory)'), _('NAME')),
4702 _('name to show in web pages (default: working directory)'), _('NAME')),
4703 ('', 'web-conf', '',
4703 ('', 'web-conf', '',
4704 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4704 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4705 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4705 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4706 _('FILE')),
4706 _('FILE')),
4707 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4707 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4708 ('', 'stdio', None, _('for remote clients')),
4708 ('', 'stdio', None, _('for remote clients')),
4709 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4709 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4710 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4710 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4711 ('', 'style', '', _('template style to use'), _('STYLE')),
4711 ('', 'style', '', _('template style to use'), _('STYLE')),
4712 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4712 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4713 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4713 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4714 _('[OPTION]...'))
4714 _('[OPTION]...'))
4715 def serve(ui, repo, **opts):
4715 def serve(ui, repo, **opts):
4716 """start stand-alone webserver
4716 """start stand-alone webserver
4717
4717
4718 Start a local HTTP repository browser and pull server. You can use
4718 Start a local HTTP repository browser and pull server. You can use
4719 this for ad-hoc sharing and browsing of repositories. It is
4719 this for ad-hoc sharing and browsing of repositories. It is
4720 recommended to use a real web server to serve a repository for
4720 recommended to use a real web server to serve a repository for
4721 longer periods of time.
4721 longer periods of time.
4722
4722
4723 Please note that the server does not implement access control.
4723 Please note that the server does not implement access control.
4724 This means that, by default, anybody can read from the server and
4724 This means that, by default, anybody can read from the server and
4725 nobody can write to it by default. Set the ``web.allow_push``
4725 nobody can write to it by default. Set the ``web.allow_push``
4726 option to ``*`` to allow everybody to push to the server. You
4726 option to ``*`` to allow everybody to push to the server. You
4727 should use a real web server if you need to authenticate users.
4727 should use a real web server if you need to authenticate users.
4728
4728
4729 By default, the server logs accesses to stdout and errors to
4729 By default, the server logs accesses to stdout and errors to
4730 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4730 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4731 files.
4731 files.
4732
4732
4733 To have the server choose a free port number to listen on, specify
4733 To have the server choose a free port number to listen on, specify
4734 a port number of 0; in this case, the server will print the port
4734 a port number of 0; in this case, the server will print the port
4735 number it uses.
4735 number it uses.
4736
4736
4737 Returns 0 on success.
4737 Returns 0 on success.
4738 """
4738 """
4739
4739
4740 if opts["stdio"] and opts["cmdserver"]:
4740 if opts["stdio"] and opts["cmdserver"]:
4741 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4741 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4742
4742
4743 def checkrepo():
4743 def checkrepo():
4744 if repo is None:
4744 if repo is None:
4745 raise error.RepoError(_("There is no Mercurial repository here"
4745 raise error.RepoError(_("There is no Mercurial repository here"
4746 " (.hg not found)"))
4746 " (.hg not found)"))
4747
4747
4748 if opts["stdio"]:
4748 if opts["stdio"]:
4749 checkrepo()
4749 checkrepo()
4750 s = sshserver.sshserver(ui, repo)
4750 s = sshserver.sshserver(ui, repo)
4751 s.serve_forever()
4751 s.serve_forever()
4752
4752
4753 if opts["cmdserver"]:
4753 if opts["cmdserver"]:
4754 checkrepo()
4754 checkrepo()
4755 s = commandserver.server(ui, repo, opts["cmdserver"])
4755 s = commandserver.server(ui, repo, opts["cmdserver"])
4756 return s.serve()
4756 return s.serve()
4757
4757
4758 # this way we can check if something was given in the command-line
4758 # this way we can check if something was given in the command-line
4759 if opts.get('port'):
4759 if opts.get('port'):
4760 opts['port'] = util.getport(opts.get('port'))
4760 opts['port'] = util.getport(opts.get('port'))
4761
4761
4762 baseui = repo and repo.baseui or ui
4762 baseui = repo and repo.baseui or ui
4763 optlist = ("name templates style address port prefix ipv6"
4763 optlist = ("name templates style address port prefix ipv6"
4764 " accesslog errorlog certificate encoding")
4764 " accesslog errorlog certificate encoding")
4765 for o in optlist.split():
4765 for o in optlist.split():
4766 val = opts.get(o, '')
4766 val = opts.get(o, '')
4767 if val in (None, ''): # should check against default options instead
4767 if val in (None, ''): # should check against default options instead
4768 continue
4768 continue
4769 baseui.setconfig("web", o, val)
4769 baseui.setconfig("web", o, val)
4770 if repo and repo.ui != baseui:
4770 if repo and repo.ui != baseui:
4771 repo.ui.setconfig("web", o, val)
4771 repo.ui.setconfig("web", o, val)
4772
4772
4773 o = opts.get('web_conf') or opts.get('webdir_conf')
4773 o = opts.get('web_conf') or opts.get('webdir_conf')
4774 if not o:
4774 if not o:
4775 if not repo:
4775 if not repo:
4776 raise error.RepoError(_("There is no Mercurial repository"
4776 raise error.RepoError(_("There is no Mercurial repository"
4777 " here (.hg not found)"))
4777 " here (.hg not found)"))
4778 o = repo.root
4778 o = repo.root
4779
4779
4780 app = hgweb.hgweb(o, baseui=ui)
4780 app = hgweb.hgweb(o, baseui=ui)
4781
4781
4782 class service(object):
4782 class service(object):
4783 def init(self):
4783 def init(self):
4784 util.setsignalhandler()
4784 util.setsignalhandler()
4785 self.httpd = hgweb.server.create_server(ui, app)
4785 self.httpd = hgweb.server.create_server(ui, app)
4786
4786
4787 if opts['port'] and not ui.verbose:
4787 if opts['port'] and not ui.verbose:
4788 return
4788 return
4789
4789
4790 if self.httpd.prefix:
4790 if self.httpd.prefix:
4791 prefix = self.httpd.prefix.strip('/') + '/'
4791 prefix = self.httpd.prefix.strip('/') + '/'
4792 else:
4792 else:
4793 prefix = ''
4793 prefix = ''
4794
4794
4795 port = ':%d' % self.httpd.port
4795 port = ':%d' % self.httpd.port
4796 if port == ':80':
4796 if port == ':80':
4797 port = ''
4797 port = ''
4798
4798
4799 bindaddr = self.httpd.addr
4799 bindaddr = self.httpd.addr
4800 if bindaddr == '0.0.0.0':
4800 if bindaddr == '0.0.0.0':
4801 bindaddr = '*'
4801 bindaddr = '*'
4802 elif ':' in bindaddr: # IPv6
4802 elif ':' in bindaddr: # IPv6
4803 bindaddr = '[%s]' % bindaddr
4803 bindaddr = '[%s]' % bindaddr
4804
4804
4805 fqaddr = self.httpd.fqaddr
4805 fqaddr = self.httpd.fqaddr
4806 if ':' in fqaddr:
4806 if ':' in fqaddr:
4807 fqaddr = '[%s]' % fqaddr
4807 fqaddr = '[%s]' % fqaddr
4808 if opts['port']:
4808 if opts['port']:
4809 write = ui.status
4809 write = ui.status
4810 else:
4810 else:
4811 write = ui.write
4811 write = ui.write
4812 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4812 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4813 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4813 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4814
4814
4815 def run(self):
4815 def run(self):
4816 self.httpd.serve_forever()
4816 self.httpd.serve_forever()
4817
4817
4818 service = service()
4818 service = service()
4819
4819
4820 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4820 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4821
4821
4822 @command('showconfig|debugconfig',
4822 @command('showconfig|debugconfig',
4823 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4823 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4824 _('[-u] [NAME]...'))
4824 _('[-u] [NAME]...'))
4825 def showconfig(ui, repo, *values, **opts):
4825 def showconfig(ui, repo, *values, **opts):
4826 """show combined config settings from all hgrc files
4826 """show combined config settings from all hgrc files
4827
4827
4828 With no arguments, print names and values of all config items.
4828 With no arguments, print names and values of all config items.
4829
4829
4830 With one argument of the form section.name, print just the value
4830 With one argument of the form section.name, print just the value
4831 of that config item.
4831 of that config item.
4832
4832
4833 With multiple arguments, print names and values of all config
4833 With multiple arguments, print names and values of all config
4834 items with matching section names.
4834 items with matching section names.
4835
4835
4836 With --debug, the source (filename and line number) is printed
4836 With --debug, the source (filename and line number) is printed
4837 for each config item.
4837 for each config item.
4838
4838
4839 Returns 0 on success.
4839 Returns 0 on success.
4840 """
4840 """
4841
4841
4842 for f in scmutil.rcpath():
4842 for f in scmutil.rcpath():
4843 ui.debug('read config from: %s\n' % f)
4843 ui.debug('read config from: %s\n' % f)
4844 untrusted = bool(opts.get('untrusted'))
4844 untrusted = bool(opts.get('untrusted'))
4845 if values:
4845 if values:
4846 sections = [v for v in values if '.' not in v]
4846 sections = [v for v in values if '.' not in v]
4847 items = [v for v in values if '.' in v]
4847 items = [v for v in values if '.' in v]
4848 if len(items) > 1 or items and sections:
4848 if len(items) > 1 or items and sections:
4849 raise util.Abort(_('only one config item permitted'))
4849 raise util.Abort(_('only one config item permitted'))
4850 for section, name, value in ui.walkconfig(untrusted=untrusted):
4850 for section, name, value in ui.walkconfig(untrusted=untrusted):
4851 value = str(value).replace('\n', '\\n')
4851 value = str(value).replace('\n', '\\n')
4852 sectname = section + '.' + name
4852 sectname = section + '.' + name
4853 if values:
4853 if values:
4854 for v in values:
4854 for v in values:
4855 if v == section:
4855 if v == section:
4856 ui.debug('%s: ' %
4856 ui.debug('%s: ' %
4857 ui.configsource(section, name, untrusted))
4857 ui.configsource(section, name, untrusted))
4858 ui.write('%s=%s\n' % (sectname, value))
4858 ui.write('%s=%s\n' % (sectname, value))
4859 elif v == sectname:
4859 elif v == sectname:
4860 ui.debug('%s: ' %
4860 ui.debug('%s: ' %
4861 ui.configsource(section, name, untrusted))
4861 ui.configsource(section, name, untrusted))
4862 ui.write(value, '\n')
4862 ui.write(value, '\n')
4863 else:
4863 else:
4864 ui.debug('%s: ' %
4864 ui.debug('%s: ' %
4865 ui.configsource(section, name, untrusted))
4865 ui.configsource(section, name, untrusted))
4866 ui.write('%s=%s\n' % (sectname, value))
4866 ui.write('%s=%s\n' % (sectname, value))
4867
4867
4868 @command('^status|st',
4868 @command('^status|st',
4869 [('A', 'all', None, _('show status of all files')),
4869 [('A', 'all', None, _('show status of all files')),
4870 ('m', 'modified', None, _('show only modified files')),
4870 ('m', 'modified', None, _('show only modified files')),
4871 ('a', 'added', None, _('show only added files')),
4871 ('a', 'added', None, _('show only added files')),
4872 ('r', 'removed', None, _('show only removed files')),
4872 ('r', 'removed', None, _('show only removed files')),
4873 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4873 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4874 ('c', 'clean', None, _('show only files without changes')),
4874 ('c', 'clean', None, _('show only files without changes')),
4875 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4875 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4876 ('i', 'ignored', None, _('show only ignored files')),
4876 ('i', 'ignored', None, _('show only ignored files')),
4877 ('n', 'no-status', None, _('hide status prefix')),
4877 ('n', 'no-status', None, _('hide status prefix')),
4878 ('C', 'copies', None, _('show source of copied files')),
4878 ('C', 'copies', None, _('show source of copied files')),
4879 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4879 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4880 ('', 'rev', [], _('show difference from revision'), _('REV')),
4880 ('', 'rev', [], _('show difference from revision'), _('REV')),
4881 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4881 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4882 ] + walkopts + subrepoopts,
4882 ] + walkopts + subrepoopts,
4883 _('[OPTION]... [FILE]...'))
4883 _('[OPTION]... [FILE]...'))
4884 def status(ui, repo, *pats, **opts):
4884 def status(ui, repo, *pats, **opts):
4885 """show changed files in the working directory
4885 """show changed files in the working directory
4886
4886
4887 Show status of files in the repository. If names are given, only
4887 Show status of files in the repository. If names are given, only
4888 files that match are shown. Files that are clean or ignored or
4888 files that match are shown. Files that are clean or ignored or
4889 the source of a copy/move operation, are not listed unless
4889 the source of a copy/move operation, are not listed unless
4890 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4890 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4891 Unless options described with "show only ..." are given, the
4891 Unless options described with "show only ..." are given, the
4892 options -mardu are used.
4892 options -mardu are used.
4893
4893
4894 Option -q/--quiet hides untracked (unknown and ignored) files
4894 Option -q/--quiet hides untracked (unknown and ignored) files
4895 unless explicitly requested with -u/--unknown or -i/--ignored.
4895 unless explicitly requested with -u/--unknown or -i/--ignored.
4896
4896
4897 .. note::
4897 .. note::
4898 status may appear to disagree with diff if permissions have
4898 status may appear to disagree with diff if permissions have
4899 changed or a merge has occurred. The standard diff format does
4899 changed or a merge has occurred. The standard diff format does
4900 not report permission changes and diff only reports changes
4900 not report permission changes and diff only reports changes
4901 relative to one merge parent.
4901 relative to one merge parent.
4902
4902
4903 If one revision is given, it is used as the base revision.
4903 If one revision is given, it is used as the base revision.
4904 If two revisions are given, the differences between them are
4904 If two revisions are given, the differences between them are
4905 shown. The --change option can also be used as a shortcut to list
4905 shown. The --change option can also be used as a shortcut to list
4906 the changed files of a revision from its first parent.
4906 the changed files of a revision from its first parent.
4907
4907
4908 The codes used to show the status of files are::
4908 The codes used to show the status of files are::
4909
4909
4910 M = modified
4910 M = modified
4911 A = added
4911 A = added
4912 R = removed
4912 R = removed
4913 C = clean
4913 C = clean
4914 ! = missing (deleted by non-hg command, but still tracked)
4914 ! = missing (deleted by non-hg command, but still tracked)
4915 ? = not tracked
4915 ? = not tracked
4916 I = ignored
4916 I = ignored
4917 = origin of the previous file listed as A (added)
4917 = origin of the previous file listed as A (added)
4918
4918
4919 .. container:: verbose
4919 .. container:: verbose
4920
4920
4921 Examples:
4921 Examples:
4922
4922
4923 - show changes in the working directory relative to a changeset:
4923 - show changes in the working directory relative to a changeset:
4924
4924
4925 hg status --rev 9353
4925 hg status --rev 9353
4926
4926
4927 - show all changes including copies in an existing changeset::
4927 - show all changes including copies in an existing changeset::
4928
4928
4929 hg status --copies --change 9353
4929 hg status --copies --change 9353
4930
4930
4931 - get a NUL separated list of added files, suitable for xargs::
4931 - get a NUL separated list of added files, suitable for xargs::
4932
4932
4933 hg status -an0
4933 hg status -an0
4934
4934
4935 Returns 0 on success.
4935 Returns 0 on success.
4936 """
4936 """
4937
4937
4938 revs = opts.get('rev')
4938 revs = opts.get('rev')
4939 change = opts.get('change')
4939 change = opts.get('change')
4940
4940
4941 if revs and change:
4941 if revs and change:
4942 msg = _('cannot specify --rev and --change at the same time')
4942 msg = _('cannot specify --rev and --change at the same time')
4943 raise util.Abort(msg)
4943 raise util.Abort(msg)
4944 elif change:
4944 elif change:
4945 node2 = repo.lookup(change)
4945 node2 = repo.lookup(change)
4946 node1 = repo[node2].p1().node()
4946 node1 = repo[node2].p1().node()
4947 else:
4947 else:
4948 node1, node2 = scmutil.revpair(repo, revs)
4948 node1, node2 = scmutil.revpair(repo, revs)
4949
4949
4950 cwd = (pats and repo.getcwd()) or ''
4950 cwd = (pats and repo.getcwd()) or ''
4951 end = opts.get('print0') and '\0' or '\n'
4951 end = opts.get('print0') and '\0' or '\n'
4952 copy = {}
4952 copy = {}
4953 states = 'modified added removed deleted unknown ignored clean'.split()
4953 states = 'modified added removed deleted unknown ignored clean'.split()
4954 show = [k for k in states if opts.get(k)]
4954 show = [k for k in states if opts.get(k)]
4955 if opts.get('all'):
4955 if opts.get('all'):
4956 show += ui.quiet and (states[:4] + ['clean']) or states
4956 show += ui.quiet and (states[:4] + ['clean']) or states
4957 if not show:
4957 if not show:
4958 show = ui.quiet and states[:4] or states[:5]
4958 show = ui.quiet and states[:4] or states[:5]
4959
4959
4960 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
4960 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
4961 'ignored' in show, 'clean' in show, 'unknown' in show,
4961 'ignored' in show, 'clean' in show, 'unknown' in show,
4962 opts.get('subrepos'))
4962 opts.get('subrepos'))
4963 changestates = zip(states, 'MAR!?IC', stat)
4963 changestates = zip(states, 'MAR!?IC', stat)
4964
4964
4965 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4965 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4966 ctxn = repo[nullid]
4966 ctxn = repo[nullid]
4967 ctx1 = repo[node1]
4967 ctx1 = repo[node1]
4968 ctx2 = repo[node2]
4968 ctx2 = repo[node2]
4969 added = stat[1]
4969 added = stat[1]
4970 if node2 is None:
4970 if node2 is None:
4971 added = stat[0] + stat[1] # merged?
4971 added = stat[0] + stat[1] # merged?
4972
4972
4973 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4973 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4974 if k in added:
4974 if k in added:
4975 copy[k] = v
4975 copy[k] = v
4976 elif v in added:
4976 elif v in added:
4977 copy[v] = k
4977 copy[v] = k
4978
4978
4979 for state, char, files in changestates:
4979 for state, char, files in changestates:
4980 if state in show:
4980 if state in show:
4981 format = "%s %%s%s" % (char, end)
4981 format = "%s %%s%s" % (char, end)
4982 if opts.get('no_status'):
4982 if opts.get('no_status'):
4983 format = "%%s%s" % end
4983 format = "%%s%s" % end
4984
4984
4985 for f in files:
4985 for f in files:
4986 ui.write(format % repo.pathto(f, cwd),
4986 ui.write(format % repo.pathto(f, cwd),
4987 label='status.' + state)
4987 label='status.' + state)
4988 if f in copy:
4988 if f in copy:
4989 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4989 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4990 label='status.copied')
4990 label='status.copied')
4991
4991
4992 @command('^summary|sum',
4992 @command('^summary|sum',
4993 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4993 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4994 def summary(ui, repo, **opts):
4994 def summary(ui, repo, **opts):
4995 """summarize working directory state
4995 """summarize working directory state
4996
4996
4997 This generates a brief summary of the working directory state,
4997 This generates a brief summary of the working directory state,
4998 including parents, branch, commit status, and available updates.
4998 including parents, branch, commit status, and available updates.
4999
4999
5000 With the --remote option, this will check the default paths for
5000 With the --remote option, this will check the default paths for
5001 incoming and outgoing changes. This can be time-consuming.
5001 incoming and outgoing changes. This can be time-consuming.
5002
5002
5003 Returns 0 on success.
5003 Returns 0 on success.
5004 """
5004 """
5005
5005
5006 ctx = repo[None]
5006 ctx = repo[None]
5007 parents = ctx.parents()
5007 parents = ctx.parents()
5008 pnode = parents[0].node()
5008 pnode = parents[0].node()
5009 marks = []
5009 marks = []
5010
5010
5011 for p in parents:
5011 for p in parents:
5012 # label with log.changeset (instead of log.parent) since this
5012 # label with log.changeset (instead of log.parent) since this
5013 # shows a working directory parent *changeset*:
5013 # shows a working directory parent *changeset*:
5014 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5014 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5015 label='log.changeset')
5015 label='log.changeset')
5016 ui.write(' '.join(p.tags()), label='log.tag')
5016 ui.write(' '.join(p.tags()), label='log.tag')
5017 if p.bookmarks():
5017 if p.bookmarks():
5018 marks.extend(p.bookmarks())
5018 marks.extend(p.bookmarks())
5019 if p.rev() == -1:
5019 if p.rev() == -1:
5020 if not len(repo):
5020 if not len(repo):
5021 ui.write(_(' (empty repository)'))
5021 ui.write(_(' (empty repository)'))
5022 else:
5022 else:
5023 ui.write(_(' (no revision checked out)'))
5023 ui.write(_(' (no revision checked out)'))
5024 ui.write('\n')
5024 ui.write('\n')
5025 if p.description():
5025 if p.description():
5026 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5026 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5027 label='log.summary')
5027 label='log.summary')
5028
5028
5029 branch = ctx.branch()
5029 branch = ctx.branch()
5030 bheads = repo.branchheads(branch)
5030 bheads = repo.branchheads(branch)
5031 m = _('branch: %s\n') % branch
5031 m = _('branch: %s\n') % branch
5032 if branch != 'default':
5032 if branch != 'default':
5033 ui.write(m, label='log.branch')
5033 ui.write(m, label='log.branch')
5034 else:
5034 else:
5035 ui.status(m, label='log.branch')
5035 ui.status(m, label='log.branch')
5036
5036
5037 if marks:
5037 if marks:
5038 current = repo._bookmarkcurrent
5038 current = repo._bookmarkcurrent
5039 ui.write(_('bookmarks:'), label='log.bookmark')
5039 ui.write(_('bookmarks:'), label='log.bookmark')
5040 if current is not None:
5040 if current is not None:
5041 try:
5041 try:
5042 marks.remove(current)
5042 marks.remove(current)
5043 ui.write(' *' + current, label='bookmarks.current')
5043 ui.write(' *' + current, label='bookmarks.current')
5044 except ValueError:
5044 except ValueError:
5045 # current bookmark not in parent ctx marks
5045 # current bookmark not in parent ctx marks
5046 pass
5046 pass
5047 for m in marks:
5047 for m in marks:
5048 ui.write(' ' + m, label='log.bookmark')
5048 ui.write(' ' + m, label='log.bookmark')
5049 ui.write('\n', label='log.bookmark')
5049 ui.write('\n', label='log.bookmark')
5050
5050
5051 st = list(repo.status(unknown=True))[:6]
5051 st = list(repo.status(unknown=True))[:6]
5052
5052
5053 c = repo.dirstate.copies()
5053 c = repo.dirstate.copies()
5054 copied, renamed = [], []
5054 copied, renamed = [], []
5055 for d, s in c.iteritems():
5055 for d, s in c.iteritems():
5056 if s in st[2]:
5056 if s in st[2]:
5057 st[2].remove(s)
5057 st[2].remove(s)
5058 renamed.append(d)
5058 renamed.append(d)
5059 else:
5059 else:
5060 copied.append(d)
5060 copied.append(d)
5061 if d in st[1]:
5061 if d in st[1]:
5062 st[1].remove(d)
5062 st[1].remove(d)
5063 st.insert(3, renamed)
5063 st.insert(3, renamed)
5064 st.insert(4, copied)
5064 st.insert(4, copied)
5065
5065
5066 ms = mergemod.mergestate(repo)
5066 ms = mergemod.mergestate(repo)
5067 st.append([f for f in ms if ms[f] == 'u'])
5067 st.append([f for f in ms if ms[f] == 'u'])
5068
5068
5069 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5069 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5070 st.append(subs)
5070 st.append(subs)
5071
5071
5072 labels = [ui.label(_('%d modified'), 'status.modified'),
5072 labels = [ui.label(_('%d modified'), 'status.modified'),
5073 ui.label(_('%d added'), 'status.added'),
5073 ui.label(_('%d added'), 'status.added'),
5074 ui.label(_('%d removed'), 'status.removed'),
5074 ui.label(_('%d removed'), 'status.removed'),
5075 ui.label(_('%d renamed'), 'status.copied'),
5075 ui.label(_('%d renamed'), 'status.copied'),
5076 ui.label(_('%d copied'), 'status.copied'),
5076 ui.label(_('%d copied'), 'status.copied'),
5077 ui.label(_('%d deleted'), 'status.deleted'),
5077 ui.label(_('%d deleted'), 'status.deleted'),
5078 ui.label(_('%d unknown'), 'status.unknown'),
5078 ui.label(_('%d unknown'), 'status.unknown'),
5079 ui.label(_('%d ignored'), 'status.ignored'),
5079 ui.label(_('%d ignored'), 'status.ignored'),
5080 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5080 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5081 ui.label(_('%d subrepos'), 'status.modified')]
5081 ui.label(_('%d subrepos'), 'status.modified')]
5082 t = []
5082 t = []
5083 for s, l in zip(st, labels):
5083 for s, l in zip(st, labels):
5084 if s:
5084 if s:
5085 t.append(l % len(s))
5085 t.append(l % len(s))
5086
5086
5087 t = ', '.join(t)
5087 t = ', '.join(t)
5088 cleanworkdir = False
5088 cleanworkdir = False
5089
5089
5090 if len(parents) > 1:
5090 if len(parents) > 1:
5091 t += _(' (merge)')
5091 t += _(' (merge)')
5092 elif branch != parents[0].branch():
5092 elif branch != parents[0].branch():
5093 t += _(' (new branch)')
5093 t += _(' (new branch)')
5094 elif (parents[0].extra().get('close') and
5094 elif (parents[0].extra().get('close') and
5095 pnode in repo.branchheads(branch, closed=True)):
5095 pnode in repo.branchheads(branch, closed=True)):
5096 t += _(' (head closed)')
5096 t += _(' (head closed)')
5097 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5097 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5098 t += _(' (clean)')
5098 t += _(' (clean)')
5099 cleanworkdir = True
5099 cleanworkdir = True
5100 elif pnode not in bheads:
5100 elif pnode not in bheads:
5101 t += _(' (new branch head)')
5101 t += _(' (new branch head)')
5102
5102
5103 if cleanworkdir:
5103 if cleanworkdir:
5104 ui.status(_('commit: %s\n') % t.strip())
5104 ui.status(_('commit: %s\n') % t.strip())
5105 else:
5105 else:
5106 ui.write(_('commit: %s\n') % t.strip())
5106 ui.write(_('commit: %s\n') % t.strip())
5107
5107
5108 # all ancestors of branch heads - all ancestors of parent = new csets
5108 # all ancestors of branch heads - all ancestors of parent = new csets
5109 new = [0] * len(repo)
5109 new = [0] * len(repo)
5110 cl = repo.changelog
5110 cl = repo.changelog
5111 for a in [cl.rev(n) for n in bheads]:
5111 for a in [cl.rev(n) for n in bheads]:
5112 new[a] = 1
5112 new[a] = 1
5113 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5113 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5114 new[a] = 1
5114 new[a] = 1
5115 for a in [p.rev() for p in parents]:
5115 for a in [p.rev() for p in parents]:
5116 if a >= 0:
5116 if a >= 0:
5117 new[a] = 0
5117 new[a] = 0
5118 for a in cl.ancestors(*[p.rev() for p in parents]):
5118 for a in cl.ancestors(*[p.rev() for p in parents]):
5119 new[a] = 0
5119 new[a] = 0
5120 new = sum(new)
5120 new = sum(new)
5121
5121
5122 if new == 0:
5122 if new == 0:
5123 ui.status(_('update: (current)\n'))
5123 ui.status(_('update: (current)\n'))
5124 elif pnode not in bheads:
5124 elif pnode not in bheads:
5125 ui.write(_('update: %d new changesets (update)\n') % new)
5125 ui.write(_('update: %d new changesets (update)\n') % new)
5126 else:
5126 else:
5127 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5127 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5128 (new, len(bheads)))
5128 (new, len(bheads)))
5129
5129
5130 if opts.get('remote'):
5130 if opts.get('remote'):
5131 t = []
5131 t = []
5132 source, branches = hg.parseurl(ui.expandpath('default'))
5132 source, branches = hg.parseurl(ui.expandpath('default'))
5133 other = hg.peer(repo, {}, source)
5133 other = hg.peer(repo, {}, source)
5134 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5134 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5135 ui.debug('comparing with %s\n' % util.hidepassword(source))
5135 ui.debug('comparing with %s\n' % util.hidepassword(source))
5136 repo.ui.pushbuffer()
5136 repo.ui.pushbuffer()
5137 commoninc = discovery.findcommonincoming(repo, other)
5137 commoninc = discovery.findcommonincoming(repo, other)
5138 _common, incoming, _rheads = commoninc
5138 _common, incoming, _rheads = commoninc
5139 repo.ui.popbuffer()
5139 repo.ui.popbuffer()
5140 if incoming:
5140 if incoming:
5141 t.append(_('1 or more incoming'))
5141 t.append(_('1 or more incoming'))
5142
5142
5143 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5143 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5144 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5144 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5145 if source != dest:
5145 if source != dest:
5146 other = hg.peer(repo, {}, dest)
5146 other = hg.peer(repo, {}, dest)
5147 commoninc = None
5147 commoninc = None
5148 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5148 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5149 repo.ui.pushbuffer()
5149 repo.ui.pushbuffer()
5150 common, outheads = discovery.findcommonoutgoing(repo, other,
5150 common, outheads = discovery.findcommonoutgoing(repo, other,
5151 commoninc=commoninc)
5151 commoninc=commoninc)
5152 repo.ui.popbuffer()
5152 repo.ui.popbuffer()
5153 o = repo.changelog.findmissing(common=common, heads=outheads)
5153 o = repo.changelog.findmissing(common=common, heads=outheads)
5154 if o:
5154 if o:
5155 t.append(_('%d outgoing') % len(o))
5155 t.append(_('%d outgoing') % len(o))
5156 if 'bookmarks' in other.listkeys('namespaces'):
5156 if 'bookmarks' in other.listkeys('namespaces'):
5157 lmarks = repo.listkeys('bookmarks')
5157 lmarks = repo.listkeys('bookmarks')
5158 rmarks = other.listkeys('bookmarks')
5158 rmarks = other.listkeys('bookmarks')
5159 diff = set(rmarks) - set(lmarks)
5159 diff = set(rmarks) - set(lmarks)
5160 if len(diff) > 0:
5160 if len(diff) > 0:
5161 t.append(_('%d incoming bookmarks') % len(diff))
5161 t.append(_('%d incoming bookmarks') % len(diff))
5162 diff = set(lmarks) - set(rmarks)
5162 diff = set(lmarks) - set(rmarks)
5163 if len(diff) > 0:
5163 if len(diff) > 0:
5164 t.append(_('%d outgoing bookmarks') % len(diff))
5164 t.append(_('%d outgoing bookmarks') % len(diff))
5165
5165
5166 if t:
5166 if t:
5167 ui.write(_('remote: %s\n') % (', '.join(t)))
5167 ui.write(_('remote: %s\n') % (', '.join(t)))
5168 else:
5168 else:
5169 ui.status(_('remote: (synced)\n'))
5169 ui.status(_('remote: (synced)\n'))
5170
5170
5171 @command('tag',
5171 @command('tag',
5172 [('f', 'force', None, _('force tag')),
5172 [('f', 'force', None, _('force tag')),
5173 ('l', 'local', None, _('make the tag local')),
5173 ('l', 'local', None, _('make the tag local')),
5174 ('r', 'rev', '', _('revision to tag'), _('REV')),
5174 ('r', 'rev', '', _('revision to tag'), _('REV')),
5175 ('', 'remove', None, _('remove a tag')),
5175 ('', 'remove', None, _('remove a tag')),
5176 # -l/--local is already there, commitopts cannot be used
5176 # -l/--local is already there, commitopts cannot be used
5177 ('e', 'edit', None, _('edit commit message')),
5177 ('e', 'edit', None, _('edit commit message')),
5178 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5178 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5179 ] + commitopts2,
5179 ] + commitopts2,
5180 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5180 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5181 def tag(ui, repo, name1, *names, **opts):
5181 def tag(ui, repo, name1, *names, **opts):
5182 """add one or more tags for the current or given revision
5182 """add one or more tags for the current or given revision
5183
5183
5184 Name a particular revision using <name>.
5184 Name a particular revision using <name>.
5185
5185
5186 Tags are used to name particular revisions of the repository and are
5186 Tags are used to name particular revisions of the repository and are
5187 very useful to compare different revisions, to go back to significant
5187 very useful to compare different revisions, to go back to significant
5188 earlier versions or to mark branch points as releases, etc. Changing
5188 earlier versions or to mark branch points as releases, etc. Changing
5189 an existing tag is normally disallowed; use -f/--force to override.
5189 an existing tag is normally disallowed; use -f/--force to override.
5190
5190
5191 If no revision is given, the parent of the working directory is
5191 If no revision is given, the parent of the working directory is
5192 used, or tip if no revision is checked out.
5192 used, or tip if no revision is checked out.
5193
5193
5194 To facilitate version control, distribution, and merging of tags,
5194 To facilitate version control, distribution, and merging of tags,
5195 they are stored as a file named ".hgtags" which is managed similarly
5195 they are stored as a file named ".hgtags" which is managed similarly
5196 to other project files and can be hand-edited if necessary. This
5196 to other project files and can be hand-edited if necessary. This
5197 also means that tagging creates a new commit. The file
5197 also means that tagging creates a new commit. The file
5198 ".hg/localtags" is used for local tags (not shared among
5198 ".hg/localtags" is used for local tags (not shared among
5199 repositories).
5199 repositories).
5200
5200
5201 Tag commits are usually made at the head of a branch. If the parent
5201 Tag commits are usually made at the head of a branch. If the parent
5202 of the working directory is not a branch head, :hg:`tag` aborts; use
5202 of the working directory is not a branch head, :hg:`tag` aborts; use
5203 -f/--force to force the tag commit to be based on a non-head
5203 -f/--force to force the tag commit to be based on a non-head
5204 changeset.
5204 changeset.
5205
5205
5206 See :hg:`help dates` for a list of formats valid for -d/--date.
5206 See :hg:`help dates` for a list of formats valid for -d/--date.
5207
5207
5208 Since tag names have priority over branch names during revision
5208 Since tag names have priority over branch names during revision
5209 lookup, using an existing branch name as a tag name is discouraged.
5209 lookup, using an existing branch name as a tag name is discouraged.
5210
5210
5211 Returns 0 on success.
5211 Returns 0 on success.
5212 """
5212 """
5213
5213
5214 rev_ = "."
5214 rev_ = "."
5215 names = [t.strip() for t in (name1,) + names]
5215 names = [t.strip() for t in (name1,) + names]
5216 if len(names) != len(set(names)):
5216 if len(names) != len(set(names)):
5217 raise util.Abort(_('tag names must be unique'))
5217 raise util.Abort(_('tag names must be unique'))
5218 for n in names:
5218 for n in names:
5219 if n in ['tip', '.', 'null']:
5219 if n in ['tip', '.', 'null']:
5220 raise util.Abort(_("the name '%s' is reserved") % n)
5220 raise util.Abort(_("the name '%s' is reserved") % n)
5221 if not n:
5221 if not n:
5222 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
5222 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
5223 if opts.get('rev') and opts.get('remove'):
5223 if opts.get('rev') and opts.get('remove'):
5224 raise util.Abort(_("--rev and --remove are incompatible"))
5224 raise util.Abort(_("--rev and --remove are incompatible"))
5225 if opts.get('rev'):
5225 if opts.get('rev'):
5226 rev_ = opts['rev']
5226 rev_ = opts['rev']
5227 message = opts.get('message')
5227 message = opts.get('message')
5228 if opts.get('remove'):
5228 if opts.get('remove'):
5229 expectedtype = opts.get('local') and 'local' or 'global'
5229 expectedtype = opts.get('local') and 'local' or 'global'
5230 for n in names:
5230 for n in names:
5231 if not repo.tagtype(n):
5231 if not repo.tagtype(n):
5232 raise util.Abort(_("tag '%s' does not exist") % n)
5232 raise util.Abort(_("tag '%s' does not exist") % n)
5233 if repo.tagtype(n) != expectedtype:
5233 if repo.tagtype(n) != expectedtype:
5234 if expectedtype == 'global':
5234 if expectedtype == 'global':
5235 raise util.Abort(_("tag '%s' is not a global tag") % n)
5235 raise util.Abort(_("tag '%s' is not a global tag") % n)
5236 else:
5236 else:
5237 raise util.Abort(_("tag '%s' is not a local tag") % n)
5237 raise util.Abort(_("tag '%s' is not a local tag") % n)
5238 rev_ = nullid
5238 rev_ = nullid
5239 if not message:
5239 if not message:
5240 # we don't translate commit messages
5240 # we don't translate commit messages
5241 message = 'Removed tag %s' % ', '.join(names)
5241 message = 'Removed tag %s' % ', '.join(names)
5242 elif not opts.get('force'):
5242 elif not opts.get('force'):
5243 for n in names:
5243 for n in names:
5244 if n in repo.tags():
5244 if n in repo.tags():
5245 raise util.Abort(_("tag '%s' already exists "
5245 raise util.Abort(_("tag '%s' already exists "
5246 "(use -f to force)") % n)
5246 "(use -f to force)") % n)
5247 if not opts.get('local'):
5247 if not opts.get('local'):
5248 p1, p2 = repo.dirstate.parents()
5248 p1, p2 = repo.dirstate.parents()
5249 if p2 != nullid:
5249 if p2 != nullid:
5250 raise util.Abort(_('uncommitted merge'))
5250 raise util.Abort(_('uncommitted merge'))
5251 bheads = repo.branchheads()
5251 bheads = repo.branchheads()
5252 if not opts.get('force') and bheads and p1 not in bheads:
5252 if not opts.get('force') and bheads and p1 not in bheads:
5253 raise util.Abort(_('not at a branch head (use -f to force)'))
5253 raise util.Abort(_('not at a branch head (use -f to force)'))
5254 r = scmutil.revsingle(repo, rev_).node()
5254 r = scmutil.revsingle(repo, rev_).node()
5255
5255
5256 if not message:
5256 if not message:
5257 # we don't translate commit messages
5257 # we don't translate commit messages
5258 message = ('Added tag %s for changeset %s' %
5258 message = ('Added tag %s for changeset %s' %
5259 (', '.join(names), short(r)))
5259 (', '.join(names), short(r)))
5260
5260
5261 date = opts.get('date')
5261 date = opts.get('date')
5262 if date:
5262 if date:
5263 date = util.parsedate(date)
5263 date = util.parsedate(date)
5264
5264
5265 if opts.get('edit'):
5265 if opts.get('edit'):
5266 message = ui.edit(message, ui.username())
5266 message = ui.edit(message, ui.username())
5267
5267
5268 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5268 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5269
5269
5270 @command('tags', [], '')
5270 @command('tags', [], '')
5271 def tags(ui, repo):
5271 def tags(ui, repo):
5272 """list repository tags
5272 """list repository tags
5273
5273
5274 This lists both regular and local tags. When the -v/--verbose
5274 This lists both regular and local tags. When the -v/--verbose
5275 switch is used, a third column "local" is printed for local tags.
5275 switch is used, a third column "local" is printed for local tags.
5276
5276
5277 Returns 0 on success.
5277 Returns 0 on success.
5278 """
5278 """
5279
5279
5280 hexfunc = ui.debugflag and hex or short
5280 hexfunc = ui.debugflag and hex or short
5281 tagtype = ""
5281 tagtype = ""
5282
5282
5283 for t, n in reversed(repo.tagslist()):
5283 for t, n in reversed(repo.tagslist()):
5284 if ui.quiet:
5284 if ui.quiet:
5285 ui.write("%s\n" % t, label='tags.normal')
5285 ui.write("%s\n" % t, label='tags.normal')
5286 continue
5286 continue
5287
5287
5288 hn = hexfunc(n)
5288 hn = hexfunc(n)
5289 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5289 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5290 rev = ui.label(r, 'log.changeset')
5290 rev = ui.label(r, 'log.changeset')
5291 spaces = " " * (30 - encoding.colwidth(t))
5291 spaces = " " * (30 - encoding.colwidth(t))
5292
5292
5293 tag = ui.label(t, 'tags.normal')
5293 tag = ui.label(t, 'tags.normal')
5294 if ui.verbose:
5294 if ui.verbose:
5295 if repo.tagtype(t) == 'local':
5295 if repo.tagtype(t) == 'local':
5296 tagtype = " local"
5296 tagtype = " local"
5297 tag = ui.label(t, 'tags.local')
5297 tag = ui.label(t, 'tags.local')
5298 else:
5298 else:
5299 tagtype = ""
5299 tagtype = ""
5300 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5300 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5301
5301
5302 @command('tip',
5302 @command('tip',
5303 [('p', 'patch', None, _('show patch')),
5303 [('p', 'patch', None, _('show patch')),
5304 ('g', 'git', None, _('use git extended diff format')),
5304 ('g', 'git', None, _('use git extended diff format')),
5305 ] + templateopts,
5305 ] + templateopts,
5306 _('[-p] [-g]'))
5306 _('[-p] [-g]'))
5307 def tip(ui, repo, **opts):
5307 def tip(ui, repo, **opts):
5308 """show the tip revision
5308 """show the tip revision
5309
5309
5310 The tip revision (usually just called the tip) is the changeset
5310 The tip revision (usually just called the tip) is the changeset
5311 most recently added to the repository (and therefore the most
5311 most recently added to the repository (and therefore the most
5312 recently changed head).
5312 recently changed head).
5313
5313
5314 If you have just made a commit, that commit will be the tip. If
5314 If you have just made a commit, that commit will be the tip. If
5315 you have just pulled changes from another repository, the tip of
5315 you have just pulled changes from another repository, the tip of
5316 that repository becomes the current tip. The "tip" tag is special
5316 that repository becomes the current tip. The "tip" tag is special
5317 and cannot be renamed or assigned to a different changeset.
5317 and cannot be renamed or assigned to a different changeset.
5318
5318
5319 Returns 0 on success.
5319 Returns 0 on success.
5320 """
5320 """
5321 displayer = cmdutil.show_changeset(ui, repo, opts)
5321 displayer = cmdutil.show_changeset(ui, repo, opts)
5322 displayer.show(repo[len(repo) - 1])
5322 displayer.show(repo[len(repo) - 1])
5323 displayer.close()
5323 displayer.close()
5324
5324
5325 @command('unbundle',
5325 @command('unbundle',
5326 [('u', 'update', None,
5326 [('u', 'update', None,
5327 _('update to new branch head if changesets were unbundled'))],
5327 _('update to new branch head if changesets were unbundled'))],
5328 _('[-u] FILE...'))
5328 _('[-u] FILE...'))
5329 def unbundle(ui, repo, fname1, *fnames, **opts):
5329 def unbundle(ui, repo, fname1, *fnames, **opts):
5330 """apply one or more changegroup files
5330 """apply one or more changegroup files
5331
5331
5332 Apply one or more compressed changegroup files generated by the
5332 Apply one or more compressed changegroup files generated by the
5333 bundle command.
5333 bundle command.
5334
5334
5335 Returns 0 on success, 1 if an update has unresolved files.
5335 Returns 0 on success, 1 if an update has unresolved files.
5336 """
5336 """
5337 fnames = (fname1,) + fnames
5337 fnames = (fname1,) + fnames
5338
5338
5339 lock = repo.lock()
5339 lock = repo.lock()
5340 wc = repo['.']
5340 wc = repo['.']
5341 try:
5341 try:
5342 for fname in fnames:
5342 for fname in fnames:
5343 f = url.open(ui, fname)
5343 f = url.open(ui, fname)
5344 gen = changegroup.readbundle(f, fname)
5344 gen = changegroup.readbundle(f, fname)
5345 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5345 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5346 lock=lock)
5346 lock=lock)
5347 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5347 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5348 finally:
5348 finally:
5349 lock.release()
5349 lock.release()
5350 return postincoming(ui, repo, modheads, opts.get('update'), None)
5350 return postincoming(ui, repo, modheads, opts.get('update'), None)
5351
5351
5352 @command('^update|up|checkout|co',
5352 @command('^update|up|checkout|co',
5353 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5353 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5354 ('c', 'check', None,
5354 ('c', 'check', None,
5355 _('update across branches if no uncommitted changes')),
5355 _('update across branches if no uncommitted changes')),
5356 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5356 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5357 ('r', 'rev', '', _('revision'), _('REV'))],
5357 ('r', 'rev', '', _('revision'), _('REV'))],
5358 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5358 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5359 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5359 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5360 """update working directory (or switch revisions)
5360 """update working directory (or switch revisions)
5361
5361
5362 Update the repository's working directory to the specified
5362 Update the repository's working directory to the specified
5363 changeset. If no changeset is specified, update to the tip of the
5363 changeset. If no changeset is specified, update to the tip of the
5364 current named branch.
5364 current named branch.
5365
5365
5366 If the changeset is not a descendant of the working directory's
5366 If the changeset is not a descendant of the working directory's
5367 parent, the update is aborted. With the -c/--check option, the
5367 parent, the update is aborted. With the -c/--check option, the
5368 working directory is checked for uncommitted changes; if none are
5368 working directory is checked for uncommitted changes; if none are
5369 found, the working directory is updated to the specified
5369 found, the working directory is updated to the specified
5370 changeset.
5370 changeset.
5371
5371
5372 Update sets the working directory's parent revison to the specified
5372 Update sets the working directory's parent revison to the specified
5373 changeset (see :hg:`help parents`).
5373 changeset (see :hg:`help parents`).
5374
5374
5375 The following rules apply when the working directory contains
5375 The following rules apply when the working directory contains
5376 uncommitted changes:
5376 uncommitted changes:
5377
5377
5378 1. If neither -c/--check nor -C/--clean is specified, and if
5378 1. If neither -c/--check nor -C/--clean is specified, and if
5379 the requested changeset is an ancestor or descendant of
5379 the requested changeset is an ancestor or descendant of
5380 the working directory's parent, the uncommitted changes
5380 the working directory's parent, the uncommitted changes
5381 are merged into the requested changeset and the merged
5381 are merged into the requested changeset and the merged
5382 result is left uncommitted. If the requested changeset is
5382 result is left uncommitted. If the requested changeset is
5383 not an ancestor or descendant (that is, it is on another
5383 not an ancestor or descendant (that is, it is on another
5384 branch), the update is aborted and the uncommitted changes
5384 branch), the update is aborted and the uncommitted changes
5385 are preserved.
5385 are preserved.
5386
5386
5387 2. With the -c/--check option, the update is aborted and the
5387 2. With the -c/--check option, the update is aborted and the
5388 uncommitted changes are preserved.
5388 uncommitted changes are preserved.
5389
5389
5390 3. With the -C/--clean option, uncommitted changes are discarded and
5390 3. With the -C/--clean option, uncommitted changes are discarded and
5391 the working directory is updated to the requested changeset.
5391 the working directory is updated to the requested changeset.
5392
5392
5393 Use null as the changeset to remove the working directory (like
5393 Use null as the changeset to remove the working directory (like
5394 :hg:`clone -U`).
5394 :hg:`clone -U`).
5395
5395
5396 If you want to revert just one file to an older revision, use
5396 If you want to revert just one file to an older revision, use
5397 :hg:`revert [-r REV] NAME`.
5397 :hg:`revert [-r REV] NAME`.
5398
5398
5399 See :hg:`help dates` for a list of formats valid for -d/--date.
5399 See :hg:`help dates` for a list of formats valid for -d/--date.
5400
5400
5401 Returns 0 on success, 1 if there are unresolved files.
5401 Returns 0 on success, 1 if there are unresolved files.
5402 """
5402 """
5403 if rev and node:
5403 if rev and node:
5404 raise util.Abort(_("please specify just one revision"))
5404 raise util.Abort(_("please specify just one revision"))
5405
5405
5406 if rev is None or rev == '':
5406 if rev is None or rev == '':
5407 rev = node
5407 rev = node
5408
5408
5409 # if we defined a bookmark, we have to remember the original bookmark name
5409 # if we defined a bookmark, we have to remember the original bookmark name
5410 brev = rev
5410 brev = rev
5411 rev = scmutil.revsingle(repo, rev, rev).rev()
5411 rev = scmutil.revsingle(repo, rev, rev).rev()
5412
5412
5413 if check and clean:
5413 if check and clean:
5414 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5414 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5415
5415
5416 if check:
5416 if check:
5417 # we could use dirty() but we can ignore merge and branch trivia
5417 # we could use dirty() but we can ignore merge and branch trivia
5418 c = repo[None]
5418 c = repo[None]
5419 if c.modified() or c.added() or c.removed():
5419 if c.modified() or c.added() or c.removed():
5420 raise util.Abort(_("uncommitted local changes"))
5420 raise util.Abort(_("uncommitted local changes"))
5421
5421
5422 if date:
5422 if date:
5423 if rev is not None:
5423 if rev is not None:
5424 raise util.Abort(_("you can't specify a revision and a date"))
5424 raise util.Abort(_("you can't specify a revision and a date"))
5425 rev = cmdutil.finddate(ui, repo, date)
5425 rev = cmdutil.finddate(ui, repo, date)
5426
5426
5427 if clean or check:
5427 if clean or check:
5428 ret = hg.clean(repo, rev)
5428 ret = hg.clean(repo, rev)
5429 else:
5429 else:
5430 ret = hg.update(repo, rev)
5430 ret = hg.update(repo, rev)
5431
5431
5432 if brev in repo._bookmarks:
5432 if brev in repo._bookmarks:
5433 bookmarks.setcurrent(repo, brev)
5433 bookmarks.setcurrent(repo, brev)
5434
5434
5435 return ret
5435 return ret
5436
5436
5437 @command('verify', [])
5437 @command('verify', [])
5438 def verify(ui, repo):
5438 def verify(ui, repo):
5439 """verify the integrity of the repository
5439 """verify the integrity of the repository
5440
5440
5441 Verify the integrity of the current repository.
5441 Verify the integrity of the current repository.
5442
5442
5443 This will perform an extensive check of the repository's
5443 This will perform an extensive check of the repository's
5444 integrity, validating the hashes and checksums of each entry in
5444 integrity, validating the hashes and checksums of each entry in
5445 the changelog, manifest, and tracked files, as well as the
5445 the changelog, manifest, and tracked files, as well as the
5446 integrity of their crosslinks and indices.
5446 integrity of their crosslinks and indices.
5447
5447
5448 Returns 0 on success, 1 if errors are encountered.
5448 Returns 0 on success, 1 if errors are encountered.
5449 """
5449 """
5450 return hg.verify(repo)
5450 return hg.verify(repo)
5451
5451
5452 @command('version', [])
5452 @command('version', [])
5453 def version_(ui):
5453 def version_(ui):
5454 """output version and copyright information"""
5454 """output version and copyright information"""
5455 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5455 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5456 % util.version())
5456 % util.version())
5457 ui.status(_(
5457 ui.status(_(
5458 "(see http://mercurial.selenic.com for more information)\n"
5458 "(see http://mercurial.selenic.com for more information)\n"
5459 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5459 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5460 "This is free software; see the source for copying conditions. "
5460 "This is free software; see the source for copying conditions. "
5461 "There is NO\nwarranty; "
5461 "There is NO\nwarranty; "
5462 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5462 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5463 ))
5463 ))
5464
5464
5465 norepo = ("clone init version help debugcommands debugcomplete"
5465 norepo = ("clone init version help debugcommands debugcomplete"
5466 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5466 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5467 " debugknown debuggetbundle debugbundle")
5467 " debugknown debuggetbundle debugbundle")
5468 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5468 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5469 " debugdata debugindex debugindexdot debugrevlog")
5469 " debugdata debugindex debugindexdot debugrevlog")
@@ -1,288 +1,288 b''
1 $ hg init basic
1 $ hg init basic
2 $ cd basic
2 $ cd basic
3
3
4 should complain
4 should complain
5
5
6 $ hg backout
6 $ hg backout
7 abort: please specify a revision to backout
7 abort: please specify a revision to backout
8 [255]
8 [255]
9 $ hg backout -r 0 0
9 $ hg backout -r 0 0
10 abort: please specify just one revision
10 abort: please specify just one revision
11 [255]
11 [255]
12
12
13 basic operation
13 basic operation
14
14
15 $ echo a > a
15 $ echo a > a
16 $ hg commit -d '0 0' -A -m a
16 $ hg commit -d '0 0' -A -m a
17 adding a
17 adding a
18 $ echo b >> a
18 $ echo b >> a
19 $ hg commit -d '1 0' -m b
19 $ hg commit -d '1 0' -m b
20
20
21 $ hg backout -d '2 0' tip --tool=true
21 $ hg backout -d '2 0' tip --tool=true
22 reverting a
22 reverting a
23 changeset 2:2929462c3dff backs out changeset 1:a820f4f40a57
23 changeset 2:2929462c3dff backs out changeset 1:a820f4f40a57
24 $ cat a
24 $ cat a
25 a
25 a
26
26
27 file that was removed is recreated
27 file that was removed is recreated
28
28
29 $ cd ..
29 $ cd ..
30 $ hg init remove
30 $ hg init remove
31 $ cd remove
31 $ cd remove
32
32
33 $ echo content > a
33 $ echo content > a
34 $ hg commit -d '0 0' -A -m a
34 $ hg commit -d '0 0' -A -m a
35 adding a
35 adding a
36
36
37 $ hg rm a
37 $ hg rm a
38 $ hg commit -d '1 0' -m b
38 $ hg commit -d '1 0' -m b
39
39
40 $ hg backout -d '2 0' tip --tool=true
40 $ hg backout -d '2 0' tip --tool=true
41 adding a
41 adding a
42 changeset 2:de31bdc76c0d backs out changeset 1:76862dcce372
42 changeset 2:de31bdc76c0d backs out changeset 1:76862dcce372
43 $ cat a
43 $ cat a
44 content
44 content
45
45
46 backout of backout is as if nothing happened
46 backout of backout is as if nothing happened
47
47
48 $ hg backout -d '3 0' --merge tip --tool=true
48 $ hg backout -d '3 0' --merge tip --tool=true
49 removing a
49 removing a
50 changeset 3:7f6d0f120113 backs out changeset 2:de31bdc76c0d
50 changeset 3:7f6d0f120113 backs out changeset 2:de31bdc76c0d
51 $ cat a 2>/dev/null || echo cat: a: No such file or directory
51 $ cat a 2>/dev/null || echo cat: a: No such file or directory
52 cat: a: No such file or directory
52 cat: a: No such file or directory
53
53
54 across branch
54 across branch
55
55
56 $ cd ..
56 $ cd ..
57 $ hg init branch
57 $ hg init branch
58 $ cd branch
58 $ cd branch
59 $ echo a > a
59 $ echo a > a
60 $ hg ci -Am0
60 $ hg ci -Am0
61 adding a
61 adding a
62 $ echo b > b
62 $ echo b > b
63 $ hg ci -Am1
63 $ hg ci -Am1
64 adding b
64 adding b
65 $ hg co -C 0
65 $ hg co -C 0
66 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
66 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
67
67
68 should fail
68 should fail
69
69
70 $ hg backout 1
70 $ hg backout 1
71 abort: cannot backout change on a different branch
71 abort: cannot backout change on a different branch
72 [255]
72 [255]
73 $ echo c > c
73 $ echo c > c
74 $ hg ci -Am2
74 $ hg ci -Am2
75 adding c
75 adding c
76 created new head
76 created new head
77
77
78 should fail
78 should fail
79
79
80 $ hg backout 1
80 $ hg backout 1
81 abort: cannot backout change on a different branch
81 abort: cannot backout change on a different branch
82 [255]
82 [255]
83
83
84 backout with merge
84 backout with merge
85
85
86 $ cd ..
86 $ cd ..
87 $ hg init merge
87 $ hg init merge
88 $ cd merge
88 $ cd merge
89
89
90 $ echo line 1 > a
90 $ echo line 1 > a
91 $ echo line 2 >> a
91 $ echo line 2 >> a
92 $ hg commit -d '0 0' -A -m a
92 $ hg commit -d '0 0' -A -m a
93 adding a
93 adding a
94
94
95 remove line 1
95 remove line 1
96
96
97 $ echo line 2 > a
97 $ echo line 2 > a
98 $ hg commit -d '1 0' -m b
98 $ hg commit -d '1 0' -m b
99
99
100 $ echo line 3 >> a
100 $ echo line 3 >> a
101 $ hg commit -d '2 0' -m c
101 $ hg commit -d '2 0' -m c
102
102
103 $ hg backout --merge -d '3 0' 1 --tool=true
103 $ hg backout --merge -d '3 0' 1 --tool=true
104 reverting a
104 reverting a
105 created new head
105 created new head
106 changeset 3:26b8ccb9ad91 backs out changeset 1:5a50a024c182
106 changeset 3:26b8ccb9ad91 backs out changeset 1:5a50a024c182
107 merging with changeset 3:26b8ccb9ad91
107 merging with changeset 3:26b8ccb9ad91
108 merging a
108 merging a
109 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
109 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
110 (branch merge, don't forget to commit)
110 (branch merge, don't forget to commit)
111 $ hg commit -d '4 0' -m d
111 $ hg commit -d '4 0' -m d
112
112
113 check line 1 is back
113 check line 1 is back
114
114
115 $ cat a
115 $ cat a
116 line 1
116 line 1
117 line 2
117 line 2
118 line 3
118 line 3
119
119
120 backout should not back out subsequent changesets
120 backout should not back out subsequent changesets
121
121
122 $ hg init onecs
122 $ hg init onecs
123 $ cd onecs
123 $ cd onecs
124 $ echo 1 > a
124 $ echo 1 > a
125 $ hg commit -d '0 0' -A -m a
125 $ hg commit -d '0 0' -A -m a
126 adding a
126 adding a
127 $ echo 2 >> a
127 $ echo 2 >> a
128 $ hg commit -d '1 0' -m b
128 $ hg commit -d '1 0' -m b
129 $ echo 1 > b
129 $ echo 1 > b
130 $ hg commit -d '2 0' -A -m c
130 $ hg commit -d '2 0' -A -m c
131 adding b
131 adding b
132
132
133 without --merge
133 without --merge
134 $ hg backout -d '3 0' 1 --tool=true
134 $ hg backout -d '3 0' 1 --tool=true
135 reverting a
135 reverting a
136 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
136 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
137 $ hg locate b
137 $ hg locate b
138 b
138 b
139 $ hg update -C tip
139 $ hg update -C tip
140 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
140 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
141 $ hg locate b
141 $ hg locate b
142 b
142 b
143
143
144 with --merge
144 with --merge
145 $ hg backout --merge -d '3 0' 1 --tool=true
145 $ hg backout --merge -d '3 0' 1 --tool=true
146 reverting a
146 reverting a
147 created new head
147 created new head
148 changeset 3:3202beb76721 backs out changeset 1:22bca4c721e5
148 changeset 3:3202beb76721 backs out changeset 1:22bca4c721e5
149 merging with changeset 3:3202beb76721
149 merging with changeset 3:3202beb76721
150 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
150 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
151 (branch merge, don't forget to commit)
151 (branch merge, don't forget to commit)
152 $ hg locate b
152 $ hg locate b
153 b
153 b
154 $ hg update -C tip
154 $ hg update -C tip
155 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
155 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
156 $ hg locate b
156 $ hg locate b
157 [1]
157 [1]
158
158
159 $ cd ..
159 $ cd ..
160 $ hg init m
160 $ hg init m
161 $ cd m
161 $ cd m
162 $ echo a > a
162 $ echo a > a
163 $ hg commit -d '0 0' -A -m a
163 $ hg commit -d '0 0' -A -m a
164 adding a
164 adding a
165 $ echo b > b
165 $ echo b > b
166 $ hg commit -d '1 0' -A -m b
166 $ hg commit -d '1 0' -A -m b
167 adding b
167 adding b
168 $ echo c > c
168 $ echo c > c
169 $ hg commit -d '2 0' -A -m b
169 $ hg commit -d '2 0' -A -m b
170 adding c
170 adding c
171 $ hg update 1
171 $ hg update 1
172 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
172 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
173 $ echo d > d
173 $ echo d > d
174 $ hg commit -d '3 0' -A -m c
174 $ hg commit -d '3 0' -A -m c
175 adding d
175 adding d
176 created new head
176 created new head
177 $ hg merge 2
177 $ hg merge 2
178 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
178 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
179 (branch merge, don't forget to commit)
179 (branch merge, don't forget to commit)
180 $ hg commit -d '4 0' -A -m d
180 $ hg commit -d '4 0' -A -m d
181
181
182 backout of merge should fail
182 backout of merge should fail
183
183
184 $ hg backout 4
184 $ hg backout 4
185 abort: cannot backout a merge changeset without --parent
185 abort: cannot backout a merge changeset
186 [255]
186 [255]
187
187
188 backout of merge with bad parent should fail
188 backout of merge with bad parent should fail
189
189
190 $ hg backout --parent 0 4
190 $ hg backout --parent 0 4
191 abort: cb9a9f314b8b is not a parent of b2f3bb92043e
191 abort: cb9a9f314b8b is not a parent of b2f3bb92043e
192 [255]
192 [255]
193
193
194 backout of non-merge with parent should fail
194 backout of non-merge with parent should fail
195
195
196 $ hg backout --parent 0 3
196 $ hg backout --parent 0 3
197 abort: cannot use --parent on non-merge changeset
197 abort: cannot use --parent on non-merge changeset
198 [255]
198 [255]
199
199
200 backout with valid parent should be ok
200 backout with valid parent should be ok
201
201
202 $ hg backout -d '5 0' --parent 2 4 --tool=true
202 $ hg backout -d '5 0' --parent 2 4 --tool=true
203 removing d
203 removing d
204 changeset 5:10e5328c8435 backs out changeset 4:b2f3bb92043e
204 changeset 5:10e5328c8435 backs out changeset 4:b2f3bb92043e
205
205
206 $ hg rollback
206 $ hg rollback
207 repository tip rolled back to revision 4 (undo commit)
207 repository tip rolled back to revision 4 (undo commit)
208 working directory now based on revision 4
208 working directory now based on revision 4
209 $ hg update -C
209 $ hg update -C
210 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
210 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
211
211
212 $ hg backout -d '6 0' --parent 3 4 --tool=true
212 $ hg backout -d '6 0' --parent 3 4 --tool=true
213 removing c
213 removing c
214 changeset 5:033590168430 backs out changeset 4:b2f3bb92043e
214 changeset 5:033590168430 backs out changeset 4:b2f3bb92043e
215
215
216 $ cd ..
216 $ cd ..
217
217
218 named branches
218 named branches
219
219
220 $ hg init named_branches
220 $ hg init named_branches
221 $ cd named_branches
221 $ cd named_branches
222
222
223 $ echo default > default
223 $ echo default > default
224 $ hg ci -d '0 0' -Am default
224 $ hg ci -d '0 0' -Am default
225 adding default
225 adding default
226 $ hg branch branch1
226 $ hg branch branch1
227 marked working directory as branch branch1
227 marked working directory as branch branch1
228 $ echo branch1 > file1
228 $ echo branch1 > file1
229 $ hg ci -d '1 0' -Am file1
229 $ hg ci -d '1 0' -Am file1
230 adding file1
230 adding file1
231 $ hg branch branch2
231 $ hg branch branch2
232 marked working directory as branch branch2
232 marked working directory as branch branch2
233 $ echo branch2 > file2
233 $ echo branch2 > file2
234 $ hg ci -d '2 0' -Am file2
234 $ hg ci -d '2 0' -Am file2
235 adding file2
235 adding file2
236
236
237 without --merge
237 without --merge
238 $ hg backout -r 1 --tool=true
238 $ hg backout -r 1 --tool=true
239 removing file1
239 removing file1
240 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
240 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
241 $ hg branch
241 $ hg branch
242 branch2
242 branch2
243 $ hg status -A
243 $ hg status -A
244 R file1
244 R file1
245 C default
245 C default
246 C file2
246 C file2
247
247
248 with --merge
248 with --merge
249 $ hg update -qC
249 $ hg update -qC
250 $ hg backout --merge -d '3 0' -r 1 -m 'backout on branch1' --tool=true
250 $ hg backout --merge -d '3 0' -r 1 -m 'backout on branch1' --tool=true
251 removing file1
251 removing file1
252 created new head
252 created new head
253 changeset 3:d4e8f6db59fb backs out changeset 1:bf1602f437f3
253 changeset 3:d4e8f6db59fb backs out changeset 1:bf1602f437f3
254 merging with changeset 3:d4e8f6db59fb
254 merging with changeset 3:d4e8f6db59fb
255 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
255 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
256 (branch merge, don't forget to commit)
256 (branch merge, don't forget to commit)
257 $ hg update -q -C 2
257 $ hg update -q -C 2
258
258
259 on branch2 with branch1 not merged, so file1 should still exist:
259 on branch2 with branch1 not merged, so file1 should still exist:
260
260
261 $ hg id
261 $ hg id
262 45bbcd363bf0 (branch2)
262 45bbcd363bf0 (branch2)
263 $ hg st -A
263 $ hg st -A
264 C default
264 C default
265 C file1
265 C file1
266 C file2
266 C file2
267
267
268 on branch2 with branch1 merged, so file1 should be gone:
268 on branch2 with branch1 merged, so file1 should be gone:
269
269
270 $ hg merge
270 $ hg merge
271 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
271 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
272 (branch merge, don't forget to commit)
272 (branch merge, don't forget to commit)
273 $ hg ci -d '4 0' -m 'merge backout of branch1'
273 $ hg ci -d '4 0' -m 'merge backout of branch1'
274 $ hg id
274 $ hg id
275 22149cdde76d (branch2) tip
275 22149cdde76d (branch2) tip
276 $ hg st -A
276 $ hg st -A
277 C default
277 C default
278 C file2
278 C file2
279
279
280 on branch1, so no file1 and file2:
280 on branch1, so no file1 and file2:
281
281
282 $ hg co -C branch1
282 $ hg co -C branch1
283 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
283 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
284 $ hg id
284 $ hg id
285 bf1602f437f3 (branch1)
285 bf1602f437f3 (branch1)
286 $ hg st -A
286 $ hg st -A
287 C default
287 C default
288 C file1
288 C file1
General Comments 0
You need to be logged in to leave comments. Login now