##// END OF EJS Templates
resolve: update documentation to mention the .orig backup
Pierre-Yves David -
r15232:5d9a5b91 default
parent child Browse files
Show More
@@ -1,5474 +1,5475 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, url, encoding, templatekw, discovery
13 import patch, help, url, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, hbisect
14 import archival, changegroup, cmdutil, hbisect
15 import sshserver, hgweb, hgweb.server, commandserver
15 import sshserver, hgweb, hgweb.server, commandserver
16 import merge as mergemod
16 import merge as mergemod
17 import minirst, revset, fileset
17 import minirst, revset, fileset
18 import dagparser, context, simplemerge
18 import dagparser, context, simplemerge
19 import random, setdiscovery, treediscovery, dagutil
19 import random, setdiscovery, treediscovery, dagutil
20
20
21 table = {}
21 table = {}
22
22
23 command = cmdutil.command(table)
23 command = cmdutil.command(table)
24
24
25 # common command options
25 # common command options
26
26
27 globalopts = [
27 globalopts = [
28 ('R', 'repository', '',
28 ('R', 'repository', '',
29 _('repository root directory or name of overlay bundle file'),
29 _('repository root directory or name of overlay bundle file'),
30 _('REPO')),
30 _('REPO')),
31 ('', 'cwd', '',
31 ('', 'cwd', '',
32 _('change working directory'), _('DIR')),
32 _('change working directory'), _('DIR')),
33 ('y', 'noninteractive', None,
33 ('y', 'noninteractive', None,
34 _('do not prompt, automatically pick the first choice for all prompts')),
34 _('do not prompt, automatically pick the first choice for all prompts')),
35 ('q', 'quiet', None, _('suppress output')),
35 ('q', 'quiet', None, _('suppress output')),
36 ('v', 'verbose', None, _('enable additional output')),
36 ('v', 'verbose', None, _('enable additional output')),
37 ('', 'config', [],
37 ('', 'config', [],
38 _('set/override config option (use \'section.name=value\')'),
38 _('set/override config option (use \'section.name=value\')'),
39 _('CONFIG')),
39 _('CONFIG')),
40 ('', 'debug', None, _('enable debugging output')),
40 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debugger', None, _('start debugger')),
41 ('', 'debugger', None, _('start debugger')),
42 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 _('ENCODE')),
43 _('ENCODE')),
44 ('', 'encodingmode', encoding.encodingmode,
44 ('', 'encodingmode', encoding.encodingmode,
45 _('set the charset encoding mode'), _('MODE')),
45 _('set the charset encoding mode'), _('MODE')),
46 ('', 'traceback', None, _('always print a traceback on exception')),
46 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'time', None, _('time how long the command takes')),
47 ('', 'time', None, _('time how long the command takes')),
48 ('', 'profile', None, _('print command execution profile')),
48 ('', 'profile', None, _('print command execution profile')),
49 ('', 'version', None, _('output version information and exit')),
49 ('', 'version', None, _('output version information and exit')),
50 ('h', 'help', None, _('display help and exit')),
50 ('h', 'help', None, _('display help and exit')),
51 ]
51 ]
52
52
53 dryrunopts = [('n', 'dry-run', None,
53 dryrunopts = [('n', 'dry-run', None,
54 _('do not perform actions, just print output'))]
54 _('do not perform actions, just print output'))]
55
55
56 remoteopts = [
56 remoteopts = [
57 ('e', 'ssh', '',
57 ('e', 'ssh', '',
58 _('specify ssh command to use'), _('CMD')),
58 _('specify ssh command to use'), _('CMD')),
59 ('', 'remotecmd', '',
59 ('', 'remotecmd', '',
60 _('specify hg command to run on the remote side'), _('CMD')),
60 _('specify hg command to run on the remote side'), _('CMD')),
61 ('', 'insecure', None,
61 ('', 'insecure', None,
62 _('do not verify server certificate (ignoring web.cacerts config)')),
62 _('do not verify server certificate (ignoring web.cacerts config)')),
63 ]
63 ]
64
64
65 walkopts = [
65 walkopts = [
66 ('I', 'include', [],
66 ('I', 'include', [],
67 _('include names matching the given patterns'), _('PATTERN')),
67 _('include names matching the given patterns'), _('PATTERN')),
68 ('X', 'exclude', [],
68 ('X', 'exclude', [],
69 _('exclude names matching the given patterns'), _('PATTERN')),
69 _('exclude names matching the given patterns'), _('PATTERN')),
70 ]
70 ]
71
71
72 commitopts = [
72 commitopts = [
73 ('m', 'message', '',
73 ('m', 'message', '',
74 _('use text as commit message'), _('TEXT')),
74 _('use text as commit message'), _('TEXT')),
75 ('l', 'logfile', '',
75 ('l', 'logfile', '',
76 _('read commit message from file'), _('FILE')),
76 _('read commit message from file'), _('FILE')),
77 ]
77 ]
78
78
79 commitopts2 = [
79 commitopts2 = [
80 ('d', 'date', '',
80 ('d', 'date', '',
81 _('record the specified date as commit date'), _('DATE')),
81 _('record the specified date as commit date'), _('DATE')),
82 ('u', 'user', '',
82 ('u', 'user', '',
83 _('record the specified user as committer'), _('USER')),
83 _('record the specified user as committer'), _('USER')),
84 ]
84 ]
85
85
86 templateopts = [
86 templateopts = [
87 ('', 'style', '',
87 ('', 'style', '',
88 _('display using template map file'), _('STYLE')),
88 _('display using template map file'), _('STYLE')),
89 ('', 'template', '',
89 ('', 'template', '',
90 _('display with template'), _('TEMPLATE')),
90 _('display with template'), _('TEMPLATE')),
91 ]
91 ]
92
92
93 logopts = [
93 logopts = [
94 ('p', 'patch', None, _('show patch')),
94 ('p', 'patch', None, _('show patch')),
95 ('g', 'git', None, _('use git extended diff format')),
95 ('g', 'git', None, _('use git extended diff format')),
96 ('l', 'limit', '',
96 ('l', 'limit', '',
97 _('limit number of changes displayed'), _('NUM')),
97 _('limit number of changes displayed'), _('NUM')),
98 ('M', 'no-merges', None, _('do not show merges')),
98 ('M', 'no-merges', None, _('do not show merges')),
99 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ] + templateopts
100 ] + templateopts
101
101
102 diffopts = [
102 diffopts = [
103 ('a', 'text', None, _('treat all files as text')),
103 ('a', 'text', None, _('treat all files as text')),
104 ('g', 'git', None, _('use git extended diff format')),
104 ('g', 'git', None, _('use git extended diff format')),
105 ('', 'nodates', None, _('omit dates from diff headers'))
105 ('', 'nodates', None, _('omit dates from diff headers'))
106 ]
106 ]
107
107
108 diffopts2 = [
108 diffopts2 = [
109 ('p', 'show-function', None, _('show which function each change is in')),
109 ('p', 'show-function', None, _('show which function each change is in')),
110 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 ('', 'reverse', None, _('produce a diff that undoes the changes')),
111 ('w', 'ignore-all-space', None,
111 ('w', 'ignore-all-space', None,
112 _('ignore white space when comparing lines')),
112 _('ignore white space when comparing lines')),
113 ('b', 'ignore-space-change', None,
113 ('b', 'ignore-space-change', None,
114 _('ignore changes in the amount of white space')),
114 _('ignore changes in the amount of white space')),
115 ('B', 'ignore-blank-lines', None,
115 ('B', 'ignore-blank-lines', None,
116 _('ignore changes whose lines are all blank')),
116 _('ignore changes whose lines are all blank')),
117 ('U', 'unified', '',
117 ('U', 'unified', '',
118 _('number of lines of context to show'), _('NUM')),
118 _('number of lines of context to show'), _('NUM')),
119 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 ('', 'stat', None, _('output diffstat-style summary of changes')),
120 ]
120 ]
121
121
122 mergetoolopts = [
122 mergetoolopts = [
123 ('t', 'tool', '', _('specify merge tool')),
123 ('t', 'tool', '', _('specify merge tool')),
124 ]
124 ]
125
125
126 similarityopts = [
126 similarityopts = [
127 ('s', 'similarity', '',
127 ('s', 'similarity', '',
128 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
128 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
129 ]
129 ]
130
130
131 subrepoopts = [
131 subrepoopts = [
132 ('S', 'subrepos', None,
132 ('S', 'subrepos', None,
133 _('recurse into subrepositories'))
133 _('recurse into subrepositories'))
134 ]
134 ]
135
135
136 # Commands start here, listed alphabetically
136 # Commands start here, listed alphabetically
137
137
138 @command('^add',
138 @command('^add',
139 walkopts + subrepoopts + dryrunopts,
139 walkopts + subrepoopts + dryrunopts,
140 _('[OPTION]... [FILE]...'))
140 _('[OPTION]... [FILE]...'))
141 def add(ui, repo, *pats, **opts):
141 def add(ui, repo, *pats, **opts):
142 """add the specified files on the next commit
142 """add the specified files on the next commit
143
143
144 Schedule files to be version controlled and added to the
144 Schedule files to be version controlled and added to the
145 repository.
145 repository.
146
146
147 The files will be added to the repository at the next commit. To
147 The files will be added to the repository at the next commit. To
148 undo an add before that, see :hg:`forget`.
148 undo an add before that, see :hg:`forget`.
149
149
150 If no names are given, add all files to the repository.
150 If no names are given, add all files to the repository.
151
151
152 .. container:: verbose
152 .. container:: verbose
153
153
154 An example showing how new (unknown) files are added
154 An example showing how new (unknown) files are added
155 automatically by :hg:`add`::
155 automatically by :hg:`add`::
156
156
157 $ ls
157 $ ls
158 foo.c
158 foo.c
159 $ hg status
159 $ hg status
160 ? foo.c
160 ? foo.c
161 $ hg add
161 $ hg add
162 adding foo.c
162 adding foo.c
163 $ hg status
163 $ hg status
164 A foo.c
164 A foo.c
165
165
166 Returns 0 if all files are successfully added.
166 Returns 0 if all files are successfully added.
167 """
167 """
168
168
169 m = scmutil.match(repo[None], pats, opts)
169 m = scmutil.match(repo[None], pats, opts)
170 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
170 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
171 opts.get('subrepos'), prefix="")
171 opts.get('subrepos'), prefix="")
172 return rejected and 1 or 0
172 return rejected and 1 or 0
173
173
174 @command('addremove',
174 @command('addremove',
175 similarityopts + walkopts + dryrunopts,
175 similarityopts + walkopts + dryrunopts,
176 _('[OPTION]... [FILE]...'))
176 _('[OPTION]... [FILE]...'))
177 def addremove(ui, repo, *pats, **opts):
177 def addremove(ui, repo, *pats, **opts):
178 """add all new files, delete all missing files
178 """add all new files, delete all missing files
179
179
180 Add all new files and remove all missing files from the
180 Add all new files and remove all missing files from the
181 repository.
181 repository.
182
182
183 New files are ignored if they match any of the patterns in
183 New files are ignored if they match any of the patterns in
184 ``.hgignore``. As with add, these changes take effect at the next
184 ``.hgignore``. As with add, these changes take effect at the next
185 commit.
185 commit.
186
186
187 Use the -s/--similarity option to detect renamed files. With a
187 Use the -s/--similarity option to detect renamed files. With a
188 parameter greater than 0, this compares every removed file with
188 parameter greater than 0, this compares every removed file with
189 every added file and records those similar enough as renames. This
189 every added file and records those similar enough as renames. This
190 option takes a percentage between 0 (disabled) and 100 (files must
190 option takes a percentage between 0 (disabled) and 100 (files must
191 be identical) as its parameter. Detecting renamed files this way
191 be identical) as its parameter. Detecting renamed files this way
192 can be expensive. After using this option, :hg:`status -C` can be
192 can be expensive. After using this option, :hg:`status -C` can be
193 used to check which files were identified as moved or renamed.
193 used to check which files were identified as moved or renamed.
194
194
195 Returns 0 if all files are successfully added.
195 Returns 0 if all files are successfully added.
196 """
196 """
197 try:
197 try:
198 sim = float(opts.get('similarity') or 100)
198 sim = float(opts.get('similarity') or 100)
199 except ValueError:
199 except ValueError:
200 raise util.Abort(_('similarity must be a number'))
200 raise util.Abort(_('similarity must be a number'))
201 if sim < 0 or sim > 100:
201 if sim < 0 or sim > 100:
202 raise util.Abort(_('similarity must be between 0 and 100'))
202 raise util.Abort(_('similarity must be between 0 and 100'))
203 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
203 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
204
204
205 @command('^annotate|blame',
205 @command('^annotate|blame',
206 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
206 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
207 ('', 'follow', None,
207 ('', 'follow', None,
208 _('follow copies/renames and list the filename (DEPRECATED)')),
208 _('follow copies/renames and list the filename (DEPRECATED)')),
209 ('', 'no-follow', None, _("don't follow copies and renames")),
209 ('', 'no-follow', None, _("don't follow copies and renames")),
210 ('a', 'text', None, _('treat all files as text')),
210 ('a', 'text', None, _('treat all files as text')),
211 ('u', 'user', None, _('list the author (long with -v)')),
211 ('u', 'user', None, _('list the author (long with -v)')),
212 ('f', 'file', None, _('list the filename')),
212 ('f', 'file', None, _('list the filename')),
213 ('d', 'date', None, _('list the date (short with -q)')),
213 ('d', 'date', None, _('list the date (short with -q)')),
214 ('n', 'number', None, _('list the revision number (default)')),
214 ('n', 'number', None, _('list the revision number (default)')),
215 ('c', 'changeset', None, _('list the changeset')),
215 ('c', 'changeset', None, _('list the changeset')),
216 ('l', 'line-number', None, _('show line number at the first appearance'))
216 ('l', 'line-number', None, _('show line number at the first appearance'))
217 ] + walkopts,
217 ] + walkopts,
218 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
218 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
219 def annotate(ui, repo, *pats, **opts):
219 def annotate(ui, repo, *pats, **opts):
220 """show changeset information by line for each file
220 """show changeset information by line for each file
221
221
222 List changes in files, showing the revision id responsible for
222 List changes in files, showing the revision id responsible for
223 each line
223 each line
224
224
225 This command is useful for discovering when a change was made and
225 This command is useful for discovering when a change was made and
226 by whom.
226 by whom.
227
227
228 Without the -a/--text option, annotate will avoid processing files
228 Without the -a/--text option, annotate will avoid processing files
229 it detects as binary. With -a, annotate will annotate the file
229 it detects as binary. With -a, annotate will annotate the file
230 anyway, although the results will probably be neither useful
230 anyway, although the results will probably be neither useful
231 nor desirable.
231 nor desirable.
232
232
233 Returns 0 on success.
233 Returns 0 on success.
234 """
234 """
235 if opts.get('follow'):
235 if opts.get('follow'):
236 # --follow is deprecated and now just an alias for -f/--file
236 # --follow is deprecated and now just an alias for -f/--file
237 # to mimic the behavior of Mercurial before version 1.5
237 # to mimic the behavior of Mercurial before version 1.5
238 opts['file'] = True
238 opts['file'] = True
239
239
240 datefunc = ui.quiet and util.shortdate or util.datestr
240 datefunc = ui.quiet and util.shortdate or util.datestr
241 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
241 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
242
242
243 if not pats:
243 if not pats:
244 raise util.Abort(_('at least one filename or pattern is required'))
244 raise util.Abort(_('at least one filename or pattern is required'))
245
245
246 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
246 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
247 ('number', ' ', lambda x: str(x[0].rev())),
247 ('number', ' ', lambda x: str(x[0].rev())),
248 ('changeset', ' ', lambda x: short(x[0].node())),
248 ('changeset', ' ', lambda x: short(x[0].node())),
249 ('date', ' ', getdate),
249 ('date', ' ', getdate),
250 ('file', ' ', lambda x: x[0].path()),
250 ('file', ' ', lambda x: x[0].path()),
251 ('line_number', ':', lambda x: str(x[1])),
251 ('line_number', ':', lambda x: str(x[1])),
252 ]
252 ]
253
253
254 if (not opts.get('user') and not opts.get('changeset')
254 if (not opts.get('user') and not opts.get('changeset')
255 and not opts.get('date') and not opts.get('file')):
255 and not opts.get('date') and not opts.get('file')):
256 opts['number'] = True
256 opts['number'] = True
257
257
258 linenumber = opts.get('line_number') is not None
258 linenumber = opts.get('line_number') is not None
259 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
259 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
260 raise util.Abort(_('at least one of -n/-c is required for -l'))
260 raise util.Abort(_('at least one of -n/-c is required for -l'))
261
261
262 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
262 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
263 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
263 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
264
264
265 def bad(x, y):
265 def bad(x, y):
266 raise util.Abort("%s: %s" % (x, y))
266 raise util.Abort("%s: %s" % (x, y))
267
267
268 ctx = scmutil.revsingle(repo, opts.get('rev'))
268 ctx = scmutil.revsingle(repo, opts.get('rev'))
269 m = scmutil.match(ctx, pats, opts)
269 m = scmutil.match(ctx, pats, opts)
270 m.bad = bad
270 m.bad = bad
271 follow = not opts.get('no_follow')
271 follow = not opts.get('no_follow')
272 for abs in ctx.walk(m):
272 for abs in ctx.walk(m):
273 fctx = ctx[abs]
273 fctx = ctx[abs]
274 if not opts.get('text') and util.binary(fctx.data()):
274 if not opts.get('text') and util.binary(fctx.data()):
275 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
275 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
276 continue
276 continue
277
277
278 lines = fctx.annotate(follow=follow, linenumber=linenumber)
278 lines = fctx.annotate(follow=follow, linenumber=linenumber)
279 pieces = []
279 pieces = []
280
280
281 for f, sep in funcmap:
281 for f, sep in funcmap:
282 l = [f(n) for n, dummy in lines]
282 l = [f(n) for n, dummy in lines]
283 if l:
283 if l:
284 sized = [(x, encoding.colwidth(x)) for x in l]
284 sized = [(x, encoding.colwidth(x)) for x in l]
285 ml = max([w for x, w in sized])
285 ml = max([w for x, w in sized])
286 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
286 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
287 for x, w in sized])
287 for x, w in sized])
288
288
289 if pieces:
289 if pieces:
290 for p, l in zip(zip(*pieces), lines):
290 for p, l in zip(zip(*pieces), lines):
291 ui.write("%s: %s" % ("".join(p), l[1]))
291 ui.write("%s: %s" % ("".join(p), l[1]))
292
292
293 @command('archive',
293 @command('archive',
294 [('', 'no-decode', None, _('do not pass files through decoders')),
294 [('', 'no-decode', None, _('do not pass files through decoders')),
295 ('p', 'prefix', '', _('directory prefix for files in archive'),
295 ('p', 'prefix', '', _('directory prefix for files in archive'),
296 _('PREFIX')),
296 _('PREFIX')),
297 ('r', 'rev', '', _('revision to distribute'), _('REV')),
297 ('r', 'rev', '', _('revision to distribute'), _('REV')),
298 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
298 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
299 ] + subrepoopts + walkopts,
299 ] + subrepoopts + walkopts,
300 _('[OPTION]... DEST'))
300 _('[OPTION]... DEST'))
301 def archive(ui, repo, dest, **opts):
301 def archive(ui, repo, dest, **opts):
302 '''create an unversioned archive of a repository revision
302 '''create an unversioned archive of a repository revision
303
303
304 By default, the revision used is the parent of the working
304 By default, the revision used is the parent of the working
305 directory; use -r/--rev to specify a different revision.
305 directory; use -r/--rev to specify a different revision.
306
306
307 The archive type is automatically detected based on file
307 The archive type is automatically detected based on file
308 extension (or override using -t/--type).
308 extension (or override using -t/--type).
309
309
310 .. container:: verbose
310 .. container:: verbose
311
311
312 Examples:
312 Examples:
313
313
314 - create a zip file containing the 1.0 release::
314 - create a zip file containing the 1.0 release::
315
315
316 hg archive -r 1.0 project-1.0.zip
316 hg archive -r 1.0 project-1.0.zip
317
317
318 - create a tarball excluding .hg files::
318 - create a tarball excluding .hg files::
319
319
320 hg archive project.tar.gz -X ".hg*"
320 hg archive project.tar.gz -X ".hg*"
321
321
322 Valid types are:
322 Valid types are:
323
323
324 :``files``: a directory full of files (default)
324 :``files``: a directory full of files (default)
325 :``tar``: tar archive, uncompressed
325 :``tar``: tar archive, uncompressed
326 :``tbz2``: tar archive, compressed using bzip2
326 :``tbz2``: tar archive, compressed using bzip2
327 :``tgz``: tar archive, compressed using gzip
327 :``tgz``: tar archive, compressed using gzip
328 :``uzip``: zip archive, uncompressed
328 :``uzip``: zip archive, uncompressed
329 :``zip``: zip archive, compressed using deflate
329 :``zip``: zip archive, compressed using deflate
330
330
331 The exact name of the destination archive or directory is given
331 The exact name of the destination archive or directory is given
332 using a format string; see :hg:`help export` for details.
332 using a format string; see :hg:`help export` for details.
333
333
334 Each member added to an archive file has a directory prefix
334 Each member added to an archive file has a directory prefix
335 prepended. Use -p/--prefix to specify a format string for the
335 prepended. Use -p/--prefix to specify a format string for the
336 prefix. The default is the basename of the archive, with suffixes
336 prefix. The default is the basename of the archive, with suffixes
337 removed.
337 removed.
338
338
339 Returns 0 on success.
339 Returns 0 on success.
340 '''
340 '''
341
341
342 ctx = scmutil.revsingle(repo, opts.get('rev'))
342 ctx = scmutil.revsingle(repo, opts.get('rev'))
343 if not ctx:
343 if not ctx:
344 raise util.Abort(_('no working directory: please specify a revision'))
344 raise util.Abort(_('no working directory: please specify a revision'))
345 node = ctx.node()
345 node = ctx.node()
346 dest = cmdutil.makefilename(repo, dest, node)
346 dest = cmdutil.makefilename(repo, dest, node)
347 if os.path.realpath(dest) == repo.root:
347 if os.path.realpath(dest) == repo.root:
348 raise util.Abort(_('repository root cannot be destination'))
348 raise util.Abort(_('repository root cannot be destination'))
349
349
350 kind = opts.get('type') or archival.guesskind(dest) or 'files'
350 kind = opts.get('type') or archival.guesskind(dest) or 'files'
351 prefix = opts.get('prefix')
351 prefix = opts.get('prefix')
352
352
353 if dest == '-':
353 if dest == '-':
354 if kind == 'files':
354 if kind == 'files':
355 raise util.Abort(_('cannot archive plain files to stdout'))
355 raise util.Abort(_('cannot archive plain files to stdout'))
356 dest = cmdutil.makefileobj(repo, dest)
356 dest = cmdutil.makefileobj(repo, dest)
357 if not prefix:
357 if not prefix:
358 prefix = os.path.basename(repo.root) + '-%h'
358 prefix = os.path.basename(repo.root) + '-%h'
359
359
360 prefix = cmdutil.makefilename(repo, prefix, node)
360 prefix = cmdutil.makefilename(repo, prefix, node)
361 matchfn = scmutil.match(ctx, [], opts)
361 matchfn = scmutil.match(ctx, [], opts)
362 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
362 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
363 matchfn, prefix, subrepos=opts.get('subrepos'))
363 matchfn, prefix, subrepos=opts.get('subrepos'))
364
364
365 @command('backout',
365 @command('backout',
366 [('', 'merge', None, _('merge with old dirstate parent after backout')),
366 [('', 'merge', None, _('merge with old dirstate parent after backout')),
367 ('', 'parent', '',
367 ('', 'parent', '',
368 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
368 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
369 ('r', 'rev', '', _('revision to backout'), _('REV')),
369 ('r', 'rev', '', _('revision to backout'), _('REV')),
370 ] + mergetoolopts + walkopts + commitopts + commitopts2,
370 ] + mergetoolopts + walkopts + commitopts + commitopts2,
371 _('[OPTION]... [-r] REV'))
371 _('[OPTION]... [-r] REV'))
372 def backout(ui, repo, node=None, rev=None, **opts):
372 def backout(ui, repo, node=None, rev=None, **opts):
373 '''reverse effect of earlier changeset
373 '''reverse effect of earlier changeset
374
374
375 Prepare a new changeset with the effect of REV undone in the
375 Prepare a new changeset with the effect of REV undone in the
376 current working directory.
376 current working directory.
377
377
378 If REV is the parent of the working directory, then this new changeset
378 If REV is the parent of the working directory, then this new changeset
379 is committed automatically. Otherwise, hg needs to merge the
379 is committed automatically. Otherwise, hg needs to merge the
380 changes and the merged result is left uncommitted.
380 changes and the merged result is left uncommitted.
381
381
382 .. note::
382 .. note::
383 backout cannot be used to fix either an unwanted or
383 backout cannot be used to fix either an unwanted or
384 incorrect merge.
384 incorrect merge.
385
385
386 .. container:: verbose
386 .. container:: verbose
387
387
388 By default, the pending changeset will have one parent,
388 By default, the pending changeset will have one parent,
389 maintaining a linear history. With --merge, the pending
389 maintaining a linear history. With --merge, the pending
390 changeset will instead have two parents: the old parent of the
390 changeset will instead have two parents: the old parent of the
391 working directory and a new child of REV that simply undoes REV.
391 working directory and a new child of REV that simply undoes REV.
392
392
393 Before version 1.7, the behavior without --merge was equivalent
393 Before version 1.7, the behavior without --merge was equivalent
394 to specifying --merge followed by :hg:`update --clean .` to
394 to specifying --merge followed by :hg:`update --clean .` to
395 cancel the merge and leave the child of REV as a head to be
395 cancel the merge and leave the child of REV as a head to be
396 merged separately.
396 merged separately.
397
397
398 See :hg:`help dates` for a list of formats valid for -d/--date.
398 See :hg:`help dates` for a list of formats valid for -d/--date.
399
399
400 Returns 0 on success.
400 Returns 0 on success.
401 '''
401 '''
402 if rev and node:
402 if rev and node:
403 raise util.Abort(_("please specify just one revision"))
403 raise util.Abort(_("please specify just one revision"))
404
404
405 if not rev:
405 if not rev:
406 rev = node
406 rev = node
407
407
408 if not rev:
408 if not rev:
409 raise util.Abort(_("please specify a revision to backout"))
409 raise util.Abort(_("please specify a revision to backout"))
410
410
411 date = opts.get('date')
411 date = opts.get('date')
412 if date:
412 if date:
413 opts['date'] = util.parsedate(date)
413 opts['date'] = util.parsedate(date)
414
414
415 cmdutil.bailifchanged(repo)
415 cmdutil.bailifchanged(repo)
416 node = scmutil.revsingle(repo, rev).node()
416 node = scmutil.revsingle(repo, rev).node()
417
417
418 op1, op2 = repo.dirstate.parents()
418 op1, op2 = repo.dirstate.parents()
419 a = repo.changelog.ancestor(op1, node)
419 a = repo.changelog.ancestor(op1, node)
420 if a != node:
420 if a != node:
421 raise util.Abort(_('cannot backout change on a different branch'))
421 raise util.Abort(_('cannot backout change on a different branch'))
422
422
423 p1, p2 = repo.changelog.parents(node)
423 p1, p2 = repo.changelog.parents(node)
424 if p1 == nullid:
424 if p1 == nullid:
425 raise util.Abort(_('cannot backout a change with no parents'))
425 raise util.Abort(_('cannot backout a change with no parents'))
426 if p2 != nullid:
426 if p2 != nullid:
427 if not opts.get('parent'):
427 if not opts.get('parent'):
428 raise util.Abort(_('cannot backout a merge changeset'))
428 raise util.Abort(_('cannot backout a merge changeset'))
429 p = repo.lookup(opts['parent'])
429 p = repo.lookup(opts['parent'])
430 if p not in (p1, p2):
430 if p not in (p1, p2):
431 raise util.Abort(_('%s is not a parent of %s') %
431 raise util.Abort(_('%s is not a parent of %s') %
432 (short(p), short(node)))
432 (short(p), short(node)))
433 parent = p
433 parent = p
434 else:
434 else:
435 if opts.get('parent'):
435 if opts.get('parent'):
436 raise util.Abort(_('cannot use --parent on non-merge changeset'))
436 raise util.Abort(_('cannot use --parent on non-merge changeset'))
437 parent = p1
437 parent = p1
438
438
439 # the backout should appear on the same branch
439 # the backout should appear on the same branch
440 branch = repo.dirstate.branch()
440 branch = repo.dirstate.branch()
441 hg.clean(repo, node, show_stats=False)
441 hg.clean(repo, node, show_stats=False)
442 repo.dirstate.setbranch(branch)
442 repo.dirstate.setbranch(branch)
443 revert_opts = opts.copy()
443 revert_opts = opts.copy()
444 revert_opts['date'] = None
444 revert_opts['date'] = None
445 revert_opts['all'] = True
445 revert_opts['all'] = True
446 revert_opts['rev'] = hex(parent)
446 revert_opts['rev'] = hex(parent)
447 revert_opts['no_backup'] = None
447 revert_opts['no_backup'] = None
448 revert(ui, repo, **revert_opts)
448 revert(ui, repo, **revert_opts)
449 if not opts.get('merge') and op1 != node:
449 if not opts.get('merge') and op1 != node:
450 try:
450 try:
451 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
452 return hg.update(repo, op1)
452 return hg.update(repo, op1)
453 finally:
453 finally:
454 ui.setconfig('ui', 'forcemerge', '')
454 ui.setconfig('ui', 'forcemerge', '')
455
455
456 commit_opts = opts.copy()
456 commit_opts = opts.copy()
457 commit_opts['addremove'] = False
457 commit_opts['addremove'] = False
458 if not commit_opts['message'] and not commit_opts['logfile']:
458 if not commit_opts['message'] and not commit_opts['logfile']:
459 # we don't translate commit messages
459 # we don't translate commit messages
460 commit_opts['message'] = "Backed out changeset %s" % short(node)
460 commit_opts['message'] = "Backed out changeset %s" % short(node)
461 commit_opts['force_editor'] = True
461 commit_opts['force_editor'] = True
462 commit(ui, repo, **commit_opts)
462 commit(ui, repo, **commit_opts)
463 def nice(node):
463 def nice(node):
464 return '%d:%s' % (repo.changelog.rev(node), short(node))
464 return '%d:%s' % (repo.changelog.rev(node), short(node))
465 ui.status(_('changeset %s backs out changeset %s\n') %
465 ui.status(_('changeset %s backs out changeset %s\n') %
466 (nice(repo.changelog.tip()), nice(node)))
466 (nice(repo.changelog.tip()), nice(node)))
467 if opts.get('merge') and op1 != node:
467 if opts.get('merge') and op1 != node:
468 hg.clean(repo, op1, show_stats=False)
468 hg.clean(repo, op1, show_stats=False)
469 ui.status(_('merging with changeset %s\n')
469 ui.status(_('merging with changeset %s\n')
470 % nice(repo.changelog.tip()))
470 % nice(repo.changelog.tip()))
471 try:
471 try:
472 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
472 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
473 return hg.merge(repo, hex(repo.changelog.tip()))
473 return hg.merge(repo, hex(repo.changelog.tip()))
474 finally:
474 finally:
475 ui.setconfig('ui', 'forcemerge', '')
475 ui.setconfig('ui', 'forcemerge', '')
476 return 0
476 return 0
477
477
478 @command('bisect',
478 @command('bisect',
479 [('r', 'reset', False, _('reset bisect state')),
479 [('r', 'reset', False, _('reset bisect state')),
480 ('g', 'good', False, _('mark changeset good')),
480 ('g', 'good', False, _('mark changeset good')),
481 ('b', 'bad', False, _('mark changeset bad')),
481 ('b', 'bad', False, _('mark changeset bad')),
482 ('s', 'skip', False, _('skip testing changeset')),
482 ('s', 'skip', False, _('skip testing changeset')),
483 ('e', 'extend', False, _('extend the bisect range')),
483 ('e', 'extend', False, _('extend the bisect range')),
484 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
484 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
485 ('U', 'noupdate', False, _('do not update to target'))],
485 ('U', 'noupdate', False, _('do not update to target'))],
486 _("[-gbsr] [-U] [-c CMD] [REV]"))
486 _("[-gbsr] [-U] [-c CMD] [REV]"))
487 def bisect(ui, repo, rev=None, extra=None, command=None,
487 def bisect(ui, repo, rev=None, extra=None, command=None,
488 reset=None, good=None, bad=None, skip=None, extend=None,
488 reset=None, good=None, bad=None, skip=None, extend=None,
489 noupdate=None):
489 noupdate=None):
490 """subdivision search of changesets
490 """subdivision search of changesets
491
491
492 This command helps to find changesets which introduce problems. To
492 This command helps to find changesets which introduce problems. To
493 use, mark the earliest changeset you know exhibits the problem as
493 use, mark the earliest changeset you know exhibits the problem as
494 bad, then mark the latest changeset which is free from the problem
494 bad, then mark the latest changeset which is free from the problem
495 as good. Bisect will update your working directory to a revision
495 as good. Bisect will update your working directory to a revision
496 for testing (unless the -U/--noupdate option is specified). Once
496 for testing (unless the -U/--noupdate option is specified). Once
497 you have performed tests, mark the working directory as good or
497 you have performed tests, mark the working directory as good or
498 bad, and bisect will either update to another candidate changeset
498 bad, and bisect will either update to another candidate changeset
499 or announce that it has found the bad revision.
499 or announce that it has found the bad revision.
500
500
501 As a shortcut, you can also use the revision argument to mark a
501 As a shortcut, you can also use the revision argument to mark a
502 revision as good or bad without checking it out first.
502 revision as good or bad without checking it out first.
503
503
504 If you supply a command, it will be used for automatic bisection.
504 If you supply a command, it will be used for automatic bisection.
505 Its exit status will be used to mark revisions as good or bad:
505 Its exit status will be used to mark revisions as good or bad:
506 status 0 means good, 125 means to skip the revision, 127
506 status 0 means good, 125 means to skip the revision, 127
507 (command not found) will abort the bisection, and any other
507 (command not found) will abort the bisection, and any other
508 non-zero exit status means the revision is bad.
508 non-zero exit status means the revision is bad.
509
509
510 .. container:: verbose
510 .. container:: verbose
511
511
512 Some examples:
512 Some examples:
513
513
514 - start a bisection with known bad revision 12, and good revision 34::
514 - start a bisection with known bad revision 12, and good revision 34::
515
515
516 hg bisect --bad 34
516 hg bisect --bad 34
517 hg bisect --good 12
517 hg bisect --good 12
518
518
519 - advance the current bisection by marking current revision as good or
519 - advance the current bisection by marking current revision as good or
520 bad::
520 bad::
521
521
522 hg bisect --good
522 hg bisect --good
523 hg bisect --bad
523 hg bisect --bad
524
524
525 - mark the current revision, or a known revision, to be skipped (eg. if
525 - mark the current revision, or a known revision, to be skipped (eg. if
526 that revision is not usable because of another issue)::
526 that revision is not usable because of another issue)::
527
527
528 hg bisect --skip
528 hg bisect --skip
529 hg bisect --skip 23
529 hg bisect --skip 23
530
530
531 - forget the current bisection::
531 - forget the current bisection::
532
532
533 hg bisect --reset
533 hg bisect --reset
534
534
535 - use 'make && make tests' to automatically find the first broken
535 - use 'make && make tests' to automatically find the first broken
536 revision::
536 revision::
537
537
538 hg bisect --reset
538 hg bisect --reset
539 hg bisect --bad 34
539 hg bisect --bad 34
540 hg bisect --good 12
540 hg bisect --good 12
541 hg bisect --command 'make && make tests'
541 hg bisect --command 'make && make tests'
542
542
543 - see all changesets whose states are already known in the current
543 - see all changesets whose states are already known in the current
544 bisection::
544 bisection::
545
545
546 hg log -r "bisect(pruned)"
546 hg log -r "bisect(pruned)"
547
547
548 - see all changesets that took part in the current bisection::
548 - see all changesets that took part in the current bisection::
549
549
550 hg log -r "bisect(range)"
550 hg log -r "bisect(range)"
551
551
552 - with the graphlog extension, you can even get a nice graph::
552 - with the graphlog extension, you can even get a nice graph::
553
553
554 hg log --graph -r "bisect(range)"
554 hg log --graph -r "bisect(range)"
555
555
556 See :hg:`help revsets` for more about the `bisect()` keyword.
556 See :hg:`help revsets` for more about the `bisect()` keyword.
557
557
558 Returns 0 on success.
558 Returns 0 on success.
559 """
559 """
560 def extendbisectrange(nodes, good):
560 def extendbisectrange(nodes, good):
561 # bisect is incomplete when it ends on a merge node and
561 # bisect is incomplete when it ends on a merge node and
562 # one of the parent was not checked.
562 # one of the parent was not checked.
563 parents = repo[nodes[0]].parents()
563 parents = repo[nodes[0]].parents()
564 if len(parents) > 1:
564 if len(parents) > 1:
565 side = good and state['bad'] or state['good']
565 side = good and state['bad'] or state['good']
566 num = len(set(i.node() for i in parents) & set(side))
566 num = len(set(i.node() for i in parents) & set(side))
567 if num == 1:
567 if num == 1:
568 return parents[0].ancestor(parents[1])
568 return parents[0].ancestor(parents[1])
569 return None
569 return None
570
570
571 def print_result(nodes, good):
571 def print_result(nodes, good):
572 displayer = cmdutil.show_changeset(ui, repo, {})
572 displayer = cmdutil.show_changeset(ui, repo, {})
573 if len(nodes) == 1:
573 if len(nodes) == 1:
574 # narrowed it down to a single revision
574 # narrowed it down to a single revision
575 if good:
575 if good:
576 ui.write(_("The first good revision is:\n"))
576 ui.write(_("The first good revision is:\n"))
577 else:
577 else:
578 ui.write(_("The first bad revision is:\n"))
578 ui.write(_("The first bad revision is:\n"))
579 displayer.show(repo[nodes[0]])
579 displayer.show(repo[nodes[0]])
580 extendnode = extendbisectrange(nodes, good)
580 extendnode = extendbisectrange(nodes, good)
581 if extendnode is not None:
581 if extendnode is not None:
582 ui.write(_('Not all ancestors of this changeset have been'
582 ui.write(_('Not all ancestors of this changeset have been'
583 ' checked.\nUse bisect --extend to continue the '
583 ' checked.\nUse bisect --extend to continue the '
584 'bisection from\nthe common ancestor, %s.\n')
584 'bisection from\nthe common ancestor, %s.\n')
585 % extendnode)
585 % extendnode)
586 else:
586 else:
587 # multiple possible revisions
587 # multiple possible revisions
588 if good:
588 if good:
589 ui.write(_("Due to skipped revisions, the first "
589 ui.write(_("Due to skipped revisions, the first "
590 "good revision could be any of:\n"))
590 "good revision could be any of:\n"))
591 else:
591 else:
592 ui.write(_("Due to skipped revisions, the first "
592 ui.write(_("Due to skipped revisions, the first "
593 "bad revision could be any of:\n"))
593 "bad revision could be any of:\n"))
594 for n in nodes:
594 for n in nodes:
595 displayer.show(repo[n])
595 displayer.show(repo[n])
596 displayer.close()
596 displayer.close()
597
597
598 def check_state(state, interactive=True):
598 def check_state(state, interactive=True):
599 if not state['good'] or not state['bad']:
599 if not state['good'] or not state['bad']:
600 if (good or bad or skip or reset) and interactive:
600 if (good or bad or skip or reset) and interactive:
601 return
601 return
602 if not state['good']:
602 if not state['good']:
603 raise util.Abort(_('cannot bisect (no known good revisions)'))
603 raise util.Abort(_('cannot bisect (no known good revisions)'))
604 else:
604 else:
605 raise util.Abort(_('cannot bisect (no known bad revisions)'))
605 raise util.Abort(_('cannot bisect (no known bad revisions)'))
606 return True
606 return True
607
607
608 # backward compatibility
608 # backward compatibility
609 if rev in "good bad reset init".split():
609 if rev in "good bad reset init".split():
610 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
610 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
611 cmd, rev, extra = rev, extra, None
611 cmd, rev, extra = rev, extra, None
612 if cmd == "good":
612 if cmd == "good":
613 good = True
613 good = True
614 elif cmd == "bad":
614 elif cmd == "bad":
615 bad = True
615 bad = True
616 else:
616 else:
617 reset = True
617 reset = True
618 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
618 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
619 raise util.Abort(_('incompatible arguments'))
619 raise util.Abort(_('incompatible arguments'))
620
620
621 if reset:
621 if reset:
622 p = repo.join("bisect.state")
622 p = repo.join("bisect.state")
623 if os.path.exists(p):
623 if os.path.exists(p):
624 os.unlink(p)
624 os.unlink(p)
625 return
625 return
626
626
627 state = hbisect.load_state(repo)
627 state = hbisect.load_state(repo)
628
628
629 if command:
629 if command:
630 changesets = 1
630 changesets = 1
631 try:
631 try:
632 while changesets:
632 while changesets:
633 # update state
633 # update state
634 status = util.system(command, out=ui.fout)
634 status = util.system(command, out=ui.fout)
635 if status == 125:
635 if status == 125:
636 transition = "skip"
636 transition = "skip"
637 elif status == 0:
637 elif status == 0:
638 transition = "good"
638 transition = "good"
639 # status < 0 means process was killed
639 # status < 0 means process was killed
640 elif status == 127:
640 elif status == 127:
641 raise util.Abort(_("failed to execute %s") % command)
641 raise util.Abort(_("failed to execute %s") % command)
642 elif status < 0:
642 elif status < 0:
643 raise util.Abort(_("%s killed") % command)
643 raise util.Abort(_("%s killed") % command)
644 else:
644 else:
645 transition = "bad"
645 transition = "bad"
646 ctx = scmutil.revsingle(repo, rev)
646 ctx = scmutil.revsingle(repo, rev)
647 rev = None # clear for future iterations
647 rev = None # clear for future iterations
648 state[transition].append(ctx.node())
648 state[transition].append(ctx.node())
649 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
649 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
650 check_state(state, interactive=False)
650 check_state(state, interactive=False)
651 # bisect
651 # bisect
652 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
652 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
653 # update to next check
653 # update to next check
654 cmdutil.bailifchanged(repo)
654 cmdutil.bailifchanged(repo)
655 hg.clean(repo, nodes[0], show_stats=False)
655 hg.clean(repo, nodes[0], show_stats=False)
656 finally:
656 finally:
657 hbisect.save_state(repo, state)
657 hbisect.save_state(repo, state)
658 print_result(nodes, good)
658 print_result(nodes, good)
659 return
659 return
660
660
661 # update state
661 # update state
662
662
663 if rev:
663 if rev:
664 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
664 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
665 else:
665 else:
666 nodes = [repo.lookup('.')]
666 nodes = [repo.lookup('.')]
667
667
668 if good or bad or skip:
668 if good or bad or skip:
669 if good:
669 if good:
670 state['good'] += nodes
670 state['good'] += nodes
671 elif bad:
671 elif bad:
672 state['bad'] += nodes
672 state['bad'] += nodes
673 elif skip:
673 elif skip:
674 state['skip'] += nodes
674 state['skip'] += nodes
675 hbisect.save_state(repo, state)
675 hbisect.save_state(repo, state)
676
676
677 if not check_state(state):
677 if not check_state(state):
678 return
678 return
679
679
680 # actually bisect
680 # actually bisect
681 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
681 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
682 if extend:
682 if extend:
683 if not changesets:
683 if not changesets:
684 extendnode = extendbisectrange(nodes, good)
684 extendnode = extendbisectrange(nodes, good)
685 if extendnode is not None:
685 if extendnode is not None:
686 ui.write(_("Extending search to changeset %d:%s\n"
686 ui.write(_("Extending search to changeset %d:%s\n"
687 % (extendnode.rev(), extendnode)))
687 % (extendnode.rev(), extendnode)))
688 if noupdate:
688 if noupdate:
689 return
689 return
690 cmdutil.bailifchanged(repo)
690 cmdutil.bailifchanged(repo)
691 return hg.clean(repo, extendnode.node())
691 return hg.clean(repo, extendnode.node())
692 raise util.Abort(_("nothing to extend"))
692 raise util.Abort(_("nothing to extend"))
693
693
694 if changesets == 0:
694 if changesets == 0:
695 print_result(nodes, good)
695 print_result(nodes, good)
696 else:
696 else:
697 assert len(nodes) == 1 # only a single node can be tested next
697 assert len(nodes) == 1 # only a single node can be tested next
698 node = nodes[0]
698 node = nodes[0]
699 # compute the approximate number of remaining tests
699 # compute the approximate number of remaining tests
700 tests, size = 0, 2
700 tests, size = 0, 2
701 while size <= changesets:
701 while size <= changesets:
702 tests, size = tests + 1, size * 2
702 tests, size = tests + 1, size * 2
703 rev = repo.changelog.rev(node)
703 rev = repo.changelog.rev(node)
704 ui.write(_("Testing changeset %d:%s "
704 ui.write(_("Testing changeset %d:%s "
705 "(%d changesets remaining, ~%d tests)\n")
705 "(%d changesets remaining, ~%d tests)\n")
706 % (rev, short(node), changesets, tests))
706 % (rev, short(node), changesets, tests))
707 if not noupdate:
707 if not noupdate:
708 cmdutil.bailifchanged(repo)
708 cmdutil.bailifchanged(repo)
709 return hg.clean(repo, node)
709 return hg.clean(repo, node)
710
710
711 @command('bookmarks',
711 @command('bookmarks',
712 [('f', 'force', False, _('force')),
712 [('f', 'force', False, _('force')),
713 ('r', 'rev', '', _('revision'), _('REV')),
713 ('r', 'rev', '', _('revision'), _('REV')),
714 ('d', 'delete', False, _('delete a given bookmark')),
714 ('d', 'delete', False, _('delete a given bookmark')),
715 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
715 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
716 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
716 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
717 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
717 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
718 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
718 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
719 rename=None, inactive=False):
719 rename=None, inactive=False):
720 '''track a line of development with movable markers
720 '''track a line of development with movable markers
721
721
722 Bookmarks are pointers to certain commits that move when
722 Bookmarks are pointers to certain commits that move when
723 committing. Bookmarks are local. They can be renamed, copied and
723 committing. Bookmarks are local. They can be renamed, copied and
724 deleted. It is possible to use bookmark names in :hg:`merge` and
724 deleted. It is possible to use bookmark names in :hg:`merge` and
725 :hg:`update` to merge and update respectively to a given bookmark.
725 :hg:`update` to merge and update respectively to a given bookmark.
726
726
727 You can use :hg:`bookmark NAME` to set a bookmark on the working
727 You can use :hg:`bookmark NAME` to set a bookmark on the working
728 directory's parent revision with the given name. If you specify
728 directory's parent revision with the given name. If you specify
729 a revision using -r REV (where REV may be an existing bookmark),
729 a revision using -r REV (where REV may be an existing bookmark),
730 the bookmark is assigned to that revision.
730 the bookmark is assigned to that revision.
731
731
732 Bookmarks can be pushed and pulled between repositories (see :hg:`help
732 Bookmarks can be pushed and pulled between repositories (see :hg:`help
733 push` and :hg:`help pull`). This requires both the local and remote
733 push` and :hg:`help pull`). This requires both the local and remote
734 repositories to support bookmarks. For versions prior to 1.8, this means
734 repositories to support bookmarks. For versions prior to 1.8, this means
735 the bookmarks extension must be enabled.
735 the bookmarks extension must be enabled.
736 '''
736 '''
737 hexfn = ui.debugflag and hex or short
737 hexfn = ui.debugflag and hex or short
738 marks = repo._bookmarks
738 marks = repo._bookmarks
739 cur = repo.changectx('.').node()
739 cur = repo.changectx('.').node()
740
740
741 if rename:
741 if rename:
742 if rename not in marks:
742 if rename not in marks:
743 raise util.Abort(_("bookmark '%s' does not exist") % rename)
743 raise util.Abort(_("bookmark '%s' does not exist") % rename)
744 if mark in marks and not force:
744 if mark in marks and not force:
745 raise util.Abort(_("bookmark '%s' already exists "
745 raise util.Abort(_("bookmark '%s' already exists "
746 "(use -f to force)") % mark)
746 "(use -f to force)") % mark)
747 if mark is None:
747 if mark is None:
748 raise util.Abort(_("new bookmark name required"))
748 raise util.Abort(_("new bookmark name required"))
749 marks[mark] = marks[rename]
749 marks[mark] = marks[rename]
750 if repo._bookmarkcurrent == rename and not inactive:
750 if repo._bookmarkcurrent == rename and not inactive:
751 bookmarks.setcurrent(repo, mark)
751 bookmarks.setcurrent(repo, mark)
752 del marks[rename]
752 del marks[rename]
753 bookmarks.write(repo)
753 bookmarks.write(repo)
754 return
754 return
755
755
756 if delete:
756 if delete:
757 if mark is None:
757 if mark is None:
758 raise util.Abort(_("bookmark name required"))
758 raise util.Abort(_("bookmark name required"))
759 if mark not in marks:
759 if mark not in marks:
760 raise util.Abort(_("bookmark '%s' does not exist") % mark)
760 raise util.Abort(_("bookmark '%s' does not exist") % mark)
761 if mark == repo._bookmarkcurrent:
761 if mark == repo._bookmarkcurrent:
762 bookmarks.setcurrent(repo, None)
762 bookmarks.setcurrent(repo, None)
763 del marks[mark]
763 del marks[mark]
764 bookmarks.write(repo)
764 bookmarks.write(repo)
765 return
765 return
766
766
767 if mark is not None:
767 if mark is not None:
768 if "\n" in mark:
768 if "\n" in mark:
769 raise util.Abort(_("bookmark name cannot contain newlines"))
769 raise util.Abort(_("bookmark name cannot contain newlines"))
770 mark = mark.strip()
770 mark = mark.strip()
771 if not mark:
771 if not mark:
772 raise util.Abort(_("bookmark names cannot consist entirely of "
772 raise util.Abort(_("bookmark names cannot consist entirely of "
773 "whitespace"))
773 "whitespace"))
774 if inactive and mark == repo._bookmarkcurrent:
774 if inactive and mark == repo._bookmarkcurrent:
775 bookmarks.setcurrent(repo, None)
775 bookmarks.setcurrent(repo, None)
776 return
776 return
777 if mark in marks and not force:
777 if mark in marks and not force:
778 raise util.Abort(_("bookmark '%s' already exists "
778 raise util.Abort(_("bookmark '%s' already exists "
779 "(use -f to force)") % mark)
779 "(use -f to force)") % mark)
780 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
780 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
781 and not force):
781 and not force):
782 raise util.Abort(
782 raise util.Abort(
783 _("a bookmark cannot have the name of an existing branch"))
783 _("a bookmark cannot have the name of an existing branch"))
784 if rev:
784 if rev:
785 marks[mark] = repo.lookup(rev)
785 marks[mark] = repo.lookup(rev)
786 else:
786 else:
787 marks[mark] = repo.changectx('.').node()
787 marks[mark] = repo.changectx('.').node()
788 if not inactive and repo.changectx('.').node() == marks[mark]:
788 if not inactive and repo.changectx('.').node() == marks[mark]:
789 bookmarks.setcurrent(repo, mark)
789 bookmarks.setcurrent(repo, mark)
790 bookmarks.write(repo)
790 bookmarks.write(repo)
791 return
791 return
792
792
793 if mark is None:
793 if mark is None:
794 if rev:
794 if rev:
795 raise util.Abort(_("bookmark name required"))
795 raise util.Abort(_("bookmark name required"))
796 if len(marks) == 0:
796 if len(marks) == 0:
797 ui.status(_("no bookmarks set\n"))
797 ui.status(_("no bookmarks set\n"))
798 else:
798 else:
799 for bmark, n in sorted(marks.iteritems()):
799 for bmark, n in sorted(marks.iteritems()):
800 current = repo._bookmarkcurrent
800 current = repo._bookmarkcurrent
801 if bmark == current and n == cur:
801 if bmark == current and n == cur:
802 prefix, label = '*', 'bookmarks.current'
802 prefix, label = '*', 'bookmarks.current'
803 else:
803 else:
804 prefix, label = ' ', ''
804 prefix, label = ' ', ''
805
805
806 if ui.quiet:
806 if ui.quiet:
807 ui.write("%s\n" % bmark, label=label)
807 ui.write("%s\n" % bmark, label=label)
808 else:
808 else:
809 ui.write(" %s %-25s %d:%s\n" % (
809 ui.write(" %s %-25s %d:%s\n" % (
810 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
810 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
811 label=label)
811 label=label)
812 return
812 return
813
813
814 @command('branch',
814 @command('branch',
815 [('f', 'force', None,
815 [('f', 'force', None,
816 _('set branch name even if it shadows an existing branch')),
816 _('set branch name even if it shadows an existing branch')),
817 ('C', 'clean', None, _('reset branch name to parent branch name'))],
817 ('C', 'clean', None, _('reset branch name to parent branch name'))],
818 _('[-fC] [NAME]'))
818 _('[-fC] [NAME]'))
819 def branch(ui, repo, label=None, **opts):
819 def branch(ui, repo, label=None, **opts):
820 """set or show the current branch name
820 """set or show the current branch name
821
821
822 With no argument, show the current branch name. With one argument,
822 With no argument, show the current branch name. With one argument,
823 set the working directory branch name (the branch will not exist
823 set the working directory branch name (the branch will not exist
824 in the repository until the next commit). Standard practice
824 in the repository until the next commit). Standard practice
825 recommends that primary development take place on the 'default'
825 recommends that primary development take place on the 'default'
826 branch.
826 branch.
827
827
828 Unless -f/--force is specified, branch will not let you set a
828 Unless -f/--force is specified, branch will not let you set a
829 branch name that already exists, even if it's inactive.
829 branch name that already exists, even if it's inactive.
830
830
831 Use -C/--clean to reset the working directory branch to that of
831 Use -C/--clean to reset the working directory branch to that of
832 the parent of the working directory, negating a previous branch
832 the parent of the working directory, negating a previous branch
833 change.
833 change.
834
834
835 Use the command :hg:`update` to switch to an existing branch. Use
835 Use the command :hg:`update` to switch to an existing branch. Use
836 :hg:`commit --close-branch` to mark this branch as closed.
836 :hg:`commit --close-branch` to mark this branch as closed.
837
837
838 .. note::
838 .. note::
839 Branch names are permanent. Use :hg:`bookmark` to create a
839 Branch names are permanent. Use :hg:`bookmark` to create a
840 light-weight bookmark instead. See :hg:`help glossary` for more
840 light-weight bookmark instead. See :hg:`help glossary` for more
841 information about named branches and bookmarks.
841 information about named branches and bookmarks.
842
842
843 Returns 0 on success.
843 Returns 0 on success.
844 """
844 """
845
845
846 if opts.get('clean'):
846 if opts.get('clean'):
847 label = repo[None].p1().branch()
847 label = repo[None].p1().branch()
848 repo.dirstate.setbranch(label)
848 repo.dirstate.setbranch(label)
849 ui.status(_('reset working directory to branch %s\n') % label)
849 ui.status(_('reset working directory to branch %s\n') % label)
850 elif label:
850 elif label:
851 if not opts.get('force') and label in repo.branchtags():
851 if not opts.get('force') and label in repo.branchtags():
852 if label not in [p.branch() for p in repo.parents()]:
852 if label not in [p.branch() for p in repo.parents()]:
853 raise util.Abort(_('a branch of the same name already exists'),
853 raise util.Abort(_('a branch of the same name already exists'),
854 # i18n: "it" refers to an existing branch
854 # i18n: "it" refers to an existing branch
855 hint=_("use 'hg update' to switch to it"))
855 hint=_("use 'hg update' to switch to it"))
856 repo.dirstate.setbranch(label)
856 repo.dirstate.setbranch(label)
857 ui.status(_('marked working directory as branch %s\n') % label)
857 ui.status(_('marked working directory as branch %s\n') % label)
858 else:
858 else:
859 ui.write("%s\n" % repo.dirstate.branch())
859 ui.write("%s\n" % repo.dirstate.branch())
860
860
861 @command('branches',
861 @command('branches',
862 [('a', 'active', False, _('show only branches that have unmerged heads')),
862 [('a', 'active', False, _('show only branches that have unmerged heads')),
863 ('c', 'closed', False, _('show normal and closed branches'))],
863 ('c', 'closed', False, _('show normal and closed branches'))],
864 _('[-ac]'))
864 _('[-ac]'))
865 def branches(ui, repo, active=False, closed=False):
865 def branches(ui, repo, active=False, closed=False):
866 """list repository named branches
866 """list repository named branches
867
867
868 List the repository's named branches, indicating which ones are
868 List the repository's named branches, indicating which ones are
869 inactive. If -c/--closed is specified, also list branches which have
869 inactive. If -c/--closed is specified, also list branches which have
870 been marked closed (see :hg:`commit --close-branch`).
870 been marked closed (see :hg:`commit --close-branch`).
871
871
872 If -a/--active is specified, only show active branches. A branch
872 If -a/--active is specified, only show active branches. A branch
873 is considered active if it contains repository heads.
873 is considered active if it contains repository heads.
874
874
875 Use the command :hg:`update` to switch to an existing branch.
875 Use the command :hg:`update` to switch to an existing branch.
876
876
877 Returns 0.
877 Returns 0.
878 """
878 """
879
879
880 hexfunc = ui.debugflag and hex or short
880 hexfunc = ui.debugflag and hex or short
881 activebranches = [repo[n].branch() for n in repo.heads()]
881 activebranches = [repo[n].branch() for n in repo.heads()]
882 def testactive(tag, node):
882 def testactive(tag, node):
883 realhead = tag in activebranches
883 realhead = tag in activebranches
884 open = node in repo.branchheads(tag, closed=False)
884 open = node in repo.branchheads(tag, closed=False)
885 return realhead and open
885 return realhead and open
886 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
886 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
887 for tag, node in repo.branchtags().items()],
887 for tag, node in repo.branchtags().items()],
888 reverse=True)
888 reverse=True)
889
889
890 for isactive, node, tag in branches:
890 for isactive, node, tag in branches:
891 if (not active) or isactive:
891 if (not active) or isactive:
892 if ui.quiet:
892 if ui.quiet:
893 ui.write("%s\n" % tag)
893 ui.write("%s\n" % tag)
894 else:
894 else:
895 hn = repo.lookup(node)
895 hn = repo.lookup(node)
896 if isactive:
896 if isactive:
897 label = 'branches.active'
897 label = 'branches.active'
898 notice = ''
898 notice = ''
899 elif hn not in repo.branchheads(tag, closed=False):
899 elif hn not in repo.branchheads(tag, closed=False):
900 if not closed:
900 if not closed:
901 continue
901 continue
902 label = 'branches.closed'
902 label = 'branches.closed'
903 notice = _(' (closed)')
903 notice = _(' (closed)')
904 else:
904 else:
905 label = 'branches.inactive'
905 label = 'branches.inactive'
906 notice = _(' (inactive)')
906 notice = _(' (inactive)')
907 if tag == repo.dirstate.branch():
907 if tag == repo.dirstate.branch():
908 label = 'branches.current'
908 label = 'branches.current'
909 rev = str(node).rjust(31 - encoding.colwidth(tag))
909 rev = str(node).rjust(31 - encoding.colwidth(tag))
910 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
910 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
911 tag = ui.label(tag, label)
911 tag = ui.label(tag, label)
912 ui.write("%s %s%s\n" % (tag, rev, notice))
912 ui.write("%s %s%s\n" % (tag, rev, notice))
913
913
914 @command('bundle',
914 @command('bundle',
915 [('f', 'force', None, _('run even when the destination is unrelated')),
915 [('f', 'force', None, _('run even when the destination is unrelated')),
916 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
916 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
917 _('REV')),
917 _('REV')),
918 ('b', 'branch', [], _('a specific branch you would like to bundle'),
918 ('b', 'branch', [], _('a specific branch you would like to bundle'),
919 _('BRANCH')),
919 _('BRANCH')),
920 ('', 'base', [],
920 ('', 'base', [],
921 _('a base changeset assumed to be available at the destination'),
921 _('a base changeset assumed to be available at the destination'),
922 _('REV')),
922 _('REV')),
923 ('a', 'all', None, _('bundle all changesets in the repository')),
923 ('a', 'all', None, _('bundle all changesets in the repository')),
924 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
924 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
925 ] + remoteopts,
925 ] + remoteopts,
926 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
926 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
927 def bundle(ui, repo, fname, dest=None, **opts):
927 def bundle(ui, repo, fname, dest=None, **opts):
928 """create a changegroup file
928 """create a changegroup file
929
929
930 Generate a compressed changegroup file collecting changesets not
930 Generate a compressed changegroup file collecting changesets not
931 known to be in another repository.
931 known to be in another repository.
932
932
933 If you omit the destination repository, then hg assumes the
933 If you omit the destination repository, then hg assumes the
934 destination will have all the nodes you specify with --base
934 destination will have all the nodes you specify with --base
935 parameters. To create a bundle containing all changesets, use
935 parameters. To create a bundle containing all changesets, use
936 -a/--all (or --base null).
936 -a/--all (or --base null).
937
937
938 You can change compression method with the -t/--type option.
938 You can change compression method with the -t/--type option.
939 The available compression methods are: none, bzip2, and
939 The available compression methods are: none, bzip2, and
940 gzip (by default, bundles are compressed using bzip2).
940 gzip (by default, bundles are compressed using bzip2).
941
941
942 The bundle file can then be transferred using conventional means
942 The bundle file can then be transferred using conventional means
943 and applied to another repository with the unbundle or pull
943 and applied to another repository with the unbundle or pull
944 command. This is useful when direct push and pull are not
944 command. This is useful when direct push and pull are not
945 available or when exporting an entire repository is undesirable.
945 available or when exporting an entire repository is undesirable.
946
946
947 Applying bundles preserves all changeset contents including
947 Applying bundles preserves all changeset contents including
948 permissions, copy/rename information, and revision history.
948 permissions, copy/rename information, and revision history.
949
949
950 Returns 0 on success, 1 if no changes found.
950 Returns 0 on success, 1 if no changes found.
951 """
951 """
952 revs = None
952 revs = None
953 if 'rev' in opts:
953 if 'rev' in opts:
954 revs = scmutil.revrange(repo, opts['rev'])
954 revs = scmutil.revrange(repo, opts['rev'])
955
955
956 if opts.get('all'):
956 if opts.get('all'):
957 base = ['null']
957 base = ['null']
958 else:
958 else:
959 base = scmutil.revrange(repo, opts.get('base'))
959 base = scmutil.revrange(repo, opts.get('base'))
960 if base:
960 if base:
961 if dest:
961 if dest:
962 raise util.Abort(_("--base is incompatible with specifying "
962 raise util.Abort(_("--base is incompatible with specifying "
963 "a destination"))
963 "a destination"))
964 common = [repo.lookup(rev) for rev in base]
964 common = [repo.lookup(rev) for rev in base]
965 heads = revs and map(repo.lookup, revs) or revs
965 heads = revs and map(repo.lookup, revs) or revs
966 else:
966 else:
967 dest = ui.expandpath(dest or 'default-push', dest or 'default')
967 dest = ui.expandpath(dest or 'default-push', dest or 'default')
968 dest, branches = hg.parseurl(dest, opts.get('branch'))
968 dest, branches = hg.parseurl(dest, opts.get('branch'))
969 other = hg.peer(repo, opts, dest)
969 other = hg.peer(repo, opts, dest)
970 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
970 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
971 heads = revs and map(repo.lookup, revs) or revs
971 heads = revs and map(repo.lookup, revs) or revs
972 common, outheads = discovery.findcommonoutgoing(repo, other,
972 common, outheads = discovery.findcommonoutgoing(repo, other,
973 onlyheads=heads,
973 onlyheads=heads,
974 force=opts.get('force'))
974 force=opts.get('force'))
975
975
976 cg = repo.getbundle('bundle', common=common, heads=heads)
976 cg = repo.getbundle('bundle', common=common, heads=heads)
977 if not cg:
977 if not cg:
978 ui.status(_("no changes found\n"))
978 ui.status(_("no changes found\n"))
979 return 1
979 return 1
980
980
981 bundletype = opts.get('type', 'bzip2').lower()
981 bundletype = opts.get('type', 'bzip2').lower()
982 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
982 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
983 bundletype = btypes.get(bundletype)
983 bundletype = btypes.get(bundletype)
984 if bundletype not in changegroup.bundletypes:
984 if bundletype not in changegroup.bundletypes:
985 raise util.Abort(_('unknown bundle type specified with --type'))
985 raise util.Abort(_('unknown bundle type specified with --type'))
986
986
987 changegroup.writebundle(cg, fname, bundletype)
987 changegroup.writebundle(cg, fname, bundletype)
988
988
989 @command('cat',
989 @command('cat',
990 [('o', 'output', '',
990 [('o', 'output', '',
991 _('print output to file with formatted name'), _('FORMAT')),
991 _('print output to file with formatted name'), _('FORMAT')),
992 ('r', 'rev', '', _('print the given revision'), _('REV')),
992 ('r', 'rev', '', _('print the given revision'), _('REV')),
993 ('', 'decode', None, _('apply any matching decode filter')),
993 ('', 'decode', None, _('apply any matching decode filter')),
994 ] + walkopts,
994 ] + walkopts,
995 _('[OPTION]... FILE...'))
995 _('[OPTION]... FILE...'))
996 def cat(ui, repo, file1, *pats, **opts):
996 def cat(ui, repo, file1, *pats, **opts):
997 """output the current or given revision of files
997 """output the current or given revision of files
998
998
999 Print the specified files as they were at the given revision. If
999 Print the specified files as they were at the given revision. If
1000 no revision is given, the parent of the working directory is used,
1000 no revision is given, the parent of the working directory is used,
1001 or tip if no revision is checked out.
1001 or tip if no revision is checked out.
1002
1002
1003 Output may be to a file, in which case the name of the file is
1003 Output may be to a file, in which case the name of the file is
1004 given using a format string. The formatting rules are the same as
1004 given using a format string. The formatting rules are the same as
1005 for the export command, with the following additions:
1005 for the export command, with the following additions:
1006
1006
1007 :``%s``: basename of file being printed
1007 :``%s``: basename of file being printed
1008 :``%d``: dirname of file being printed, or '.' if in repository root
1008 :``%d``: dirname of file being printed, or '.' if in repository root
1009 :``%p``: root-relative path name of file being printed
1009 :``%p``: root-relative path name of file being printed
1010
1010
1011 Returns 0 on success.
1011 Returns 0 on success.
1012 """
1012 """
1013 ctx = scmutil.revsingle(repo, opts.get('rev'))
1013 ctx = scmutil.revsingle(repo, opts.get('rev'))
1014 err = 1
1014 err = 1
1015 m = scmutil.match(ctx, (file1,) + pats, opts)
1015 m = scmutil.match(ctx, (file1,) + pats, opts)
1016 for abs in ctx.walk(m):
1016 for abs in ctx.walk(m):
1017 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1017 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1018 pathname=abs)
1018 pathname=abs)
1019 data = ctx[abs].data()
1019 data = ctx[abs].data()
1020 if opts.get('decode'):
1020 if opts.get('decode'):
1021 data = repo.wwritedata(abs, data)
1021 data = repo.wwritedata(abs, data)
1022 fp.write(data)
1022 fp.write(data)
1023 fp.close()
1023 fp.close()
1024 err = 0
1024 err = 0
1025 return err
1025 return err
1026
1026
1027 @command('^clone',
1027 @command('^clone',
1028 [('U', 'noupdate', None,
1028 [('U', 'noupdate', None,
1029 _('the clone will include an empty working copy (only a repository)')),
1029 _('the clone will include an empty working copy (only a repository)')),
1030 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1030 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1031 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1031 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1032 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1032 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1033 ('', 'pull', None, _('use pull protocol to copy metadata')),
1033 ('', 'pull', None, _('use pull protocol to copy metadata')),
1034 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1034 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1035 ] + remoteopts,
1035 ] + remoteopts,
1036 _('[OPTION]... SOURCE [DEST]'))
1036 _('[OPTION]... SOURCE [DEST]'))
1037 def clone(ui, source, dest=None, **opts):
1037 def clone(ui, source, dest=None, **opts):
1038 """make a copy of an existing repository
1038 """make a copy of an existing repository
1039
1039
1040 Create a copy of an existing repository in a new directory.
1040 Create a copy of an existing repository in a new directory.
1041
1041
1042 If no destination directory name is specified, it defaults to the
1042 If no destination directory name is specified, it defaults to the
1043 basename of the source.
1043 basename of the source.
1044
1044
1045 The location of the source is added to the new repository's
1045 The location of the source is added to the new repository's
1046 ``.hg/hgrc`` file, as the default to be used for future pulls.
1046 ``.hg/hgrc`` file, as the default to be used for future pulls.
1047
1047
1048 Only local paths and ``ssh://`` URLs are supported as
1048 Only local paths and ``ssh://`` URLs are supported as
1049 destinations. For ``ssh://`` destinations, no working directory or
1049 destinations. For ``ssh://`` destinations, no working directory or
1050 ``.hg/hgrc`` will be created on the remote side.
1050 ``.hg/hgrc`` will be created on the remote side.
1051
1051
1052 To pull only a subset of changesets, specify one or more revisions
1052 To pull only a subset of changesets, specify one or more revisions
1053 identifiers with -r/--rev or branches with -b/--branch. The
1053 identifiers with -r/--rev or branches with -b/--branch. The
1054 resulting clone will contain only the specified changesets and
1054 resulting clone will contain only the specified changesets and
1055 their ancestors. These options (or 'clone src#rev dest') imply
1055 their ancestors. These options (or 'clone src#rev dest') imply
1056 --pull, even for local source repositories. Note that specifying a
1056 --pull, even for local source repositories. Note that specifying a
1057 tag will include the tagged changeset but not the changeset
1057 tag will include the tagged changeset but not the changeset
1058 containing the tag.
1058 containing the tag.
1059
1059
1060 To check out a particular version, use -u/--update, or
1060 To check out a particular version, use -u/--update, or
1061 -U/--noupdate to create a clone with no working directory.
1061 -U/--noupdate to create a clone with no working directory.
1062
1062
1063 .. container:: verbose
1063 .. container:: verbose
1064
1064
1065 For efficiency, hardlinks are used for cloning whenever the
1065 For efficiency, hardlinks are used for cloning whenever the
1066 source and destination are on the same filesystem (note this
1066 source and destination are on the same filesystem (note this
1067 applies only to the repository data, not to the working
1067 applies only to the repository data, not to the working
1068 directory). Some filesystems, such as AFS, implement hardlinking
1068 directory). Some filesystems, such as AFS, implement hardlinking
1069 incorrectly, but do not report errors. In these cases, use the
1069 incorrectly, but do not report errors. In these cases, use the
1070 --pull option to avoid hardlinking.
1070 --pull option to avoid hardlinking.
1071
1071
1072 In some cases, you can clone repositories and the working
1072 In some cases, you can clone repositories and the working
1073 directory using full hardlinks with ::
1073 directory using full hardlinks with ::
1074
1074
1075 $ cp -al REPO REPOCLONE
1075 $ cp -al REPO REPOCLONE
1076
1076
1077 This is the fastest way to clone, but it is not always safe. The
1077 This is the fastest way to clone, but it is not always safe. The
1078 operation is not atomic (making sure REPO is not modified during
1078 operation is not atomic (making sure REPO is not modified during
1079 the operation is up to you) and you have to make sure your
1079 the operation is up to you) and you have to make sure your
1080 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1080 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1081 so). Also, this is not compatible with certain extensions that
1081 so). Also, this is not compatible with certain extensions that
1082 place their metadata under the .hg directory, such as mq.
1082 place their metadata under the .hg directory, such as mq.
1083
1083
1084 Mercurial will update the working directory to the first applicable
1084 Mercurial will update the working directory to the first applicable
1085 revision from this list:
1085 revision from this list:
1086
1086
1087 a) null if -U or the source repository has no changesets
1087 a) null if -U or the source repository has no changesets
1088 b) if -u . and the source repository is local, the first parent of
1088 b) if -u . and the source repository is local, the first parent of
1089 the source repository's working directory
1089 the source repository's working directory
1090 c) the changeset specified with -u (if a branch name, this means the
1090 c) the changeset specified with -u (if a branch name, this means the
1091 latest head of that branch)
1091 latest head of that branch)
1092 d) the changeset specified with -r
1092 d) the changeset specified with -r
1093 e) the tipmost head specified with -b
1093 e) the tipmost head specified with -b
1094 f) the tipmost head specified with the url#branch source syntax
1094 f) the tipmost head specified with the url#branch source syntax
1095 g) the tipmost head of the default branch
1095 g) the tipmost head of the default branch
1096 h) tip
1096 h) tip
1097
1097
1098 Examples:
1098 Examples:
1099
1099
1100 - clone a remote repository to a new directory named hg/::
1100 - clone a remote repository to a new directory named hg/::
1101
1101
1102 hg clone http://selenic.com/hg
1102 hg clone http://selenic.com/hg
1103
1103
1104 - create a lightweight local clone::
1104 - create a lightweight local clone::
1105
1105
1106 hg clone project/ project-feature/
1106 hg clone project/ project-feature/
1107
1107
1108 - clone from an absolute path on an ssh server (note double-slash)::
1108 - clone from an absolute path on an ssh server (note double-slash)::
1109
1109
1110 hg clone ssh://user@server//home/projects/alpha/
1110 hg clone ssh://user@server//home/projects/alpha/
1111
1111
1112 - do a high-speed clone over a LAN while checking out a
1112 - do a high-speed clone over a LAN while checking out a
1113 specified version::
1113 specified version::
1114
1114
1115 hg clone --uncompressed http://server/repo -u 1.5
1115 hg clone --uncompressed http://server/repo -u 1.5
1116
1116
1117 - create a repository without changesets after a particular revision::
1117 - create a repository without changesets after a particular revision::
1118
1118
1119 hg clone -r 04e544 experimental/ good/
1119 hg clone -r 04e544 experimental/ good/
1120
1120
1121 - clone (and track) a particular named branch::
1121 - clone (and track) a particular named branch::
1122
1122
1123 hg clone http://selenic.com/hg#stable
1123 hg clone http://selenic.com/hg#stable
1124
1124
1125 See :hg:`help urls` for details on specifying URLs.
1125 See :hg:`help urls` for details on specifying URLs.
1126
1126
1127 Returns 0 on success.
1127 Returns 0 on success.
1128 """
1128 """
1129 if opts.get('noupdate') and opts.get('updaterev'):
1129 if opts.get('noupdate') and opts.get('updaterev'):
1130 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1130 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1131
1131
1132 r = hg.clone(ui, opts, source, dest,
1132 r = hg.clone(ui, opts, source, dest,
1133 pull=opts.get('pull'),
1133 pull=opts.get('pull'),
1134 stream=opts.get('uncompressed'),
1134 stream=opts.get('uncompressed'),
1135 rev=opts.get('rev'),
1135 rev=opts.get('rev'),
1136 update=opts.get('updaterev') or not opts.get('noupdate'),
1136 update=opts.get('updaterev') or not opts.get('noupdate'),
1137 branch=opts.get('branch'))
1137 branch=opts.get('branch'))
1138
1138
1139 return r is None
1139 return r is None
1140
1140
1141 @command('^commit|ci',
1141 @command('^commit|ci',
1142 [('A', 'addremove', None,
1142 [('A', 'addremove', None,
1143 _('mark new/missing files as added/removed before committing')),
1143 _('mark new/missing files as added/removed before committing')),
1144 ('', 'close-branch', None,
1144 ('', 'close-branch', None,
1145 _('mark a branch as closed, hiding it from the branch list')),
1145 _('mark a branch as closed, hiding it from the branch list')),
1146 ] + walkopts + commitopts + commitopts2,
1146 ] + walkopts + commitopts + commitopts2,
1147 _('[OPTION]... [FILE]...'))
1147 _('[OPTION]... [FILE]...'))
1148 def commit(ui, repo, *pats, **opts):
1148 def commit(ui, repo, *pats, **opts):
1149 """commit the specified files or all outstanding changes
1149 """commit the specified files or all outstanding changes
1150
1150
1151 Commit changes to the given files into the repository. Unlike a
1151 Commit changes to the given files into the repository. Unlike a
1152 centralized SCM, this operation is a local operation. See
1152 centralized SCM, this operation is a local operation. See
1153 :hg:`push` for a way to actively distribute your changes.
1153 :hg:`push` for a way to actively distribute your changes.
1154
1154
1155 If a list of files is omitted, all changes reported by :hg:`status`
1155 If a list of files is omitted, all changes reported by :hg:`status`
1156 will be committed.
1156 will be committed.
1157
1157
1158 If you are committing the result of a merge, do not provide any
1158 If you are committing the result of a merge, do not provide any
1159 filenames or -I/-X filters.
1159 filenames or -I/-X filters.
1160
1160
1161 If no commit message is specified, Mercurial starts your
1161 If no commit message is specified, Mercurial starts your
1162 configured editor where you can enter a message. In case your
1162 configured editor where you can enter a message. In case your
1163 commit fails, you will find a backup of your message in
1163 commit fails, you will find a backup of your message in
1164 ``.hg/last-message.txt``.
1164 ``.hg/last-message.txt``.
1165
1165
1166 See :hg:`help dates` for a list of formats valid for -d/--date.
1166 See :hg:`help dates` for a list of formats valid for -d/--date.
1167
1167
1168 Returns 0 on success, 1 if nothing changed.
1168 Returns 0 on success, 1 if nothing changed.
1169 """
1169 """
1170 extra = {}
1170 extra = {}
1171 if opts.get('close_branch'):
1171 if opts.get('close_branch'):
1172 if repo['.'].node() not in repo.branchheads():
1172 if repo['.'].node() not in repo.branchheads():
1173 # The topo heads set is included in the branch heads set of the
1173 # The topo heads set is included in the branch heads set of the
1174 # current branch, so it's sufficient to test branchheads
1174 # current branch, so it's sufficient to test branchheads
1175 raise util.Abort(_('can only close branch heads'))
1175 raise util.Abort(_('can only close branch heads'))
1176 extra['close'] = 1
1176 extra['close'] = 1
1177 e = cmdutil.commiteditor
1177 e = cmdutil.commiteditor
1178 if opts.get('force_editor'):
1178 if opts.get('force_editor'):
1179 e = cmdutil.commitforceeditor
1179 e = cmdutil.commitforceeditor
1180
1180
1181 def commitfunc(ui, repo, message, match, opts):
1181 def commitfunc(ui, repo, message, match, opts):
1182 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1182 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1183 editor=e, extra=extra)
1183 editor=e, extra=extra)
1184
1184
1185 branch = repo[None].branch()
1185 branch = repo[None].branch()
1186 bheads = repo.branchheads(branch)
1186 bheads = repo.branchheads(branch)
1187
1187
1188 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1188 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1189 if not node:
1189 if not node:
1190 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1190 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1191 if stat[3]:
1191 if stat[3]:
1192 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1192 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1193 % len(stat[3]))
1193 % len(stat[3]))
1194 else:
1194 else:
1195 ui.status(_("nothing changed\n"))
1195 ui.status(_("nothing changed\n"))
1196 return 1
1196 return 1
1197
1197
1198 ctx = repo[node]
1198 ctx = repo[node]
1199 parents = ctx.parents()
1199 parents = ctx.parents()
1200
1200
1201 if (bheads and node not in bheads and not
1201 if (bheads and node not in bheads and not
1202 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1202 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1203 ui.status(_('created new head\n'))
1203 ui.status(_('created new head\n'))
1204 # The message is not printed for initial roots. For the other
1204 # The message is not printed for initial roots. For the other
1205 # changesets, it is printed in the following situations:
1205 # changesets, it is printed in the following situations:
1206 #
1206 #
1207 # Par column: for the 2 parents with ...
1207 # Par column: for the 2 parents with ...
1208 # N: null or no parent
1208 # N: null or no parent
1209 # B: parent is on another named branch
1209 # B: parent is on another named branch
1210 # C: parent is a regular non head changeset
1210 # C: parent is a regular non head changeset
1211 # H: parent was a branch head of the current branch
1211 # H: parent was a branch head of the current branch
1212 # Msg column: whether we print "created new head" message
1212 # Msg column: whether we print "created new head" message
1213 # In the following, it is assumed that there already exists some
1213 # In the following, it is assumed that there already exists some
1214 # initial branch heads of the current branch, otherwise nothing is
1214 # initial branch heads of the current branch, otherwise nothing is
1215 # printed anyway.
1215 # printed anyway.
1216 #
1216 #
1217 # Par Msg Comment
1217 # Par Msg Comment
1218 # NN y additional topo root
1218 # NN y additional topo root
1219 #
1219 #
1220 # BN y additional branch root
1220 # BN y additional branch root
1221 # CN y additional topo head
1221 # CN y additional topo head
1222 # HN n usual case
1222 # HN n usual case
1223 #
1223 #
1224 # BB y weird additional branch root
1224 # BB y weird additional branch root
1225 # CB y branch merge
1225 # CB y branch merge
1226 # HB n merge with named branch
1226 # HB n merge with named branch
1227 #
1227 #
1228 # CC y additional head from merge
1228 # CC y additional head from merge
1229 # CH n merge with a head
1229 # CH n merge with a head
1230 #
1230 #
1231 # HH n head merge: head count decreases
1231 # HH n head merge: head count decreases
1232
1232
1233 if not opts.get('close_branch'):
1233 if not opts.get('close_branch'):
1234 for r in parents:
1234 for r in parents:
1235 if r.extra().get('close') and r.branch() == branch:
1235 if r.extra().get('close') and r.branch() == branch:
1236 ui.status(_('reopening closed branch head %d\n') % r)
1236 ui.status(_('reopening closed branch head %d\n') % r)
1237
1237
1238 if ui.debugflag:
1238 if ui.debugflag:
1239 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1239 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1240 elif ui.verbose:
1240 elif ui.verbose:
1241 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1241 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1242
1242
1243 @command('copy|cp',
1243 @command('copy|cp',
1244 [('A', 'after', None, _('record a copy that has already occurred')),
1244 [('A', 'after', None, _('record a copy that has already occurred')),
1245 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1245 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1246 ] + walkopts + dryrunopts,
1246 ] + walkopts + dryrunopts,
1247 _('[OPTION]... [SOURCE]... DEST'))
1247 _('[OPTION]... [SOURCE]... DEST'))
1248 def copy(ui, repo, *pats, **opts):
1248 def copy(ui, repo, *pats, **opts):
1249 """mark files as copied for the next commit
1249 """mark files as copied for the next commit
1250
1250
1251 Mark dest as having copies of source files. If dest is a
1251 Mark dest as having copies of source files. If dest is a
1252 directory, copies are put in that directory. If dest is a file,
1252 directory, copies are put in that directory. If dest is a file,
1253 the source must be a single file.
1253 the source must be a single file.
1254
1254
1255 By default, this command copies the contents of files as they
1255 By default, this command copies the contents of files as they
1256 exist in the working directory. If invoked with -A/--after, the
1256 exist in the working directory. If invoked with -A/--after, the
1257 operation is recorded, but no copying is performed.
1257 operation is recorded, but no copying is performed.
1258
1258
1259 This command takes effect with the next commit. To undo a copy
1259 This command takes effect with the next commit. To undo a copy
1260 before that, see :hg:`revert`.
1260 before that, see :hg:`revert`.
1261
1261
1262 Returns 0 on success, 1 if errors are encountered.
1262 Returns 0 on success, 1 if errors are encountered.
1263 """
1263 """
1264 wlock = repo.wlock(False)
1264 wlock = repo.wlock(False)
1265 try:
1265 try:
1266 return cmdutil.copy(ui, repo, pats, opts)
1266 return cmdutil.copy(ui, repo, pats, opts)
1267 finally:
1267 finally:
1268 wlock.release()
1268 wlock.release()
1269
1269
1270 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1270 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1271 def debugancestor(ui, repo, *args):
1271 def debugancestor(ui, repo, *args):
1272 """find the ancestor revision of two revisions in a given index"""
1272 """find the ancestor revision of two revisions in a given index"""
1273 if len(args) == 3:
1273 if len(args) == 3:
1274 index, rev1, rev2 = args
1274 index, rev1, rev2 = args
1275 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1275 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1276 lookup = r.lookup
1276 lookup = r.lookup
1277 elif len(args) == 2:
1277 elif len(args) == 2:
1278 if not repo:
1278 if not repo:
1279 raise util.Abort(_("there is no Mercurial repository here "
1279 raise util.Abort(_("there is no Mercurial repository here "
1280 "(.hg not found)"))
1280 "(.hg not found)"))
1281 rev1, rev2 = args
1281 rev1, rev2 = args
1282 r = repo.changelog
1282 r = repo.changelog
1283 lookup = repo.lookup
1283 lookup = repo.lookup
1284 else:
1284 else:
1285 raise util.Abort(_('either two or three arguments required'))
1285 raise util.Abort(_('either two or three arguments required'))
1286 a = r.ancestor(lookup(rev1), lookup(rev2))
1286 a = r.ancestor(lookup(rev1), lookup(rev2))
1287 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1287 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1288
1288
1289 @command('debugbuilddag',
1289 @command('debugbuilddag',
1290 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1290 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1291 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1291 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1292 ('n', 'new-file', None, _('add new file at each rev'))],
1292 ('n', 'new-file', None, _('add new file at each rev'))],
1293 _('[OPTION]... [TEXT]'))
1293 _('[OPTION]... [TEXT]'))
1294 def debugbuilddag(ui, repo, text=None,
1294 def debugbuilddag(ui, repo, text=None,
1295 mergeable_file=False,
1295 mergeable_file=False,
1296 overwritten_file=False,
1296 overwritten_file=False,
1297 new_file=False):
1297 new_file=False):
1298 """builds a repo with a given DAG from scratch in the current empty repo
1298 """builds a repo with a given DAG from scratch in the current empty repo
1299
1299
1300 The description of the DAG is read from stdin if not given on the
1300 The description of the DAG is read from stdin if not given on the
1301 command line.
1301 command line.
1302
1302
1303 Elements:
1303 Elements:
1304
1304
1305 - "+n" is a linear run of n nodes based on the current default parent
1305 - "+n" is a linear run of n nodes based on the current default parent
1306 - "." is a single node based on the current default parent
1306 - "." is a single node based on the current default parent
1307 - "$" resets the default parent to null (implied at the start);
1307 - "$" resets the default parent to null (implied at the start);
1308 otherwise the default parent is always the last node created
1308 otherwise the default parent is always the last node created
1309 - "<p" sets the default parent to the backref p
1309 - "<p" sets the default parent to the backref p
1310 - "*p" is a fork at parent p, which is a backref
1310 - "*p" is a fork at parent p, which is a backref
1311 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1311 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1312 - "/p2" is a merge of the preceding node and p2
1312 - "/p2" is a merge of the preceding node and p2
1313 - ":tag" defines a local tag for the preceding node
1313 - ":tag" defines a local tag for the preceding node
1314 - "@branch" sets the named branch for subsequent nodes
1314 - "@branch" sets the named branch for subsequent nodes
1315 - "#...\\n" is a comment up to the end of the line
1315 - "#...\\n" is a comment up to the end of the line
1316
1316
1317 Whitespace between the above elements is ignored.
1317 Whitespace between the above elements is ignored.
1318
1318
1319 A backref is either
1319 A backref is either
1320
1320
1321 - a number n, which references the node curr-n, where curr is the current
1321 - a number n, which references the node curr-n, where curr is the current
1322 node, or
1322 node, or
1323 - the name of a local tag you placed earlier using ":tag", or
1323 - the name of a local tag you placed earlier using ":tag", or
1324 - empty to denote the default parent.
1324 - empty to denote the default parent.
1325
1325
1326 All string valued-elements are either strictly alphanumeric, or must
1326 All string valued-elements are either strictly alphanumeric, or must
1327 be enclosed in double quotes ("..."), with "\\" as escape character.
1327 be enclosed in double quotes ("..."), with "\\" as escape character.
1328 """
1328 """
1329
1329
1330 if text is None:
1330 if text is None:
1331 ui.status(_("reading DAG from stdin\n"))
1331 ui.status(_("reading DAG from stdin\n"))
1332 text = ui.fin.read()
1332 text = ui.fin.read()
1333
1333
1334 cl = repo.changelog
1334 cl = repo.changelog
1335 if len(cl) > 0:
1335 if len(cl) > 0:
1336 raise util.Abort(_('repository is not empty'))
1336 raise util.Abort(_('repository is not empty'))
1337
1337
1338 # determine number of revs in DAG
1338 # determine number of revs in DAG
1339 total = 0
1339 total = 0
1340 for type, data in dagparser.parsedag(text):
1340 for type, data in dagparser.parsedag(text):
1341 if type == 'n':
1341 if type == 'n':
1342 total += 1
1342 total += 1
1343
1343
1344 if mergeable_file:
1344 if mergeable_file:
1345 linesperrev = 2
1345 linesperrev = 2
1346 # make a file with k lines per rev
1346 # make a file with k lines per rev
1347 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1347 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1348 initialmergedlines.append("")
1348 initialmergedlines.append("")
1349
1349
1350 tags = []
1350 tags = []
1351
1351
1352 tr = repo.transaction("builddag")
1352 tr = repo.transaction("builddag")
1353 try:
1353 try:
1354
1354
1355 at = -1
1355 at = -1
1356 atbranch = 'default'
1356 atbranch = 'default'
1357 nodeids = []
1357 nodeids = []
1358 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1358 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1359 for type, data in dagparser.parsedag(text):
1359 for type, data in dagparser.parsedag(text):
1360 if type == 'n':
1360 if type == 'n':
1361 ui.note('node %s\n' % str(data))
1361 ui.note('node %s\n' % str(data))
1362 id, ps = data
1362 id, ps = data
1363
1363
1364 files = []
1364 files = []
1365 fctxs = {}
1365 fctxs = {}
1366
1366
1367 p2 = None
1367 p2 = None
1368 if mergeable_file:
1368 if mergeable_file:
1369 fn = "mf"
1369 fn = "mf"
1370 p1 = repo[ps[0]]
1370 p1 = repo[ps[0]]
1371 if len(ps) > 1:
1371 if len(ps) > 1:
1372 p2 = repo[ps[1]]
1372 p2 = repo[ps[1]]
1373 pa = p1.ancestor(p2)
1373 pa = p1.ancestor(p2)
1374 base, local, other = [x[fn].data() for x in pa, p1, p2]
1374 base, local, other = [x[fn].data() for x in pa, p1, p2]
1375 m3 = simplemerge.Merge3Text(base, local, other)
1375 m3 = simplemerge.Merge3Text(base, local, other)
1376 ml = [l.strip() for l in m3.merge_lines()]
1376 ml = [l.strip() for l in m3.merge_lines()]
1377 ml.append("")
1377 ml.append("")
1378 elif at > 0:
1378 elif at > 0:
1379 ml = p1[fn].data().split("\n")
1379 ml = p1[fn].data().split("\n")
1380 else:
1380 else:
1381 ml = initialmergedlines
1381 ml = initialmergedlines
1382 ml[id * linesperrev] += " r%i" % id
1382 ml[id * linesperrev] += " r%i" % id
1383 mergedtext = "\n".join(ml)
1383 mergedtext = "\n".join(ml)
1384 files.append(fn)
1384 files.append(fn)
1385 fctxs[fn] = context.memfilectx(fn, mergedtext)
1385 fctxs[fn] = context.memfilectx(fn, mergedtext)
1386
1386
1387 if overwritten_file:
1387 if overwritten_file:
1388 fn = "of"
1388 fn = "of"
1389 files.append(fn)
1389 files.append(fn)
1390 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1390 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1391
1391
1392 if new_file:
1392 if new_file:
1393 fn = "nf%i" % id
1393 fn = "nf%i" % id
1394 files.append(fn)
1394 files.append(fn)
1395 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1395 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1396 if len(ps) > 1:
1396 if len(ps) > 1:
1397 if not p2:
1397 if not p2:
1398 p2 = repo[ps[1]]
1398 p2 = repo[ps[1]]
1399 for fn in p2:
1399 for fn in p2:
1400 if fn.startswith("nf"):
1400 if fn.startswith("nf"):
1401 files.append(fn)
1401 files.append(fn)
1402 fctxs[fn] = p2[fn]
1402 fctxs[fn] = p2[fn]
1403
1403
1404 def fctxfn(repo, cx, path):
1404 def fctxfn(repo, cx, path):
1405 return fctxs.get(path)
1405 return fctxs.get(path)
1406
1406
1407 if len(ps) == 0 or ps[0] < 0:
1407 if len(ps) == 0 or ps[0] < 0:
1408 pars = [None, None]
1408 pars = [None, None]
1409 elif len(ps) == 1:
1409 elif len(ps) == 1:
1410 pars = [nodeids[ps[0]], None]
1410 pars = [nodeids[ps[0]], None]
1411 else:
1411 else:
1412 pars = [nodeids[p] for p in ps]
1412 pars = [nodeids[p] for p in ps]
1413 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1413 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1414 date=(id, 0),
1414 date=(id, 0),
1415 user="debugbuilddag",
1415 user="debugbuilddag",
1416 extra={'branch': atbranch})
1416 extra={'branch': atbranch})
1417 nodeid = repo.commitctx(cx)
1417 nodeid = repo.commitctx(cx)
1418 nodeids.append(nodeid)
1418 nodeids.append(nodeid)
1419 at = id
1419 at = id
1420 elif type == 'l':
1420 elif type == 'l':
1421 id, name = data
1421 id, name = data
1422 ui.note('tag %s\n' % name)
1422 ui.note('tag %s\n' % name)
1423 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1423 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1424 elif type == 'a':
1424 elif type == 'a':
1425 ui.note('branch %s\n' % data)
1425 ui.note('branch %s\n' % data)
1426 atbranch = data
1426 atbranch = data
1427 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1427 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1428 tr.close()
1428 tr.close()
1429 finally:
1429 finally:
1430 ui.progress(_('building'), None)
1430 ui.progress(_('building'), None)
1431 tr.release()
1431 tr.release()
1432
1432
1433 if tags:
1433 if tags:
1434 repo.opener.write("localtags", "".join(tags))
1434 repo.opener.write("localtags", "".join(tags))
1435
1435
1436 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1436 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1437 def debugbundle(ui, bundlepath, all=None, **opts):
1437 def debugbundle(ui, bundlepath, all=None, **opts):
1438 """lists the contents of a bundle"""
1438 """lists the contents of a bundle"""
1439 f = url.open(ui, bundlepath)
1439 f = url.open(ui, bundlepath)
1440 try:
1440 try:
1441 gen = changegroup.readbundle(f, bundlepath)
1441 gen = changegroup.readbundle(f, bundlepath)
1442 if all:
1442 if all:
1443 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1443 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1444
1444
1445 def showchunks(named):
1445 def showchunks(named):
1446 ui.write("\n%s\n" % named)
1446 ui.write("\n%s\n" % named)
1447 chain = None
1447 chain = None
1448 while True:
1448 while True:
1449 chunkdata = gen.deltachunk(chain)
1449 chunkdata = gen.deltachunk(chain)
1450 if not chunkdata:
1450 if not chunkdata:
1451 break
1451 break
1452 node = chunkdata['node']
1452 node = chunkdata['node']
1453 p1 = chunkdata['p1']
1453 p1 = chunkdata['p1']
1454 p2 = chunkdata['p2']
1454 p2 = chunkdata['p2']
1455 cs = chunkdata['cs']
1455 cs = chunkdata['cs']
1456 deltabase = chunkdata['deltabase']
1456 deltabase = chunkdata['deltabase']
1457 delta = chunkdata['delta']
1457 delta = chunkdata['delta']
1458 ui.write("%s %s %s %s %s %s\n" %
1458 ui.write("%s %s %s %s %s %s\n" %
1459 (hex(node), hex(p1), hex(p2),
1459 (hex(node), hex(p1), hex(p2),
1460 hex(cs), hex(deltabase), len(delta)))
1460 hex(cs), hex(deltabase), len(delta)))
1461 chain = node
1461 chain = node
1462
1462
1463 chunkdata = gen.changelogheader()
1463 chunkdata = gen.changelogheader()
1464 showchunks("changelog")
1464 showchunks("changelog")
1465 chunkdata = gen.manifestheader()
1465 chunkdata = gen.manifestheader()
1466 showchunks("manifest")
1466 showchunks("manifest")
1467 while True:
1467 while True:
1468 chunkdata = gen.filelogheader()
1468 chunkdata = gen.filelogheader()
1469 if not chunkdata:
1469 if not chunkdata:
1470 break
1470 break
1471 fname = chunkdata['filename']
1471 fname = chunkdata['filename']
1472 showchunks(fname)
1472 showchunks(fname)
1473 else:
1473 else:
1474 chunkdata = gen.changelogheader()
1474 chunkdata = gen.changelogheader()
1475 chain = None
1475 chain = None
1476 while True:
1476 while True:
1477 chunkdata = gen.deltachunk(chain)
1477 chunkdata = gen.deltachunk(chain)
1478 if not chunkdata:
1478 if not chunkdata:
1479 break
1479 break
1480 node = chunkdata['node']
1480 node = chunkdata['node']
1481 ui.write("%s\n" % hex(node))
1481 ui.write("%s\n" % hex(node))
1482 chain = node
1482 chain = node
1483 finally:
1483 finally:
1484 f.close()
1484 f.close()
1485
1485
1486 @command('debugcheckstate', [], '')
1486 @command('debugcheckstate', [], '')
1487 def debugcheckstate(ui, repo):
1487 def debugcheckstate(ui, repo):
1488 """validate the correctness of the current dirstate"""
1488 """validate the correctness of the current dirstate"""
1489 parent1, parent2 = repo.dirstate.parents()
1489 parent1, parent2 = repo.dirstate.parents()
1490 m1 = repo[parent1].manifest()
1490 m1 = repo[parent1].manifest()
1491 m2 = repo[parent2].manifest()
1491 m2 = repo[parent2].manifest()
1492 errors = 0
1492 errors = 0
1493 for f in repo.dirstate:
1493 for f in repo.dirstate:
1494 state = repo.dirstate[f]
1494 state = repo.dirstate[f]
1495 if state in "nr" and f not in m1:
1495 if state in "nr" and f not in m1:
1496 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1496 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1497 errors += 1
1497 errors += 1
1498 if state in "a" and f in m1:
1498 if state in "a" and f in m1:
1499 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1499 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1500 errors += 1
1500 errors += 1
1501 if state in "m" and f not in m1 and f not in m2:
1501 if state in "m" and f not in m1 and f not in m2:
1502 ui.warn(_("%s in state %s, but not in either manifest\n") %
1502 ui.warn(_("%s in state %s, but not in either manifest\n") %
1503 (f, state))
1503 (f, state))
1504 errors += 1
1504 errors += 1
1505 for f in m1:
1505 for f in m1:
1506 state = repo.dirstate[f]
1506 state = repo.dirstate[f]
1507 if state not in "nrm":
1507 if state not in "nrm":
1508 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1508 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1509 errors += 1
1509 errors += 1
1510 if errors:
1510 if errors:
1511 error = _(".hg/dirstate inconsistent with current parent's manifest")
1511 error = _(".hg/dirstate inconsistent with current parent's manifest")
1512 raise util.Abort(error)
1512 raise util.Abort(error)
1513
1513
1514 @command('debugcommands', [], _('[COMMAND]'))
1514 @command('debugcommands', [], _('[COMMAND]'))
1515 def debugcommands(ui, cmd='', *args):
1515 def debugcommands(ui, cmd='', *args):
1516 """list all available commands and options"""
1516 """list all available commands and options"""
1517 for cmd, vals in sorted(table.iteritems()):
1517 for cmd, vals in sorted(table.iteritems()):
1518 cmd = cmd.split('|')[0].strip('^')
1518 cmd = cmd.split('|')[0].strip('^')
1519 opts = ', '.join([i[1] for i in vals[1]])
1519 opts = ', '.join([i[1] for i in vals[1]])
1520 ui.write('%s: %s\n' % (cmd, opts))
1520 ui.write('%s: %s\n' % (cmd, opts))
1521
1521
1522 @command('debugcomplete',
1522 @command('debugcomplete',
1523 [('o', 'options', None, _('show the command options'))],
1523 [('o', 'options', None, _('show the command options'))],
1524 _('[-o] CMD'))
1524 _('[-o] CMD'))
1525 def debugcomplete(ui, cmd='', **opts):
1525 def debugcomplete(ui, cmd='', **opts):
1526 """returns the completion list associated with the given command"""
1526 """returns the completion list associated with the given command"""
1527
1527
1528 if opts.get('options'):
1528 if opts.get('options'):
1529 options = []
1529 options = []
1530 otables = [globalopts]
1530 otables = [globalopts]
1531 if cmd:
1531 if cmd:
1532 aliases, entry = cmdutil.findcmd(cmd, table, False)
1532 aliases, entry = cmdutil.findcmd(cmd, table, False)
1533 otables.append(entry[1])
1533 otables.append(entry[1])
1534 for t in otables:
1534 for t in otables:
1535 for o in t:
1535 for o in t:
1536 if "(DEPRECATED)" in o[3]:
1536 if "(DEPRECATED)" in o[3]:
1537 continue
1537 continue
1538 if o[0]:
1538 if o[0]:
1539 options.append('-%s' % o[0])
1539 options.append('-%s' % o[0])
1540 options.append('--%s' % o[1])
1540 options.append('--%s' % o[1])
1541 ui.write("%s\n" % "\n".join(options))
1541 ui.write("%s\n" % "\n".join(options))
1542 return
1542 return
1543
1543
1544 cmdlist = cmdutil.findpossible(cmd, table)
1544 cmdlist = cmdutil.findpossible(cmd, table)
1545 if ui.verbose:
1545 if ui.verbose:
1546 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1546 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1547 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1547 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1548
1548
1549 @command('debugdag',
1549 @command('debugdag',
1550 [('t', 'tags', None, _('use tags as labels')),
1550 [('t', 'tags', None, _('use tags as labels')),
1551 ('b', 'branches', None, _('annotate with branch names')),
1551 ('b', 'branches', None, _('annotate with branch names')),
1552 ('', 'dots', None, _('use dots for runs')),
1552 ('', 'dots', None, _('use dots for runs')),
1553 ('s', 'spaces', None, _('separate elements by spaces'))],
1553 ('s', 'spaces', None, _('separate elements by spaces'))],
1554 _('[OPTION]... [FILE [REV]...]'))
1554 _('[OPTION]... [FILE [REV]...]'))
1555 def debugdag(ui, repo, file_=None, *revs, **opts):
1555 def debugdag(ui, repo, file_=None, *revs, **opts):
1556 """format the changelog or an index DAG as a concise textual description
1556 """format the changelog or an index DAG as a concise textual description
1557
1557
1558 If you pass a revlog index, the revlog's DAG is emitted. If you list
1558 If you pass a revlog index, the revlog's DAG is emitted. If you list
1559 revision numbers, they get labelled in the output as rN.
1559 revision numbers, they get labelled in the output as rN.
1560
1560
1561 Otherwise, the changelog DAG of the current repo is emitted.
1561 Otherwise, the changelog DAG of the current repo is emitted.
1562 """
1562 """
1563 spaces = opts.get('spaces')
1563 spaces = opts.get('spaces')
1564 dots = opts.get('dots')
1564 dots = opts.get('dots')
1565 if file_:
1565 if file_:
1566 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1566 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1567 revs = set((int(r) for r in revs))
1567 revs = set((int(r) for r in revs))
1568 def events():
1568 def events():
1569 for r in rlog:
1569 for r in rlog:
1570 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1570 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1571 if r in revs:
1571 if r in revs:
1572 yield 'l', (r, "r%i" % r)
1572 yield 'l', (r, "r%i" % r)
1573 elif repo:
1573 elif repo:
1574 cl = repo.changelog
1574 cl = repo.changelog
1575 tags = opts.get('tags')
1575 tags = opts.get('tags')
1576 branches = opts.get('branches')
1576 branches = opts.get('branches')
1577 if tags:
1577 if tags:
1578 labels = {}
1578 labels = {}
1579 for l, n in repo.tags().items():
1579 for l, n in repo.tags().items():
1580 labels.setdefault(cl.rev(n), []).append(l)
1580 labels.setdefault(cl.rev(n), []).append(l)
1581 def events():
1581 def events():
1582 b = "default"
1582 b = "default"
1583 for r in cl:
1583 for r in cl:
1584 if branches:
1584 if branches:
1585 newb = cl.read(cl.node(r))[5]['branch']
1585 newb = cl.read(cl.node(r))[5]['branch']
1586 if newb != b:
1586 if newb != b:
1587 yield 'a', newb
1587 yield 'a', newb
1588 b = newb
1588 b = newb
1589 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1589 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1590 if tags:
1590 if tags:
1591 ls = labels.get(r)
1591 ls = labels.get(r)
1592 if ls:
1592 if ls:
1593 for l in ls:
1593 for l in ls:
1594 yield 'l', (r, l)
1594 yield 'l', (r, l)
1595 else:
1595 else:
1596 raise util.Abort(_('need repo for changelog dag'))
1596 raise util.Abort(_('need repo for changelog dag'))
1597
1597
1598 for line in dagparser.dagtextlines(events(),
1598 for line in dagparser.dagtextlines(events(),
1599 addspaces=spaces,
1599 addspaces=spaces,
1600 wraplabels=True,
1600 wraplabels=True,
1601 wrapannotations=True,
1601 wrapannotations=True,
1602 wrapnonlinear=dots,
1602 wrapnonlinear=dots,
1603 usedots=dots,
1603 usedots=dots,
1604 maxlinewidth=70):
1604 maxlinewidth=70):
1605 ui.write(line)
1605 ui.write(line)
1606 ui.write("\n")
1606 ui.write("\n")
1607
1607
1608 @command('debugdata',
1608 @command('debugdata',
1609 [('c', 'changelog', False, _('open changelog')),
1609 [('c', 'changelog', False, _('open changelog')),
1610 ('m', 'manifest', False, _('open manifest'))],
1610 ('m', 'manifest', False, _('open manifest'))],
1611 _('-c|-m|FILE REV'))
1611 _('-c|-m|FILE REV'))
1612 def debugdata(ui, repo, file_, rev = None, **opts):
1612 def debugdata(ui, repo, file_, rev = None, **opts):
1613 """dump the contents of a data file revision"""
1613 """dump the contents of a data file revision"""
1614 if opts.get('changelog') or opts.get('manifest'):
1614 if opts.get('changelog') or opts.get('manifest'):
1615 file_, rev = None, file_
1615 file_, rev = None, file_
1616 elif rev is None:
1616 elif rev is None:
1617 raise error.CommandError('debugdata', _('invalid arguments'))
1617 raise error.CommandError('debugdata', _('invalid arguments'))
1618 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1618 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1619 try:
1619 try:
1620 ui.write(r.revision(r.lookup(rev)))
1620 ui.write(r.revision(r.lookup(rev)))
1621 except KeyError:
1621 except KeyError:
1622 raise util.Abort(_('invalid revision identifier %s') % rev)
1622 raise util.Abort(_('invalid revision identifier %s') % rev)
1623
1623
1624 @command('debugdate',
1624 @command('debugdate',
1625 [('e', 'extended', None, _('try extended date formats'))],
1625 [('e', 'extended', None, _('try extended date formats'))],
1626 _('[-e] DATE [RANGE]'))
1626 _('[-e] DATE [RANGE]'))
1627 def debugdate(ui, date, range=None, **opts):
1627 def debugdate(ui, date, range=None, **opts):
1628 """parse and display a date"""
1628 """parse and display a date"""
1629 if opts["extended"]:
1629 if opts["extended"]:
1630 d = util.parsedate(date, util.extendeddateformats)
1630 d = util.parsedate(date, util.extendeddateformats)
1631 else:
1631 else:
1632 d = util.parsedate(date)
1632 d = util.parsedate(date)
1633 ui.write("internal: %s %s\n" % d)
1633 ui.write("internal: %s %s\n" % d)
1634 ui.write("standard: %s\n" % util.datestr(d))
1634 ui.write("standard: %s\n" % util.datestr(d))
1635 if range:
1635 if range:
1636 m = util.matchdate(range)
1636 m = util.matchdate(range)
1637 ui.write("match: %s\n" % m(d[0]))
1637 ui.write("match: %s\n" % m(d[0]))
1638
1638
1639 @command('debugdiscovery',
1639 @command('debugdiscovery',
1640 [('', 'old', None, _('use old-style discovery')),
1640 [('', 'old', None, _('use old-style discovery')),
1641 ('', 'nonheads', None,
1641 ('', 'nonheads', None,
1642 _('use old-style discovery with non-heads included')),
1642 _('use old-style discovery with non-heads included')),
1643 ] + remoteopts,
1643 ] + remoteopts,
1644 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1644 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1645 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1645 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1646 """runs the changeset discovery protocol in isolation"""
1646 """runs the changeset discovery protocol in isolation"""
1647 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1647 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1648 remote = hg.peer(repo, opts, remoteurl)
1648 remote = hg.peer(repo, opts, remoteurl)
1649 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1649 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1650
1650
1651 # make sure tests are repeatable
1651 # make sure tests are repeatable
1652 random.seed(12323)
1652 random.seed(12323)
1653
1653
1654 def doit(localheads, remoteheads):
1654 def doit(localheads, remoteheads):
1655 if opts.get('old'):
1655 if opts.get('old'):
1656 if localheads:
1656 if localheads:
1657 raise util.Abort('cannot use localheads with old style discovery')
1657 raise util.Abort('cannot use localheads with old style discovery')
1658 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1658 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1659 force=True)
1659 force=True)
1660 common = set(common)
1660 common = set(common)
1661 if not opts.get('nonheads'):
1661 if not opts.get('nonheads'):
1662 ui.write("unpruned common: %s\n" % " ".join([short(n)
1662 ui.write("unpruned common: %s\n" % " ".join([short(n)
1663 for n in common]))
1663 for n in common]))
1664 dag = dagutil.revlogdag(repo.changelog)
1664 dag = dagutil.revlogdag(repo.changelog)
1665 all = dag.ancestorset(dag.internalizeall(common))
1665 all = dag.ancestorset(dag.internalizeall(common))
1666 common = dag.externalizeall(dag.headsetofconnecteds(all))
1666 common = dag.externalizeall(dag.headsetofconnecteds(all))
1667 else:
1667 else:
1668 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1668 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1669 common = set(common)
1669 common = set(common)
1670 rheads = set(hds)
1670 rheads = set(hds)
1671 lheads = set(repo.heads())
1671 lheads = set(repo.heads())
1672 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1672 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1673 if lheads <= common:
1673 if lheads <= common:
1674 ui.write("local is subset\n")
1674 ui.write("local is subset\n")
1675 elif rheads <= common:
1675 elif rheads <= common:
1676 ui.write("remote is subset\n")
1676 ui.write("remote is subset\n")
1677
1677
1678 serverlogs = opts.get('serverlog')
1678 serverlogs = opts.get('serverlog')
1679 if serverlogs:
1679 if serverlogs:
1680 for filename in serverlogs:
1680 for filename in serverlogs:
1681 logfile = open(filename, 'r')
1681 logfile = open(filename, 'r')
1682 try:
1682 try:
1683 line = logfile.readline()
1683 line = logfile.readline()
1684 while line:
1684 while line:
1685 parts = line.strip().split(';')
1685 parts = line.strip().split(';')
1686 op = parts[1]
1686 op = parts[1]
1687 if op == 'cg':
1687 if op == 'cg':
1688 pass
1688 pass
1689 elif op == 'cgss':
1689 elif op == 'cgss':
1690 doit(parts[2].split(' '), parts[3].split(' '))
1690 doit(parts[2].split(' '), parts[3].split(' '))
1691 elif op == 'unb':
1691 elif op == 'unb':
1692 doit(parts[3].split(' '), parts[2].split(' '))
1692 doit(parts[3].split(' '), parts[2].split(' '))
1693 line = logfile.readline()
1693 line = logfile.readline()
1694 finally:
1694 finally:
1695 logfile.close()
1695 logfile.close()
1696
1696
1697 else:
1697 else:
1698 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1698 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1699 opts.get('remote_head'))
1699 opts.get('remote_head'))
1700 localrevs = opts.get('local_head')
1700 localrevs = opts.get('local_head')
1701 doit(localrevs, remoterevs)
1701 doit(localrevs, remoterevs)
1702
1702
1703 @command('debugfileset', [], ('REVSPEC'))
1703 @command('debugfileset', [], ('REVSPEC'))
1704 def debugfileset(ui, repo, expr):
1704 def debugfileset(ui, repo, expr):
1705 '''parse and apply a fileset specification'''
1705 '''parse and apply a fileset specification'''
1706 if ui.verbose:
1706 if ui.verbose:
1707 tree = fileset.parse(expr)[0]
1707 tree = fileset.parse(expr)[0]
1708 ui.note(tree, "\n")
1708 ui.note(tree, "\n")
1709
1709
1710 for f in fileset.getfileset(repo[None], expr):
1710 for f in fileset.getfileset(repo[None], expr):
1711 ui.write("%s\n" % f)
1711 ui.write("%s\n" % f)
1712
1712
1713 @command('debugfsinfo', [], _('[PATH]'))
1713 @command('debugfsinfo', [], _('[PATH]'))
1714 def debugfsinfo(ui, path = "."):
1714 def debugfsinfo(ui, path = "."):
1715 """show information detected about current filesystem"""
1715 """show information detected about current filesystem"""
1716 util.writefile('.debugfsinfo', '')
1716 util.writefile('.debugfsinfo', '')
1717 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1717 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1718 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1718 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1719 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1719 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1720 and 'yes' or 'no'))
1720 and 'yes' or 'no'))
1721 os.unlink('.debugfsinfo')
1721 os.unlink('.debugfsinfo')
1722
1722
1723 @command('debuggetbundle',
1723 @command('debuggetbundle',
1724 [('H', 'head', [], _('id of head node'), _('ID')),
1724 [('H', 'head', [], _('id of head node'), _('ID')),
1725 ('C', 'common', [], _('id of common node'), _('ID')),
1725 ('C', 'common', [], _('id of common node'), _('ID')),
1726 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1726 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1727 _('REPO FILE [-H|-C ID]...'))
1727 _('REPO FILE [-H|-C ID]...'))
1728 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1728 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1729 """retrieves a bundle from a repo
1729 """retrieves a bundle from a repo
1730
1730
1731 Every ID must be a full-length hex node id string. Saves the bundle to the
1731 Every ID must be a full-length hex node id string. Saves the bundle to the
1732 given file.
1732 given file.
1733 """
1733 """
1734 repo = hg.peer(ui, opts, repopath)
1734 repo = hg.peer(ui, opts, repopath)
1735 if not repo.capable('getbundle'):
1735 if not repo.capable('getbundle'):
1736 raise util.Abort("getbundle() not supported by target repository")
1736 raise util.Abort("getbundle() not supported by target repository")
1737 args = {}
1737 args = {}
1738 if common:
1738 if common:
1739 args['common'] = [bin(s) for s in common]
1739 args['common'] = [bin(s) for s in common]
1740 if head:
1740 if head:
1741 args['heads'] = [bin(s) for s in head]
1741 args['heads'] = [bin(s) for s in head]
1742 bundle = repo.getbundle('debug', **args)
1742 bundle = repo.getbundle('debug', **args)
1743
1743
1744 bundletype = opts.get('type', 'bzip2').lower()
1744 bundletype = opts.get('type', 'bzip2').lower()
1745 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1745 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1746 bundletype = btypes.get(bundletype)
1746 bundletype = btypes.get(bundletype)
1747 if bundletype not in changegroup.bundletypes:
1747 if bundletype not in changegroup.bundletypes:
1748 raise util.Abort(_('unknown bundle type specified with --type'))
1748 raise util.Abort(_('unknown bundle type specified with --type'))
1749 changegroup.writebundle(bundle, bundlepath, bundletype)
1749 changegroup.writebundle(bundle, bundlepath, bundletype)
1750
1750
1751 @command('debugignore', [], '')
1751 @command('debugignore', [], '')
1752 def debugignore(ui, repo, *values, **opts):
1752 def debugignore(ui, repo, *values, **opts):
1753 """display the combined ignore pattern"""
1753 """display the combined ignore pattern"""
1754 ignore = repo.dirstate._ignore
1754 ignore = repo.dirstate._ignore
1755 includepat = getattr(ignore, 'includepat', None)
1755 includepat = getattr(ignore, 'includepat', None)
1756 if includepat is not None:
1756 if includepat is not None:
1757 ui.write("%s\n" % includepat)
1757 ui.write("%s\n" % includepat)
1758 else:
1758 else:
1759 raise util.Abort(_("no ignore patterns found"))
1759 raise util.Abort(_("no ignore patterns found"))
1760
1760
1761 @command('debugindex',
1761 @command('debugindex',
1762 [('c', 'changelog', False, _('open changelog')),
1762 [('c', 'changelog', False, _('open changelog')),
1763 ('m', 'manifest', False, _('open manifest')),
1763 ('m', 'manifest', False, _('open manifest')),
1764 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1764 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1765 _('[-f FORMAT] -c|-m|FILE'))
1765 _('[-f FORMAT] -c|-m|FILE'))
1766 def debugindex(ui, repo, file_ = None, **opts):
1766 def debugindex(ui, repo, file_ = None, **opts):
1767 """dump the contents of an index file"""
1767 """dump the contents of an index file"""
1768 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1768 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1769 format = opts.get('format', 0)
1769 format = opts.get('format', 0)
1770 if format not in (0, 1):
1770 if format not in (0, 1):
1771 raise util.Abort(_("unknown format %d") % format)
1771 raise util.Abort(_("unknown format %d") % format)
1772
1772
1773 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1773 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1774 if generaldelta:
1774 if generaldelta:
1775 basehdr = ' delta'
1775 basehdr = ' delta'
1776 else:
1776 else:
1777 basehdr = ' base'
1777 basehdr = ' base'
1778
1778
1779 if format == 0:
1779 if format == 0:
1780 ui.write(" rev offset length " + basehdr + " linkrev"
1780 ui.write(" rev offset length " + basehdr + " linkrev"
1781 " nodeid p1 p2\n")
1781 " nodeid p1 p2\n")
1782 elif format == 1:
1782 elif format == 1:
1783 ui.write(" rev flag offset length"
1783 ui.write(" rev flag offset length"
1784 " size " + basehdr + " link p1 p2 nodeid\n")
1784 " size " + basehdr + " link p1 p2 nodeid\n")
1785
1785
1786 for i in r:
1786 for i in r:
1787 node = r.node(i)
1787 node = r.node(i)
1788 if generaldelta:
1788 if generaldelta:
1789 base = r.deltaparent(i)
1789 base = r.deltaparent(i)
1790 else:
1790 else:
1791 base = r.chainbase(i)
1791 base = r.chainbase(i)
1792 if format == 0:
1792 if format == 0:
1793 try:
1793 try:
1794 pp = r.parents(node)
1794 pp = r.parents(node)
1795 except:
1795 except:
1796 pp = [nullid, nullid]
1796 pp = [nullid, nullid]
1797 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1797 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1798 i, r.start(i), r.length(i), base, r.linkrev(i),
1798 i, r.start(i), r.length(i), base, r.linkrev(i),
1799 short(node), short(pp[0]), short(pp[1])))
1799 short(node), short(pp[0]), short(pp[1])))
1800 elif format == 1:
1800 elif format == 1:
1801 pr = r.parentrevs(i)
1801 pr = r.parentrevs(i)
1802 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1802 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1803 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1803 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1804 base, r.linkrev(i), pr[0], pr[1], short(node)))
1804 base, r.linkrev(i), pr[0], pr[1], short(node)))
1805
1805
1806 @command('debugindexdot', [], _('FILE'))
1806 @command('debugindexdot', [], _('FILE'))
1807 def debugindexdot(ui, repo, file_):
1807 def debugindexdot(ui, repo, file_):
1808 """dump an index DAG as a graphviz dot file"""
1808 """dump an index DAG as a graphviz dot file"""
1809 r = None
1809 r = None
1810 if repo:
1810 if repo:
1811 filelog = repo.file(file_)
1811 filelog = repo.file(file_)
1812 if len(filelog):
1812 if len(filelog):
1813 r = filelog
1813 r = filelog
1814 if not r:
1814 if not r:
1815 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1815 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1816 ui.write("digraph G {\n")
1816 ui.write("digraph G {\n")
1817 for i in r:
1817 for i in r:
1818 node = r.node(i)
1818 node = r.node(i)
1819 pp = r.parents(node)
1819 pp = r.parents(node)
1820 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1820 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1821 if pp[1] != nullid:
1821 if pp[1] != nullid:
1822 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1822 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1823 ui.write("}\n")
1823 ui.write("}\n")
1824
1824
1825 @command('debuginstall', [], '')
1825 @command('debuginstall', [], '')
1826 def debuginstall(ui):
1826 def debuginstall(ui):
1827 '''test Mercurial installation
1827 '''test Mercurial installation
1828
1828
1829 Returns 0 on success.
1829 Returns 0 on success.
1830 '''
1830 '''
1831
1831
1832 def writetemp(contents):
1832 def writetemp(contents):
1833 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1833 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1834 f = os.fdopen(fd, "wb")
1834 f = os.fdopen(fd, "wb")
1835 f.write(contents)
1835 f.write(contents)
1836 f.close()
1836 f.close()
1837 return name
1837 return name
1838
1838
1839 problems = 0
1839 problems = 0
1840
1840
1841 # encoding
1841 # encoding
1842 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1842 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1843 try:
1843 try:
1844 encoding.fromlocal("test")
1844 encoding.fromlocal("test")
1845 except util.Abort, inst:
1845 except util.Abort, inst:
1846 ui.write(" %s\n" % inst)
1846 ui.write(" %s\n" % inst)
1847 ui.write(_(" (check that your locale is properly set)\n"))
1847 ui.write(_(" (check that your locale is properly set)\n"))
1848 problems += 1
1848 problems += 1
1849
1849
1850 # compiled modules
1850 # compiled modules
1851 ui.status(_("Checking installed modules (%s)...\n")
1851 ui.status(_("Checking installed modules (%s)...\n")
1852 % os.path.dirname(__file__))
1852 % os.path.dirname(__file__))
1853 try:
1853 try:
1854 import bdiff, mpatch, base85, osutil
1854 import bdiff, mpatch, base85, osutil
1855 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1855 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
1856 except Exception, inst:
1856 except Exception, inst:
1857 ui.write(" %s\n" % inst)
1857 ui.write(" %s\n" % inst)
1858 ui.write(_(" One or more extensions could not be found"))
1858 ui.write(_(" One or more extensions could not be found"))
1859 ui.write(_(" (check that you compiled the extensions)\n"))
1859 ui.write(_(" (check that you compiled the extensions)\n"))
1860 problems += 1
1860 problems += 1
1861
1861
1862 # templates
1862 # templates
1863 import templater
1863 import templater
1864 p = templater.templatepath()
1864 p = templater.templatepath()
1865 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1865 ui.status(_("Checking templates (%s)...\n") % ' '.join(p))
1866 try:
1866 try:
1867 templater.templater(templater.templatepath("map-cmdline.default"))
1867 templater.templater(templater.templatepath("map-cmdline.default"))
1868 except Exception, inst:
1868 except Exception, inst:
1869 ui.write(" %s\n" % inst)
1869 ui.write(" %s\n" % inst)
1870 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1870 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1871 problems += 1
1871 problems += 1
1872
1872
1873 # editor
1873 # editor
1874 ui.status(_("Checking commit editor...\n"))
1874 ui.status(_("Checking commit editor...\n"))
1875 editor = ui.geteditor()
1875 editor = ui.geteditor()
1876 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1876 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1877 if not cmdpath:
1877 if not cmdpath:
1878 if editor == 'vi':
1878 if editor == 'vi':
1879 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1879 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1880 ui.write(_(" (specify a commit editor in your configuration"
1880 ui.write(_(" (specify a commit editor in your configuration"
1881 " file)\n"))
1881 " file)\n"))
1882 else:
1882 else:
1883 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1883 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1884 ui.write(_(" (specify a commit editor in your configuration"
1884 ui.write(_(" (specify a commit editor in your configuration"
1885 " file)\n"))
1885 " file)\n"))
1886 problems += 1
1886 problems += 1
1887
1887
1888 # check username
1888 # check username
1889 ui.status(_("Checking username...\n"))
1889 ui.status(_("Checking username...\n"))
1890 try:
1890 try:
1891 ui.username()
1891 ui.username()
1892 except util.Abort, e:
1892 except util.Abort, e:
1893 ui.write(" %s\n" % e)
1893 ui.write(" %s\n" % e)
1894 ui.write(_(" (specify a username in your configuration file)\n"))
1894 ui.write(_(" (specify a username in your configuration file)\n"))
1895 problems += 1
1895 problems += 1
1896
1896
1897 if not problems:
1897 if not problems:
1898 ui.status(_("No problems detected\n"))
1898 ui.status(_("No problems detected\n"))
1899 else:
1899 else:
1900 ui.write(_("%s problems detected,"
1900 ui.write(_("%s problems detected,"
1901 " please check your install!\n") % problems)
1901 " please check your install!\n") % problems)
1902
1902
1903 return problems
1903 return problems
1904
1904
1905 @command('debugknown', [], _('REPO ID...'))
1905 @command('debugknown', [], _('REPO ID...'))
1906 def debugknown(ui, repopath, *ids, **opts):
1906 def debugknown(ui, repopath, *ids, **opts):
1907 """test whether node ids are known to a repo
1907 """test whether node ids are known to a repo
1908
1908
1909 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1909 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1910 indicating unknown/known.
1910 indicating unknown/known.
1911 """
1911 """
1912 repo = hg.peer(ui, opts, repopath)
1912 repo = hg.peer(ui, opts, repopath)
1913 if not repo.capable('known'):
1913 if not repo.capable('known'):
1914 raise util.Abort("known() not supported by target repository")
1914 raise util.Abort("known() not supported by target repository")
1915 flags = repo.known([bin(s) for s in ids])
1915 flags = repo.known([bin(s) for s in ids])
1916 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1916 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1917
1917
1918 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1918 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1919 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1919 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1920 '''access the pushkey key/value protocol
1920 '''access the pushkey key/value protocol
1921
1921
1922 With two args, list the keys in the given namespace.
1922 With two args, list the keys in the given namespace.
1923
1923
1924 With five args, set a key to new if it currently is set to old.
1924 With five args, set a key to new if it currently is set to old.
1925 Reports success or failure.
1925 Reports success or failure.
1926 '''
1926 '''
1927
1927
1928 target = hg.peer(ui, {}, repopath)
1928 target = hg.peer(ui, {}, repopath)
1929 if keyinfo:
1929 if keyinfo:
1930 key, old, new = keyinfo
1930 key, old, new = keyinfo
1931 r = target.pushkey(namespace, key, old, new)
1931 r = target.pushkey(namespace, key, old, new)
1932 ui.status(str(r) + '\n')
1932 ui.status(str(r) + '\n')
1933 return not r
1933 return not r
1934 else:
1934 else:
1935 for k, v in target.listkeys(namespace).iteritems():
1935 for k, v in target.listkeys(namespace).iteritems():
1936 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1936 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1937 v.encode('string-escape')))
1937 v.encode('string-escape')))
1938
1938
1939 @command('debugrebuildstate',
1939 @command('debugrebuildstate',
1940 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1940 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1941 _('[-r REV] [REV]'))
1941 _('[-r REV] [REV]'))
1942 def debugrebuildstate(ui, repo, rev="tip"):
1942 def debugrebuildstate(ui, repo, rev="tip"):
1943 """rebuild the dirstate as it would look like for the given revision"""
1943 """rebuild the dirstate as it would look like for the given revision"""
1944 ctx = scmutil.revsingle(repo, rev)
1944 ctx = scmutil.revsingle(repo, rev)
1945 wlock = repo.wlock()
1945 wlock = repo.wlock()
1946 try:
1946 try:
1947 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1947 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1948 finally:
1948 finally:
1949 wlock.release()
1949 wlock.release()
1950
1950
1951 @command('debugrename',
1951 @command('debugrename',
1952 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1952 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1953 _('[-r REV] FILE'))
1953 _('[-r REV] FILE'))
1954 def debugrename(ui, repo, file1, *pats, **opts):
1954 def debugrename(ui, repo, file1, *pats, **opts):
1955 """dump rename information"""
1955 """dump rename information"""
1956
1956
1957 ctx = scmutil.revsingle(repo, opts.get('rev'))
1957 ctx = scmutil.revsingle(repo, opts.get('rev'))
1958 m = scmutil.match(ctx, (file1,) + pats, opts)
1958 m = scmutil.match(ctx, (file1,) + pats, opts)
1959 for abs in ctx.walk(m):
1959 for abs in ctx.walk(m):
1960 fctx = ctx[abs]
1960 fctx = ctx[abs]
1961 o = fctx.filelog().renamed(fctx.filenode())
1961 o = fctx.filelog().renamed(fctx.filenode())
1962 rel = m.rel(abs)
1962 rel = m.rel(abs)
1963 if o:
1963 if o:
1964 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1964 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1965 else:
1965 else:
1966 ui.write(_("%s not renamed\n") % rel)
1966 ui.write(_("%s not renamed\n") % rel)
1967
1967
1968 @command('debugrevlog',
1968 @command('debugrevlog',
1969 [('c', 'changelog', False, _('open changelog')),
1969 [('c', 'changelog', False, _('open changelog')),
1970 ('m', 'manifest', False, _('open manifest')),
1970 ('m', 'manifest', False, _('open manifest')),
1971 ('d', 'dump', False, _('dump index data'))],
1971 ('d', 'dump', False, _('dump index data'))],
1972 _('-c|-m|FILE'))
1972 _('-c|-m|FILE'))
1973 def debugrevlog(ui, repo, file_ = None, **opts):
1973 def debugrevlog(ui, repo, file_ = None, **opts):
1974 """show data and statistics about a revlog"""
1974 """show data and statistics about a revlog"""
1975 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1975 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1976
1976
1977 if opts.get("dump"):
1977 if opts.get("dump"):
1978 numrevs = len(r)
1978 numrevs = len(r)
1979 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1979 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1980 " rawsize totalsize compression heads\n")
1980 " rawsize totalsize compression heads\n")
1981 ts = 0
1981 ts = 0
1982 heads = set()
1982 heads = set()
1983 for rev in xrange(numrevs):
1983 for rev in xrange(numrevs):
1984 dbase = r.deltaparent(rev)
1984 dbase = r.deltaparent(rev)
1985 if dbase == -1:
1985 if dbase == -1:
1986 dbase = rev
1986 dbase = rev
1987 cbase = r.chainbase(rev)
1987 cbase = r.chainbase(rev)
1988 p1, p2 = r.parentrevs(rev)
1988 p1, p2 = r.parentrevs(rev)
1989 rs = r.rawsize(rev)
1989 rs = r.rawsize(rev)
1990 ts = ts + rs
1990 ts = ts + rs
1991 heads -= set(r.parentrevs(rev))
1991 heads -= set(r.parentrevs(rev))
1992 heads.add(rev)
1992 heads.add(rev)
1993 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1993 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1994 (rev, p1, p2, r.start(rev), r.end(rev),
1994 (rev, p1, p2, r.start(rev), r.end(rev),
1995 r.start(dbase), r.start(cbase),
1995 r.start(dbase), r.start(cbase),
1996 r.start(p1), r.start(p2),
1996 r.start(p1), r.start(p2),
1997 rs, ts, ts / r.end(rev), len(heads)))
1997 rs, ts, ts / r.end(rev), len(heads)))
1998 return 0
1998 return 0
1999
1999
2000 v = r.version
2000 v = r.version
2001 format = v & 0xFFFF
2001 format = v & 0xFFFF
2002 flags = []
2002 flags = []
2003 gdelta = False
2003 gdelta = False
2004 if v & revlog.REVLOGNGINLINEDATA:
2004 if v & revlog.REVLOGNGINLINEDATA:
2005 flags.append('inline')
2005 flags.append('inline')
2006 if v & revlog.REVLOGGENERALDELTA:
2006 if v & revlog.REVLOGGENERALDELTA:
2007 gdelta = True
2007 gdelta = True
2008 flags.append('generaldelta')
2008 flags.append('generaldelta')
2009 if not flags:
2009 if not flags:
2010 flags = ['(none)']
2010 flags = ['(none)']
2011
2011
2012 nummerges = 0
2012 nummerges = 0
2013 numfull = 0
2013 numfull = 0
2014 numprev = 0
2014 numprev = 0
2015 nump1 = 0
2015 nump1 = 0
2016 nump2 = 0
2016 nump2 = 0
2017 numother = 0
2017 numother = 0
2018 nump1prev = 0
2018 nump1prev = 0
2019 nump2prev = 0
2019 nump2prev = 0
2020 chainlengths = []
2020 chainlengths = []
2021
2021
2022 datasize = [None, 0, 0L]
2022 datasize = [None, 0, 0L]
2023 fullsize = [None, 0, 0L]
2023 fullsize = [None, 0, 0L]
2024 deltasize = [None, 0, 0L]
2024 deltasize = [None, 0, 0L]
2025
2025
2026 def addsize(size, l):
2026 def addsize(size, l):
2027 if l[0] is None or size < l[0]:
2027 if l[0] is None or size < l[0]:
2028 l[0] = size
2028 l[0] = size
2029 if size > l[1]:
2029 if size > l[1]:
2030 l[1] = size
2030 l[1] = size
2031 l[2] += size
2031 l[2] += size
2032
2032
2033 numrevs = len(r)
2033 numrevs = len(r)
2034 for rev in xrange(numrevs):
2034 for rev in xrange(numrevs):
2035 p1, p2 = r.parentrevs(rev)
2035 p1, p2 = r.parentrevs(rev)
2036 delta = r.deltaparent(rev)
2036 delta = r.deltaparent(rev)
2037 if format > 0:
2037 if format > 0:
2038 addsize(r.rawsize(rev), datasize)
2038 addsize(r.rawsize(rev), datasize)
2039 if p2 != nullrev:
2039 if p2 != nullrev:
2040 nummerges += 1
2040 nummerges += 1
2041 size = r.length(rev)
2041 size = r.length(rev)
2042 if delta == nullrev:
2042 if delta == nullrev:
2043 chainlengths.append(0)
2043 chainlengths.append(0)
2044 numfull += 1
2044 numfull += 1
2045 addsize(size, fullsize)
2045 addsize(size, fullsize)
2046 else:
2046 else:
2047 chainlengths.append(chainlengths[delta] + 1)
2047 chainlengths.append(chainlengths[delta] + 1)
2048 addsize(size, deltasize)
2048 addsize(size, deltasize)
2049 if delta == rev - 1:
2049 if delta == rev - 1:
2050 numprev += 1
2050 numprev += 1
2051 if delta == p1:
2051 if delta == p1:
2052 nump1prev += 1
2052 nump1prev += 1
2053 elif delta == p2:
2053 elif delta == p2:
2054 nump2prev += 1
2054 nump2prev += 1
2055 elif delta == p1:
2055 elif delta == p1:
2056 nump1 += 1
2056 nump1 += 1
2057 elif delta == p2:
2057 elif delta == p2:
2058 nump2 += 1
2058 nump2 += 1
2059 elif delta != nullrev:
2059 elif delta != nullrev:
2060 numother += 1
2060 numother += 1
2061
2061
2062 numdeltas = numrevs - numfull
2062 numdeltas = numrevs - numfull
2063 numoprev = numprev - nump1prev - nump2prev
2063 numoprev = numprev - nump1prev - nump2prev
2064 totalrawsize = datasize[2]
2064 totalrawsize = datasize[2]
2065 datasize[2] /= numrevs
2065 datasize[2] /= numrevs
2066 fulltotal = fullsize[2]
2066 fulltotal = fullsize[2]
2067 fullsize[2] /= numfull
2067 fullsize[2] /= numfull
2068 deltatotal = deltasize[2]
2068 deltatotal = deltasize[2]
2069 deltasize[2] /= numrevs - numfull
2069 deltasize[2] /= numrevs - numfull
2070 totalsize = fulltotal + deltatotal
2070 totalsize = fulltotal + deltatotal
2071 avgchainlen = sum(chainlengths) / numrevs
2071 avgchainlen = sum(chainlengths) / numrevs
2072 compratio = totalrawsize / totalsize
2072 compratio = totalrawsize / totalsize
2073
2073
2074 basedfmtstr = '%%%dd\n'
2074 basedfmtstr = '%%%dd\n'
2075 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2075 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2076
2076
2077 def dfmtstr(max):
2077 def dfmtstr(max):
2078 return basedfmtstr % len(str(max))
2078 return basedfmtstr % len(str(max))
2079 def pcfmtstr(max, padding=0):
2079 def pcfmtstr(max, padding=0):
2080 return basepcfmtstr % (len(str(max)), ' ' * padding)
2080 return basepcfmtstr % (len(str(max)), ' ' * padding)
2081
2081
2082 def pcfmt(value, total):
2082 def pcfmt(value, total):
2083 return (value, 100 * float(value) / total)
2083 return (value, 100 * float(value) / total)
2084
2084
2085 ui.write('format : %d\n' % format)
2085 ui.write('format : %d\n' % format)
2086 ui.write('flags : %s\n' % ', '.join(flags))
2086 ui.write('flags : %s\n' % ', '.join(flags))
2087
2087
2088 ui.write('\n')
2088 ui.write('\n')
2089 fmt = pcfmtstr(totalsize)
2089 fmt = pcfmtstr(totalsize)
2090 fmt2 = dfmtstr(totalsize)
2090 fmt2 = dfmtstr(totalsize)
2091 ui.write('revisions : ' + fmt2 % numrevs)
2091 ui.write('revisions : ' + fmt2 % numrevs)
2092 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2092 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
2093 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2093 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
2094 ui.write('revisions : ' + fmt2 % numrevs)
2094 ui.write('revisions : ' + fmt2 % numrevs)
2095 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2095 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
2096 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2096 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
2097 ui.write('revision size : ' + fmt2 % totalsize)
2097 ui.write('revision size : ' + fmt2 % totalsize)
2098 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2098 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2099 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2099 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2100
2100
2101 ui.write('\n')
2101 ui.write('\n')
2102 fmt = dfmtstr(max(avgchainlen, compratio))
2102 fmt = dfmtstr(max(avgchainlen, compratio))
2103 ui.write('avg chain length : ' + fmt % avgchainlen)
2103 ui.write('avg chain length : ' + fmt % avgchainlen)
2104 ui.write('compression ratio : ' + fmt % compratio)
2104 ui.write('compression ratio : ' + fmt % compratio)
2105
2105
2106 if format > 0:
2106 if format > 0:
2107 ui.write('\n')
2107 ui.write('\n')
2108 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2108 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2109 % tuple(datasize))
2109 % tuple(datasize))
2110 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2110 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2111 % tuple(fullsize))
2111 % tuple(fullsize))
2112 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2112 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2113 % tuple(deltasize))
2113 % tuple(deltasize))
2114
2114
2115 if numdeltas > 0:
2115 if numdeltas > 0:
2116 ui.write('\n')
2116 ui.write('\n')
2117 fmt = pcfmtstr(numdeltas)
2117 fmt = pcfmtstr(numdeltas)
2118 fmt2 = pcfmtstr(numdeltas, 4)
2118 fmt2 = pcfmtstr(numdeltas, 4)
2119 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2119 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2120 if numprev > 0:
2120 if numprev > 0:
2121 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2121 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2122 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2122 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2123 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2123 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2124 if gdelta:
2124 if gdelta:
2125 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2125 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2126 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2126 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2127 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2127 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2128
2128
2129 @command('debugrevspec', [], ('REVSPEC'))
2129 @command('debugrevspec', [], ('REVSPEC'))
2130 def debugrevspec(ui, repo, expr):
2130 def debugrevspec(ui, repo, expr):
2131 '''parse and apply a revision specification'''
2131 '''parse and apply a revision specification'''
2132 if ui.verbose:
2132 if ui.verbose:
2133 tree = revset.parse(expr)[0]
2133 tree = revset.parse(expr)[0]
2134 ui.note(tree, "\n")
2134 ui.note(tree, "\n")
2135 newtree = revset.findaliases(ui, tree)
2135 newtree = revset.findaliases(ui, tree)
2136 if newtree != tree:
2136 if newtree != tree:
2137 ui.note(newtree, "\n")
2137 ui.note(newtree, "\n")
2138 func = revset.match(ui, expr)
2138 func = revset.match(ui, expr)
2139 for c in func(repo, range(len(repo))):
2139 for c in func(repo, range(len(repo))):
2140 ui.write("%s\n" % c)
2140 ui.write("%s\n" % c)
2141
2141
2142 @command('debugsetparents', [], _('REV1 [REV2]'))
2142 @command('debugsetparents', [], _('REV1 [REV2]'))
2143 def debugsetparents(ui, repo, rev1, rev2=None):
2143 def debugsetparents(ui, repo, rev1, rev2=None):
2144 """manually set the parents of the current working directory
2144 """manually set the parents of the current working directory
2145
2145
2146 This is useful for writing repository conversion tools, but should
2146 This is useful for writing repository conversion tools, but should
2147 be used with care.
2147 be used with care.
2148
2148
2149 Returns 0 on success.
2149 Returns 0 on success.
2150 """
2150 """
2151
2151
2152 r1 = scmutil.revsingle(repo, rev1).node()
2152 r1 = scmutil.revsingle(repo, rev1).node()
2153 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2153 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2154
2154
2155 wlock = repo.wlock()
2155 wlock = repo.wlock()
2156 try:
2156 try:
2157 repo.dirstate.setparents(r1, r2)
2157 repo.dirstate.setparents(r1, r2)
2158 finally:
2158 finally:
2159 wlock.release()
2159 wlock.release()
2160
2160
2161 @command('debugstate',
2161 @command('debugstate',
2162 [('', 'nodates', None, _('do not display the saved mtime')),
2162 [('', 'nodates', None, _('do not display the saved mtime')),
2163 ('', 'datesort', None, _('sort by saved mtime'))],
2163 ('', 'datesort', None, _('sort by saved mtime'))],
2164 _('[OPTION]...'))
2164 _('[OPTION]...'))
2165 def debugstate(ui, repo, nodates=None, datesort=None):
2165 def debugstate(ui, repo, nodates=None, datesort=None):
2166 """show the contents of the current dirstate"""
2166 """show the contents of the current dirstate"""
2167 timestr = ""
2167 timestr = ""
2168 showdate = not nodates
2168 showdate = not nodates
2169 if datesort:
2169 if datesort:
2170 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2170 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2171 else:
2171 else:
2172 keyfunc = None # sort by filename
2172 keyfunc = None # sort by filename
2173 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2173 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2174 if showdate:
2174 if showdate:
2175 if ent[3] == -1:
2175 if ent[3] == -1:
2176 # Pad or slice to locale representation
2176 # Pad or slice to locale representation
2177 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2177 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2178 time.localtime(0)))
2178 time.localtime(0)))
2179 timestr = 'unset'
2179 timestr = 'unset'
2180 timestr = (timestr[:locale_len] +
2180 timestr = (timestr[:locale_len] +
2181 ' ' * (locale_len - len(timestr)))
2181 ' ' * (locale_len - len(timestr)))
2182 else:
2182 else:
2183 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2183 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2184 time.localtime(ent[3]))
2184 time.localtime(ent[3]))
2185 if ent[1] & 020000:
2185 if ent[1] & 020000:
2186 mode = 'lnk'
2186 mode = 'lnk'
2187 else:
2187 else:
2188 mode = '%3o' % (ent[1] & 0777)
2188 mode = '%3o' % (ent[1] & 0777)
2189 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2189 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2190 for f in repo.dirstate.copies():
2190 for f in repo.dirstate.copies():
2191 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2191 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2192
2192
2193 @command('debugsub',
2193 @command('debugsub',
2194 [('r', 'rev', '',
2194 [('r', 'rev', '',
2195 _('revision to check'), _('REV'))],
2195 _('revision to check'), _('REV'))],
2196 _('[-r REV] [REV]'))
2196 _('[-r REV] [REV]'))
2197 def debugsub(ui, repo, rev=None):
2197 def debugsub(ui, repo, rev=None):
2198 ctx = scmutil.revsingle(repo, rev, None)
2198 ctx = scmutil.revsingle(repo, rev, None)
2199 for k, v in sorted(ctx.substate.items()):
2199 for k, v in sorted(ctx.substate.items()):
2200 ui.write('path %s\n' % k)
2200 ui.write('path %s\n' % k)
2201 ui.write(' source %s\n' % v[0])
2201 ui.write(' source %s\n' % v[0])
2202 ui.write(' revision %s\n' % v[1])
2202 ui.write(' revision %s\n' % v[1])
2203
2203
2204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2204 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2205 def debugwalk(ui, repo, *pats, **opts):
2205 def debugwalk(ui, repo, *pats, **opts):
2206 """show how files match on given patterns"""
2206 """show how files match on given patterns"""
2207 m = scmutil.match(repo[None], pats, opts)
2207 m = scmutil.match(repo[None], pats, opts)
2208 items = list(repo.walk(m))
2208 items = list(repo.walk(m))
2209 if not items:
2209 if not items:
2210 return
2210 return
2211 fmt = 'f %%-%ds %%-%ds %%s' % (
2211 fmt = 'f %%-%ds %%-%ds %%s' % (
2212 max([len(abs) for abs in items]),
2212 max([len(abs) for abs in items]),
2213 max([len(m.rel(abs)) for abs in items]))
2213 max([len(m.rel(abs)) for abs in items]))
2214 for abs in items:
2214 for abs in items:
2215 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2215 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2216 ui.write("%s\n" % line.rstrip())
2216 ui.write("%s\n" % line.rstrip())
2217
2217
2218 @command('debugwireargs',
2218 @command('debugwireargs',
2219 [('', 'three', '', 'three'),
2219 [('', 'three', '', 'three'),
2220 ('', 'four', '', 'four'),
2220 ('', 'four', '', 'four'),
2221 ('', 'five', '', 'five'),
2221 ('', 'five', '', 'five'),
2222 ] + remoteopts,
2222 ] + remoteopts,
2223 _('REPO [OPTIONS]... [ONE [TWO]]'))
2223 _('REPO [OPTIONS]... [ONE [TWO]]'))
2224 def debugwireargs(ui, repopath, *vals, **opts):
2224 def debugwireargs(ui, repopath, *vals, **opts):
2225 repo = hg.peer(ui, opts, repopath)
2225 repo = hg.peer(ui, opts, repopath)
2226 for opt in remoteopts:
2226 for opt in remoteopts:
2227 del opts[opt[1]]
2227 del opts[opt[1]]
2228 args = {}
2228 args = {}
2229 for k, v in opts.iteritems():
2229 for k, v in opts.iteritems():
2230 if v:
2230 if v:
2231 args[k] = v
2231 args[k] = v
2232 # run twice to check that we don't mess up the stream for the next command
2232 # run twice to check that we don't mess up the stream for the next command
2233 res1 = repo.debugwireargs(*vals, **args)
2233 res1 = repo.debugwireargs(*vals, **args)
2234 res2 = repo.debugwireargs(*vals, **args)
2234 res2 = repo.debugwireargs(*vals, **args)
2235 ui.write("%s\n" % res1)
2235 ui.write("%s\n" % res1)
2236 if res1 != res2:
2236 if res1 != res2:
2237 ui.warn("%s\n" % res2)
2237 ui.warn("%s\n" % res2)
2238
2238
2239 @command('^diff',
2239 @command('^diff',
2240 [('r', 'rev', [], _('revision'), _('REV')),
2240 [('r', 'rev', [], _('revision'), _('REV')),
2241 ('c', 'change', '', _('change made by revision'), _('REV'))
2241 ('c', 'change', '', _('change made by revision'), _('REV'))
2242 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2242 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2243 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2243 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2244 def diff(ui, repo, *pats, **opts):
2244 def diff(ui, repo, *pats, **opts):
2245 """diff repository (or selected files)
2245 """diff repository (or selected files)
2246
2246
2247 Show differences between revisions for the specified files.
2247 Show differences between revisions for the specified files.
2248
2248
2249 Differences between files are shown using the unified diff format.
2249 Differences between files are shown using the unified diff format.
2250
2250
2251 .. note::
2251 .. note::
2252 diff may generate unexpected results for merges, as it will
2252 diff may generate unexpected results for merges, as it will
2253 default to comparing against the working directory's first
2253 default to comparing against the working directory's first
2254 parent changeset if no revisions are specified.
2254 parent changeset if no revisions are specified.
2255
2255
2256 When two revision arguments are given, then changes are shown
2256 When two revision arguments are given, then changes are shown
2257 between those revisions. If only one revision is specified then
2257 between those revisions. If only one revision is specified then
2258 that revision is compared to the working directory, and, when no
2258 that revision is compared to the working directory, and, when no
2259 revisions are specified, the working directory files are compared
2259 revisions are specified, the working directory files are compared
2260 to its parent.
2260 to its parent.
2261
2261
2262 Alternatively you can specify -c/--change with a revision to see
2262 Alternatively you can specify -c/--change with a revision to see
2263 the changes in that changeset relative to its first parent.
2263 the changes in that changeset relative to its first parent.
2264
2264
2265 Without the -a/--text option, diff will avoid generating diffs of
2265 Without the -a/--text option, diff will avoid generating diffs of
2266 files it detects as binary. With -a, diff will generate a diff
2266 files it detects as binary. With -a, diff will generate a diff
2267 anyway, probably with undesirable results.
2267 anyway, probably with undesirable results.
2268
2268
2269 Use the -g/--git option to generate diffs in the git extended diff
2269 Use the -g/--git option to generate diffs in the git extended diff
2270 format. For more information, read :hg:`help diffs`.
2270 format. For more information, read :hg:`help diffs`.
2271
2271
2272 .. container:: verbose
2272 .. container:: verbose
2273
2273
2274 Examples:
2274 Examples:
2275
2275
2276 - compare a file in the current working directory to its parent::
2276 - compare a file in the current working directory to its parent::
2277
2277
2278 hg diff foo.c
2278 hg diff foo.c
2279
2279
2280 - compare two historical versions of a directory, with rename info::
2280 - compare two historical versions of a directory, with rename info::
2281
2281
2282 hg diff --git -r 1.0:1.2 lib/
2282 hg diff --git -r 1.0:1.2 lib/
2283
2283
2284 - get change stats relative to the last change on some date::
2284 - get change stats relative to the last change on some date::
2285
2285
2286 hg diff --stat -r "date('may 2')"
2286 hg diff --stat -r "date('may 2')"
2287
2287
2288 - diff all newly-added files that contain a keyword::
2288 - diff all newly-added files that contain a keyword::
2289
2289
2290 hg diff "set:added() and grep(GNU)"
2290 hg diff "set:added() and grep(GNU)"
2291
2291
2292 - compare a revision and its parents::
2292 - compare a revision and its parents::
2293
2293
2294 hg diff -c 9353 # compare against first parent
2294 hg diff -c 9353 # compare against first parent
2295 hg diff -r 9353^:9353 # same using revset syntax
2295 hg diff -r 9353^:9353 # same using revset syntax
2296 hg diff -r 9353^2:9353 # compare against the second parent
2296 hg diff -r 9353^2:9353 # compare against the second parent
2297
2297
2298 Returns 0 on success.
2298 Returns 0 on success.
2299 """
2299 """
2300
2300
2301 revs = opts.get('rev')
2301 revs = opts.get('rev')
2302 change = opts.get('change')
2302 change = opts.get('change')
2303 stat = opts.get('stat')
2303 stat = opts.get('stat')
2304 reverse = opts.get('reverse')
2304 reverse = opts.get('reverse')
2305
2305
2306 if revs and change:
2306 if revs and change:
2307 msg = _('cannot specify --rev and --change at the same time')
2307 msg = _('cannot specify --rev and --change at the same time')
2308 raise util.Abort(msg)
2308 raise util.Abort(msg)
2309 elif change:
2309 elif change:
2310 node2 = scmutil.revsingle(repo, change, None).node()
2310 node2 = scmutil.revsingle(repo, change, None).node()
2311 node1 = repo[node2].p1().node()
2311 node1 = repo[node2].p1().node()
2312 else:
2312 else:
2313 node1, node2 = scmutil.revpair(repo, revs)
2313 node1, node2 = scmutil.revpair(repo, revs)
2314
2314
2315 if reverse:
2315 if reverse:
2316 node1, node2 = node2, node1
2316 node1, node2 = node2, node1
2317
2317
2318 diffopts = patch.diffopts(ui, opts)
2318 diffopts = patch.diffopts(ui, opts)
2319 m = scmutil.match(repo[node2], pats, opts)
2319 m = scmutil.match(repo[node2], pats, opts)
2320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2320 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2321 listsubrepos=opts.get('subrepos'))
2321 listsubrepos=opts.get('subrepos'))
2322
2322
2323 @command('^export',
2323 @command('^export',
2324 [('o', 'output', '',
2324 [('o', 'output', '',
2325 _('print output to file with formatted name'), _('FORMAT')),
2325 _('print output to file with formatted name'), _('FORMAT')),
2326 ('', 'switch-parent', None, _('diff against the second parent')),
2326 ('', 'switch-parent', None, _('diff against the second parent')),
2327 ('r', 'rev', [], _('revisions to export'), _('REV')),
2327 ('r', 'rev', [], _('revisions to export'), _('REV')),
2328 ] + diffopts,
2328 ] + diffopts,
2329 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2329 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2330 def export(ui, repo, *changesets, **opts):
2330 def export(ui, repo, *changesets, **opts):
2331 """dump the header and diffs for one or more changesets
2331 """dump the header and diffs for one or more changesets
2332
2332
2333 Print the changeset header and diffs for one or more revisions.
2333 Print the changeset header and diffs for one or more revisions.
2334
2334
2335 The information shown in the changeset header is: author, date,
2335 The information shown in the changeset header is: author, date,
2336 branch name (if non-default), changeset hash, parent(s) and commit
2336 branch name (if non-default), changeset hash, parent(s) and commit
2337 comment.
2337 comment.
2338
2338
2339 .. note::
2339 .. note::
2340 export may generate unexpected diff output for merge
2340 export may generate unexpected diff output for merge
2341 changesets, as it will compare the merge changeset against its
2341 changesets, as it will compare the merge changeset against its
2342 first parent only.
2342 first parent only.
2343
2343
2344 Output may be to a file, in which case the name of the file is
2344 Output may be to a file, in which case the name of the file is
2345 given using a format string. The formatting rules are as follows:
2345 given using a format string. The formatting rules are as follows:
2346
2346
2347 :``%%``: literal "%" character
2347 :``%%``: literal "%" character
2348 :``%H``: changeset hash (40 hexadecimal digits)
2348 :``%H``: changeset hash (40 hexadecimal digits)
2349 :``%N``: number of patches being generated
2349 :``%N``: number of patches being generated
2350 :``%R``: changeset revision number
2350 :``%R``: changeset revision number
2351 :``%b``: basename of the exporting repository
2351 :``%b``: basename of the exporting repository
2352 :``%h``: short-form changeset hash (12 hexadecimal digits)
2352 :``%h``: short-form changeset hash (12 hexadecimal digits)
2353 :``%m``: first line of the commit message (only alphanumeric characters)
2353 :``%m``: first line of the commit message (only alphanumeric characters)
2354 :``%n``: zero-padded sequence number, starting at 1
2354 :``%n``: zero-padded sequence number, starting at 1
2355 :``%r``: zero-padded changeset revision number
2355 :``%r``: zero-padded changeset revision number
2356
2356
2357 Without the -a/--text option, export will avoid generating diffs
2357 Without the -a/--text option, export will avoid generating diffs
2358 of files it detects as binary. With -a, export will generate a
2358 of files it detects as binary. With -a, export will generate a
2359 diff anyway, probably with undesirable results.
2359 diff anyway, probably with undesirable results.
2360
2360
2361 Use the -g/--git option to generate diffs in the git extended diff
2361 Use the -g/--git option to generate diffs in the git extended diff
2362 format. See :hg:`help diffs` for more information.
2362 format. See :hg:`help diffs` for more information.
2363
2363
2364 With the --switch-parent option, the diff will be against the
2364 With the --switch-parent option, the diff will be against the
2365 second parent. It can be useful to review a merge.
2365 second parent. It can be useful to review a merge.
2366
2366
2367 .. container:: verbose
2367 .. container:: verbose
2368
2368
2369 Examples:
2369 Examples:
2370
2370
2371 - use export and import to transplant a bugfix to the current
2371 - use export and import to transplant a bugfix to the current
2372 branch::
2372 branch::
2373
2373
2374 hg export -r 9353 | hg import -
2374 hg export -r 9353 | hg import -
2375
2375
2376 - export all the changesets between two revisions to a file with
2376 - export all the changesets between two revisions to a file with
2377 rename information::
2377 rename information::
2378
2378
2379 hg export --git -r 123:150 > changes.txt
2379 hg export --git -r 123:150 > changes.txt
2380
2380
2381 - split outgoing changes into a series of patches with
2381 - split outgoing changes into a series of patches with
2382 descriptive names::
2382 descriptive names::
2383
2383
2384 hg export -r "outgoing()" -o "%n-%m.patch"
2384 hg export -r "outgoing()" -o "%n-%m.patch"
2385
2385
2386 Returns 0 on success.
2386 Returns 0 on success.
2387 """
2387 """
2388 changesets += tuple(opts.get('rev', []))
2388 changesets += tuple(opts.get('rev', []))
2389 if not changesets:
2389 if not changesets:
2390 raise util.Abort(_("export requires at least one changeset"))
2390 raise util.Abort(_("export requires at least one changeset"))
2391 revs = scmutil.revrange(repo, changesets)
2391 revs = scmutil.revrange(repo, changesets)
2392 if len(revs) > 1:
2392 if len(revs) > 1:
2393 ui.note(_('exporting patches:\n'))
2393 ui.note(_('exporting patches:\n'))
2394 else:
2394 else:
2395 ui.note(_('exporting patch:\n'))
2395 ui.note(_('exporting patch:\n'))
2396 cmdutil.export(repo, revs, template=opts.get('output'),
2396 cmdutil.export(repo, revs, template=opts.get('output'),
2397 switch_parent=opts.get('switch_parent'),
2397 switch_parent=opts.get('switch_parent'),
2398 opts=patch.diffopts(ui, opts))
2398 opts=patch.diffopts(ui, opts))
2399
2399
2400 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2400 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2401 def forget(ui, repo, *pats, **opts):
2401 def forget(ui, repo, *pats, **opts):
2402 """forget the specified files on the next commit
2402 """forget the specified files on the next commit
2403
2403
2404 Mark the specified files so they will no longer be tracked
2404 Mark the specified files so they will no longer be tracked
2405 after the next commit.
2405 after the next commit.
2406
2406
2407 This only removes files from the current branch, not from the
2407 This only removes files from the current branch, not from the
2408 entire project history, and it does not delete them from the
2408 entire project history, and it does not delete them from the
2409 working directory.
2409 working directory.
2410
2410
2411 To undo a forget before the next commit, see :hg:`add`.
2411 To undo a forget before the next commit, see :hg:`add`.
2412
2412
2413 .. container:: verbose
2413 .. container:: verbose
2414
2414
2415 Examples:
2415 Examples:
2416
2416
2417 - forget newly-added binary files::
2417 - forget newly-added binary files::
2418
2418
2419 hg forget "set:added() and binary()"
2419 hg forget "set:added() and binary()"
2420
2420
2421 - forget files that would be excluded by .hgignore::
2421 - forget files that would be excluded by .hgignore::
2422
2422
2423 hg forget "set:hgignore()"
2423 hg forget "set:hgignore()"
2424
2424
2425 Returns 0 on success.
2425 Returns 0 on success.
2426 """
2426 """
2427
2427
2428 if not pats:
2428 if not pats:
2429 raise util.Abort(_('no files specified'))
2429 raise util.Abort(_('no files specified'))
2430
2430
2431 m = scmutil.match(repo[None], pats, opts)
2431 m = scmutil.match(repo[None], pats, opts)
2432 s = repo.status(match=m, clean=True)
2432 s = repo.status(match=m, clean=True)
2433 forget = sorted(s[0] + s[1] + s[3] + s[6])
2433 forget = sorted(s[0] + s[1] + s[3] + s[6])
2434 errs = 0
2434 errs = 0
2435
2435
2436 for f in m.files():
2436 for f in m.files():
2437 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2437 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2438 if os.path.exists(m.rel(f)):
2438 if os.path.exists(m.rel(f)):
2439 ui.warn(_('not removing %s: file is already untracked\n')
2439 ui.warn(_('not removing %s: file is already untracked\n')
2440 % m.rel(f))
2440 % m.rel(f))
2441 errs = 1
2441 errs = 1
2442
2442
2443 for f in forget:
2443 for f in forget:
2444 if ui.verbose or not m.exact(f):
2444 if ui.verbose or not m.exact(f):
2445 ui.status(_('removing %s\n') % m.rel(f))
2445 ui.status(_('removing %s\n') % m.rel(f))
2446
2446
2447 repo[None].forget(forget)
2447 repo[None].forget(forget)
2448 return errs
2448 return errs
2449
2449
2450 @command('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 ('e', 'edit', False, _('invoke editor on commit messages')),
3189 ('e', 'edit', False, _('invoke editor on commit messages')),
3190 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3190 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3191 ('', 'no-commit', None,
3191 ('', 'no-commit', None,
3192 _("don't commit, just update the working directory")),
3192 _("don't commit, just update the working directory")),
3193 ('', 'bypass', None,
3193 ('', 'bypass', None,
3194 _("apply patch without touching the working directory")),
3194 _("apply patch without touching the working directory")),
3195 ('', 'exact', None,
3195 ('', 'exact', None,
3196 _('apply patch to the nodes from which it was generated')),
3196 _('apply patch to the nodes from which it was generated')),
3197 ('', 'import-branch', None,
3197 ('', 'import-branch', None,
3198 _('use any branch information in patch (implied by --exact)'))] +
3198 _('use any branch information in patch (implied by --exact)'))] +
3199 commitopts + commitopts2 + similarityopts,
3199 commitopts + commitopts2 + similarityopts,
3200 _('[OPTION]... PATCH...'))
3200 _('[OPTION]... PATCH...'))
3201 def import_(ui, repo, patch1, *patches, **opts):
3201 def import_(ui, repo, patch1, *patches, **opts):
3202 """import an ordered set of patches
3202 """import an ordered set of patches
3203
3203
3204 Import a list of patches and commit them individually (unless
3204 Import a list of patches and commit them individually (unless
3205 --no-commit is specified).
3205 --no-commit is specified).
3206
3206
3207 If there are outstanding changes in the working directory, import
3207 If there are outstanding changes in the working directory, import
3208 will abort unless given the -f/--force flag.
3208 will abort unless given the -f/--force flag.
3209
3209
3210 You can import a patch straight from a mail message. Even patches
3210 You can import a patch straight from a mail message. Even patches
3211 as attachments work (to use the body part, it must have type
3211 as attachments work (to use the body part, it must have type
3212 text/plain or text/x-patch). From and Subject headers of email
3212 text/plain or text/x-patch). From and Subject headers of email
3213 message are used as default committer and commit message. All
3213 message are used as default committer and commit message. All
3214 text/plain body parts before first diff are added to commit
3214 text/plain body parts before first diff are added to commit
3215 message.
3215 message.
3216
3216
3217 If the imported patch was generated by :hg:`export`, user and
3217 If the imported patch was generated by :hg:`export`, user and
3218 description from patch override values from message headers and
3218 description from patch override values from message headers and
3219 body. Values given on command line with -m/--message and -u/--user
3219 body. Values given on command line with -m/--message and -u/--user
3220 override these.
3220 override these.
3221
3221
3222 If --exact is specified, import will set the working directory to
3222 If --exact is specified, import will set the working directory to
3223 the parent of each patch before applying it, and will abort if the
3223 the parent of each patch before applying it, and will abort if the
3224 resulting changeset has a different ID than the one recorded in
3224 resulting changeset has a different ID than the one recorded in
3225 the patch. This may happen due to character set problems or other
3225 the patch. This may happen due to character set problems or other
3226 deficiencies in the text patch format.
3226 deficiencies in the text patch format.
3227
3227
3228 Use --bypass to apply and commit patches directly to the
3228 Use --bypass to apply and commit patches directly to the
3229 repository, not touching the working directory. Without --exact,
3229 repository, not touching the working directory. Without --exact,
3230 patches will be applied on top of the working directory parent
3230 patches will be applied on top of the working directory parent
3231 revision.
3231 revision.
3232
3232
3233 With -s/--similarity, hg will attempt to discover renames and
3233 With -s/--similarity, hg will attempt to discover renames and
3234 copies in the patch in the same way as 'addremove'.
3234 copies in the patch in the same way as 'addremove'.
3235
3235
3236 To read a patch from standard input, use "-" as the patch name. If
3236 To read a patch from standard input, use "-" as the patch name. If
3237 a URL is specified, the patch will be downloaded from it.
3237 a URL is specified, the patch will be downloaded from it.
3238 See :hg:`help dates` for a list of formats valid for -d/--date.
3238 See :hg:`help dates` for a list of formats valid for -d/--date.
3239
3239
3240 .. container:: verbose
3240 .. container:: verbose
3241
3241
3242 Examples:
3242 Examples:
3243
3243
3244 - import a traditional patch from a website and detect renames::
3244 - import a traditional patch from a website and detect renames::
3245
3245
3246 hg import -s 80 http://example.com/bugfix.patch
3246 hg import -s 80 http://example.com/bugfix.patch
3247
3247
3248 - import a changeset from an hgweb server::
3248 - import a changeset from an hgweb server::
3249
3249
3250 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3250 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3251
3251
3252 - import all the patches in an Unix-style mbox::
3252 - import all the patches in an Unix-style mbox::
3253
3253
3254 hg import incoming-patches.mbox
3254 hg import incoming-patches.mbox
3255
3255
3256 - attempt to exactly restore an exported changeset (not always
3256 - attempt to exactly restore an exported changeset (not always
3257 possible)::
3257 possible)::
3258
3258
3259 hg import --exact proposed-fix.patch
3259 hg import --exact proposed-fix.patch
3260
3260
3261 Returns 0 on success.
3261 Returns 0 on success.
3262 """
3262 """
3263 patches = (patch1,) + patches
3263 patches = (patch1,) + patches
3264
3264
3265 date = opts.get('date')
3265 date = opts.get('date')
3266 if date:
3266 if date:
3267 opts['date'] = util.parsedate(date)
3267 opts['date'] = util.parsedate(date)
3268
3268
3269 editor = cmdutil.commiteditor
3269 editor = cmdutil.commiteditor
3270 if opts.get('edit'):
3270 if opts.get('edit'):
3271 editor = cmdutil.commitforceeditor
3271 editor = cmdutil.commitforceeditor
3272
3272
3273 update = not opts.get('bypass')
3273 update = not opts.get('bypass')
3274 if not update and opts.get('no_commit'):
3274 if not update and opts.get('no_commit'):
3275 raise util.Abort(_('cannot use --no-commit with --bypass'))
3275 raise util.Abort(_('cannot use --no-commit with --bypass'))
3276 try:
3276 try:
3277 sim = float(opts.get('similarity') or 0)
3277 sim = float(opts.get('similarity') or 0)
3278 except ValueError:
3278 except ValueError:
3279 raise util.Abort(_('similarity must be a number'))
3279 raise util.Abort(_('similarity must be a number'))
3280 if sim < 0 or sim > 100:
3280 if sim < 0 or sim > 100:
3281 raise util.Abort(_('similarity must be between 0 and 100'))
3281 raise util.Abort(_('similarity must be between 0 and 100'))
3282 if sim and not update:
3282 if sim and not update:
3283 raise util.Abort(_('cannot use --similarity with --bypass'))
3283 raise util.Abort(_('cannot use --similarity with --bypass'))
3284
3284
3285 if (opts.get('exact') or not opts.get('force')) and update:
3285 if (opts.get('exact') or not opts.get('force')) and update:
3286 cmdutil.bailifchanged(repo)
3286 cmdutil.bailifchanged(repo)
3287
3287
3288 base = opts["base"]
3288 base = opts["base"]
3289 strip = opts["strip"]
3289 strip = opts["strip"]
3290 wlock = lock = tr = None
3290 wlock = lock = tr = None
3291 msgs = []
3291 msgs = []
3292
3292
3293 def checkexact(repo, n, nodeid):
3293 def checkexact(repo, n, nodeid):
3294 if opts.get('exact') and hex(n) != nodeid:
3294 if opts.get('exact') and hex(n) != nodeid:
3295 repo.rollback()
3295 repo.rollback()
3296 raise util.Abort(_('patch is damaged or loses information'))
3296 raise util.Abort(_('patch is damaged or loses information'))
3297
3297
3298 def tryone(ui, hunk, parents):
3298 def tryone(ui, hunk, parents):
3299 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3299 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3300 patch.extract(ui, hunk)
3300 patch.extract(ui, hunk)
3301
3301
3302 if not tmpname:
3302 if not tmpname:
3303 return (None, None)
3303 return (None, None)
3304 msg = _('applied to working directory')
3304 msg = _('applied to working directory')
3305
3305
3306 try:
3306 try:
3307 cmdline_message = cmdutil.logmessage(ui, opts)
3307 cmdline_message = cmdutil.logmessage(ui, opts)
3308 if cmdline_message:
3308 if cmdline_message:
3309 # pickup the cmdline msg
3309 # pickup the cmdline msg
3310 message = cmdline_message
3310 message = cmdline_message
3311 elif message:
3311 elif message:
3312 # pickup the patch msg
3312 # pickup the patch msg
3313 message = message.strip()
3313 message = message.strip()
3314 else:
3314 else:
3315 # launch the editor
3315 # launch the editor
3316 message = None
3316 message = None
3317 ui.debug('message:\n%s\n' % message)
3317 ui.debug('message:\n%s\n' % message)
3318
3318
3319 if len(parents) == 1:
3319 if len(parents) == 1:
3320 parents.append(repo[nullid])
3320 parents.append(repo[nullid])
3321 if opts.get('exact'):
3321 if opts.get('exact'):
3322 if not nodeid or not p1:
3322 if not nodeid or not p1:
3323 raise util.Abort(_('not a Mercurial patch'))
3323 raise util.Abort(_('not a Mercurial patch'))
3324 p1 = repo[p1]
3324 p1 = repo[p1]
3325 p2 = repo[p2 or nullid]
3325 p2 = repo[p2 or nullid]
3326 elif p2:
3326 elif p2:
3327 try:
3327 try:
3328 p1 = repo[p1]
3328 p1 = repo[p1]
3329 p2 = repo[p2]
3329 p2 = repo[p2]
3330 except error.RepoError:
3330 except error.RepoError:
3331 p1, p2 = parents
3331 p1, p2 = parents
3332 else:
3332 else:
3333 p1, p2 = parents
3333 p1, p2 = parents
3334
3334
3335 n = None
3335 n = None
3336 if update:
3336 if update:
3337 if opts.get('exact') and p1 != parents[0]:
3337 if opts.get('exact') and p1 != parents[0]:
3338 hg.clean(repo, p1.node())
3338 hg.clean(repo, p1.node())
3339 if p1 != parents[0] and p2 != parents[1]:
3339 if p1 != parents[0] and p2 != parents[1]:
3340 repo.dirstate.setparents(p1.node(), p2.node())
3340 repo.dirstate.setparents(p1.node(), p2.node())
3341
3341
3342 if opts.get('exact') or opts.get('import_branch'):
3342 if opts.get('exact') or opts.get('import_branch'):
3343 repo.dirstate.setbranch(branch or 'default')
3343 repo.dirstate.setbranch(branch or 'default')
3344
3344
3345 files = set()
3345 files = set()
3346 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3346 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3347 eolmode=None, similarity=sim / 100.0)
3347 eolmode=None, similarity=sim / 100.0)
3348 files = list(files)
3348 files = list(files)
3349 if opts.get('no_commit'):
3349 if opts.get('no_commit'):
3350 if message:
3350 if message:
3351 msgs.append(message)
3351 msgs.append(message)
3352 else:
3352 else:
3353 if opts.get('exact'):
3353 if opts.get('exact'):
3354 m = None
3354 m = None
3355 else:
3355 else:
3356 m = scmutil.matchfiles(repo, files or [])
3356 m = scmutil.matchfiles(repo, files or [])
3357 n = repo.commit(message, opts.get('user') or user,
3357 n = repo.commit(message, opts.get('user') or user,
3358 opts.get('date') or date, match=m,
3358 opts.get('date') or date, match=m,
3359 editor=editor)
3359 editor=editor)
3360 checkexact(repo, n, nodeid)
3360 checkexact(repo, n, nodeid)
3361 else:
3361 else:
3362 if opts.get('exact') or opts.get('import_branch'):
3362 if opts.get('exact') or opts.get('import_branch'):
3363 branch = branch or 'default'
3363 branch = branch or 'default'
3364 else:
3364 else:
3365 branch = p1.branch()
3365 branch = p1.branch()
3366 store = patch.filestore()
3366 store = patch.filestore()
3367 try:
3367 try:
3368 files = set()
3368 files = set()
3369 try:
3369 try:
3370 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3370 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3371 files, eolmode=None)
3371 files, eolmode=None)
3372 except patch.PatchError, e:
3372 except patch.PatchError, e:
3373 raise util.Abort(str(e))
3373 raise util.Abort(str(e))
3374 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3374 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3375 message,
3375 message,
3376 opts.get('user') or user,
3376 opts.get('user') or user,
3377 opts.get('date') or date,
3377 opts.get('date') or date,
3378 branch, files, store,
3378 branch, files, store,
3379 editor=cmdutil.commiteditor)
3379 editor=cmdutil.commiteditor)
3380 repo.savecommitmessage(memctx.description())
3380 repo.savecommitmessage(memctx.description())
3381 n = memctx.commit()
3381 n = memctx.commit()
3382 checkexact(repo, n, nodeid)
3382 checkexact(repo, n, nodeid)
3383 finally:
3383 finally:
3384 store.close()
3384 store.close()
3385 if n:
3385 if n:
3386 msg = _('created %s') % short(n)
3386 msg = _('created %s') % short(n)
3387 return (msg, n)
3387 return (msg, n)
3388 finally:
3388 finally:
3389 os.unlink(tmpname)
3389 os.unlink(tmpname)
3390
3390
3391 try:
3391 try:
3392 wlock = repo.wlock()
3392 wlock = repo.wlock()
3393 lock = repo.lock()
3393 lock = repo.lock()
3394 tr = repo.transaction('import')
3394 tr = repo.transaction('import')
3395 parents = repo.parents()
3395 parents = repo.parents()
3396 for patchurl in patches:
3396 for patchurl in patches:
3397 if patchurl == '-':
3397 if patchurl == '-':
3398 ui.status(_('applying patch from stdin\n'))
3398 ui.status(_('applying patch from stdin\n'))
3399 patchfile = ui.fin
3399 patchfile = ui.fin
3400 patchurl = 'stdin' # for error message
3400 patchurl = 'stdin' # for error message
3401 else:
3401 else:
3402 patchurl = os.path.join(base, patchurl)
3402 patchurl = os.path.join(base, patchurl)
3403 ui.status(_('applying %s\n') % patchurl)
3403 ui.status(_('applying %s\n') % patchurl)
3404 patchfile = url.open(ui, patchurl)
3404 patchfile = url.open(ui, patchurl)
3405
3405
3406 haspatch = False
3406 haspatch = False
3407 for hunk in patch.split(patchfile):
3407 for hunk in patch.split(patchfile):
3408 (msg, node) = tryone(ui, hunk, parents)
3408 (msg, node) = tryone(ui, hunk, parents)
3409 if msg:
3409 if msg:
3410 haspatch = True
3410 haspatch = True
3411 ui.note(msg + '\n')
3411 ui.note(msg + '\n')
3412 if update or opts.get('exact'):
3412 if update or opts.get('exact'):
3413 parents = repo.parents()
3413 parents = repo.parents()
3414 else:
3414 else:
3415 parents = [repo[node]]
3415 parents = [repo[node]]
3416
3416
3417 if not haspatch:
3417 if not haspatch:
3418 raise util.Abort(_('%s: no diffs found') % patchurl)
3418 raise util.Abort(_('%s: no diffs found') % patchurl)
3419
3419
3420 tr.close()
3420 tr.close()
3421 if msgs:
3421 if msgs:
3422 repo.savecommitmessage('\n* * *\n'.join(msgs))
3422 repo.savecommitmessage('\n* * *\n'.join(msgs))
3423 except:
3423 except:
3424 # wlock.release() indirectly calls dirstate.write(): since
3424 # wlock.release() indirectly calls dirstate.write(): since
3425 # we're crashing, we do not want to change the working dir
3425 # we're crashing, we do not want to change the working dir
3426 # parent after all, so make sure it writes nothing
3426 # parent after all, so make sure it writes nothing
3427 repo.dirstate.invalidate()
3427 repo.dirstate.invalidate()
3428 raise
3428 raise
3429 finally:
3429 finally:
3430 if tr:
3430 if tr:
3431 tr.release()
3431 tr.release()
3432 release(lock, wlock)
3432 release(lock, wlock)
3433
3433
3434 @command('incoming|in',
3434 @command('incoming|in',
3435 [('f', 'force', None,
3435 [('f', 'force', None,
3436 _('run even if remote repository is unrelated')),
3436 _('run even if remote repository is unrelated')),
3437 ('n', 'newest-first', None, _('show newest record first')),
3437 ('n', 'newest-first', None, _('show newest record first')),
3438 ('', 'bundle', '',
3438 ('', 'bundle', '',
3439 _('file to store the bundles into'), _('FILE')),
3439 _('file to store the bundles into'), _('FILE')),
3440 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3440 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3441 ('B', 'bookmarks', False, _("compare bookmarks")),
3441 ('B', 'bookmarks', False, _("compare bookmarks")),
3442 ('b', 'branch', [],
3442 ('b', 'branch', [],
3443 _('a specific branch you would like to pull'), _('BRANCH')),
3443 _('a specific branch you would like to pull'), _('BRANCH')),
3444 ] + logopts + remoteopts + subrepoopts,
3444 ] + logopts + remoteopts + subrepoopts,
3445 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3445 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3446 def incoming(ui, repo, source="default", **opts):
3446 def incoming(ui, repo, source="default", **opts):
3447 """show new changesets found in source
3447 """show new changesets found in source
3448
3448
3449 Show new changesets found in the specified path/URL or the default
3449 Show new changesets found in the specified path/URL or the default
3450 pull location. These are the changesets that would have been pulled
3450 pull location. These are the changesets that would have been pulled
3451 if a pull at the time you issued this command.
3451 if a pull at the time you issued this command.
3452
3452
3453 For remote repository, using --bundle avoids downloading the
3453 For remote repository, using --bundle avoids downloading the
3454 changesets twice if the incoming is followed by a pull.
3454 changesets twice if the incoming is followed by a pull.
3455
3455
3456 See pull for valid source format details.
3456 See pull for valid source format details.
3457
3457
3458 Returns 0 if there are incoming changes, 1 otherwise.
3458 Returns 0 if there are incoming changes, 1 otherwise.
3459 """
3459 """
3460 if opts.get('bundle') and opts.get('subrepos'):
3460 if opts.get('bundle') and opts.get('subrepos'):
3461 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3461 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3462
3462
3463 if opts.get('bookmarks'):
3463 if opts.get('bookmarks'):
3464 source, branches = hg.parseurl(ui.expandpath(source),
3464 source, branches = hg.parseurl(ui.expandpath(source),
3465 opts.get('branch'))
3465 opts.get('branch'))
3466 other = hg.peer(repo, opts, source)
3466 other = hg.peer(repo, opts, source)
3467 if 'bookmarks' not in other.listkeys('namespaces'):
3467 if 'bookmarks' not in other.listkeys('namespaces'):
3468 ui.warn(_("remote doesn't support bookmarks\n"))
3468 ui.warn(_("remote doesn't support bookmarks\n"))
3469 return 0
3469 return 0
3470 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3470 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3471 return bookmarks.diff(ui, repo, other)
3471 return bookmarks.diff(ui, repo, other)
3472
3472
3473 repo._subtoppath = ui.expandpath(source)
3473 repo._subtoppath = ui.expandpath(source)
3474 try:
3474 try:
3475 return hg.incoming(ui, repo, source, opts)
3475 return hg.incoming(ui, repo, source, opts)
3476 finally:
3476 finally:
3477 del repo._subtoppath
3477 del repo._subtoppath
3478
3478
3479
3479
3480 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3480 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3481 def init(ui, dest=".", **opts):
3481 def init(ui, dest=".", **opts):
3482 """create a new repository in the given directory
3482 """create a new repository in the given directory
3483
3483
3484 Initialize a new repository in the given directory. If the given
3484 Initialize a new repository in the given directory. If the given
3485 directory does not exist, it will be created.
3485 directory does not exist, it will be created.
3486
3486
3487 If no directory is given, the current directory is used.
3487 If no directory is given, the current directory is used.
3488
3488
3489 It is possible to specify an ``ssh://`` URL as the destination.
3489 It is possible to specify an ``ssh://`` URL as the destination.
3490 See :hg:`help urls` for more information.
3490 See :hg:`help urls` for more information.
3491
3491
3492 Returns 0 on success.
3492 Returns 0 on success.
3493 """
3493 """
3494 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3494 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3495
3495
3496 @command('locate',
3496 @command('locate',
3497 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3497 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3498 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3498 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3499 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3499 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3500 ] + walkopts,
3500 ] + walkopts,
3501 _('[OPTION]... [PATTERN]...'))
3501 _('[OPTION]... [PATTERN]...'))
3502 def locate(ui, repo, *pats, **opts):
3502 def locate(ui, repo, *pats, **opts):
3503 """locate files matching specific patterns
3503 """locate files matching specific patterns
3504
3504
3505 Print files under Mercurial control in the working directory whose
3505 Print files under Mercurial control in the working directory whose
3506 names match the given patterns.
3506 names match the given patterns.
3507
3507
3508 By default, this command searches all directories in the working
3508 By default, this command searches all directories in the working
3509 directory. To search just the current directory and its
3509 directory. To search just the current directory and its
3510 subdirectories, use "--include .".
3510 subdirectories, use "--include .".
3511
3511
3512 If no patterns are given to match, this command prints the names
3512 If no patterns are given to match, this command prints the names
3513 of all files under Mercurial control in the working directory.
3513 of all files under Mercurial control in the working directory.
3514
3514
3515 If you want to feed the output of this command into the "xargs"
3515 If you want to feed the output of this command into the "xargs"
3516 command, use the -0 option to both this command and "xargs". This
3516 command, use the -0 option to both this command and "xargs". This
3517 will avoid the problem of "xargs" treating single filenames that
3517 will avoid the problem of "xargs" treating single filenames that
3518 contain whitespace as multiple filenames.
3518 contain whitespace as multiple filenames.
3519
3519
3520 Returns 0 if a match is found, 1 otherwise.
3520 Returns 0 if a match is found, 1 otherwise.
3521 """
3521 """
3522 end = opts.get('print0') and '\0' or '\n'
3522 end = opts.get('print0') and '\0' or '\n'
3523 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3523 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3524
3524
3525 ret = 1
3525 ret = 1
3526 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3526 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3527 m.bad = lambda x, y: False
3527 m.bad = lambda x, y: False
3528 for abs in repo[rev].walk(m):
3528 for abs in repo[rev].walk(m):
3529 if not rev and abs not in repo.dirstate:
3529 if not rev and abs not in repo.dirstate:
3530 continue
3530 continue
3531 if opts.get('fullpath'):
3531 if opts.get('fullpath'):
3532 ui.write(repo.wjoin(abs), end)
3532 ui.write(repo.wjoin(abs), end)
3533 else:
3533 else:
3534 ui.write(((pats and m.rel(abs)) or abs), end)
3534 ui.write(((pats and m.rel(abs)) or abs), end)
3535 ret = 0
3535 ret = 0
3536
3536
3537 return ret
3537 return ret
3538
3538
3539 @command('^log|history',
3539 @command('^log|history',
3540 [('f', 'follow', None,
3540 [('f', 'follow', None,
3541 _('follow changeset history, or file history across copies and renames')),
3541 _('follow changeset history, or file history across copies and renames')),
3542 ('', 'follow-first', None,
3542 ('', 'follow-first', None,
3543 _('only follow the first parent of merge changesets')),
3543 _('only follow the first parent of merge changesets')),
3544 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3544 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3545 ('C', 'copies', None, _('show copied files')),
3545 ('C', 'copies', None, _('show copied files')),
3546 ('k', 'keyword', [],
3546 ('k', 'keyword', [],
3547 _('do case-insensitive search for a given text'), _('TEXT')),
3547 _('do case-insensitive search for a given text'), _('TEXT')),
3548 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3548 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3549 ('', 'removed', None, _('include revisions where files were removed')),
3549 ('', 'removed', None, _('include revisions where files were removed')),
3550 ('m', 'only-merges', None, _('show only merges')),
3550 ('m', 'only-merges', None, _('show only merges')),
3551 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3551 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3552 ('', 'only-branch', [],
3552 ('', 'only-branch', [],
3553 _('show only changesets within the given named branch (DEPRECATED)'),
3553 _('show only changesets within the given named branch (DEPRECATED)'),
3554 _('BRANCH')),
3554 _('BRANCH')),
3555 ('b', 'branch', [],
3555 ('b', 'branch', [],
3556 _('show changesets within the given named branch'), _('BRANCH')),
3556 _('show changesets within the given named branch'), _('BRANCH')),
3557 ('P', 'prune', [],
3557 ('P', 'prune', [],
3558 _('do not display revision or any of its ancestors'), _('REV')),
3558 _('do not display revision or any of its ancestors'), _('REV')),
3559 ('', 'hidden', False, _('show hidden changesets')),
3559 ('', 'hidden', False, _('show hidden changesets')),
3560 ] + logopts + walkopts,
3560 ] + logopts + walkopts,
3561 _('[OPTION]... [FILE]'))
3561 _('[OPTION]... [FILE]'))
3562 def log(ui, repo, *pats, **opts):
3562 def log(ui, repo, *pats, **opts):
3563 """show revision history of entire repository or files
3563 """show revision history of entire repository or files
3564
3564
3565 Print the revision history of the specified files or the entire
3565 Print the revision history of the specified files or the entire
3566 project.
3566 project.
3567
3567
3568 If no revision range is specified, the default is ``tip:0`` unless
3568 If no revision range is specified, the default is ``tip:0`` unless
3569 --follow is set, in which case the working directory parent is
3569 --follow is set, in which case the working directory parent is
3570 used as the starting revision.
3570 used as the starting revision.
3571
3571
3572 File history is shown without following rename or copy history of
3572 File history is shown without following rename or copy history of
3573 files. Use -f/--follow with a filename to follow history across
3573 files. Use -f/--follow with a filename to follow history across
3574 renames and copies. --follow without a filename will only show
3574 renames and copies. --follow without a filename will only show
3575 ancestors or descendants of the starting revision.
3575 ancestors or descendants of the starting revision.
3576
3576
3577 By default this command prints revision number and changeset id,
3577 By default this command prints revision number and changeset id,
3578 tags, non-trivial parents, user, date and time, and a summary for
3578 tags, non-trivial parents, user, date and time, and a summary for
3579 each commit. When the -v/--verbose switch is used, the list of
3579 each commit. When the -v/--verbose switch is used, the list of
3580 changed files and full commit message are shown.
3580 changed files and full commit message are shown.
3581
3581
3582 .. note::
3582 .. note::
3583 log -p/--patch may generate unexpected diff output for merge
3583 log -p/--patch may generate unexpected diff output for merge
3584 changesets, as it will only compare the merge changeset against
3584 changesets, as it will only compare the merge changeset against
3585 its first parent. Also, only files different from BOTH parents
3585 its first parent. Also, only files different from BOTH parents
3586 will appear in files:.
3586 will appear in files:.
3587
3587
3588 .. note::
3588 .. note::
3589 for performance reasons, log FILE may omit duplicate changes
3589 for performance reasons, log FILE may omit duplicate changes
3590 made on branches and will not show deletions. To see all
3590 made on branches and will not show deletions. To see all
3591 changes including duplicates and deletions, use the --removed
3591 changes including duplicates and deletions, use the --removed
3592 switch.
3592 switch.
3593
3593
3594 .. container:: verbose
3594 .. container:: verbose
3595
3595
3596 Some examples:
3596 Some examples:
3597
3597
3598 - changesets with full descriptions and file lists::
3598 - changesets with full descriptions and file lists::
3599
3599
3600 hg log -v
3600 hg log -v
3601
3601
3602 - changesets ancestral to the working directory::
3602 - changesets ancestral to the working directory::
3603
3603
3604 hg log -f
3604 hg log -f
3605
3605
3606 - last 10 commits on the current branch::
3606 - last 10 commits on the current branch::
3607
3607
3608 hg log -l 10 -b .
3608 hg log -l 10 -b .
3609
3609
3610 - changesets showing all modifications of a file, including removals::
3610 - changesets showing all modifications of a file, including removals::
3611
3611
3612 hg log --removed file.c
3612 hg log --removed file.c
3613
3613
3614 - all changesets that touch a directory, with diffs, excluding merges::
3614 - all changesets that touch a directory, with diffs, excluding merges::
3615
3615
3616 hg log -Mp lib/
3616 hg log -Mp lib/
3617
3617
3618 - all revision numbers that match a keyword::
3618 - all revision numbers that match a keyword::
3619
3619
3620 hg log -k bug --template "{rev}\\n"
3620 hg log -k bug --template "{rev}\\n"
3621
3621
3622 - check if a given changeset is included is a tagged release::
3622 - check if a given changeset is included is a tagged release::
3623
3623
3624 hg log -r "a21ccf and ancestor(1.9)"
3624 hg log -r "a21ccf and ancestor(1.9)"
3625
3625
3626 - find all changesets by some user in a date range::
3626 - find all changesets by some user in a date range::
3627
3627
3628 hg log -k alice -d "may 2008 to jul 2008"
3628 hg log -k alice -d "may 2008 to jul 2008"
3629
3629
3630 - summary of all changesets after the last tag::
3630 - summary of all changesets after the last tag::
3631
3631
3632 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3632 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3633
3633
3634 See :hg:`help dates` for a list of formats valid for -d/--date.
3634 See :hg:`help dates` for a list of formats valid for -d/--date.
3635
3635
3636 See :hg:`help revisions` and :hg:`help revsets` for more about
3636 See :hg:`help revisions` and :hg:`help revsets` for more about
3637 specifying revisions.
3637 specifying revisions.
3638
3638
3639 Returns 0 on success.
3639 Returns 0 on success.
3640 """
3640 """
3641
3641
3642 matchfn = scmutil.match(repo[None], pats, opts)
3642 matchfn = scmutil.match(repo[None], pats, opts)
3643 limit = cmdutil.loglimit(opts)
3643 limit = cmdutil.loglimit(opts)
3644 count = 0
3644 count = 0
3645
3645
3646 endrev = None
3646 endrev = None
3647 if opts.get('copies') and opts.get('rev'):
3647 if opts.get('copies') and opts.get('rev'):
3648 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3648 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3649
3649
3650 df = False
3650 df = False
3651 if opts["date"]:
3651 if opts["date"]:
3652 df = util.matchdate(opts["date"])
3652 df = util.matchdate(opts["date"])
3653
3653
3654 branches = opts.get('branch', []) + opts.get('only_branch', [])
3654 branches = opts.get('branch', []) + opts.get('only_branch', [])
3655 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3655 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3656
3656
3657 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3657 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3658 def prep(ctx, fns):
3658 def prep(ctx, fns):
3659 rev = ctx.rev()
3659 rev = ctx.rev()
3660 parents = [p for p in repo.changelog.parentrevs(rev)
3660 parents = [p for p in repo.changelog.parentrevs(rev)
3661 if p != nullrev]
3661 if p != nullrev]
3662 if opts.get('no_merges') and len(parents) == 2:
3662 if opts.get('no_merges') and len(parents) == 2:
3663 return
3663 return
3664 if opts.get('only_merges') and len(parents) != 2:
3664 if opts.get('only_merges') and len(parents) != 2:
3665 return
3665 return
3666 if opts.get('branch') and ctx.branch() not in opts['branch']:
3666 if opts.get('branch') and ctx.branch() not in opts['branch']:
3667 return
3667 return
3668 if not opts.get('hidden') and ctx.hidden():
3668 if not opts.get('hidden') and ctx.hidden():
3669 return
3669 return
3670 if df and not df(ctx.date()[0]):
3670 if df and not df(ctx.date()[0]):
3671 return
3671 return
3672 if opts['user'] and not [k for k in opts['user']
3672 if opts['user'] and not [k for k in opts['user']
3673 if k.lower() in ctx.user().lower()]:
3673 if k.lower() in ctx.user().lower()]:
3674 return
3674 return
3675 if opts.get('keyword'):
3675 if opts.get('keyword'):
3676 for k in [kw.lower() for kw in opts['keyword']]:
3676 for k in [kw.lower() for kw in opts['keyword']]:
3677 if (k in ctx.user().lower() or
3677 if (k in ctx.user().lower() or
3678 k in ctx.description().lower() or
3678 k in ctx.description().lower() or
3679 k in " ".join(ctx.files()).lower()):
3679 k in " ".join(ctx.files()).lower()):
3680 break
3680 break
3681 else:
3681 else:
3682 return
3682 return
3683
3683
3684 copies = None
3684 copies = None
3685 if opts.get('copies') and rev:
3685 if opts.get('copies') and rev:
3686 copies = []
3686 copies = []
3687 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3687 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3688 for fn in ctx.files():
3688 for fn in ctx.files():
3689 rename = getrenamed(fn, rev)
3689 rename = getrenamed(fn, rev)
3690 if rename:
3690 if rename:
3691 copies.append((fn, rename[0]))
3691 copies.append((fn, rename[0]))
3692
3692
3693 revmatchfn = None
3693 revmatchfn = None
3694 if opts.get('patch') or opts.get('stat'):
3694 if opts.get('patch') or opts.get('stat'):
3695 if opts.get('follow') or opts.get('follow_first'):
3695 if opts.get('follow') or opts.get('follow_first'):
3696 # note: this might be wrong when following through merges
3696 # note: this might be wrong when following through merges
3697 revmatchfn = scmutil.match(repo[None], fns, default='path')
3697 revmatchfn = scmutil.match(repo[None], fns, default='path')
3698 else:
3698 else:
3699 revmatchfn = matchfn
3699 revmatchfn = matchfn
3700
3700
3701 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3701 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3702
3702
3703 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3703 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3704 if count == limit:
3704 if count == limit:
3705 break
3705 break
3706 if displayer.flush(ctx.rev()):
3706 if displayer.flush(ctx.rev()):
3707 count += 1
3707 count += 1
3708 displayer.close()
3708 displayer.close()
3709
3709
3710 @command('manifest',
3710 @command('manifest',
3711 [('r', 'rev', '', _('revision to display'), _('REV')),
3711 [('r', 'rev', '', _('revision to display'), _('REV')),
3712 ('', 'all', False, _("list files from all revisions"))],
3712 ('', 'all', False, _("list files from all revisions"))],
3713 _('[-r REV]'))
3713 _('[-r REV]'))
3714 def manifest(ui, repo, node=None, rev=None, **opts):
3714 def manifest(ui, repo, node=None, rev=None, **opts):
3715 """output the current or given revision of the project manifest
3715 """output the current or given revision of the project manifest
3716
3716
3717 Print a list of version controlled files for the given revision.
3717 Print a list of version controlled files for the given revision.
3718 If no revision is given, the first parent of the working directory
3718 If no revision is given, the first parent of the working directory
3719 is used, or the null revision if no revision is checked out.
3719 is used, or the null revision if no revision is checked out.
3720
3720
3721 With -v, print file permissions, symlink and executable bits.
3721 With -v, print file permissions, symlink and executable bits.
3722 With --debug, print file revision hashes.
3722 With --debug, print file revision hashes.
3723
3723
3724 If option --all is specified, the list of all files from all revisions
3724 If option --all is specified, the list of all files from all revisions
3725 is printed. This includes deleted and renamed files.
3725 is printed. This includes deleted and renamed files.
3726
3726
3727 Returns 0 on success.
3727 Returns 0 on success.
3728 """
3728 """
3729 if opts.get('all'):
3729 if opts.get('all'):
3730 if rev or node:
3730 if rev or node:
3731 raise util.Abort(_("can't specify a revision with --all"))
3731 raise util.Abort(_("can't specify a revision with --all"))
3732
3732
3733 res = []
3733 res = []
3734 prefix = "data/"
3734 prefix = "data/"
3735 suffix = ".i"
3735 suffix = ".i"
3736 plen = len(prefix)
3736 plen = len(prefix)
3737 slen = len(suffix)
3737 slen = len(suffix)
3738 lock = repo.lock()
3738 lock = repo.lock()
3739 try:
3739 try:
3740 for fn, b, size in repo.store.datafiles():
3740 for fn, b, size in repo.store.datafiles():
3741 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3741 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3742 res.append(fn[plen:-slen])
3742 res.append(fn[plen:-slen])
3743 finally:
3743 finally:
3744 lock.release()
3744 lock.release()
3745 for f in sorted(res):
3745 for f in sorted(res):
3746 ui.write("%s\n" % f)
3746 ui.write("%s\n" % f)
3747 return
3747 return
3748
3748
3749 if rev and node:
3749 if rev and node:
3750 raise util.Abort(_("please specify just one revision"))
3750 raise util.Abort(_("please specify just one revision"))
3751
3751
3752 if not node:
3752 if not node:
3753 node = rev
3753 node = rev
3754
3754
3755 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3755 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3756 ctx = scmutil.revsingle(repo, node)
3756 ctx = scmutil.revsingle(repo, node)
3757 for f in ctx:
3757 for f in ctx:
3758 if ui.debugflag:
3758 if ui.debugflag:
3759 ui.write("%40s " % hex(ctx.manifest()[f]))
3759 ui.write("%40s " % hex(ctx.manifest()[f]))
3760 if ui.verbose:
3760 if ui.verbose:
3761 ui.write(decor[ctx.flags(f)])
3761 ui.write(decor[ctx.flags(f)])
3762 ui.write("%s\n" % f)
3762 ui.write("%s\n" % f)
3763
3763
3764 @command('^merge',
3764 @command('^merge',
3765 [('f', 'force', None, _('force a merge with outstanding changes')),
3765 [('f', 'force', None, _('force a merge with outstanding changes')),
3766 ('r', 'rev', '', _('revision to merge'), _('REV')),
3766 ('r', 'rev', '', _('revision to merge'), _('REV')),
3767 ('P', 'preview', None,
3767 ('P', 'preview', None,
3768 _('review revisions to merge (no merge is performed)'))
3768 _('review revisions to merge (no merge is performed)'))
3769 ] + mergetoolopts,
3769 ] + mergetoolopts,
3770 _('[-P] [-f] [[-r] REV]'))
3770 _('[-P] [-f] [[-r] REV]'))
3771 def merge(ui, repo, node=None, **opts):
3771 def merge(ui, repo, node=None, **opts):
3772 """merge working directory with another revision
3772 """merge working directory with another revision
3773
3773
3774 The current working directory is updated with all changes made in
3774 The current working directory is updated with all changes made in
3775 the requested revision since the last common predecessor revision.
3775 the requested revision since the last common predecessor revision.
3776
3776
3777 Files that changed between either parent are marked as changed for
3777 Files that changed between either parent are marked as changed for
3778 the next commit and a commit must be performed before any further
3778 the next commit and a commit must be performed before any further
3779 updates to the repository are allowed. The next commit will have
3779 updates to the repository are allowed. The next commit will have
3780 two parents.
3780 two parents.
3781
3781
3782 ``--tool`` can be used to specify the merge tool used for file
3782 ``--tool`` can be used to specify the merge tool used for file
3783 merges. It overrides the HGMERGE environment variable and your
3783 merges. It overrides the HGMERGE environment variable and your
3784 configuration files. See :hg:`help merge-tools` for options.
3784 configuration files. See :hg:`help merge-tools` for options.
3785
3785
3786 If no revision is specified, the working directory's parent is a
3786 If no revision is specified, the working directory's parent is a
3787 head revision, and the current branch contains exactly one other
3787 head revision, and the current branch contains exactly one other
3788 head, the other head is merged with by default. Otherwise, an
3788 head, the other head is merged with by default. Otherwise, an
3789 explicit revision with which to merge with must be provided.
3789 explicit revision with which to merge with must be provided.
3790
3790
3791 :hg:`resolve` must be used to resolve unresolved files.
3791 :hg:`resolve` must be used to resolve unresolved files.
3792
3792
3793 To undo an uncommitted merge, use :hg:`update --clean .` which
3793 To undo an uncommitted merge, use :hg:`update --clean .` which
3794 will check out a clean copy of the original merge parent, losing
3794 will check out a clean copy of the original merge parent, losing
3795 all changes.
3795 all changes.
3796
3796
3797 Returns 0 on success, 1 if there are unresolved files.
3797 Returns 0 on success, 1 if there are unresolved files.
3798 """
3798 """
3799
3799
3800 if opts.get('rev') and node:
3800 if opts.get('rev') and node:
3801 raise util.Abort(_("please specify just one revision"))
3801 raise util.Abort(_("please specify just one revision"))
3802 if not node:
3802 if not node:
3803 node = opts.get('rev')
3803 node = opts.get('rev')
3804
3804
3805 if not node:
3805 if not node:
3806 branch = repo[None].branch()
3806 branch = repo[None].branch()
3807 bheads = repo.branchheads(branch)
3807 bheads = repo.branchheads(branch)
3808 if len(bheads) > 2:
3808 if len(bheads) > 2:
3809 raise util.Abort(_("branch '%s' has %d heads - "
3809 raise util.Abort(_("branch '%s' has %d heads - "
3810 "please merge with an explicit rev")
3810 "please merge with an explicit rev")
3811 % (branch, len(bheads)),
3811 % (branch, len(bheads)),
3812 hint=_("run 'hg heads .' to see heads"))
3812 hint=_("run 'hg heads .' to see heads"))
3813
3813
3814 parent = repo.dirstate.p1()
3814 parent = repo.dirstate.p1()
3815 if len(bheads) == 1:
3815 if len(bheads) == 1:
3816 if len(repo.heads()) > 1:
3816 if len(repo.heads()) > 1:
3817 raise util.Abort(_("branch '%s' has one head - "
3817 raise util.Abort(_("branch '%s' has one head - "
3818 "please merge with an explicit rev")
3818 "please merge with an explicit rev")
3819 % branch,
3819 % branch,
3820 hint=_("run 'hg heads' to see all heads"))
3820 hint=_("run 'hg heads' to see all heads"))
3821 msg = _('there is nothing to merge')
3821 msg = _('there is nothing to merge')
3822 if parent != repo.lookup(repo[None].branch()):
3822 if parent != repo.lookup(repo[None].branch()):
3823 msg = _('%s - use "hg update" instead') % msg
3823 msg = _('%s - use "hg update" instead') % msg
3824 raise util.Abort(msg)
3824 raise util.Abort(msg)
3825
3825
3826 if parent not in bheads:
3826 if parent not in bheads:
3827 raise util.Abort(_('working directory not at a head revision'),
3827 raise util.Abort(_('working directory not at a head revision'),
3828 hint=_("use 'hg update' or merge with an "
3828 hint=_("use 'hg update' or merge with an "
3829 "explicit revision"))
3829 "explicit revision"))
3830 node = parent == bheads[0] and bheads[-1] or bheads[0]
3830 node = parent == bheads[0] and bheads[-1] or bheads[0]
3831 else:
3831 else:
3832 node = scmutil.revsingle(repo, node).node()
3832 node = scmutil.revsingle(repo, node).node()
3833
3833
3834 if opts.get('preview'):
3834 if opts.get('preview'):
3835 # find nodes that are ancestors of p2 but not of p1
3835 # find nodes that are ancestors of p2 but not of p1
3836 p1 = repo.lookup('.')
3836 p1 = repo.lookup('.')
3837 p2 = repo.lookup(node)
3837 p2 = repo.lookup(node)
3838 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3838 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3839
3839
3840 displayer = cmdutil.show_changeset(ui, repo, opts)
3840 displayer = cmdutil.show_changeset(ui, repo, opts)
3841 for node in nodes:
3841 for node in nodes:
3842 displayer.show(repo[node])
3842 displayer.show(repo[node])
3843 displayer.close()
3843 displayer.close()
3844 return 0
3844 return 0
3845
3845
3846 try:
3846 try:
3847 # ui.forcemerge is an internal variable, do not document
3847 # ui.forcemerge is an internal variable, do not document
3848 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3848 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3849 return hg.merge(repo, node, force=opts.get('force'))
3849 return hg.merge(repo, node, force=opts.get('force'))
3850 finally:
3850 finally:
3851 ui.setconfig('ui', 'forcemerge', '')
3851 ui.setconfig('ui', 'forcemerge', '')
3852
3852
3853 @command('outgoing|out',
3853 @command('outgoing|out',
3854 [('f', 'force', None, _('run even when the destination is unrelated')),
3854 [('f', 'force', None, _('run even when the destination is unrelated')),
3855 ('r', 'rev', [],
3855 ('r', 'rev', [],
3856 _('a changeset intended to be included in the destination'), _('REV')),
3856 _('a changeset intended to be included in the destination'), _('REV')),
3857 ('n', 'newest-first', None, _('show newest record first')),
3857 ('n', 'newest-first', None, _('show newest record first')),
3858 ('B', 'bookmarks', False, _('compare bookmarks')),
3858 ('B', 'bookmarks', False, _('compare bookmarks')),
3859 ('b', 'branch', [], _('a specific branch you would like to push'),
3859 ('b', 'branch', [], _('a specific branch you would like to push'),
3860 _('BRANCH')),
3860 _('BRANCH')),
3861 ] + logopts + remoteopts + subrepoopts,
3861 ] + logopts + remoteopts + subrepoopts,
3862 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3862 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3863 def outgoing(ui, repo, dest=None, **opts):
3863 def outgoing(ui, repo, dest=None, **opts):
3864 """show changesets not found in the destination
3864 """show changesets not found in the destination
3865
3865
3866 Show changesets not found in the specified destination repository
3866 Show changesets not found in the specified destination repository
3867 or the default push location. These are the changesets that would
3867 or the default push location. These are the changesets that would
3868 be pushed if a push was requested.
3868 be pushed if a push was requested.
3869
3869
3870 See pull for details of valid destination formats.
3870 See pull for details of valid destination formats.
3871
3871
3872 Returns 0 if there are outgoing changes, 1 otherwise.
3872 Returns 0 if there are outgoing changes, 1 otherwise.
3873 """
3873 """
3874
3874
3875 if opts.get('bookmarks'):
3875 if opts.get('bookmarks'):
3876 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3876 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3877 dest, branches = hg.parseurl(dest, opts.get('branch'))
3877 dest, branches = hg.parseurl(dest, opts.get('branch'))
3878 other = hg.peer(repo, opts, dest)
3878 other = hg.peer(repo, opts, dest)
3879 if 'bookmarks' not in other.listkeys('namespaces'):
3879 if 'bookmarks' not in other.listkeys('namespaces'):
3880 ui.warn(_("remote doesn't support bookmarks\n"))
3880 ui.warn(_("remote doesn't support bookmarks\n"))
3881 return 0
3881 return 0
3882 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3882 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3883 return bookmarks.diff(ui, other, repo)
3883 return bookmarks.diff(ui, other, repo)
3884
3884
3885 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3885 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3886 try:
3886 try:
3887 return hg.outgoing(ui, repo, dest, opts)
3887 return hg.outgoing(ui, repo, dest, opts)
3888 finally:
3888 finally:
3889 del repo._subtoppath
3889 del repo._subtoppath
3890
3890
3891 @command('parents',
3891 @command('parents',
3892 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3892 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3893 ] + templateopts,
3893 ] + templateopts,
3894 _('[-r REV] [FILE]'))
3894 _('[-r REV] [FILE]'))
3895 def parents(ui, repo, file_=None, **opts):
3895 def parents(ui, repo, file_=None, **opts):
3896 """show the parents of the working directory or revision
3896 """show the parents of the working directory or revision
3897
3897
3898 Print the working directory's parent revisions. If a revision is
3898 Print the working directory's parent revisions. If a revision is
3899 given via -r/--rev, the parent of that revision will be printed.
3899 given via -r/--rev, the parent of that revision will be printed.
3900 If a file argument is given, the revision in which the file was
3900 If a file argument is given, the revision in which the file was
3901 last changed (before the working directory revision or the
3901 last changed (before the working directory revision or the
3902 argument to --rev if given) is printed.
3902 argument to --rev if given) is printed.
3903
3903
3904 Returns 0 on success.
3904 Returns 0 on success.
3905 """
3905 """
3906
3906
3907 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3907 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3908
3908
3909 if file_:
3909 if file_:
3910 m = scmutil.match(ctx, (file_,), opts)
3910 m = scmutil.match(ctx, (file_,), opts)
3911 if m.anypats() or len(m.files()) != 1:
3911 if m.anypats() or len(m.files()) != 1:
3912 raise util.Abort(_('can only specify an explicit filename'))
3912 raise util.Abort(_('can only specify an explicit filename'))
3913 file_ = m.files()[0]
3913 file_ = m.files()[0]
3914 filenodes = []
3914 filenodes = []
3915 for cp in ctx.parents():
3915 for cp in ctx.parents():
3916 if not cp:
3916 if not cp:
3917 continue
3917 continue
3918 try:
3918 try:
3919 filenodes.append(cp.filenode(file_))
3919 filenodes.append(cp.filenode(file_))
3920 except error.LookupError:
3920 except error.LookupError:
3921 pass
3921 pass
3922 if not filenodes:
3922 if not filenodes:
3923 raise util.Abort(_("'%s' not found in manifest!") % file_)
3923 raise util.Abort(_("'%s' not found in manifest!") % file_)
3924 fl = repo.file(file_)
3924 fl = repo.file(file_)
3925 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3925 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3926 else:
3926 else:
3927 p = [cp.node() for cp in ctx.parents()]
3927 p = [cp.node() for cp in ctx.parents()]
3928
3928
3929 displayer = cmdutil.show_changeset(ui, repo, opts)
3929 displayer = cmdutil.show_changeset(ui, repo, opts)
3930 for n in p:
3930 for n in p:
3931 if n != nullid:
3931 if n != nullid:
3932 displayer.show(repo[n])
3932 displayer.show(repo[n])
3933 displayer.close()
3933 displayer.close()
3934
3934
3935 @command('paths', [], _('[NAME]'))
3935 @command('paths', [], _('[NAME]'))
3936 def paths(ui, repo, search=None):
3936 def paths(ui, repo, search=None):
3937 """show aliases for remote repositories
3937 """show aliases for remote repositories
3938
3938
3939 Show definition of symbolic path name NAME. If no name is given,
3939 Show definition of symbolic path name NAME. If no name is given,
3940 show definition of all available names.
3940 show definition of all available names.
3941
3941
3942 Option -q/--quiet suppresses all output when searching for NAME
3942 Option -q/--quiet suppresses all output when searching for NAME
3943 and shows only the path names when listing all definitions.
3943 and shows only the path names when listing all definitions.
3944
3944
3945 Path names are defined in the [paths] section of your
3945 Path names are defined in the [paths] section of your
3946 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3946 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3947 repository, ``.hg/hgrc`` is used, too.
3947 repository, ``.hg/hgrc`` is used, too.
3948
3948
3949 The path names ``default`` and ``default-push`` have a special
3949 The path names ``default`` and ``default-push`` have a special
3950 meaning. When performing a push or pull operation, they are used
3950 meaning. When performing a push or pull operation, they are used
3951 as fallbacks if no location is specified on the command-line.
3951 as fallbacks if no location is specified on the command-line.
3952 When ``default-push`` is set, it will be used for push and
3952 When ``default-push`` is set, it will be used for push and
3953 ``default`` will be used for pull; otherwise ``default`` is used
3953 ``default`` will be used for pull; otherwise ``default`` is used
3954 as the fallback for both. When cloning a repository, the clone
3954 as the fallback for both. When cloning a repository, the clone
3955 source is written as ``default`` in ``.hg/hgrc``. Note that
3955 source is written as ``default`` in ``.hg/hgrc``. Note that
3956 ``default`` and ``default-push`` apply to all inbound (e.g.
3956 ``default`` and ``default-push`` apply to all inbound (e.g.
3957 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3957 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3958 :hg:`bundle`) operations.
3958 :hg:`bundle`) operations.
3959
3959
3960 See :hg:`help urls` for more information.
3960 See :hg:`help urls` for more information.
3961
3961
3962 Returns 0 on success.
3962 Returns 0 on success.
3963 """
3963 """
3964 if search:
3964 if search:
3965 for name, path in ui.configitems("paths"):
3965 for name, path in ui.configitems("paths"):
3966 if name == search:
3966 if name == search:
3967 ui.status("%s\n" % util.hidepassword(path))
3967 ui.status("%s\n" % util.hidepassword(path))
3968 return
3968 return
3969 if not ui.quiet:
3969 if not ui.quiet:
3970 ui.warn(_("not found!\n"))
3970 ui.warn(_("not found!\n"))
3971 return 1
3971 return 1
3972 else:
3972 else:
3973 for name, path in ui.configitems("paths"):
3973 for name, path in ui.configitems("paths"):
3974 if ui.quiet:
3974 if ui.quiet:
3975 ui.write("%s\n" % name)
3975 ui.write("%s\n" % name)
3976 else:
3976 else:
3977 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3977 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3978
3978
3979 def postincoming(ui, repo, modheads, optupdate, checkout):
3979 def postincoming(ui, repo, modheads, optupdate, checkout):
3980 if modheads == 0:
3980 if modheads == 0:
3981 return
3981 return
3982 if optupdate:
3982 if optupdate:
3983 try:
3983 try:
3984 return hg.update(repo, checkout)
3984 return hg.update(repo, checkout)
3985 except util.Abort, inst:
3985 except util.Abort, inst:
3986 ui.warn(_("not updating: %s\n" % str(inst)))
3986 ui.warn(_("not updating: %s\n" % str(inst)))
3987 return 0
3987 return 0
3988 if modheads > 1:
3988 if modheads > 1:
3989 currentbranchheads = len(repo.branchheads())
3989 currentbranchheads = len(repo.branchheads())
3990 if currentbranchheads == modheads:
3990 if currentbranchheads == modheads:
3991 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3991 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3992 elif currentbranchheads > 1:
3992 elif currentbranchheads > 1:
3993 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3993 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3994 else:
3994 else:
3995 ui.status(_("(run 'hg heads' to see heads)\n"))
3995 ui.status(_("(run 'hg heads' to see heads)\n"))
3996 else:
3996 else:
3997 ui.status(_("(run 'hg update' to get a working copy)\n"))
3997 ui.status(_("(run 'hg update' to get a working copy)\n"))
3998
3998
3999 @command('^pull',
3999 @command('^pull',
4000 [('u', 'update', None,
4000 [('u', 'update', None,
4001 _('update to new branch head if changesets were pulled')),
4001 _('update to new branch head if changesets were pulled')),
4002 ('f', 'force', None, _('run even when remote repository is unrelated')),
4002 ('f', 'force', None, _('run even when remote repository is unrelated')),
4003 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4003 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4004 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4004 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4005 ('b', 'branch', [], _('a specific branch you would like to pull'),
4005 ('b', 'branch', [], _('a specific branch you would like to pull'),
4006 _('BRANCH')),
4006 _('BRANCH')),
4007 ] + remoteopts,
4007 ] + remoteopts,
4008 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4008 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4009 def pull(ui, repo, source="default", **opts):
4009 def pull(ui, repo, source="default", **opts):
4010 """pull changes from the specified source
4010 """pull changes from the specified source
4011
4011
4012 Pull changes from a remote repository to a local one.
4012 Pull changes from a remote repository to a local one.
4013
4013
4014 This finds all changes from the repository at the specified path
4014 This finds all changes from the repository at the specified path
4015 or URL and adds them to a local repository (the current one unless
4015 or URL and adds them to a local repository (the current one unless
4016 -R is specified). By default, this does not update the copy of the
4016 -R is specified). By default, this does not update the copy of the
4017 project in the working directory.
4017 project in the working directory.
4018
4018
4019 Use :hg:`incoming` if you want to see what would have been added
4019 Use :hg:`incoming` if you want to see what would have been added
4020 by a pull at the time you issued this command. If you then decide
4020 by a pull at the time you issued this command. If you then decide
4021 to add those changes to the repository, you should use :hg:`pull
4021 to add those changes to the repository, you should use :hg:`pull
4022 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4022 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4023
4023
4024 If SOURCE is omitted, the 'default' path will be used.
4024 If SOURCE is omitted, the 'default' path will be used.
4025 See :hg:`help urls` for more information.
4025 See :hg:`help urls` for more information.
4026
4026
4027 Returns 0 on success, 1 if an update had unresolved files.
4027 Returns 0 on success, 1 if an update had unresolved files.
4028 """
4028 """
4029 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4029 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4030 other = hg.peer(repo, opts, source)
4030 other = hg.peer(repo, opts, source)
4031 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4031 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4032 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4032 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4033
4033
4034 if opts.get('bookmark'):
4034 if opts.get('bookmark'):
4035 if not revs:
4035 if not revs:
4036 revs = []
4036 revs = []
4037 rb = other.listkeys('bookmarks')
4037 rb = other.listkeys('bookmarks')
4038 for b in opts['bookmark']:
4038 for b in opts['bookmark']:
4039 if b not in rb:
4039 if b not in rb:
4040 raise util.Abort(_('remote bookmark %s not found!') % b)
4040 raise util.Abort(_('remote bookmark %s not found!') % b)
4041 revs.append(rb[b])
4041 revs.append(rb[b])
4042
4042
4043 if revs:
4043 if revs:
4044 try:
4044 try:
4045 revs = [other.lookup(rev) for rev in revs]
4045 revs = [other.lookup(rev) for rev in revs]
4046 except error.CapabilityError:
4046 except error.CapabilityError:
4047 err = _("other repository doesn't support revision lookup, "
4047 err = _("other repository doesn't support revision lookup, "
4048 "so a rev cannot be specified.")
4048 "so a rev cannot be specified.")
4049 raise util.Abort(err)
4049 raise util.Abort(err)
4050
4050
4051 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4051 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4052 bookmarks.updatefromremote(ui, repo, other)
4052 bookmarks.updatefromremote(ui, repo, other)
4053 if checkout:
4053 if checkout:
4054 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4054 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4055 repo._subtoppath = source
4055 repo._subtoppath = source
4056 try:
4056 try:
4057 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4057 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4058
4058
4059 finally:
4059 finally:
4060 del repo._subtoppath
4060 del repo._subtoppath
4061
4061
4062 # update specified bookmarks
4062 # update specified bookmarks
4063 if opts.get('bookmark'):
4063 if opts.get('bookmark'):
4064 for b in opts['bookmark']:
4064 for b in opts['bookmark']:
4065 # explicit pull overrides local bookmark if any
4065 # explicit pull overrides local bookmark if any
4066 ui.status(_("importing bookmark %s\n") % b)
4066 ui.status(_("importing bookmark %s\n") % b)
4067 repo._bookmarks[b] = repo[rb[b]].node()
4067 repo._bookmarks[b] = repo[rb[b]].node()
4068 bookmarks.write(repo)
4068 bookmarks.write(repo)
4069
4069
4070 return ret
4070 return ret
4071
4071
4072 @command('^push',
4072 @command('^push',
4073 [('f', 'force', None, _('force push')),
4073 [('f', 'force', None, _('force push')),
4074 ('r', 'rev', [],
4074 ('r', 'rev', [],
4075 _('a changeset intended to be included in the destination'),
4075 _('a changeset intended to be included in the destination'),
4076 _('REV')),
4076 _('REV')),
4077 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4077 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4078 ('b', 'branch', [],
4078 ('b', 'branch', [],
4079 _('a specific branch you would like to push'), _('BRANCH')),
4079 _('a specific branch you would like to push'), _('BRANCH')),
4080 ('', 'new-branch', False, _('allow pushing a new branch')),
4080 ('', 'new-branch', False, _('allow pushing a new branch')),
4081 ] + remoteopts,
4081 ] + remoteopts,
4082 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4082 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4083 def push(ui, repo, dest=None, **opts):
4083 def push(ui, repo, dest=None, **opts):
4084 """push changes to the specified destination
4084 """push changes to the specified destination
4085
4085
4086 Push changesets from the local repository to the specified
4086 Push changesets from the local repository to the specified
4087 destination.
4087 destination.
4088
4088
4089 This operation is symmetrical to pull: it is identical to a pull
4089 This operation is symmetrical to pull: it is identical to a pull
4090 in the destination repository from the current one.
4090 in the destination repository from the current one.
4091
4091
4092 By default, push will not allow creation of new heads at the
4092 By default, push will not allow creation of new heads at the
4093 destination, since multiple heads would make it unclear which head
4093 destination, since multiple heads would make it unclear which head
4094 to use. In this situation, it is recommended to pull and merge
4094 to use. In this situation, it is recommended to pull and merge
4095 before pushing.
4095 before pushing.
4096
4096
4097 Use --new-branch if you want to allow push to create a new named
4097 Use --new-branch if you want to allow push to create a new named
4098 branch that is not present at the destination. This allows you to
4098 branch that is not present at the destination. This allows you to
4099 only create a new branch without forcing other changes.
4099 only create a new branch without forcing other changes.
4100
4100
4101 Use -f/--force to override the default behavior and push all
4101 Use -f/--force to override the default behavior and push all
4102 changesets on all branches.
4102 changesets on all branches.
4103
4103
4104 If -r/--rev is used, the specified revision and all its ancestors
4104 If -r/--rev is used, the specified revision and all its ancestors
4105 will be pushed to the remote repository.
4105 will be pushed to the remote repository.
4106
4106
4107 Please see :hg:`help urls` for important details about ``ssh://``
4107 Please see :hg:`help urls` for important details about ``ssh://``
4108 URLs. If DESTINATION is omitted, a default path will be used.
4108 URLs. If DESTINATION is omitted, a default path will be used.
4109
4109
4110 Returns 0 if push was successful, 1 if nothing to push.
4110 Returns 0 if push was successful, 1 if nothing to push.
4111 """
4111 """
4112
4112
4113 if opts.get('bookmark'):
4113 if opts.get('bookmark'):
4114 for b in opts['bookmark']:
4114 for b in opts['bookmark']:
4115 # translate -B options to -r so changesets get pushed
4115 # translate -B options to -r so changesets get pushed
4116 if b in repo._bookmarks:
4116 if b in repo._bookmarks:
4117 opts.setdefault('rev', []).append(b)
4117 opts.setdefault('rev', []).append(b)
4118 else:
4118 else:
4119 # if we try to push a deleted bookmark, translate it to null
4119 # if we try to push a deleted bookmark, translate it to null
4120 # this lets simultaneous -r, -b options continue working
4120 # this lets simultaneous -r, -b options continue working
4121 opts.setdefault('rev', []).append("null")
4121 opts.setdefault('rev', []).append("null")
4122
4122
4123 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4123 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4124 dest, branches = hg.parseurl(dest, opts.get('branch'))
4124 dest, branches = hg.parseurl(dest, opts.get('branch'))
4125 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4125 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4126 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4126 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4127 other = hg.peer(repo, opts, dest)
4127 other = hg.peer(repo, opts, dest)
4128 if revs:
4128 if revs:
4129 revs = [repo.lookup(rev) for rev in revs]
4129 revs = [repo.lookup(rev) for rev in revs]
4130
4130
4131 repo._subtoppath = dest
4131 repo._subtoppath = dest
4132 try:
4132 try:
4133 # push subrepos depth-first for coherent ordering
4133 # push subrepos depth-first for coherent ordering
4134 c = repo['']
4134 c = repo['']
4135 subs = c.substate # only repos that are committed
4135 subs = c.substate # only repos that are committed
4136 for s in sorted(subs):
4136 for s in sorted(subs):
4137 if not c.sub(s).push(opts.get('force')):
4137 if not c.sub(s).push(opts.get('force')):
4138 return False
4138 return False
4139 finally:
4139 finally:
4140 del repo._subtoppath
4140 del repo._subtoppath
4141 result = repo.push(other, opts.get('force'), revs=revs,
4141 result = repo.push(other, opts.get('force'), revs=revs,
4142 newbranch=opts.get('new_branch'))
4142 newbranch=opts.get('new_branch'))
4143
4143
4144 result = (result == 0)
4144 result = (result == 0)
4145
4145
4146 if opts.get('bookmark'):
4146 if opts.get('bookmark'):
4147 rb = other.listkeys('bookmarks')
4147 rb = other.listkeys('bookmarks')
4148 for b in opts['bookmark']:
4148 for b in opts['bookmark']:
4149 # explicit push overrides remote bookmark if any
4149 # explicit push overrides remote bookmark if any
4150 if b in repo._bookmarks:
4150 if b in repo._bookmarks:
4151 ui.status(_("exporting bookmark %s\n") % b)
4151 ui.status(_("exporting bookmark %s\n") % b)
4152 new = repo[b].hex()
4152 new = repo[b].hex()
4153 elif b in rb:
4153 elif b in rb:
4154 ui.status(_("deleting remote bookmark %s\n") % b)
4154 ui.status(_("deleting remote bookmark %s\n") % b)
4155 new = '' # delete
4155 new = '' # delete
4156 else:
4156 else:
4157 ui.warn(_('bookmark %s does not exist on the local '
4157 ui.warn(_('bookmark %s does not exist on the local '
4158 'or remote repository!\n') % b)
4158 'or remote repository!\n') % b)
4159 return 2
4159 return 2
4160 old = rb.get(b, '')
4160 old = rb.get(b, '')
4161 r = other.pushkey('bookmarks', b, old, new)
4161 r = other.pushkey('bookmarks', b, old, new)
4162 if not r:
4162 if not r:
4163 ui.warn(_('updating bookmark %s failed!\n') % b)
4163 ui.warn(_('updating bookmark %s failed!\n') % b)
4164 if not result:
4164 if not result:
4165 result = 2
4165 result = 2
4166
4166
4167 return result
4167 return result
4168
4168
4169 @command('recover', [])
4169 @command('recover', [])
4170 def recover(ui, repo):
4170 def recover(ui, repo):
4171 """roll back an interrupted transaction
4171 """roll back an interrupted transaction
4172
4172
4173 Recover from an interrupted commit or pull.
4173 Recover from an interrupted commit or pull.
4174
4174
4175 This command tries to fix the repository status after an
4175 This command tries to fix the repository status after an
4176 interrupted operation. It should only be necessary when Mercurial
4176 interrupted operation. It should only be necessary when Mercurial
4177 suggests it.
4177 suggests it.
4178
4178
4179 Returns 0 if successful, 1 if nothing to recover or verify fails.
4179 Returns 0 if successful, 1 if nothing to recover or verify fails.
4180 """
4180 """
4181 if repo.recover():
4181 if repo.recover():
4182 return hg.verify(repo)
4182 return hg.verify(repo)
4183 return 1
4183 return 1
4184
4184
4185 @command('^remove|rm',
4185 @command('^remove|rm',
4186 [('A', 'after', None, _('record delete for missing files')),
4186 [('A', 'after', None, _('record delete for missing files')),
4187 ('f', 'force', None,
4187 ('f', 'force', None,
4188 _('remove (and delete) file even if added or modified')),
4188 _('remove (and delete) file even if added or modified')),
4189 ] + walkopts,
4189 ] + walkopts,
4190 _('[OPTION]... FILE...'))
4190 _('[OPTION]... FILE...'))
4191 def remove(ui, repo, *pats, **opts):
4191 def remove(ui, repo, *pats, **opts):
4192 """remove the specified files on the next commit
4192 """remove the specified files on the next commit
4193
4193
4194 Schedule the indicated files for removal from the current branch.
4194 Schedule the indicated files for removal from the current branch.
4195
4195
4196 This command schedules the files to be removed at the next commit.
4196 This command schedules the files to be removed at the next commit.
4197 To undo a remove before that, see :hg:`revert`. To undo added
4197 To undo a remove before that, see :hg:`revert`. To undo added
4198 files, see :hg:`forget`.
4198 files, see :hg:`forget`.
4199
4199
4200 .. container:: verbose
4200 .. container:: verbose
4201
4201
4202 -A/--after can be used to remove only files that have already
4202 -A/--after can be used to remove only files that have already
4203 been deleted, -f/--force can be used to force deletion, and -Af
4203 been deleted, -f/--force can be used to force deletion, and -Af
4204 can be used to remove files from the next revision without
4204 can be used to remove files from the next revision without
4205 deleting them from the working directory.
4205 deleting them from the working directory.
4206
4206
4207 The following table details the behavior of remove for different
4207 The following table details the behavior of remove for different
4208 file states (columns) and option combinations (rows). The file
4208 file states (columns) and option combinations (rows). The file
4209 states are Added [A], Clean [C], Modified [M] and Missing [!]
4209 states are Added [A], Clean [C], Modified [M] and Missing [!]
4210 (as reported by :hg:`status`). The actions are Warn, Remove
4210 (as reported by :hg:`status`). The actions are Warn, Remove
4211 (from branch) and Delete (from disk):
4211 (from branch) and Delete (from disk):
4212
4212
4213 ======= == == == ==
4213 ======= == == == ==
4214 A C M !
4214 A C M !
4215 ======= == == == ==
4215 ======= == == == ==
4216 none W RD W R
4216 none W RD W R
4217 -f R RD RD R
4217 -f R RD RD R
4218 -A W W W R
4218 -A W W W R
4219 -Af R R R R
4219 -Af R R R R
4220 ======= == == == ==
4220 ======= == == == ==
4221
4221
4222 Note that remove never deletes files in Added [A] state from the
4222 Note that remove never deletes files in Added [A] state from the
4223 working directory, not even if option --force is specified.
4223 working directory, not even if option --force is specified.
4224
4224
4225 Returns 0 on success, 1 if any warnings encountered.
4225 Returns 0 on success, 1 if any warnings encountered.
4226 """
4226 """
4227
4227
4228 ret = 0
4228 ret = 0
4229 after, force = opts.get('after'), opts.get('force')
4229 after, force = opts.get('after'), opts.get('force')
4230 if not pats and not after:
4230 if not pats and not after:
4231 raise util.Abort(_('no files specified'))
4231 raise util.Abort(_('no files specified'))
4232
4232
4233 m = scmutil.match(repo[None], pats, opts)
4233 m = scmutil.match(repo[None], pats, opts)
4234 s = repo.status(match=m, clean=True)
4234 s = repo.status(match=m, clean=True)
4235 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4235 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4236
4236
4237 for f in m.files():
4237 for f in m.files():
4238 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4238 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
4239 if os.path.exists(m.rel(f)):
4239 if os.path.exists(m.rel(f)):
4240 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4240 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4241 ret = 1
4241 ret = 1
4242
4242
4243 if force:
4243 if force:
4244 list = modified + deleted + clean + added
4244 list = modified + deleted + clean + added
4245 elif after:
4245 elif after:
4246 list = deleted
4246 list = deleted
4247 for f in modified + added + clean:
4247 for f in modified + added + clean:
4248 ui.warn(_('not removing %s: file still exists (use -f'
4248 ui.warn(_('not removing %s: file still exists (use -f'
4249 ' to force removal)\n') % m.rel(f))
4249 ' to force removal)\n') % m.rel(f))
4250 ret = 1
4250 ret = 1
4251 else:
4251 else:
4252 list = deleted + clean
4252 list = deleted + clean
4253 for f in modified:
4253 for f in modified:
4254 ui.warn(_('not removing %s: file is modified (use -f'
4254 ui.warn(_('not removing %s: file is modified (use -f'
4255 ' to force removal)\n') % m.rel(f))
4255 ' to force removal)\n') % m.rel(f))
4256 ret = 1
4256 ret = 1
4257 for f in added:
4257 for f in added:
4258 ui.warn(_('not removing %s: file has been marked for add'
4258 ui.warn(_('not removing %s: file has been marked for add'
4259 ' (use forget to undo)\n') % m.rel(f))
4259 ' (use forget to undo)\n') % m.rel(f))
4260 ret = 1
4260 ret = 1
4261
4261
4262 for f in sorted(list):
4262 for f in sorted(list):
4263 if ui.verbose or not m.exact(f):
4263 if ui.verbose or not m.exact(f):
4264 ui.status(_('removing %s\n') % m.rel(f))
4264 ui.status(_('removing %s\n') % m.rel(f))
4265
4265
4266 wlock = repo.wlock()
4266 wlock = repo.wlock()
4267 try:
4267 try:
4268 if not after:
4268 if not after:
4269 for f in list:
4269 for f in list:
4270 if f in added:
4270 if f in added:
4271 continue # we never unlink added files on remove
4271 continue # we never unlink added files on remove
4272 try:
4272 try:
4273 util.unlinkpath(repo.wjoin(f))
4273 util.unlinkpath(repo.wjoin(f))
4274 except OSError, inst:
4274 except OSError, inst:
4275 if inst.errno != errno.ENOENT:
4275 if inst.errno != errno.ENOENT:
4276 raise
4276 raise
4277 repo[None].forget(list)
4277 repo[None].forget(list)
4278 finally:
4278 finally:
4279 wlock.release()
4279 wlock.release()
4280
4280
4281 return ret
4281 return ret
4282
4282
4283 @command('rename|move|mv',
4283 @command('rename|move|mv',
4284 [('A', 'after', None, _('record a rename that has already occurred')),
4284 [('A', 'after', None, _('record a rename that has already occurred')),
4285 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4285 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4286 ] + walkopts + dryrunopts,
4286 ] + walkopts + dryrunopts,
4287 _('[OPTION]... SOURCE... DEST'))
4287 _('[OPTION]... SOURCE... DEST'))
4288 def rename(ui, repo, *pats, **opts):
4288 def rename(ui, repo, *pats, **opts):
4289 """rename files; equivalent of copy + remove
4289 """rename files; equivalent of copy + remove
4290
4290
4291 Mark dest as copies of sources; mark sources for deletion. If dest
4291 Mark dest as copies of sources; mark sources for deletion. If dest
4292 is a directory, copies are put in that directory. If dest is a
4292 is a directory, copies are put in that directory. If dest is a
4293 file, there can only be one source.
4293 file, there can only be one source.
4294
4294
4295 By default, this command copies the contents of files as they
4295 By default, this command copies the contents of files as they
4296 exist in the working directory. If invoked with -A/--after, the
4296 exist in the working directory. If invoked with -A/--after, the
4297 operation is recorded, but no copying is performed.
4297 operation is recorded, but no copying is performed.
4298
4298
4299 This command takes effect at the next commit. To undo a rename
4299 This command takes effect at the next commit. To undo a rename
4300 before that, see :hg:`revert`.
4300 before that, see :hg:`revert`.
4301
4301
4302 Returns 0 on success, 1 if errors are encountered.
4302 Returns 0 on success, 1 if errors are encountered.
4303 """
4303 """
4304 wlock = repo.wlock(False)
4304 wlock = repo.wlock(False)
4305 try:
4305 try:
4306 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4306 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4307 finally:
4307 finally:
4308 wlock.release()
4308 wlock.release()
4309
4309
4310 @command('resolve',
4310 @command('resolve',
4311 [('a', 'all', None, _('select all unresolved files')),
4311 [('a', 'all', None, _('select all unresolved files')),
4312 ('l', 'list', None, _('list state of files needing merge')),
4312 ('l', 'list', None, _('list state of files needing merge')),
4313 ('m', 'mark', None, _('mark files as resolved')),
4313 ('m', 'mark', None, _('mark files as resolved')),
4314 ('u', 'unmark', None, _('mark files as unresolved')),
4314 ('u', 'unmark', None, _('mark files as unresolved')),
4315 ('n', 'no-status', None, _('hide status prefix'))]
4315 ('n', 'no-status', None, _('hide status prefix'))]
4316 + mergetoolopts + walkopts,
4316 + mergetoolopts + walkopts,
4317 _('[OPTION]... [FILE]...'))
4317 _('[OPTION]... [FILE]...'))
4318 def resolve(ui, repo, *pats, **opts):
4318 def resolve(ui, repo, *pats, **opts):
4319 """redo merges or set/view the merge status of files
4319 """redo merges or set/view the merge status of files
4320
4320
4321 Merges with unresolved conflicts are often the result of
4321 Merges with unresolved conflicts are often the result of
4322 non-interactive merging using the ``internal:merge`` configuration
4322 non-interactive merging using the ``internal:merge`` configuration
4323 setting, or a command-line merge tool like ``diff3``. The resolve
4323 setting, or a command-line merge tool like ``diff3``. The resolve
4324 command is used to manage the files involved in a merge, after
4324 command is used to manage the files involved in a merge, after
4325 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4325 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4326 working directory must have two parents).
4326 working directory must have two parents).
4327
4327
4328 The resolve command can be used in the following ways:
4328 The resolve command can be used in the following ways:
4329
4329
4330 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4330 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4331 files, discarding any previous merge attempts. Re-merging is not
4331 files, discarding any previous merge attempts. Re-merging is not
4332 performed for files already marked as resolved. Use ``--all/-a``
4332 performed for files already marked as resolved. Use ``--all/-a``
4333 to select all unresolved files. ``--tool`` can be used to specify
4333 to select all unresolved files. ``--tool`` can be used to specify
4334 the merge tool used for the given files. It overrides the HGMERGE
4334 the merge tool used for the given files. It overrides the HGMERGE
4335 environment variable and your configuration files.
4335 environment variable and your configuration files. Previous file
4336 contents are saved with a ``.orig`` suffix.
4336
4337
4337 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4338 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4338 (e.g. after having manually fixed-up the files). The default is
4339 (e.g. after having manually fixed-up the files). The default is
4339 to mark all unresolved files.
4340 to mark all unresolved files.
4340
4341
4341 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4342 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4342 default is to mark all resolved files.
4343 default is to mark all resolved files.
4343
4344
4344 - :hg:`resolve -l`: list files which had or still have conflicts.
4345 - :hg:`resolve -l`: list files which had or still have conflicts.
4345 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4346 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4346
4347
4347 Note that Mercurial will not let you commit files with unresolved
4348 Note that Mercurial will not let you commit files with unresolved
4348 merge conflicts. You must use :hg:`resolve -m ...` before you can
4349 merge conflicts. You must use :hg:`resolve -m ...` before you can
4349 commit after a conflicting merge.
4350 commit after a conflicting merge.
4350
4351
4351 Returns 0 on success, 1 if any files fail a resolve attempt.
4352 Returns 0 on success, 1 if any files fail a resolve attempt.
4352 """
4353 """
4353
4354
4354 all, mark, unmark, show, nostatus = \
4355 all, mark, unmark, show, nostatus = \
4355 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4356 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4356
4357
4357 if (show and (mark or unmark)) or (mark and unmark):
4358 if (show and (mark or unmark)) or (mark and unmark):
4358 raise util.Abort(_("too many options specified"))
4359 raise util.Abort(_("too many options specified"))
4359 if pats and all:
4360 if pats and all:
4360 raise util.Abort(_("can't specify --all and patterns"))
4361 raise util.Abort(_("can't specify --all and patterns"))
4361 if not (all or pats or show or mark or unmark):
4362 if not (all or pats or show or mark or unmark):
4362 raise util.Abort(_('no files or directories specified; '
4363 raise util.Abort(_('no files or directories specified; '
4363 'use --all to remerge all files'))
4364 'use --all to remerge all files'))
4364
4365
4365 ms = mergemod.mergestate(repo)
4366 ms = mergemod.mergestate(repo)
4366 m = scmutil.match(repo[None], pats, opts)
4367 m = scmutil.match(repo[None], pats, opts)
4367 ret = 0
4368 ret = 0
4368
4369
4369 for f in ms:
4370 for f in ms:
4370 if m(f):
4371 if m(f):
4371 if show:
4372 if show:
4372 if nostatus:
4373 if nostatus:
4373 ui.write("%s\n" % f)
4374 ui.write("%s\n" % f)
4374 else:
4375 else:
4375 ui.write("%s %s\n" % (ms[f].upper(), f),
4376 ui.write("%s %s\n" % (ms[f].upper(), f),
4376 label='resolve.' +
4377 label='resolve.' +
4377 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4378 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4378 elif mark:
4379 elif mark:
4379 ms.mark(f, "r")
4380 ms.mark(f, "r")
4380 elif unmark:
4381 elif unmark:
4381 ms.mark(f, "u")
4382 ms.mark(f, "u")
4382 else:
4383 else:
4383 wctx = repo[None]
4384 wctx = repo[None]
4384 mctx = wctx.parents()[-1]
4385 mctx = wctx.parents()[-1]
4385
4386
4386 # backup pre-resolve (merge uses .orig for its own purposes)
4387 # backup pre-resolve (merge uses .orig for its own purposes)
4387 a = repo.wjoin(f)
4388 a = repo.wjoin(f)
4388 util.copyfile(a, a + ".resolve")
4389 util.copyfile(a, a + ".resolve")
4389
4390
4390 try:
4391 try:
4391 # resolve file
4392 # resolve file
4392 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4393 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4393 if ms.resolve(f, wctx, mctx):
4394 if ms.resolve(f, wctx, mctx):
4394 ret = 1
4395 ret = 1
4395 finally:
4396 finally:
4396 ui.setconfig('ui', 'forcemerge', '')
4397 ui.setconfig('ui', 'forcemerge', '')
4397
4398
4398 # replace filemerge's .orig file with our resolve file
4399 # replace filemerge's .orig file with our resolve file
4399 util.rename(a + ".resolve", a + ".orig")
4400 util.rename(a + ".resolve", a + ".orig")
4400
4401
4401 ms.commit()
4402 ms.commit()
4402 return ret
4403 return ret
4403
4404
4404 @command('revert',
4405 @command('revert',
4405 [('a', 'all', None, _('revert all changes when no arguments given')),
4406 [('a', 'all', None, _('revert all changes when no arguments given')),
4406 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4407 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4407 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4408 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4408 ('C', 'no-backup', None, _('do not save backup copies of files')),
4409 ('C', 'no-backup', None, _('do not save backup copies of files')),
4409 ] + walkopts + dryrunopts,
4410 ] + walkopts + dryrunopts,
4410 _('[OPTION]... [-r REV] [NAME]...'))
4411 _('[OPTION]... [-r REV] [NAME]...'))
4411 def revert(ui, repo, *pats, **opts):
4412 def revert(ui, repo, *pats, **opts):
4412 """restore files to their checkout state
4413 """restore files to their checkout state
4413
4414
4414 .. note::
4415 .. note::
4415 To check out earlier revisions, you should use :hg:`update REV`.
4416 To check out earlier revisions, you should use :hg:`update REV`.
4416 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4417 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4417
4418
4418 With no revision specified, revert the specified files or directories
4419 With no revision specified, revert the specified files or directories
4419 to the contents they had in the parent of the working directory.
4420 to the contents they had in the parent of the working directory.
4420 This restores the contents of files to an unmodified
4421 This restores the contents of files to an unmodified
4421 state and unschedules adds, removes, copies, and renames. If the
4422 state and unschedules adds, removes, copies, and renames. If the
4422 working directory has two parents, you must explicitly specify a
4423 working directory has two parents, you must explicitly specify a
4423 revision.
4424 revision.
4424
4425
4425 Using the -r/--rev or -d/--date options, revert the given files or
4426 Using the -r/--rev or -d/--date options, revert the given files or
4426 directories to their states as of a specific revision. Because
4427 directories to their states as of a specific revision. Because
4427 revert does not change the working directory parents, this will
4428 revert does not change the working directory parents, this will
4428 cause these files to appear modified. This can be helpful to "back
4429 cause these files to appear modified. This can be helpful to "back
4429 out" some or all of an earlier change. See :hg:`backout` for a
4430 out" some or all of an earlier change. See :hg:`backout` for a
4430 related method.
4431 related method.
4431
4432
4432 Modified files are saved with a .orig suffix before reverting.
4433 Modified files are saved with a .orig suffix before reverting.
4433 To disable these backups, use --no-backup.
4434 To disable these backups, use --no-backup.
4434
4435
4435 See :hg:`help dates` for a list of formats valid for -d/--date.
4436 See :hg:`help dates` for a list of formats valid for -d/--date.
4436
4437
4437 Returns 0 on success.
4438 Returns 0 on success.
4438 """
4439 """
4439
4440
4440 if opts.get("date"):
4441 if opts.get("date"):
4441 if opts.get("rev"):
4442 if opts.get("rev"):
4442 raise util.Abort(_("you can't specify a revision and a date"))
4443 raise util.Abort(_("you can't specify a revision and a date"))
4443 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4444 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4444
4445
4445 parent, p2 = repo.dirstate.parents()
4446 parent, p2 = repo.dirstate.parents()
4446 if not opts.get('rev') and p2 != nullid:
4447 if not opts.get('rev') and p2 != nullid:
4447 # revert after merge is a trap for new users (issue2915)
4448 # revert after merge is a trap for new users (issue2915)
4448 raise util.Abort(_('uncommitted merge with no revision specified'),
4449 raise util.Abort(_('uncommitted merge with no revision specified'),
4449 hint=_('use "hg update" or see "hg help revert"'))
4450 hint=_('use "hg update" or see "hg help revert"'))
4450
4451
4451 ctx = scmutil.revsingle(repo, opts.get('rev'))
4452 ctx = scmutil.revsingle(repo, opts.get('rev'))
4452 node = ctx.node()
4453 node = ctx.node()
4453
4454
4454 if not pats and not opts.get('all'):
4455 if not pats and not opts.get('all'):
4455 msg = _("no files or directories specified")
4456 msg = _("no files or directories specified")
4456 if p2 != nullid:
4457 if p2 != nullid:
4457 hint = _("uncommitted merge, use --all to discard all changes,"
4458 hint = _("uncommitted merge, use --all to discard all changes,"
4458 " or 'hg update -C .' to abort the merge")
4459 " or 'hg update -C .' to abort the merge")
4459 raise util.Abort(msg, hint=hint)
4460 raise util.Abort(msg, hint=hint)
4460 dirty = util.any(repo.status())
4461 dirty = util.any(repo.status())
4461 if node != parent:
4462 if node != parent:
4462 if dirty:
4463 if dirty:
4463 hint = _("uncommitted changes, use --all to discard all"
4464 hint = _("uncommitted changes, use --all to discard all"
4464 " changes, or 'hg update %s' to update") % ctx.rev()
4465 " changes, or 'hg update %s' to update") % ctx.rev()
4465 else:
4466 else:
4466 hint = _("use --all to revert all files,"
4467 hint = _("use --all to revert all files,"
4467 " or 'hg update %s' to update") % ctx.rev()
4468 " or 'hg update %s' to update") % ctx.rev()
4468 elif dirty:
4469 elif dirty:
4469 hint = _("uncommitted changes, use --all to discard all changes")
4470 hint = _("uncommitted changes, use --all to discard all changes")
4470 else:
4471 else:
4471 hint = _("use --all to revert all files")
4472 hint = _("use --all to revert all files")
4472 raise util.Abort(msg, hint=hint)
4473 raise util.Abort(msg, hint=hint)
4473
4474
4474 mf = ctx.manifest()
4475 mf = ctx.manifest()
4475 if node == parent:
4476 if node == parent:
4476 pmf = mf
4477 pmf = mf
4477 else:
4478 else:
4478 pmf = None
4479 pmf = None
4479
4480
4480 # need all matching names in dirstate and manifest of target rev,
4481 # need all matching names in dirstate and manifest of target rev,
4481 # so have to walk both. do not print errors if files exist in one
4482 # so have to walk both. do not print errors if files exist in one
4482 # but not other.
4483 # but not other.
4483
4484
4484 names = {}
4485 names = {}
4485
4486
4486 wlock = repo.wlock()
4487 wlock = repo.wlock()
4487 try:
4488 try:
4488 # walk dirstate.
4489 # walk dirstate.
4489
4490
4490 m = scmutil.match(repo[None], pats, opts)
4491 m = scmutil.match(repo[None], pats, opts)
4491 m.bad = lambda x, y: False
4492 m.bad = lambda x, y: False
4492 for abs in repo.walk(m):
4493 for abs in repo.walk(m):
4493 names[abs] = m.rel(abs), m.exact(abs)
4494 names[abs] = m.rel(abs), m.exact(abs)
4494
4495
4495 # walk target manifest.
4496 # walk target manifest.
4496
4497
4497 def badfn(path, msg):
4498 def badfn(path, msg):
4498 if path in names:
4499 if path in names:
4499 return
4500 return
4500 path_ = path + '/'
4501 path_ = path + '/'
4501 for f in names:
4502 for f in names:
4502 if f.startswith(path_):
4503 if f.startswith(path_):
4503 return
4504 return
4504 ui.warn("%s: %s\n" % (m.rel(path), msg))
4505 ui.warn("%s: %s\n" % (m.rel(path), msg))
4505
4506
4506 m = scmutil.match(repo[node], pats, opts)
4507 m = scmutil.match(repo[node], pats, opts)
4507 m.bad = badfn
4508 m.bad = badfn
4508 for abs in repo[node].walk(m):
4509 for abs in repo[node].walk(m):
4509 if abs not in names:
4510 if abs not in names:
4510 names[abs] = m.rel(abs), m.exact(abs)
4511 names[abs] = m.rel(abs), m.exact(abs)
4511
4512
4512 m = scmutil.matchfiles(repo, names)
4513 m = scmutil.matchfiles(repo, names)
4513 changes = repo.status(match=m)[:4]
4514 changes = repo.status(match=m)[:4]
4514 modified, added, removed, deleted = map(set, changes)
4515 modified, added, removed, deleted = map(set, changes)
4515
4516
4516 # if f is a rename, also revert the source
4517 # if f is a rename, also revert the source
4517 cwd = repo.getcwd()
4518 cwd = repo.getcwd()
4518 for f in added:
4519 for f in added:
4519 src = repo.dirstate.copied(f)
4520 src = repo.dirstate.copied(f)
4520 if src and src not in names and repo.dirstate[src] == 'r':
4521 if src and src not in names and repo.dirstate[src] == 'r':
4521 removed.add(src)
4522 removed.add(src)
4522 names[src] = (repo.pathto(src, cwd), True)
4523 names[src] = (repo.pathto(src, cwd), True)
4523
4524
4524 def removeforget(abs):
4525 def removeforget(abs):
4525 if repo.dirstate[abs] == 'a':
4526 if repo.dirstate[abs] == 'a':
4526 return _('forgetting %s\n')
4527 return _('forgetting %s\n')
4527 return _('removing %s\n')
4528 return _('removing %s\n')
4528
4529
4529 revert = ([], _('reverting %s\n'))
4530 revert = ([], _('reverting %s\n'))
4530 add = ([], _('adding %s\n'))
4531 add = ([], _('adding %s\n'))
4531 remove = ([], removeforget)
4532 remove = ([], removeforget)
4532 undelete = ([], _('undeleting %s\n'))
4533 undelete = ([], _('undeleting %s\n'))
4533
4534
4534 disptable = (
4535 disptable = (
4535 # dispatch table:
4536 # dispatch table:
4536 # file state
4537 # file state
4537 # action if in target manifest
4538 # action if in target manifest
4538 # action if not in target manifest
4539 # action if not in target manifest
4539 # make backup if in target manifest
4540 # make backup if in target manifest
4540 # make backup if not in target manifest
4541 # make backup if not in target manifest
4541 (modified, revert, remove, True, True),
4542 (modified, revert, remove, True, True),
4542 (added, revert, remove, True, False),
4543 (added, revert, remove, True, False),
4543 (removed, undelete, None, False, False),
4544 (removed, undelete, None, False, False),
4544 (deleted, revert, remove, False, False),
4545 (deleted, revert, remove, False, False),
4545 )
4546 )
4546
4547
4547 for abs, (rel, exact) in sorted(names.items()):
4548 for abs, (rel, exact) in sorted(names.items()):
4548 mfentry = mf.get(abs)
4549 mfentry = mf.get(abs)
4549 target = repo.wjoin(abs)
4550 target = repo.wjoin(abs)
4550 def handle(xlist, dobackup):
4551 def handle(xlist, dobackup):
4551 xlist[0].append(abs)
4552 xlist[0].append(abs)
4552 if (dobackup and not opts.get('no_backup') and
4553 if (dobackup and not opts.get('no_backup') and
4553 os.path.lexists(target)):
4554 os.path.lexists(target)):
4554 bakname = "%s.orig" % rel
4555 bakname = "%s.orig" % rel
4555 ui.note(_('saving current version of %s as %s\n') %
4556 ui.note(_('saving current version of %s as %s\n') %
4556 (rel, bakname))
4557 (rel, bakname))
4557 if not opts.get('dry_run'):
4558 if not opts.get('dry_run'):
4558 util.rename(target, bakname)
4559 util.rename(target, bakname)
4559 if ui.verbose or not exact:
4560 if ui.verbose or not exact:
4560 msg = xlist[1]
4561 msg = xlist[1]
4561 if not isinstance(msg, basestring):
4562 if not isinstance(msg, basestring):
4562 msg = msg(abs)
4563 msg = msg(abs)
4563 ui.status(msg % rel)
4564 ui.status(msg % rel)
4564 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4565 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4565 if abs not in table:
4566 if abs not in table:
4566 continue
4567 continue
4567 # file has changed in dirstate
4568 # file has changed in dirstate
4568 if mfentry:
4569 if mfentry:
4569 handle(hitlist, backuphit)
4570 handle(hitlist, backuphit)
4570 elif misslist is not None:
4571 elif misslist is not None:
4571 handle(misslist, backupmiss)
4572 handle(misslist, backupmiss)
4572 break
4573 break
4573 else:
4574 else:
4574 if abs not in repo.dirstate:
4575 if abs not in repo.dirstate:
4575 if mfentry:
4576 if mfentry:
4576 handle(add, True)
4577 handle(add, True)
4577 elif exact:
4578 elif exact:
4578 ui.warn(_('file not managed: %s\n') % rel)
4579 ui.warn(_('file not managed: %s\n') % rel)
4579 continue
4580 continue
4580 # file has not changed in dirstate
4581 # file has not changed in dirstate
4581 if node == parent:
4582 if node == parent:
4582 if exact:
4583 if exact:
4583 ui.warn(_('no changes needed to %s\n') % rel)
4584 ui.warn(_('no changes needed to %s\n') % rel)
4584 continue
4585 continue
4585 if pmf is None:
4586 if pmf is None:
4586 # only need parent manifest in this unlikely case,
4587 # only need parent manifest in this unlikely case,
4587 # so do not read by default
4588 # so do not read by default
4588 pmf = repo[parent].manifest()
4589 pmf = repo[parent].manifest()
4589 if abs in pmf:
4590 if abs in pmf:
4590 if mfentry:
4591 if mfentry:
4591 # if version of file is same in parent and target
4592 # if version of file is same in parent and target
4592 # manifests, do nothing
4593 # manifests, do nothing
4593 if (pmf[abs] != mfentry or
4594 if (pmf[abs] != mfentry or
4594 pmf.flags(abs) != mf.flags(abs)):
4595 pmf.flags(abs) != mf.flags(abs)):
4595 handle(revert, False)
4596 handle(revert, False)
4596 else:
4597 else:
4597 handle(remove, False)
4598 handle(remove, False)
4598
4599
4599 if not opts.get('dry_run'):
4600 if not opts.get('dry_run'):
4600 def checkout(f):
4601 def checkout(f):
4601 fc = ctx[f]
4602 fc = ctx[f]
4602 repo.wwrite(f, fc.data(), fc.flags())
4603 repo.wwrite(f, fc.data(), fc.flags())
4603
4604
4604 audit_path = scmutil.pathauditor(repo.root)
4605 audit_path = scmutil.pathauditor(repo.root)
4605 for f in remove[0]:
4606 for f in remove[0]:
4606 if repo.dirstate[f] == 'a':
4607 if repo.dirstate[f] == 'a':
4607 repo.dirstate.drop(f)
4608 repo.dirstate.drop(f)
4608 continue
4609 continue
4609 audit_path(f)
4610 audit_path(f)
4610 try:
4611 try:
4611 util.unlinkpath(repo.wjoin(f))
4612 util.unlinkpath(repo.wjoin(f))
4612 except OSError:
4613 except OSError:
4613 pass
4614 pass
4614 repo.dirstate.remove(f)
4615 repo.dirstate.remove(f)
4615
4616
4616 normal = None
4617 normal = None
4617 if node == parent:
4618 if node == parent:
4618 # We're reverting to our parent. If possible, we'd like status
4619 # We're reverting to our parent. If possible, we'd like status
4619 # to report the file as clean. We have to use normallookup for
4620 # to report the file as clean. We have to use normallookup for
4620 # merges to avoid losing information about merged/dirty files.
4621 # merges to avoid losing information about merged/dirty files.
4621 if p2 != nullid:
4622 if p2 != nullid:
4622 normal = repo.dirstate.normallookup
4623 normal = repo.dirstate.normallookup
4623 else:
4624 else:
4624 normal = repo.dirstate.normal
4625 normal = repo.dirstate.normal
4625 for f in revert[0]:
4626 for f in revert[0]:
4626 checkout(f)
4627 checkout(f)
4627 if normal:
4628 if normal:
4628 normal(f)
4629 normal(f)
4629
4630
4630 for f in add[0]:
4631 for f in add[0]:
4631 checkout(f)
4632 checkout(f)
4632 repo.dirstate.add(f)
4633 repo.dirstate.add(f)
4633
4634
4634 normal = repo.dirstate.normallookup
4635 normal = repo.dirstate.normallookup
4635 if node == parent and p2 == nullid:
4636 if node == parent and p2 == nullid:
4636 normal = repo.dirstate.normal
4637 normal = repo.dirstate.normal
4637 for f in undelete[0]:
4638 for f in undelete[0]:
4638 checkout(f)
4639 checkout(f)
4639 normal(f)
4640 normal(f)
4640
4641
4641 finally:
4642 finally:
4642 wlock.release()
4643 wlock.release()
4643
4644
4644 @command('rollback', dryrunopts +
4645 @command('rollback', dryrunopts +
4645 [('f', 'force', False, _('ignore safety measures'))])
4646 [('f', 'force', False, _('ignore safety measures'))])
4646 def rollback(ui, repo, **opts):
4647 def rollback(ui, repo, **opts):
4647 """roll back the last transaction (dangerous)
4648 """roll back the last transaction (dangerous)
4648
4649
4649 This command should be used with care. There is only one level of
4650 This command should be used with care. There is only one level of
4650 rollback, and there is no way to undo a rollback. It will also
4651 rollback, and there is no way to undo a rollback. It will also
4651 restore the dirstate at the time of the last transaction, losing
4652 restore the dirstate at the time of the last transaction, losing
4652 any dirstate changes since that time. This command does not alter
4653 any dirstate changes since that time. This command does not alter
4653 the working directory.
4654 the working directory.
4654
4655
4655 Transactions are used to encapsulate the effects of all commands
4656 Transactions are used to encapsulate the effects of all commands
4656 that create new changesets or propagate existing changesets into a
4657 that create new changesets or propagate existing changesets into a
4657 repository. For example, the following commands are transactional,
4658 repository. For example, the following commands are transactional,
4658 and their effects can be rolled back:
4659 and their effects can be rolled back:
4659
4660
4660 - commit
4661 - commit
4661 - import
4662 - import
4662 - pull
4663 - pull
4663 - push (with this repository as the destination)
4664 - push (with this repository as the destination)
4664 - unbundle
4665 - unbundle
4665
4666
4666 It's possible to lose data with rollback: commit, update back to
4667 It's possible to lose data with rollback: commit, update back to
4667 an older changeset, and then rollback. The update removes the
4668 an older changeset, and then rollback. The update removes the
4668 changes you committed from the working directory, and rollback
4669 changes you committed from the working directory, and rollback
4669 removes them from history. To avoid data loss, you must pass
4670 removes them from history. To avoid data loss, you must pass
4670 --force in this case.
4671 --force in this case.
4671
4672
4672 This command is not intended for use on public repositories. Once
4673 This command is not intended for use on public repositories. Once
4673 changes are visible for pull by other users, rolling a transaction
4674 changes are visible for pull by other users, rolling a transaction
4674 back locally is ineffective (someone else may already have pulled
4675 back locally is ineffective (someone else may already have pulled
4675 the changes). Furthermore, a race is possible with readers of the
4676 the changes). Furthermore, a race is possible with readers of the
4676 repository; for example an in-progress pull from the repository
4677 repository; for example an in-progress pull from the repository
4677 may fail if a rollback is performed.
4678 may fail if a rollback is performed.
4678
4679
4679 Returns 0 on success, 1 if no rollback data is available.
4680 Returns 0 on success, 1 if no rollback data is available.
4680 """
4681 """
4681 return repo.rollback(dryrun=opts.get('dry_run'),
4682 return repo.rollback(dryrun=opts.get('dry_run'),
4682 force=opts.get('force'))
4683 force=opts.get('force'))
4683
4684
4684 @command('root', [])
4685 @command('root', [])
4685 def root(ui, repo):
4686 def root(ui, repo):
4686 """print the root (top) of the current working directory
4687 """print the root (top) of the current working directory
4687
4688
4688 Print the root directory of the current repository.
4689 Print the root directory of the current repository.
4689
4690
4690 Returns 0 on success.
4691 Returns 0 on success.
4691 """
4692 """
4692 ui.write(repo.root + "\n")
4693 ui.write(repo.root + "\n")
4693
4694
4694 @command('^serve',
4695 @command('^serve',
4695 [('A', 'accesslog', '', _('name of access log file to write to'),
4696 [('A', 'accesslog', '', _('name of access log file to write to'),
4696 _('FILE')),
4697 _('FILE')),
4697 ('d', 'daemon', None, _('run server in background')),
4698 ('d', 'daemon', None, _('run server in background')),
4698 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4699 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4699 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4700 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4700 # use string type, then we can check if something was passed
4701 # use string type, then we can check if something was passed
4701 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4702 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4702 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4703 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4703 _('ADDR')),
4704 _('ADDR')),
4704 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4705 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4705 _('PREFIX')),
4706 _('PREFIX')),
4706 ('n', 'name', '',
4707 ('n', 'name', '',
4707 _('name to show in web pages (default: working directory)'), _('NAME')),
4708 _('name to show in web pages (default: working directory)'), _('NAME')),
4708 ('', 'web-conf', '',
4709 ('', 'web-conf', '',
4709 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4710 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4710 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4711 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4711 _('FILE')),
4712 _('FILE')),
4712 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4713 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4713 ('', 'stdio', None, _('for remote clients')),
4714 ('', 'stdio', None, _('for remote clients')),
4714 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4715 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
4715 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4716 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4716 ('', 'style', '', _('template style to use'), _('STYLE')),
4717 ('', 'style', '', _('template style to use'), _('STYLE')),
4717 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4718 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4718 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4719 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4719 _('[OPTION]...'))
4720 _('[OPTION]...'))
4720 def serve(ui, repo, **opts):
4721 def serve(ui, repo, **opts):
4721 """start stand-alone webserver
4722 """start stand-alone webserver
4722
4723
4723 Start a local HTTP repository browser and pull server. You can use
4724 Start a local HTTP repository browser and pull server. You can use
4724 this for ad-hoc sharing and browsing of repositories. It is
4725 this for ad-hoc sharing and browsing of repositories. It is
4725 recommended to use a real web server to serve a repository for
4726 recommended to use a real web server to serve a repository for
4726 longer periods of time.
4727 longer periods of time.
4727
4728
4728 Please note that the server does not implement access control.
4729 Please note that the server does not implement access control.
4729 This means that, by default, anybody can read from the server and
4730 This means that, by default, anybody can read from the server and
4730 nobody can write to it by default. Set the ``web.allow_push``
4731 nobody can write to it by default. Set the ``web.allow_push``
4731 option to ``*`` to allow everybody to push to the server. You
4732 option to ``*`` to allow everybody to push to the server. You
4732 should use a real web server if you need to authenticate users.
4733 should use a real web server if you need to authenticate users.
4733
4734
4734 By default, the server logs accesses to stdout and errors to
4735 By default, the server logs accesses to stdout and errors to
4735 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4736 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4736 files.
4737 files.
4737
4738
4738 To have the server choose a free port number to listen on, specify
4739 To have the server choose a free port number to listen on, specify
4739 a port number of 0; in this case, the server will print the port
4740 a port number of 0; in this case, the server will print the port
4740 number it uses.
4741 number it uses.
4741
4742
4742 Returns 0 on success.
4743 Returns 0 on success.
4743 """
4744 """
4744
4745
4745 if opts["stdio"] and opts["cmdserver"]:
4746 if opts["stdio"] and opts["cmdserver"]:
4746 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4747 raise util.Abort(_("cannot use --stdio with --cmdserver"))
4747
4748
4748 def checkrepo():
4749 def checkrepo():
4749 if repo is None:
4750 if repo is None:
4750 raise error.RepoError(_("There is no Mercurial repository here"
4751 raise error.RepoError(_("There is no Mercurial repository here"
4751 " (.hg not found)"))
4752 " (.hg not found)"))
4752
4753
4753 if opts["stdio"]:
4754 if opts["stdio"]:
4754 checkrepo()
4755 checkrepo()
4755 s = sshserver.sshserver(ui, repo)
4756 s = sshserver.sshserver(ui, repo)
4756 s.serve_forever()
4757 s.serve_forever()
4757
4758
4758 if opts["cmdserver"]:
4759 if opts["cmdserver"]:
4759 checkrepo()
4760 checkrepo()
4760 s = commandserver.server(ui, repo, opts["cmdserver"])
4761 s = commandserver.server(ui, repo, opts["cmdserver"])
4761 return s.serve()
4762 return s.serve()
4762
4763
4763 # this way we can check if something was given in the command-line
4764 # this way we can check if something was given in the command-line
4764 if opts.get('port'):
4765 if opts.get('port'):
4765 opts['port'] = util.getport(opts.get('port'))
4766 opts['port'] = util.getport(opts.get('port'))
4766
4767
4767 baseui = repo and repo.baseui or ui
4768 baseui = repo and repo.baseui or ui
4768 optlist = ("name templates style address port prefix ipv6"
4769 optlist = ("name templates style address port prefix ipv6"
4769 " accesslog errorlog certificate encoding")
4770 " accesslog errorlog certificate encoding")
4770 for o in optlist.split():
4771 for o in optlist.split():
4771 val = opts.get(o, '')
4772 val = opts.get(o, '')
4772 if val in (None, ''): # should check against default options instead
4773 if val in (None, ''): # should check against default options instead
4773 continue
4774 continue
4774 baseui.setconfig("web", o, val)
4775 baseui.setconfig("web", o, val)
4775 if repo and repo.ui != baseui:
4776 if repo and repo.ui != baseui:
4776 repo.ui.setconfig("web", o, val)
4777 repo.ui.setconfig("web", o, val)
4777
4778
4778 o = opts.get('web_conf') or opts.get('webdir_conf')
4779 o = opts.get('web_conf') or opts.get('webdir_conf')
4779 if not o:
4780 if not o:
4780 if not repo:
4781 if not repo:
4781 raise error.RepoError(_("There is no Mercurial repository"
4782 raise error.RepoError(_("There is no Mercurial repository"
4782 " here (.hg not found)"))
4783 " here (.hg not found)"))
4783 o = repo.root
4784 o = repo.root
4784
4785
4785 app = hgweb.hgweb(o, baseui=ui)
4786 app = hgweb.hgweb(o, baseui=ui)
4786
4787
4787 class service(object):
4788 class service(object):
4788 def init(self):
4789 def init(self):
4789 util.setsignalhandler()
4790 util.setsignalhandler()
4790 self.httpd = hgweb.server.create_server(ui, app)
4791 self.httpd = hgweb.server.create_server(ui, app)
4791
4792
4792 if opts['port'] and not ui.verbose:
4793 if opts['port'] and not ui.verbose:
4793 return
4794 return
4794
4795
4795 if self.httpd.prefix:
4796 if self.httpd.prefix:
4796 prefix = self.httpd.prefix.strip('/') + '/'
4797 prefix = self.httpd.prefix.strip('/') + '/'
4797 else:
4798 else:
4798 prefix = ''
4799 prefix = ''
4799
4800
4800 port = ':%d' % self.httpd.port
4801 port = ':%d' % self.httpd.port
4801 if port == ':80':
4802 if port == ':80':
4802 port = ''
4803 port = ''
4803
4804
4804 bindaddr = self.httpd.addr
4805 bindaddr = self.httpd.addr
4805 if bindaddr == '0.0.0.0':
4806 if bindaddr == '0.0.0.0':
4806 bindaddr = '*'
4807 bindaddr = '*'
4807 elif ':' in bindaddr: # IPv6
4808 elif ':' in bindaddr: # IPv6
4808 bindaddr = '[%s]' % bindaddr
4809 bindaddr = '[%s]' % bindaddr
4809
4810
4810 fqaddr = self.httpd.fqaddr
4811 fqaddr = self.httpd.fqaddr
4811 if ':' in fqaddr:
4812 if ':' in fqaddr:
4812 fqaddr = '[%s]' % fqaddr
4813 fqaddr = '[%s]' % fqaddr
4813 if opts['port']:
4814 if opts['port']:
4814 write = ui.status
4815 write = ui.status
4815 else:
4816 else:
4816 write = ui.write
4817 write = ui.write
4817 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4818 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4818 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4819 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4819
4820
4820 def run(self):
4821 def run(self):
4821 self.httpd.serve_forever()
4822 self.httpd.serve_forever()
4822
4823
4823 service = service()
4824 service = service()
4824
4825
4825 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4826 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4826
4827
4827 @command('showconfig|debugconfig',
4828 @command('showconfig|debugconfig',
4828 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4829 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4829 _('[-u] [NAME]...'))
4830 _('[-u] [NAME]...'))
4830 def showconfig(ui, repo, *values, **opts):
4831 def showconfig(ui, repo, *values, **opts):
4831 """show combined config settings from all hgrc files
4832 """show combined config settings from all hgrc files
4832
4833
4833 With no arguments, print names and values of all config items.
4834 With no arguments, print names and values of all config items.
4834
4835
4835 With one argument of the form section.name, print just the value
4836 With one argument of the form section.name, print just the value
4836 of that config item.
4837 of that config item.
4837
4838
4838 With multiple arguments, print names and values of all config
4839 With multiple arguments, print names and values of all config
4839 items with matching section names.
4840 items with matching section names.
4840
4841
4841 With --debug, the source (filename and line number) is printed
4842 With --debug, the source (filename and line number) is printed
4842 for each config item.
4843 for each config item.
4843
4844
4844 Returns 0 on success.
4845 Returns 0 on success.
4845 """
4846 """
4846
4847
4847 for f in scmutil.rcpath():
4848 for f in scmutil.rcpath():
4848 ui.debug('read config from: %s\n' % f)
4849 ui.debug('read config from: %s\n' % f)
4849 untrusted = bool(opts.get('untrusted'))
4850 untrusted = bool(opts.get('untrusted'))
4850 if values:
4851 if values:
4851 sections = [v for v in values if '.' not in v]
4852 sections = [v for v in values if '.' not in v]
4852 items = [v for v in values if '.' in v]
4853 items = [v for v in values if '.' in v]
4853 if len(items) > 1 or items and sections:
4854 if len(items) > 1 or items and sections:
4854 raise util.Abort(_('only one config item permitted'))
4855 raise util.Abort(_('only one config item permitted'))
4855 for section, name, value in ui.walkconfig(untrusted=untrusted):
4856 for section, name, value in ui.walkconfig(untrusted=untrusted):
4856 value = str(value).replace('\n', '\\n')
4857 value = str(value).replace('\n', '\\n')
4857 sectname = section + '.' + name
4858 sectname = section + '.' + name
4858 if values:
4859 if values:
4859 for v in values:
4860 for v in values:
4860 if v == section:
4861 if v == section:
4861 ui.debug('%s: ' %
4862 ui.debug('%s: ' %
4862 ui.configsource(section, name, untrusted))
4863 ui.configsource(section, name, untrusted))
4863 ui.write('%s=%s\n' % (sectname, value))
4864 ui.write('%s=%s\n' % (sectname, value))
4864 elif v == sectname:
4865 elif v == sectname:
4865 ui.debug('%s: ' %
4866 ui.debug('%s: ' %
4866 ui.configsource(section, name, untrusted))
4867 ui.configsource(section, name, untrusted))
4867 ui.write(value, '\n')
4868 ui.write(value, '\n')
4868 else:
4869 else:
4869 ui.debug('%s: ' %
4870 ui.debug('%s: ' %
4870 ui.configsource(section, name, untrusted))
4871 ui.configsource(section, name, untrusted))
4871 ui.write('%s=%s\n' % (sectname, value))
4872 ui.write('%s=%s\n' % (sectname, value))
4872
4873
4873 @command('^status|st',
4874 @command('^status|st',
4874 [('A', 'all', None, _('show status of all files')),
4875 [('A', 'all', None, _('show status of all files')),
4875 ('m', 'modified', None, _('show only modified files')),
4876 ('m', 'modified', None, _('show only modified files')),
4876 ('a', 'added', None, _('show only added files')),
4877 ('a', 'added', None, _('show only added files')),
4877 ('r', 'removed', None, _('show only removed files')),
4878 ('r', 'removed', None, _('show only removed files')),
4878 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4879 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4879 ('c', 'clean', None, _('show only files without changes')),
4880 ('c', 'clean', None, _('show only files without changes')),
4880 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4881 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4881 ('i', 'ignored', None, _('show only ignored files')),
4882 ('i', 'ignored', None, _('show only ignored files')),
4882 ('n', 'no-status', None, _('hide status prefix')),
4883 ('n', 'no-status', None, _('hide status prefix')),
4883 ('C', 'copies', None, _('show source of copied files')),
4884 ('C', 'copies', None, _('show source of copied files')),
4884 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4885 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4885 ('', 'rev', [], _('show difference from revision'), _('REV')),
4886 ('', 'rev', [], _('show difference from revision'), _('REV')),
4886 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4887 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4887 ] + walkopts + subrepoopts,
4888 ] + walkopts + subrepoopts,
4888 _('[OPTION]... [FILE]...'))
4889 _('[OPTION]... [FILE]...'))
4889 def status(ui, repo, *pats, **opts):
4890 def status(ui, repo, *pats, **opts):
4890 """show changed files in the working directory
4891 """show changed files in the working directory
4891
4892
4892 Show status of files in the repository. If names are given, only
4893 Show status of files in the repository. If names are given, only
4893 files that match are shown. Files that are clean or ignored or
4894 files that match are shown. Files that are clean or ignored or
4894 the source of a copy/move operation, are not listed unless
4895 the source of a copy/move operation, are not listed unless
4895 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4896 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4896 Unless options described with "show only ..." are given, the
4897 Unless options described with "show only ..." are given, the
4897 options -mardu are used.
4898 options -mardu are used.
4898
4899
4899 Option -q/--quiet hides untracked (unknown and ignored) files
4900 Option -q/--quiet hides untracked (unknown and ignored) files
4900 unless explicitly requested with -u/--unknown or -i/--ignored.
4901 unless explicitly requested with -u/--unknown or -i/--ignored.
4901
4902
4902 .. note::
4903 .. note::
4903 status may appear to disagree with diff if permissions have
4904 status may appear to disagree with diff if permissions have
4904 changed or a merge has occurred. The standard diff format does
4905 changed or a merge has occurred. The standard diff format does
4905 not report permission changes and diff only reports changes
4906 not report permission changes and diff only reports changes
4906 relative to one merge parent.
4907 relative to one merge parent.
4907
4908
4908 If one revision is given, it is used as the base revision.
4909 If one revision is given, it is used as the base revision.
4909 If two revisions are given, the differences between them are
4910 If two revisions are given, the differences between them are
4910 shown. The --change option can also be used as a shortcut to list
4911 shown. The --change option can also be used as a shortcut to list
4911 the changed files of a revision from its first parent.
4912 the changed files of a revision from its first parent.
4912
4913
4913 The codes used to show the status of files are::
4914 The codes used to show the status of files are::
4914
4915
4915 M = modified
4916 M = modified
4916 A = added
4917 A = added
4917 R = removed
4918 R = removed
4918 C = clean
4919 C = clean
4919 ! = missing (deleted by non-hg command, but still tracked)
4920 ! = missing (deleted by non-hg command, but still tracked)
4920 ? = not tracked
4921 ? = not tracked
4921 I = ignored
4922 I = ignored
4922 = origin of the previous file listed as A (added)
4923 = origin of the previous file listed as A (added)
4923
4924
4924 .. container:: verbose
4925 .. container:: verbose
4925
4926
4926 Examples:
4927 Examples:
4927
4928
4928 - show changes in the working directory relative to a changeset:
4929 - show changes in the working directory relative to a changeset:
4929
4930
4930 hg status --rev 9353
4931 hg status --rev 9353
4931
4932
4932 - show all changes including copies in an existing changeset::
4933 - show all changes including copies in an existing changeset::
4933
4934
4934 hg status --copies --change 9353
4935 hg status --copies --change 9353
4935
4936
4936 - get a NUL separated list of added files, suitable for xargs::
4937 - get a NUL separated list of added files, suitable for xargs::
4937
4938
4938 hg status -an0
4939 hg status -an0
4939
4940
4940 Returns 0 on success.
4941 Returns 0 on success.
4941 """
4942 """
4942
4943
4943 revs = opts.get('rev')
4944 revs = opts.get('rev')
4944 change = opts.get('change')
4945 change = opts.get('change')
4945
4946
4946 if revs and change:
4947 if revs and change:
4947 msg = _('cannot specify --rev and --change at the same time')
4948 msg = _('cannot specify --rev and --change at the same time')
4948 raise util.Abort(msg)
4949 raise util.Abort(msg)
4949 elif change:
4950 elif change:
4950 node2 = repo.lookup(change)
4951 node2 = repo.lookup(change)
4951 node1 = repo[node2].p1().node()
4952 node1 = repo[node2].p1().node()
4952 else:
4953 else:
4953 node1, node2 = scmutil.revpair(repo, revs)
4954 node1, node2 = scmutil.revpair(repo, revs)
4954
4955
4955 cwd = (pats and repo.getcwd()) or ''
4956 cwd = (pats and repo.getcwd()) or ''
4956 end = opts.get('print0') and '\0' or '\n'
4957 end = opts.get('print0') and '\0' or '\n'
4957 copy = {}
4958 copy = {}
4958 states = 'modified added removed deleted unknown ignored clean'.split()
4959 states = 'modified added removed deleted unknown ignored clean'.split()
4959 show = [k for k in states if opts.get(k)]
4960 show = [k for k in states if opts.get(k)]
4960 if opts.get('all'):
4961 if opts.get('all'):
4961 show += ui.quiet and (states[:4] + ['clean']) or states
4962 show += ui.quiet and (states[:4] + ['clean']) or states
4962 if not show:
4963 if not show:
4963 show = ui.quiet and states[:4] or states[:5]
4964 show = ui.quiet and states[:4] or states[:5]
4964
4965
4965 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
4966 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
4966 'ignored' in show, 'clean' in show, 'unknown' in show,
4967 'ignored' in show, 'clean' in show, 'unknown' in show,
4967 opts.get('subrepos'))
4968 opts.get('subrepos'))
4968 changestates = zip(states, 'MAR!?IC', stat)
4969 changestates = zip(states, 'MAR!?IC', stat)
4969
4970
4970 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4971 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4971 ctxn = repo[nullid]
4972 ctxn = repo[nullid]
4972 ctx1 = repo[node1]
4973 ctx1 = repo[node1]
4973 ctx2 = repo[node2]
4974 ctx2 = repo[node2]
4974 added = stat[1]
4975 added = stat[1]
4975 if node2 is None:
4976 if node2 is None:
4976 added = stat[0] + stat[1] # merged?
4977 added = stat[0] + stat[1] # merged?
4977
4978
4978 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4979 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4979 if k in added:
4980 if k in added:
4980 copy[k] = v
4981 copy[k] = v
4981 elif v in added:
4982 elif v in added:
4982 copy[v] = k
4983 copy[v] = k
4983
4984
4984 for state, char, files in changestates:
4985 for state, char, files in changestates:
4985 if state in show:
4986 if state in show:
4986 format = "%s %%s%s" % (char, end)
4987 format = "%s %%s%s" % (char, end)
4987 if opts.get('no_status'):
4988 if opts.get('no_status'):
4988 format = "%%s%s" % end
4989 format = "%%s%s" % end
4989
4990
4990 for f in files:
4991 for f in files:
4991 ui.write(format % repo.pathto(f, cwd),
4992 ui.write(format % repo.pathto(f, cwd),
4992 label='status.' + state)
4993 label='status.' + state)
4993 if f in copy:
4994 if f in copy:
4994 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4995 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4995 label='status.copied')
4996 label='status.copied')
4996
4997
4997 @command('^summary|sum',
4998 @command('^summary|sum',
4998 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4999 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4999 def summary(ui, repo, **opts):
5000 def summary(ui, repo, **opts):
5000 """summarize working directory state
5001 """summarize working directory state
5001
5002
5002 This generates a brief summary of the working directory state,
5003 This generates a brief summary of the working directory state,
5003 including parents, branch, commit status, and available updates.
5004 including parents, branch, commit status, and available updates.
5004
5005
5005 With the --remote option, this will check the default paths for
5006 With the --remote option, this will check the default paths for
5006 incoming and outgoing changes. This can be time-consuming.
5007 incoming and outgoing changes. This can be time-consuming.
5007
5008
5008 Returns 0 on success.
5009 Returns 0 on success.
5009 """
5010 """
5010
5011
5011 ctx = repo[None]
5012 ctx = repo[None]
5012 parents = ctx.parents()
5013 parents = ctx.parents()
5013 pnode = parents[0].node()
5014 pnode = parents[0].node()
5014 marks = []
5015 marks = []
5015
5016
5016 for p in parents:
5017 for p in parents:
5017 # label with log.changeset (instead of log.parent) since this
5018 # label with log.changeset (instead of log.parent) since this
5018 # shows a working directory parent *changeset*:
5019 # shows a working directory parent *changeset*:
5019 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5020 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5020 label='log.changeset')
5021 label='log.changeset')
5021 ui.write(' '.join(p.tags()), label='log.tag')
5022 ui.write(' '.join(p.tags()), label='log.tag')
5022 if p.bookmarks():
5023 if p.bookmarks():
5023 marks.extend(p.bookmarks())
5024 marks.extend(p.bookmarks())
5024 if p.rev() == -1:
5025 if p.rev() == -1:
5025 if not len(repo):
5026 if not len(repo):
5026 ui.write(_(' (empty repository)'))
5027 ui.write(_(' (empty repository)'))
5027 else:
5028 else:
5028 ui.write(_(' (no revision checked out)'))
5029 ui.write(_(' (no revision checked out)'))
5029 ui.write('\n')
5030 ui.write('\n')
5030 if p.description():
5031 if p.description():
5031 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5032 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5032 label='log.summary')
5033 label='log.summary')
5033
5034
5034 branch = ctx.branch()
5035 branch = ctx.branch()
5035 bheads = repo.branchheads(branch)
5036 bheads = repo.branchheads(branch)
5036 m = _('branch: %s\n') % branch
5037 m = _('branch: %s\n') % branch
5037 if branch != 'default':
5038 if branch != 'default':
5038 ui.write(m, label='log.branch')
5039 ui.write(m, label='log.branch')
5039 else:
5040 else:
5040 ui.status(m, label='log.branch')
5041 ui.status(m, label='log.branch')
5041
5042
5042 if marks:
5043 if marks:
5043 current = repo._bookmarkcurrent
5044 current = repo._bookmarkcurrent
5044 ui.write(_('bookmarks:'), label='log.bookmark')
5045 ui.write(_('bookmarks:'), label='log.bookmark')
5045 if current is not None:
5046 if current is not None:
5046 try:
5047 try:
5047 marks.remove(current)
5048 marks.remove(current)
5048 ui.write(' *' + current, label='bookmarks.current')
5049 ui.write(' *' + current, label='bookmarks.current')
5049 except ValueError:
5050 except ValueError:
5050 # current bookmark not in parent ctx marks
5051 # current bookmark not in parent ctx marks
5051 pass
5052 pass
5052 for m in marks:
5053 for m in marks:
5053 ui.write(' ' + m, label='log.bookmark')
5054 ui.write(' ' + m, label='log.bookmark')
5054 ui.write('\n', label='log.bookmark')
5055 ui.write('\n', label='log.bookmark')
5055
5056
5056 st = list(repo.status(unknown=True))[:6]
5057 st = list(repo.status(unknown=True))[:6]
5057
5058
5058 c = repo.dirstate.copies()
5059 c = repo.dirstate.copies()
5059 copied, renamed = [], []
5060 copied, renamed = [], []
5060 for d, s in c.iteritems():
5061 for d, s in c.iteritems():
5061 if s in st[2]:
5062 if s in st[2]:
5062 st[2].remove(s)
5063 st[2].remove(s)
5063 renamed.append(d)
5064 renamed.append(d)
5064 else:
5065 else:
5065 copied.append(d)
5066 copied.append(d)
5066 if d in st[1]:
5067 if d in st[1]:
5067 st[1].remove(d)
5068 st[1].remove(d)
5068 st.insert(3, renamed)
5069 st.insert(3, renamed)
5069 st.insert(4, copied)
5070 st.insert(4, copied)
5070
5071
5071 ms = mergemod.mergestate(repo)
5072 ms = mergemod.mergestate(repo)
5072 st.append([f for f in ms if ms[f] == 'u'])
5073 st.append([f for f in ms if ms[f] == 'u'])
5073
5074
5074 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5075 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5075 st.append(subs)
5076 st.append(subs)
5076
5077
5077 labels = [ui.label(_('%d modified'), 'status.modified'),
5078 labels = [ui.label(_('%d modified'), 'status.modified'),
5078 ui.label(_('%d added'), 'status.added'),
5079 ui.label(_('%d added'), 'status.added'),
5079 ui.label(_('%d removed'), 'status.removed'),
5080 ui.label(_('%d removed'), 'status.removed'),
5080 ui.label(_('%d renamed'), 'status.copied'),
5081 ui.label(_('%d renamed'), 'status.copied'),
5081 ui.label(_('%d copied'), 'status.copied'),
5082 ui.label(_('%d copied'), 'status.copied'),
5082 ui.label(_('%d deleted'), 'status.deleted'),
5083 ui.label(_('%d deleted'), 'status.deleted'),
5083 ui.label(_('%d unknown'), 'status.unknown'),
5084 ui.label(_('%d unknown'), 'status.unknown'),
5084 ui.label(_('%d ignored'), 'status.ignored'),
5085 ui.label(_('%d ignored'), 'status.ignored'),
5085 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5086 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5086 ui.label(_('%d subrepos'), 'status.modified')]
5087 ui.label(_('%d subrepos'), 'status.modified')]
5087 t = []
5088 t = []
5088 for s, l in zip(st, labels):
5089 for s, l in zip(st, labels):
5089 if s:
5090 if s:
5090 t.append(l % len(s))
5091 t.append(l % len(s))
5091
5092
5092 t = ', '.join(t)
5093 t = ', '.join(t)
5093 cleanworkdir = False
5094 cleanworkdir = False
5094
5095
5095 if len(parents) > 1:
5096 if len(parents) > 1:
5096 t += _(' (merge)')
5097 t += _(' (merge)')
5097 elif branch != parents[0].branch():
5098 elif branch != parents[0].branch():
5098 t += _(' (new branch)')
5099 t += _(' (new branch)')
5099 elif (parents[0].extra().get('close') and
5100 elif (parents[0].extra().get('close') and
5100 pnode in repo.branchheads(branch, closed=True)):
5101 pnode in repo.branchheads(branch, closed=True)):
5101 t += _(' (head closed)')
5102 t += _(' (head closed)')
5102 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5103 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5103 t += _(' (clean)')
5104 t += _(' (clean)')
5104 cleanworkdir = True
5105 cleanworkdir = True
5105 elif pnode not in bheads:
5106 elif pnode not in bheads:
5106 t += _(' (new branch head)')
5107 t += _(' (new branch head)')
5107
5108
5108 if cleanworkdir:
5109 if cleanworkdir:
5109 ui.status(_('commit: %s\n') % t.strip())
5110 ui.status(_('commit: %s\n') % t.strip())
5110 else:
5111 else:
5111 ui.write(_('commit: %s\n') % t.strip())
5112 ui.write(_('commit: %s\n') % t.strip())
5112
5113
5113 # all ancestors of branch heads - all ancestors of parent = new csets
5114 # all ancestors of branch heads - all ancestors of parent = new csets
5114 new = [0] * len(repo)
5115 new = [0] * len(repo)
5115 cl = repo.changelog
5116 cl = repo.changelog
5116 for a in [cl.rev(n) for n in bheads]:
5117 for a in [cl.rev(n) for n in bheads]:
5117 new[a] = 1
5118 new[a] = 1
5118 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5119 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
5119 new[a] = 1
5120 new[a] = 1
5120 for a in [p.rev() for p in parents]:
5121 for a in [p.rev() for p in parents]:
5121 if a >= 0:
5122 if a >= 0:
5122 new[a] = 0
5123 new[a] = 0
5123 for a in cl.ancestors(*[p.rev() for p in parents]):
5124 for a in cl.ancestors(*[p.rev() for p in parents]):
5124 new[a] = 0
5125 new[a] = 0
5125 new = sum(new)
5126 new = sum(new)
5126
5127
5127 if new == 0:
5128 if new == 0:
5128 ui.status(_('update: (current)\n'))
5129 ui.status(_('update: (current)\n'))
5129 elif pnode not in bheads:
5130 elif pnode not in bheads:
5130 ui.write(_('update: %d new changesets (update)\n') % new)
5131 ui.write(_('update: %d new changesets (update)\n') % new)
5131 else:
5132 else:
5132 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5133 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5133 (new, len(bheads)))
5134 (new, len(bheads)))
5134
5135
5135 if opts.get('remote'):
5136 if opts.get('remote'):
5136 t = []
5137 t = []
5137 source, branches = hg.parseurl(ui.expandpath('default'))
5138 source, branches = hg.parseurl(ui.expandpath('default'))
5138 other = hg.peer(repo, {}, source)
5139 other = hg.peer(repo, {}, source)
5139 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5140 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
5140 ui.debug('comparing with %s\n' % util.hidepassword(source))
5141 ui.debug('comparing with %s\n' % util.hidepassword(source))
5141 repo.ui.pushbuffer()
5142 repo.ui.pushbuffer()
5142 commoninc = discovery.findcommonincoming(repo, other)
5143 commoninc = discovery.findcommonincoming(repo, other)
5143 _common, incoming, _rheads = commoninc
5144 _common, incoming, _rheads = commoninc
5144 repo.ui.popbuffer()
5145 repo.ui.popbuffer()
5145 if incoming:
5146 if incoming:
5146 t.append(_('1 or more incoming'))
5147 t.append(_('1 or more incoming'))
5147
5148
5148 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5149 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5149 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5150 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5150 if source != dest:
5151 if source != dest:
5151 other = hg.peer(repo, {}, dest)
5152 other = hg.peer(repo, {}, dest)
5152 commoninc = None
5153 commoninc = None
5153 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5154 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5154 repo.ui.pushbuffer()
5155 repo.ui.pushbuffer()
5155 common, outheads = discovery.findcommonoutgoing(repo, other,
5156 common, outheads = discovery.findcommonoutgoing(repo, other,
5156 commoninc=commoninc)
5157 commoninc=commoninc)
5157 repo.ui.popbuffer()
5158 repo.ui.popbuffer()
5158 o = repo.changelog.findmissing(common=common, heads=outheads)
5159 o = repo.changelog.findmissing(common=common, heads=outheads)
5159 if o:
5160 if o:
5160 t.append(_('%d outgoing') % len(o))
5161 t.append(_('%d outgoing') % len(o))
5161 if 'bookmarks' in other.listkeys('namespaces'):
5162 if 'bookmarks' in other.listkeys('namespaces'):
5162 lmarks = repo.listkeys('bookmarks')
5163 lmarks = repo.listkeys('bookmarks')
5163 rmarks = other.listkeys('bookmarks')
5164 rmarks = other.listkeys('bookmarks')
5164 diff = set(rmarks) - set(lmarks)
5165 diff = set(rmarks) - set(lmarks)
5165 if len(diff) > 0:
5166 if len(diff) > 0:
5166 t.append(_('%d incoming bookmarks') % len(diff))
5167 t.append(_('%d incoming bookmarks') % len(diff))
5167 diff = set(lmarks) - set(rmarks)
5168 diff = set(lmarks) - set(rmarks)
5168 if len(diff) > 0:
5169 if len(diff) > 0:
5169 t.append(_('%d outgoing bookmarks') % len(diff))
5170 t.append(_('%d outgoing bookmarks') % len(diff))
5170
5171
5171 if t:
5172 if t:
5172 ui.write(_('remote: %s\n') % (', '.join(t)))
5173 ui.write(_('remote: %s\n') % (', '.join(t)))
5173 else:
5174 else:
5174 ui.status(_('remote: (synced)\n'))
5175 ui.status(_('remote: (synced)\n'))
5175
5176
5176 @command('tag',
5177 @command('tag',
5177 [('f', 'force', None, _('force tag')),
5178 [('f', 'force', None, _('force tag')),
5178 ('l', 'local', None, _('make the tag local')),
5179 ('l', 'local', None, _('make the tag local')),
5179 ('r', 'rev', '', _('revision to tag'), _('REV')),
5180 ('r', 'rev', '', _('revision to tag'), _('REV')),
5180 ('', 'remove', None, _('remove a tag')),
5181 ('', 'remove', None, _('remove a tag')),
5181 # -l/--local is already there, commitopts cannot be used
5182 # -l/--local is already there, commitopts cannot be used
5182 ('e', 'edit', None, _('edit commit message')),
5183 ('e', 'edit', None, _('edit commit message')),
5183 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5184 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5184 ] + commitopts2,
5185 ] + commitopts2,
5185 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5186 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5186 def tag(ui, repo, name1, *names, **opts):
5187 def tag(ui, repo, name1, *names, **opts):
5187 """add one or more tags for the current or given revision
5188 """add one or more tags for the current or given revision
5188
5189
5189 Name a particular revision using <name>.
5190 Name a particular revision using <name>.
5190
5191
5191 Tags are used to name particular revisions of the repository and are
5192 Tags are used to name particular revisions of the repository and are
5192 very useful to compare different revisions, to go back to significant
5193 very useful to compare different revisions, to go back to significant
5193 earlier versions or to mark branch points as releases, etc. Changing
5194 earlier versions or to mark branch points as releases, etc. Changing
5194 an existing tag is normally disallowed; use -f/--force to override.
5195 an existing tag is normally disallowed; use -f/--force to override.
5195
5196
5196 If no revision is given, the parent of the working directory is
5197 If no revision is given, the parent of the working directory is
5197 used, or tip if no revision is checked out.
5198 used, or tip if no revision is checked out.
5198
5199
5199 To facilitate version control, distribution, and merging of tags,
5200 To facilitate version control, distribution, and merging of tags,
5200 they are stored as a file named ".hgtags" which is managed similarly
5201 they are stored as a file named ".hgtags" which is managed similarly
5201 to other project files and can be hand-edited if necessary. This
5202 to other project files and can be hand-edited if necessary. This
5202 also means that tagging creates a new commit. The file
5203 also means that tagging creates a new commit. The file
5203 ".hg/localtags" is used for local tags (not shared among
5204 ".hg/localtags" is used for local tags (not shared among
5204 repositories).
5205 repositories).
5205
5206
5206 Tag commits are usually made at the head of a branch. If the parent
5207 Tag commits are usually made at the head of a branch. If the parent
5207 of the working directory is not a branch head, :hg:`tag` aborts; use
5208 of the working directory is not a branch head, :hg:`tag` aborts; use
5208 -f/--force to force the tag commit to be based on a non-head
5209 -f/--force to force the tag commit to be based on a non-head
5209 changeset.
5210 changeset.
5210
5211
5211 See :hg:`help dates` for a list of formats valid for -d/--date.
5212 See :hg:`help dates` for a list of formats valid for -d/--date.
5212
5213
5213 Since tag names have priority over branch names during revision
5214 Since tag names have priority over branch names during revision
5214 lookup, using an existing branch name as a tag name is discouraged.
5215 lookup, using an existing branch name as a tag name is discouraged.
5215
5216
5216 Returns 0 on success.
5217 Returns 0 on success.
5217 """
5218 """
5218
5219
5219 rev_ = "."
5220 rev_ = "."
5220 names = [t.strip() for t in (name1,) + names]
5221 names = [t.strip() for t in (name1,) + names]
5221 if len(names) != len(set(names)):
5222 if len(names) != len(set(names)):
5222 raise util.Abort(_('tag names must be unique'))
5223 raise util.Abort(_('tag names must be unique'))
5223 for n in names:
5224 for n in names:
5224 if n in ['tip', '.', 'null']:
5225 if n in ['tip', '.', 'null']:
5225 raise util.Abort(_("the name '%s' is reserved") % n)
5226 raise util.Abort(_("the name '%s' is reserved") % n)
5226 if not n:
5227 if not n:
5227 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
5228 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
5228 if opts.get('rev') and opts.get('remove'):
5229 if opts.get('rev') and opts.get('remove'):
5229 raise util.Abort(_("--rev and --remove are incompatible"))
5230 raise util.Abort(_("--rev and --remove are incompatible"))
5230 if opts.get('rev'):
5231 if opts.get('rev'):
5231 rev_ = opts['rev']
5232 rev_ = opts['rev']
5232 message = opts.get('message')
5233 message = opts.get('message')
5233 if opts.get('remove'):
5234 if opts.get('remove'):
5234 expectedtype = opts.get('local') and 'local' or 'global'
5235 expectedtype = opts.get('local') and 'local' or 'global'
5235 for n in names:
5236 for n in names:
5236 if not repo.tagtype(n):
5237 if not repo.tagtype(n):
5237 raise util.Abort(_("tag '%s' does not exist") % n)
5238 raise util.Abort(_("tag '%s' does not exist") % n)
5238 if repo.tagtype(n) != expectedtype:
5239 if repo.tagtype(n) != expectedtype:
5239 if expectedtype == 'global':
5240 if expectedtype == 'global':
5240 raise util.Abort(_("tag '%s' is not a global tag") % n)
5241 raise util.Abort(_("tag '%s' is not a global tag") % n)
5241 else:
5242 else:
5242 raise util.Abort(_("tag '%s' is not a local tag") % n)
5243 raise util.Abort(_("tag '%s' is not a local tag") % n)
5243 rev_ = nullid
5244 rev_ = nullid
5244 if not message:
5245 if not message:
5245 # we don't translate commit messages
5246 # we don't translate commit messages
5246 message = 'Removed tag %s' % ', '.join(names)
5247 message = 'Removed tag %s' % ', '.join(names)
5247 elif not opts.get('force'):
5248 elif not opts.get('force'):
5248 for n in names:
5249 for n in names:
5249 if n in repo.tags():
5250 if n in repo.tags():
5250 raise util.Abort(_("tag '%s' already exists "
5251 raise util.Abort(_("tag '%s' already exists "
5251 "(use -f to force)") % n)
5252 "(use -f to force)") % n)
5252 if not opts.get('local'):
5253 if not opts.get('local'):
5253 p1, p2 = repo.dirstate.parents()
5254 p1, p2 = repo.dirstate.parents()
5254 if p2 != nullid:
5255 if p2 != nullid:
5255 raise util.Abort(_('uncommitted merge'))
5256 raise util.Abort(_('uncommitted merge'))
5256 bheads = repo.branchheads()
5257 bheads = repo.branchheads()
5257 if not opts.get('force') and bheads and p1 not in bheads:
5258 if not opts.get('force') and bheads and p1 not in bheads:
5258 raise util.Abort(_('not at a branch head (use -f to force)'))
5259 raise util.Abort(_('not at a branch head (use -f to force)'))
5259 r = scmutil.revsingle(repo, rev_).node()
5260 r = scmutil.revsingle(repo, rev_).node()
5260
5261
5261 if not message:
5262 if not message:
5262 # we don't translate commit messages
5263 # we don't translate commit messages
5263 message = ('Added tag %s for changeset %s' %
5264 message = ('Added tag %s for changeset %s' %
5264 (', '.join(names), short(r)))
5265 (', '.join(names), short(r)))
5265
5266
5266 date = opts.get('date')
5267 date = opts.get('date')
5267 if date:
5268 if date:
5268 date = util.parsedate(date)
5269 date = util.parsedate(date)
5269
5270
5270 if opts.get('edit'):
5271 if opts.get('edit'):
5271 message = ui.edit(message, ui.username())
5272 message = ui.edit(message, ui.username())
5272
5273
5273 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5274 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5274
5275
5275 @command('tags', [], '')
5276 @command('tags', [], '')
5276 def tags(ui, repo):
5277 def tags(ui, repo):
5277 """list repository tags
5278 """list repository tags
5278
5279
5279 This lists both regular and local tags. When the -v/--verbose
5280 This lists both regular and local tags. When the -v/--verbose
5280 switch is used, a third column "local" is printed for local tags.
5281 switch is used, a third column "local" is printed for local tags.
5281
5282
5282 Returns 0 on success.
5283 Returns 0 on success.
5283 """
5284 """
5284
5285
5285 hexfunc = ui.debugflag and hex or short
5286 hexfunc = ui.debugflag and hex or short
5286 tagtype = ""
5287 tagtype = ""
5287
5288
5288 for t, n in reversed(repo.tagslist()):
5289 for t, n in reversed(repo.tagslist()):
5289 if ui.quiet:
5290 if ui.quiet:
5290 ui.write("%s\n" % t, label='tags.normal')
5291 ui.write("%s\n" % t, label='tags.normal')
5291 continue
5292 continue
5292
5293
5293 hn = hexfunc(n)
5294 hn = hexfunc(n)
5294 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5295 r = "%5d:%s" % (repo.changelog.rev(n), hn)
5295 rev = ui.label(r, 'log.changeset')
5296 rev = ui.label(r, 'log.changeset')
5296 spaces = " " * (30 - encoding.colwidth(t))
5297 spaces = " " * (30 - encoding.colwidth(t))
5297
5298
5298 tag = ui.label(t, 'tags.normal')
5299 tag = ui.label(t, 'tags.normal')
5299 if ui.verbose:
5300 if ui.verbose:
5300 if repo.tagtype(t) == 'local':
5301 if repo.tagtype(t) == 'local':
5301 tagtype = " local"
5302 tagtype = " local"
5302 tag = ui.label(t, 'tags.local')
5303 tag = ui.label(t, 'tags.local')
5303 else:
5304 else:
5304 tagtype = ""
5305 tagtype = ""
5305 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5306 ui.write("%s%s %s%s\n" % (tag, spaces, rev, tagtype))
5306
5307
5307 @command('tip',
5308 @command('tip',
5308 [('p', 'patch', None, _('show patch')),
5309 [('p', 'patch', None, _('show patch')),
5309 ('g', 'git', None, _('use git extended diff format')),
5310 ('g', 'git', None, _('use git extended diff format')),
5310 ] + templateopts,
5311 ] + templateopts,
5311 _('[-p] [-g]'))
5312 _('[-p] [-g]'))
5312 def tip(ui, repo, **opts):
5313 def tip(ui, repo, **opts):
5313 """show the tip revision
5314 """show the tip revision
5314
5315
5315 The tip revision (usually just called the tip) is the changeset
5316 The tip revision (usually just called the tip) is the changeset
5316 most recently added to the repository (and therefore the most
5317 most recently added to the repository (and therefore the most
5317 recently changed head).
5318 recently changed head).
5318
5319
5319 If you have just made a commit, that commit will be the tip. If
5320 If you have just made a commit, that commit will be the tip. If
5320 you have just pulled changes from another repository, the tip of
5321 you have just pulled changes from another repository, the tip of
5321 that repository becomes the current tip. The "tip" tag is special
5322 that repository becomes the current tip. The "tip" tag is special
5322 and cannot be renamed or assigned to a different changeset.
5323 and cannot be renamed or assigned to a different changeset.
5323
5324
5324 Returns 0 on success.
5325 Returns 0 on success.
5325 """
5326 """
5326 displayer = cmdutil.show_changeset(ui, repo, opts)
5327 displayer = cmdutil.show_changeset(ui, repo, opts)
5327 displayer.show(repo[len(repo) - 1])
5328 displayer.show(repo[len(repo) - 1])
5328 displayer.close()
5329 displayer.close()
5329
5330
5330 @command('unbundle',
5331 @command('unbundle',
5331 [('u', 'update', None,
5332 [('u', 'update', None,
5332 _('update to new branch head if changesets were unbundled'))],
5333 _('update to new branch head if changesets were unbundled'))],
5333 _('[-u] FILE...'))
5334 _('[-u] FILE...'))
5334 def unbundle(ui, repo, fname1, *fnames, **opts):
5335 def unbundle(ui, repo, fname1, *fnames, **opts):
5335 """apply one or more changegroup files
5336 """apply one or more changegroup files
5336
5337
5337 Apply one or more compressed changegroup files generated by the
5338 Apply one or more compressed changegroup files generated by the
5338 bundle command.
5339 bundle command.
5339
5340
5340 Returns 0 on success, 1 if an update has unresolved files.
5341 Returns 0 on success, 1 if an update has unresolved files.
5341 """
5342 """
5342 fnames = (fname1,) + fnames
5343 fnames = (fname1,) + fnames
5343
5344
5344 lock = repo.lock()
5345 lock = repo.lock()
5345 wc = repo['.']
5346 wc = repo['.']
5346 try:
5347 try:
5347 for fname in fnames:
5348 for fname in fnames:
5348 f = url.open(ui, fname)
5349 f = url.open(ui, fname)
5349 gen = changegroup.readbundle(f, fname)
5350 gen = changegroup.readbundle(f, fname)
5350 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5351 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5351 lock=lock)
5352 lock=lock)
5352 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5353 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5353 finally:
5354 finally:
5354 lock.release()
5355 lock.release()
5355 return postincoming(ui, repo, modheads, opts.get('update'), None)
5356 return postincoming(ui, repo, modheads, opts.get('update'), None)
5356
5357
5357 @command('^update|up|checkout|co',
5358 @command('^update|up|checkout|co',
5358 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5359 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5359 ('c', 'check', None,
5360 ('c', 'check', None,
5360 _('update across branches if no uncommitted changes')),
5361 _('update across branches if no uncommitted changes')),
5361 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5362 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5362 ('r', 'rev', '', _('revision'), _('REV'))],
5363 ('r', 'rev', '', _('revision'), _('REV'))],
5363 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5364 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5364 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5365 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5365 """update working directory (or switch revisions)
5366 """update working directory (or switch revisions)
5366
5367
5367 Update the repository's working directory to the specified
5368 Update the repository's working directory to the specified
5368 changeset. If no changeset is specified, update to the tip of the
5369 changeset. If no changeset is specified, update to the tip of the
5369 current named branch.
5370 current named branch.
5370
5371
5371 If the changeset is not a descendant of the working directory's
5372 If the changeset is not a descendant of the working directory's
5372 parent, the update is aborted. With the -c/--check option, the
5373 parent, the update is aborted. With the -c/--check option, the
5373 working directory is checked for uncommitted changes; if none are
5374 working directory is checked for uncommitted changes; if none are
5374 found, the working directory is updated to the specified
5375 found, the working directory is updated to the specified
5375 changeset.
5376 changeset.
5376
5377
5377 Update sets the working directory's parent revison to the specified
5378 Update sets the working directory's parent revison to the specified
5378 changeset (see :hg:`help parents`).
5379 changeset (see :hg:`help parents`).
5379
5380
5380 The following rules apply when the working directory contains
5381 The following rules apply when the working directory contains
5381 uncommitted changes:
5382 uncommitted changes:
5382
5383
5383 1. If neither -c/--check nor -C/--clean is specified, and if
5384 1. If neither -c/--check nor -C/--clean is specified, and if
5384 the requested changeset is an ancestor or descendant of
5385 the requested changeset is an ancestor or descendant of
5385 the working directory's parent, the uncommitted changes
5386 the working directory's parent, the uncommitted changes
5386 are merged into the requested changeset and the merged
5387 are merged into the requested changeset and the merged
5387 result is left uncommitted. If the requested changeset is
5388 result is left uncommitted. If the requested changeset is
5388 not an ancestor or descendant (that is, it is on another
5389 not an ancestor or descendant (that is, it is on another
5389 branch), the update is aborted and the uncommitted changes
5390 branch), the update is aborted and the uncommitted changes
5390 are preserved.
5391 are preserved.
5391
5392
5392 2. With the -c/--check option, the update is aborted and the
5393 2. With the -c/--check option, the update is aborted and the
5393 uncommitted changes are preserved.
5394 uncommitted changes are preserved.
5394
5395
5395 3. With the -C/--clean option, uncommitted changes are discarded and
5396 3. With the -C/--clean option, uncommitted changes are discarded and
5396 the working directory is updated to the requested changeset.
5397 the working directory is updated to the requested changeset.
5397
5398
5398 Use null as the changeset to remove the working directory (like
5399 Use null as the changeset to remove the working directory (like
5399 :hg:`clone -U`).
5400 :hg:`clone -U`).
5400
5401
5401 If you want to revert just one file to an older revision, use
5402 If you want to revert just one file to an older revision, use
5402 :hg:`revert [-r REV] NAME`.
5403 :hg:`revert [-r REV] NAME`.
5403
5404
5404 See :hg:`help dates` for a list of formats valid for -d/--date.
5405 See :hg:`help dates` for a list of formats valid for -d/--date.
5405
5406
5406 Returns 0 on success, 1 if there are unresolved files.
5407 Returns 0 on success, 1 if there are unresolved files.
5407 """
5408 """
5408 if rev and node:
5409 if rev and node:
5409 raise util.Abort(_("please specify just one revision"))
5410 raise util.Abort(_("please specify just one revision"))
5410
5411
5411 if rev is None or rev == '':
5412 if rev is None or rev == '':
5412 rev = node
5413 rev = node
5413
5414
5414 # if we defined a bookmark, we have to remember the original bookmark name
5415 # if we defined a bookmark, we have to remember the original bookmark name
5415 brev = rev
5416 brev = rev
5416 rev = scmutil.revsingle(repo, rev, rev).rev()
5417 rev = scmutil.revsingle(repo, rev, rev).rev()
5417
5418
5418 if check and clean:
5419 if check and clean:
5419 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5420 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5420
5421
5421 if check:
5422 if check:
5422 # we could use dirty() but we can ignore merge and branch trivia
5423 # we could use dirty() but we can ignore merge and branch trivia
5423 c = repo[None]
5424 c = repo[None]
5424 if c.modified() or c.added() or c.removed():
5425 if c.modified() or c.added() or c.removed():
5425 raise util.Abort(_("uncommitted local changes"))
5426 raise util.Abort(_("uncommitted local changes"))
5426
5427
5427 if date:
5428 if date:
5428 if rev is not None:
5429 if rev is not None:
5429 raise util.Abort(_("you can't specify a revision and a date"))
5430 raise util.Abort(_("you can't specify a revision and a date"))
5430 rev = cmdutil.finddate(ui, repo, date)
5431 rev = cmdutil.finddate(ui, repo, date)
5431
5432
5432 if clean or check:
5433 if clean or check:
5433 ret = hg.clean(repo, rev)
5434 ret = hg.clean(repo, rev)
5434 else:
5435 else:
5435 ret = hg.update(repo, rev)
5436 ret = hg.update(repo, rev)
5436
5437
5437 if brev in repo._bookmarks:
5438 if brev in repo._bookmarks:
5438 bookmarks.setcurrent(repo, brev)
5439 bookmarks.setcurrent(repo, brev)
5439
5440
5440 return ret
5441 return ret
5441
5442
5442 @command('verify', [])
5443 @command('verify', [])
5443 def verify(ui, repo):
5444 def verify(ui, repo):
5444 """verify the integrity of the repository
5445 """verify the integrity of the repository
5445
5446
5446 Verify the integrity of the current repository.
5447 Verify the integrity of the current repository.
5447
5448
5448 This will perform an extensive check of the repository's
5449 This will perform an extensive check of the repository's
5449 integrity, validating the hashes and checksums of each entry in
5450 integrity, validating the hashes and checksums of each entry in
5450 the changelog, manifest, and tracked files, as well as the
5451 the changelog, manifest, and tracked files, as well as the
5451 integrity of their crosslinks and indices.
5452 integrity of their crosslinks and indices.
5452
5453
5453 Returns 0 on success, 1 if errors are encountered.
5454 Returns 0 on success, 1 if errors are encountered.
5454 """
5455 """
5455 return hg.verify(repo)
5456 return hg.verify(repo)
5456
5457
5457 @command('version', [])
5458 @command('version', [])
5458 def version_(ui):
5459 def version_(ui):
5459 """output version and copyright information"""
5460 """output version and copyright information"""
5460 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5461 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5461 % util.version())
5462 % util.version())
5462 ui.status(_(
5463 ui.status(_(
5463 "(see http://mercurial.selenic.com for more information)\n"
5464 "(see http://mercurial.selenic.com for more information)\n"
5464 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5465 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5465 "This is free software; see the source for copying conditions. "
5466 "This is free software; see the source for copying conditions. "
5466 "There is NO\nwarranty; "
5467 "There is NO\nwarranty; "
5467 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5468 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5468 ))
5469 ))
5469
5470
5470 norepo = ("clone init version help debugcommands debugcomplete"
5471 norepo = ("clone init version help debugcommands debugcomplete"
5471 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5472 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5472 " debugknown debuggetbundle debugbundle")
5473 " debugknown debuggetbundle debugbundle")
5473 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5474 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5474 " debugdata debugindex debugindexdot debugrevlog")
5475 " debugdata debugindex debugindexdot debugrevlog")
General Comments 0
You need to be logged in to leave comments. Login now