##// END OF EJS Templates
rm: drop misleading 'use -f' hint for the rm --after 'not removing' warning...
Mads Kiilerich -
r18053:0c2f0048 default
parent child Browse files
Show More
@@ -1,5985 +1,5984 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 import patch, help, encoding, templatekw, discovery
13 import patch, help, encoding, templatekw, discovery
14 import archival, changegroup, cmdutil, hbisect
14 import archival, changegroup, cmdutil, hbisect
15 import sshserver, hgweb, hgweb.server, commandserver
15 import sshserver, hgweb, hgweb.server, commandserver
16 import merge as mergemod
16 import merge as mergemod
17 import minirst, revset, fileset
17 import minirst, revset, fileset
18 import dagparser, context, simplemerge, graphmod
18 import dagparser, context, simplemerge, graphmod
19 import random, setdiscovery, treediscovery, dagutil, pvec, localrepo
19 import random, setdiscovery, treediscovery, dagutil, pvec, localrepo
20 import phases, obsolete
20 import phases, obsolete
21
21
22 table = {}
22 table = {}
23
23
24 command = cmdutil.command(table)
24 command = cmdutil.command(table)
25
25
26 # common command options
26 # common command options
27
27
28 globalopts = [
28 globalopts = [
29 ('R', 'repository', '',
29 ('R', 'repository', '',
30 _('repository root directory or name of overlay bundle file'),
30 _('repository root directory or name of overlay bundle file'),
31 _('REPO')),
31 _('REPO')),
32 ('', 'cwd', '',
32 ('', 'cwd', '',
33 _('change working directory'), _('DIR')),
33 _('change working directory'), _('DIR')),
34 ('y', 'noninteractive', None,
34 ('y', 'noninteractive', None,
35 _('do not prompt, automatically pick the first choice for all prompts')),
35 _('do not prompt, automatically pick the first choice for all prompts')),
36 ('q', 'quiet', None, _('suppress output')),
36 ('q', 'quiet', None, _('suppress output')),
37 ('v', 'verbose', None, _('enable additional output')),
37 ('v', 'verbose', None, _('enable additional output')),
38 ('', 'config', [],
38 ('', 'config', [],
39 _('set/override config option (use \'section.name=value\')'),
39 _('set/override config option (use \'section.name=value\')'),
40 _('CONFIG')),
40 _('CONFIG')),
41 ('', 'debug', None, _('enable debugging output')),
41 ('', 'debug', None, _('enable debugging output')),
42 ('', 'debugger', None, _('start debugger')),
42 ('', 'debugger', None, _('start debugger')),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
43 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
44 _('ENCODE')),
44 _('ENCODE')),
45 ('', 'encodingmode', encoding.encodingmode,
45 ('', 'encodingmode', encoding.encodingmode,
46 _('set the charset encoding mode'), _('MODE')),
46 _('set the charset encoding mode'), _('MODE')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
47 ('', 'traceback', None, _('always print a traceback on exception')),
48 ('', 'time', None, _('time how long the command takes')),
48 ('', 'time', None, _('time how long the command takes')),
49 ('', 'profile', None, _('print command execution profile')),
49 ('', 'profile', None, _('print command execution profile')),
50 ('', 'version', None, _('output version information and exit')),
50 ('', 'version', None, _('output version information and exit')),
51 ('h', 'help', None, _('display help and exit')),
51 ('h', 'help', None, _('display help and exit')),
52 ]
52 ]
53
53
54 dryrunopts = [('n', 'dry-run', None,
54 dryrunopts = [('n', 'dry-run', None,
55 _('do not perform actions, just print output'))]
55 _('do not perform actions, just print output'))]
56
56
57 remoteopts = [
57 remoteopts = [
58 ('e', 'ssh', '',
58 ('e', 'ssh', '',
59 _('specify ssh command to use'), _('CMD')),
59 _('specify ssh command to use'), _('CMD')),
60 ('', 'remotecmd', '',
60 ('', 'remotecmd', '',
61 _('specify hg command to run on the remote side'), _('CMD')),
61 _('specify hg command to run on the remote side'), _('CMD')),
62 ('', 'insecure', None,
62 ('', 'insecure', None,
63 _('do not verify server certificate (ignoring web.cacerts config)')),
63 _('do not verify server certificate (ignoring web.cacerts config)')),
64 ]
64 ]
65
65
66 walkopts = [
66 walkopts = [
67 ('I', 'include', [],
67 ('I', 'include', [],
68 _('include names matching the given patterns'), _('PATTERN')),
68 _('include names matching the given patterns'), _('PATTERN')),
69 ('X', 'exclude', [],
69 ('X', 'exclude', [],
70 _('exclude names matching the given patterns'), _('PATTERN')),
70 _('exclude names matching the given patterns'), _('PATTERN')),
71 ]
71 ]
72
72
73 commitopts = [
73 commitopts = [
74 ('m', 'message', '',
74 ('m', 'message', '',
75 _('use text as commit message'), _('TEXT')),
75 _('use text as commit message'), _('TEXT')),
76 ('l', 'logfile', '',
76 ('l', 'logfile', '',
77 _('read commit message from file'), _('FILE')),
77 _('read commit message from file'), _('FILE')),
78 ]
78 ]
79
79
80 commitopts2 = [
80 commitopts2 = [
81 ('d', 'date', '',
81 ('d', 'date', '',
82 _('record the specified date as commit date'), _('DATE')),
82 _('record the specified date as commit date'), _('DATE')),
83 ('u', 'user', '',
83 ('u', 'user', '',
84 _('record the specified user as committer'), _('USER')),
84 _('record the specified user as committer'), _('USER')),
85 ]
85 ]
86
86
87 templateopts = [
87 templateopts = [
88 ('', 'style', '',
88 ('', 'style', '',
89 _('display using template map file'), _('STYLE')),
89 _('display using template map file'), _('STYLE')),
90 ('', 'template', '',
90 ('', 'template', '',
91 _('display with template'), _('TEMPLATE')),
91 _('display with template'), _('TEMPLATE')),
92 ]
92 ]
93
93
94 logopts = [
94 logopts = [
95 ('p', 'patch', None, _('show patch')),
95 ('p', 'patch', None, _('show patch')),
96 ('g', 'git', None, _('use git extended diff format')),
96 ('g', 'git', None, _('use git extended diff format')),
97 ('l', 'limit', '',
97 ('l', 'limit', '',
98 _('limit number of changes displayed'), _('NUM')),
98 _('limit number of changes displayed'), _('NUM')),
99 ('M', 'no-merges', None, _('do not show merges')),
99 ('M', 'no-merges', None, _('do not show merges')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
100 ('', 'stat', None, _('output diffstat-style summary of changes')),
101 ('G', 'graph', None, _("show the revision DAG")),
101 ('G', 'graph', None, _("show the revision DAG")),
102 ] + templateopts
102 ] + templateopts
103
103
104 diffopts = [
104 diffopts = [
105 ('a', 'text', None, _('treat all files as text')),
105 ('a', 'text', None, _('treat all files as text')),
106 ('g', 'git', None, _('use git extended diff format')),
106 ('g', 'git', None, _('use git extended diff format')),
107 ('', 'nodates', None, _('omit dates from diff headers'))
107 ('', 'nodates', None, _('omit dates from diff headers'))
108 ]
108 ]
109
109
110 diffwsopts = [
110 diffwsopts = [
111 ('w', 'ignore-all-space', None,
111 ('w', 'ignore-all-space', None,
112 _('ignore white space when comparing lines')),
112 _('ignore white space when comparing lines')),
113 ('b', 'ignore-space-change', None,
113 ('b', 'ignore-space-change', None,
114 _('ignore changes in the amount of white space')),
114 _('ignore changes in the amount of white space')),
115 ('B', 'ignore-blank-lines', None,
115 ('B', 'ignore-blank-lines', None,
116 _('ignore changes whose lines are all blank')),
116 _('ignore changes whose lines are all blank')),
117 ]
117 ]
118
118
119 diffopts2 = [
119 diffopts2 = [
120 ('p', 'show-function', None, _('show which function each change is in')),
120 ('p', 'show-function', None, _('show which function each change is in')),
121 ('', 'reverse', None, _('produce a diff that undoes the changes')),
121 ('', 'reverse', None, _('produce a diff that undoes the changes')),
122 ] + diffwsopts + [
122 ] + diffwsopts + [
123 ('U', 'unified', '',
123 ('U', 'unified', '',
124 _('number of lines of context to show'), _('NUM')),
124 _('number of lines of context to show'), _('NUM')),
125 ('', 'stat', None, _('output diffstat-style summary of changes')),
125 ('', 'stat', None, _('output diffstat-style summary of changes')),
126 ]
126 ]
127
127
128 mergetoolopts = [
128 mergetoolopts = [
129 ('t', 'tool', '', _('specify merge tool')),
129 ('t', 'tool', '', _('specify merge tool')),
130 ]
130 ]
131
131
132 similarityopts = [
132 similarityopts = [
133 ('s', 'similarity', '',
133 ('s', 'similarity', '',
134 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
134 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
135 ]
135 ]
136
136
137 subrepoopts = [
137 subrepoopts = [
138 ('S', 'subrepos', None,
138 ('S', 'subrepos', None,
139 _('recurse into subrepositories'))
139 _('recurse into subrepositories'))
140 ]
140 ]
141
141
142 # Commands start here, listed alphabetically
142 # Commands start here, listed alphabetically
143
143
144 @command('^add',
144 @command('^add',
145 walkopts + subrepoopts + dryrunopts,
145 walkopts + subrepoopts + dryrunopts,
146 _('[OPTION]... [FILE]...'))
146 _('[OPTION]... [FILE]...'))
147 def add(ui, repo, *pats, **opts):
147 def add(ui, repo, *pats, **opts):
148 """add the specified files on the next commit
148 """add the specified files on the next commit
149
149
150 Schedule files to be version controlled and added to the
150 Schedule files to be version controlled and added to the
151 repository.
151 repository.
152
152
153 The files will be added to the repository at the next commit. To
153 The files will be added to the repository at the next commit. To
154 undo an add before that, see :hg:`forget`.
154 undo an add before that, see :hg:`forget`.
155
155
156 If no names are given, add all files to the repository.
156 If no names are given, add all files to the repository.
157
157
158 .. container:: verbose
158 .. container:: verbose
159
159
160 An example showing how new (unknown) files are added
160 An example showing how new (unknown) files are added
161 automatically by :hg:`add`::
161 automatically by :hg:`add`::
162
162
163 $ ls
163 $ ls
164 foo.c
164 foo.c
165 $ hg status
165 $ hg status
166 ? foo.c
166 ? foo.c
167 $ hg add
167 $ hg add
168 adding foo.c
168 adding foo.c
169 $ hg status
169 $ hg status
170 A foo.c
170 A foo.c
171
171
172 Returns 0 if all files are successfully added.
172 Returns 0 if all files are successfully added.
173 """
173 """
174
174
175 m = scmutil.match(repo[None], pats, opts)
175 m = scmutil.match(repo[None], pats, opts)
176 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
176 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
177 opts.get('subrepos'), prefix="", explicitonly=False)
177 opts.get('subrepos'), prefix="", explicitonly=False)
178 return rejected and 1 or 0
178 return rejected and 1 or 0
179
179
180 @command('addremove',
180 @command('addremove',
181 similarityopts + walkopts + dryrunopts,
181 similarityopts + walkopts + dryrunopts,
182 _('[OPTION]... [FILE]...'))
182 _('[OPTION]... [FILE]...'))
183 def addremove(ui, repo, *pats, **opts):
183 def addremove(ui, repo, *pats, **opts):
184 """add all new files, delete all missing files
184 """add all new files, delete all missing files
185
185
186 Add all new files and remove all missing files from the
186 Add all new files and remove all missing files from the
187 repository.
187 repository.
188
188
189 New files are ignored if they match any of the patterns in
189 New files are ignored if they match any of the patterns in
190 ``.hgignore``. As with add, these changes take effect at the next
190 ``.hgignore``. As with add, these changes take effect at the next
191 commit.
191 commit.
192
192
193 Use the -s/--similarity option to detect renamed files. This
193 Use the -s/--similarity option to detect renamed files. This
194 option takes a percentage between 0 (disabled) and 100 (files must
194 option takes a percentage between 0 (disabled) and 100 (files must
195 be identical) as its parameter. With a parameter greater than 0,
195 be identical) as its parameter. With a parameter greater than 0,
196 this compares every removed file with every added file and records
196 this compares every removed file with every added file and records
197 those similar enough as renames. Detecting renamed files this way
197 those similar enough as renames. Detecting renamed files this way
198 can be expensive. After using this option, :hg:`status -C` can be
198 can be expensive. After using this option, :hg:`status -C` can be
199 used to check which files were identified as moved or renamed. If
199 used to check which files were identified as moved or renamed. If
200 not specified, -s/--similarity defaults to 100 and only renames of
200 not specified, -s/--similarity defaults to 100 and only renames of
201 identical files are detected.
201 identical files are detected.
202
202
203 Returns 0 if all files are successfully added.
203 Returns 0 if all files are successfully added.
204 """
204 """
205 try:
205 try:
206 sim = float(opts.get('similarity') or 100)
206 sim = float(opts.get('similarity') or 100)
207 except ValueError:
207 except ValueError:
208 raise util.Abort(_('similarity must be a number'))
208 raise util.Abort(_('similarity must be a number'))
209 if sim < 0 or sim > 100:
209 if sim < 0 or sim > 100:
210 raise util.Abort(_('similarity must be between 0 and 100'))
210 raise util.Abort(_('similarity must be between 0 and 100'))
211 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
211 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
212
212
213 @command('^annotate|blame',
213 @command('^annotate|blame',
214 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
214 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
215 ('', 'follow', None,
215 ('', 'follow', None,
216 _('follow copies/renames and list the filename (DEPRECATED)')),
216 _('follow copies/renames and list the filename (DEPRECATED)')),
217 ('', 'no-follow', None, _("don't follow copies and renames")),
217 ('', 'no-follow', None, _("don't follow copies and renames")),
218 ('a', 'text', None, _('treat all files as text')),
218 ('a', 'text', None, _('treat all files as text')),
219 ('u', 'user', None, _('list the author (long with -v)')),
219 ('u', 'user', None, _('list the author (long with -v)')),
220 ('f', 'file', None, _('list the filename')),
220 ('f', 'file', None, _('list the filename')),
221 ('d', 'date', None, _('list the date (short with -q)')),
221 ('d', 'date', None, _('list the date (short with -q)')),
222 ('n', 'number', None, _('list the revision number (default)')),
222 ('n', 'number', None, _('list the revision number (default)')),
223 ('c', 'changeset', None, _('list the changeset')),
223 ('c', 'changeset', None, _('list the changeset')),
224 ('l', 'line-number', None, _('show line number at the first appearance'))
224 ('l', 'line-number', None, _('show line number at the first appearance'))
225 ] + diffwsopts + walkopts,
225 ] + diffwsopts + walkopts,
226 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
226 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
227 def annotate(ui, repo, *pats, **opts):
227 def annotate(ui, repo, *pats, **opts):
228 """show changeset information by line for each file
228 """show changeset information by line for each file
229
229
230 List changes in files, showing the revision id responsible for
230 List changes in files, showing the revision id responsible for
231 each line
231 each line
232
232
233 This command is useful for discovering when a change was made and
233 This command is useful for discovering when a change was made and
234 by whom.
234 by whom.
235
235
236 Without the -a/--text option, annotate will avoid processing files
236 Without the -a/--text option, annotate will avoid processing files
237 it detects as binary. With -a, annotate will annotate the file
237 it detects as binary. With -a, annotate will annotate the file
238 anyway, although the results will probably be neither useful
238 anyway, although the results will probably be neither useful
239 nor desirable.
239 nor desirable.
240
240
241 Returns 0 on success.
241 Returns 0 on success.
242 """
242 """
243 if opts.get('follow'):
243 if opts.get('follow'):
244 # --follow is deprecated and now just an alias for -f/--file
244 # --follow is deprecated and now just an alias for -f/--file
245 # to mimic the behavior of Mercurial before version 1.5
245 # to mimic the behavior of Mercurial before version 1.5
246 opts['file'] = True
246 opts['file'] = True
247
247
248 datefunc = ui.quiet and util.shortdate or util.datestr
248 datefunc = ui.quiet and util.shortdate or util.datestr
249 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
249 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
250
250
251 if not pats:
251 if not pats:
252 raise util.Abort(_('at least one filename or pattern is required'))
252 raise util.Abort(_('at least one filename or pattern is required'))
253
253
254 hexfn = ui.debugflag and hex or short
254 hexfn = ui.debugflag and hex or short
255
255
256 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
256 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
257 ('number', ' ', lambda x: str(x[0].rev())),
257 ('number', ' ', lambda x: str(x[0].rev())),
258 ('changeset', ' ', lambda x: hexfn(x[0].node())),
258 ('changeset', ' ', lambda x: hexfn(x[0].node())),
259 ('date', ' ', getdate),
259 ('date', ' ', getdate),
260 ('file', ' ', lambda x: x[0].path()),
260 ('file', ' ', lambda x: x[0].path()),
261 ('line_number', ':', lambda x: str(x[1])),
261 ('line_number', ':', lambda x: str(x[1])),
262 ]
262 ]
263
263
264 if (not opts.get('user') and not opts.get('changeset')
264 if (not opts.get('user') and not opts.get('changeset')
265 and not opts.get('date') and not opts.get('file')):
265 and not opts.get('date') and not opts.get('file')):
266 opts['number'] = True
266 opts['number'] = True
267
267
268 linenumber = opts.get('line_number') is not None
268 linenumber = opts.get('line_number') is not None
269 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
269 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
270 raise util.Abort(_('at least one of -n/-c is required for -l'))
270 raise util.Abort(_('at least one of -n/-c is required for -l'))
271
271
272 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
272 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
273 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
273 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
274
274
275 def bad(x, y):
275 def bad(x, y):
276 raise util.Abort("%s: %s" % (x, y))
276 raise util.Abort("%s: %s" % (x, y))
277
277
278 ctx = scmutil.revsingle(repo, opts.get('rev'))
278 ctx = scmutil.revsingle(repo, opts.get('rev'))
279 m = scmutil.match(ctx, pats, opts)
279 m = scmutil.match(ctx, pats, opts)
280 m.bad = bad
280 m.bad = bad
281 follow = not opts.get('no_follow')
281 follow = not opts.get('no_follow')
282 diffopts = patch.diffopts(ui, opts, section='annotate')
282 diffopts = patch.diffopts(ui, opts, section='annotate')
283 for abs in ctx.walk(m):
283 for abs in ctx.walk(m):
284 fctx = ctx[abs]
284 fctx = ctx[abs]
285 if not opts.get('text') and util.binary(fctx.data()):
285 if not opts.get('text') and util.binary(fctx.data()):
286 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
286 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
287 continue
287 continue
288
288
289 lines = fctx.annotate(follow=follow, linenumber=linenumber,
289 lines = fctx.annotate(follow=follow, linenumber=linenumber,
290 diffopts=diffopts)
290 diffopts=diffopts)
291 pieces = []
291 pieces = []
292
292
293 for f, sep in funcmap:
293 for f, sep in funcmap:
294 l = [f(n) for n, dummy in lines]
294 l = [f(n) for n, dummy in lines]
295 if l:
295 if l:
296 sized = [(x, encoding.colwidth(x)) for x in l]
296 sized = [(x, encoding.colwidth(x)) for x in l]
297 ml = max([w for x, w in sized])
297 ml = max([w for x, w in sized])
298 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
298 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
299 for x, w in sized])
299 for x, w in sized])
300
300
301 if pieces:
301 if pieces:
302 for p, l in zip(zip(*pieces), lines):
302 for p, l in zip(zip(*pieces), lines):
303 ui.write("%s: %s" % ("".join(p), l[1]))
303 ui.write("%s: %s" % ("".join(p), l[1]))
304
304
305 if lines and not lines[-1][1].endswith('\n'):
305 if lines and not lines[-1][1].endswith('\n'):
306 ui.write('\n')
306 ui.write('\n')
307
307
308 @command('archive',
308 @command('archive',
309 [('', 'no-decode', None, _('do not pass files through decoders')),
309 [('', 'no-decode', None, _('do not pass files through decoders')),
310 ('p', 'prefix', '', _('directory prefix for files in archive'),
310 ('p', 'prefix', '', _('directory prefix for files in archive'),
311 _('PREFIX')),
311 _('PREFIX')),
312 ('r', 'rev', '', _('revision to distribute'), _('REV')),
312 ('r', 'rev', '', _('revision to distribute'), _('REV')),
313 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
313 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
314 ] + subrepoopts + walkopts,
314 ] + subrepoopts + walkopts,
315 _('[OPTION]... DEST'))
315 _('[OPTION]... DEST'))
316 def archive(ui, repo, dest, **opts):
316 def archive(ui, repo, dest, **opts):
317 '''create an unversioned archive of a repository revision
317 '''create an unversioned archive of a repository revision
318
318
319 By default, the revision used is the parent of the working
319 By default, the revision used is the parent of the working
320 directory; use -r/--rev to specify a different revision.
320 directory; use -r/--rev to specify a different revision.
321
321
322 The archive type is automatically detected based on file
322 The archive type is automatically detected based on file
323 extension (or override using -t/--type).
323 extension (or override using -t/--type).
324
324
325 .. container:: verbose
325 .. container:: verbose
326
326
327 Examples:
327 Examples:
328
328
329 - create a zip file containing the 1.0 release::
329 - create a zip file containing the 1.0 release::
330
330
331 hg archive -r 1.0 project-1.0.zip
331 hg archive -r 1.0 project-1.0.zip
332
332
333 - create a tarball excluding .hg files::
333 - create a tarball excluding .hg files::
334
334
335 hg archive project.tar.gz -X ".hg*"
335 hg archive project.tar.gz -X ".hg*"
336
336
337 Valid types are:
337 Valid types are:
338
338
339 :``files``: a directory full of files (default)
339 :``files``: a directory full of files (default)
340 :``tar``: tar archive, uncompressed
340 :``tar``: tar archive, uncompressed
341 :``tbz2``: tar archive, compressed using bzip2
341 :``tbz2``: tar archive, compressed using bzip2
342 :``tgz``: tar archive, compressed using gzip
342 :``tgz``: tar archive, compressed using gzip
343 :``uzip``: zip archive, uncompressed
343 :``uzip``: zip archive, uncompressed
344 :``zip``: zip archive, compressed using deflate
344 :``zip``: zip archive, compressed using deflate
345
345
346 The exact name of the destination archive or directory is given
346 The exact name of the destination archive or directory is given
347 using a format string; see :hg:`help export` for details.
347 using a format string; see :hg:`help export` for details.
348
348
349 Each member added to an archive file has a directory prefix
349 Each member added to an archive file has a directory prefix
350 prepended. Use -p/--prefix to specify a format string for the
350 prepended. Use -p/--prefix to specify a format string for the
351 prefix. The default is the basename of the archive, with suffixes
351 prefix. The default is the basename of the archive, with suffixes
352 removed.
352 removed.
353
353
354 Returns 0 on success.
354 Returns 0 on success.
355 '''
355 '''
356
356
357 ctx = scmutil.revsingle(repo, opts.get('rev'))
357 ctx = scmutil.revsingle(repo, opts.get('rev'))
358 if not ctx:
358 if not ctx:
359 raise util.Abort(_('no working directory: please specify a revision'))
359 raise util.Abort(_('no working directory: please specify a revision'))
360 node = ctx.node()
360 node = ctx.node()
361 dest = cmdutil.makefilename(repo, dest, node)
361 dest = cmdutil.makefilename(repo, dest, node)
362 if os.path.realpath(dest) == repo.root:
362 if os.path.realpath(dest) == repo.root:
363 raise util.Abort(_('repository root cannot be destination'))
363 raise util.Abort(_('repository root cannot be destination'))
364
364
365 kind = opts.get('type') or archival.guesskind(dest) or 'files'
365 kind = opts.get('type') or archival.guesskind(dest) or 'files'
366 prefix = opts.get('prefix')
366 prefix = opts.get('prefix')
367
367
368 if dest == '-':
368 if dest == '-':
369 if kind == 'files':
369 if kind == 'files':
370 raise util.Abort(_('cannot archive plain files to stdout'))
370 raise util.Abort(_('cannot archive plain files to stdout'))
371 dest = cmdutil.makefileobj(repo, dest)
371 dest = cmdutil.makefileobj(repo, dest)
372 if not prefix:
372 if not prefix:
373 prefix = os.path.basename(repo.root) + '-%h'
373 prefix = os.path.basename(repo.root) + '-%h'
374
374
375 prefix = cmdutil.makefilename(repo, prefix, node)
375 prefix = cmdutil.makefilename(repo, prefix, node)
376 matchfn = scmutil.match(ctx, [], opts)
376 matchfn = scmutil.match(ctx, [], opts)
377 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
377 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
378 matchfn, prefix, subrepos=opts.get('subrepos'))
378 matchfn, prefix, subrepos=opts.get('subrepos'))
379
379
380 @command('backout',
380 @command('backout',
381 [('', 'merge', None, _('merge with old dirstate parent after backout')),
381 [('', 'merge', None, _('merge with old dirstate parent after backout')),
382 ('', 'parent', '',
382 ('', 'parent', '',
383 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
383 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
384 ('r', 'rev', '', _('revision to backout'), _('REV')),
384 ('r', 'rev', '', _('revision to backout'), _('REV')),
385 ] + mergetoolopts + walkopts + commitopts + commitopts2,
385 ] + mergetoolopts + walkopts + commitopts + commitopts2,
386 _('[OPTION]... [-r] REV'))
386 _('[OPTION]... [-r] REV'))
387 def backout(ui, repo, node=None, rev=None, **opts):
387 def backout(ui, repo, node=None, rev=None, **opts):
388 '''reverse effect of earlier changeset
388 '''reverse effect of earlier changeset
389
389
390 Prepare a new changeset with the effect of REV undone in the
390 Prepare a new changeset with the effect of REV undone in the
391 current working directory.
391 current working directory.
392
392
393 If REV is the parent of the working directory, then this new changeset
393 If REV is the parent of the working directory, then this new changeset
394 is committed automatically. Otherwise, hg needs to merge the
394 is committed automatically. Otherwise, hg needs to merge the
395 changes and the merged result is left uncommitted.
395 changes and the merged result is left uncommitted.
396
396
397 .. note::
397 .. note::
398 backout cannot be used to fix either an unwanted or
398 backout cannot be used to fix either an unwanted or
399 incorrect merge.
399 incorrect merge.
400
400
401 .. container:: verbose
401 .. container:: verbose
402
402
403 By default, the pending changeset will have one parent,
403 By default, the pending changeset will have one parent,
404 maintaining a linear history. With --merge, the pending
404 maintaining a linear history. With --merge, the pending
405 changeset will instead have two parents: the old parent of the
405 changeset will instead have two parents: the old parent of the
406 working directory and a new child of REV that simply undoes REV.
406 working directory and a new child of REV that simply undoes REV.
407
407
408 Before version 1.7, the behavior without --merge was equivalent
408 Before version 1.7, the behavior without --merge was equivalent
409 to specifying --merge followed by :hg:`update --clean .` to
409 to specifying --merge followed by :hg:`update --clean .` to
410 cancel the merge and leave the child of REV as a head to be
410 cancel the merge and leave the child of REV as a head to be
411 merged separately.
411 merged separately.
412
412
413 See :hg:`help dates` for a list of formats valid for -d/--date.
413 See :hg:`help dates` for a list of formats valid for -d/--date.
414
414
415 Returns 0 on success.
415 Returns 0 on success.
416 '''
416 '''
417 if rev and node:
417 if rev and node:
418 raise util.Abort(_("please specify just one revision"))
418 raise util.Abort(_("please specify just one revision"))
419
419
420 if not rev:
420 if not rev:
421 rev = node
421 rev = node
422
422
423 if not rev:
423 if not rev:
424 raise util.Abort(_("please specify a revision to backout"))
424 raise util.Abort(_("please specify a revision to backout"))
425
425
426 date = opts.get('date')
426 date = opts.get('date')
427 if date:
427 if date:
428 opts['date'] = util.parsedate(date)
428 opts['date'] = util.parsedate(date)
429
429
430 cmdutil.bailifchanged(repo)
430 cmdutil.bailifchanged(repo)
431 node = scmutil.revsingle(repo, rev).node()
431 node = scmutil.revsingle(repo, rev).node()
432
432
433 op1, op2 = repo.dirstate.parents()
433 op1, op2 = repo.dirstate.parents()
434 a = repo.changelog.ancestor(op1, node)
434 a = repo.changelog.ancestor(op1, node)
435 if a != node:
435 if a != node:
436 raise util.Abort(_('cannot backout change on a different branch'))
436 raise util.Abort(_('cannot backout change on a different branch'))
437
437
438 p1, p2 = repo.changelog.parents(node)
438 p1, p2 = repo.changelog.parents(node)
439 if p1 == nullid:
439 if p1 == nullid:
440 raise util.Abort(_('cannot backout a change with no parents'))
440 raise util.Abort(_('cannot backout a change with no parents'))
441 if p2 != nullid:
441 if p2 != nullid:
442 if not opts.get('parent'):
442 if not opts.get('parent'):
443 raise util.Abort(_('cannot backout a merge changeset'))
443 raise util.Abort(_('cannot backout a merge changeset'))
444 p = repo.lookup(opts['parent'])
444 p = repo.lookup(opts['parent'])
445 if p not in (p1, p2):
445 if p not in (p1, p2):
446 raise util.Abort(_('%s is not a parent of %s') %
446 raise util.Abort(_('%s is not a parent of %s') %
447 (short(p), short(node)))
447 (short(p), short(node)))
448 parent = p
448 parent = p
449 else:
449 else:
450 if opts.get('parent'):
450 if opts.get('parent'):
451 raise util.Abort(_('cannot use --parent on non-merge changeset'))
451 raise util.Abort(_('cannot use --parent on non-merge changeset'))
452 parent = p1
452 parent = p1
453
453
454 # the backout should appear on the same branch
454 # the backout should appear on the same branch
455 wlock = repo.wlock()
455 wlock = repo.wlock()
456 try:
456 try:
457 branch = repo.dirstate.branch()
457 branch = repo.dirstate.branch()
458 hg.clean(repo, node, show_stats=False)
458 hg.clean(repo, node, show_stats=False)
459 repo.dirstate.setbranch(branch)
459 repo.dirstate.setbranch(branch)
460 revert_opts = opts.copy()
460 revert_opts = opts.copy()
461 revert_opts['date'] = None
461 revert_opts['date'] = None
462 revert_opts['all'] = True
462 revert_opts['all'] = True
463 revert_opts['rev'] = hex(parent)
463 revert_opts['rev'] = hex(parent)
464 revert_opts['no_backup'] = None
464 revert_opts['no_backup'] = None
465 revert(ui, repo, **revert_opts)
465 revert(ui, repo, **revert_opts)
466 if not opts.get('merge') and op1 != node:
466 if not opts.get('merge') and op1 != node:
467 try:
467 try:
468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
469 return hg.update(repo, op1)
469 return hg.update(repo, op1)
470 finally:
470 finally:
471 ui.setconfig('ui', 'forcemerge', '')
471 ui.setconfig('ui', 'forcemerge', '')
472
472
473 commit_opts = opts.copy()
473 commit_opts = opts.copy()
474 commit_opts['addremove'] = False
474 commit_opts['addremove'] = False
475 if not commit_opts['message'] and not commit_opts['logfile']:
475 if not commit_opts['message'] and not commit_opts['logfile']:
476 # we don't translate commit messages
476 # we don't translate commit messages
477 commit_opts['message'] = "Backed out changeset %s" % short(node)
477 commit_opts['message'] = "Backed out changeset %s" % short(node)
478 commit_opts['force_editor'] = True
478 commit_opts['force_editor'] = True
479 commit(ui, repo, **commit_opts)
479 commit(ui, repo, **commit_opts)
480 def nice(node):
480 def nice(node):
481 return '%d:%s' % (repo.changelog.rev(node), short(node))
481 return '%d:%s' % (repo.changelog.rev(node), short(node))
482 ui.status(_('changeset %s backs out changeset %s\n') %
482 ui.status(_('changeset %s backs out changeset %s\n') %
483 (nice(repo.changelog.tip()), nice(node)))
483 (nice(repo.changelog.tip()), nice(node)))
484 if opts.get('merge') and op1 != node:
484 if opts.get('merge') and op1 != node:
485 hg.clean(repo, op1, show_stats=False)
485 hg.clean(repo, op1, show_stats=False)
486 ui.status(_('merging with changeset %s\n')
486 ui.status(_('merging with changeset %s\n')
487 % nice(repo.changelog.tip()))
487 % nice(repo.changelog.tip()))
488 try:
488 try:
489 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
489 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
490 return hg.merge(repo, hex(repo.changelog.tip()))
490 return hg.merge(repo, hex(repo.changelog.tip()))
491 finally:
491 finally:
492 ui.setconfig('ui', 'forcemerge', '')
492 ui.setconfig('ui', 'forcemerge', '')
493 finally:
493 finally:
494 wlock.release()
494 wlock.release()
495 return 0
495 return 0
496
496
497 @command('bisect',
497 @command('bisect',
498 [('r', 'reset', False, _('reset bisect state')),
498 [('r', 'reset', False, _('reset bisect state')),
499 ('g', 'good', False, _('mark changeset good')),
499 ('g', 'good', False, _('mark changeset good')),
500 ('b', 'bad', False, _('mark changeset bad')),
500 ('b', 'bad', False, _('mark changeset bad')),
501 ('s', 'skip', False, _('skip testing changeset')),
501 ('s', 'skip', False, _('skip testing changeset')),
502 ('e', 'extend', False, _('extend the bisect range')),
502 ('e', 'extend', False, _('extend the bisect range')),
503 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
503 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
504 ('U', 'noupdate', False, _('do not update to target'))],
504 ('U', 'noupdate', False, _('do not update to target'))],
505 _("[-gbsr] [-U] [-c CMD] [REV]"))
505 _("[-gbsr] [-U] [-c CMD] [REV]"))
506 def bisect(ui, repo, rev=None, extra=None, command=None,
506 def bisect(ui, repo, rev=None, extra=None, command=None,
507 reset=None, good=None, bad=None, skip=None, extend=None,
507 reset=None, good=None, bad=None, skip=None, extend=None,
508 noupdate=None):
508 noupdate=None):
509 """subdivision search of changesets
509 """subdivision search of changesets
510
510
511 This command helps to find changesets which introduce problems. To
511 This command helps to find changesets which introduce problems. To
512 use, mark the earliest changeset you know exhibits the problem as
512 use, mark the earliest changeset you know exhibits the problem as
513 bad, then mark the latest changeset which is free from the problem
513 bad, then mark the latest changeset which is free from the problem
514 as good. Bisect will update your working directory to a revision
514 as good. Bisect will update your working directory to a revision
515 for testing (unless the -U/--noupdate option is specified). Once
515 for testing (unless the -U/--noupdate option is specified). Once
516 you have performed tests, mark the working directory as good or
516 you have performed tests, mark the working directory as good or
517 bad, and bisect will either update to another candidate changeset
517 bad, and bisect will either update to another candidate changeset
518 or announce that it has found the bad revision.
518 or announce that it has found the bad revision.
519
519
520 As a shortcut, you can also use the revision argument to mark a
520 As a shortcut, you can also use the revision argument to mark a
521 revision as good or bad without checking it out first.
521 revision as good or bad without checking it out first.
522
522
523 If you supply a command, it will be used for automatic bisection.
523 If you supply a command, it will be used for automatic bisection.
524 The environment variable HG_NODE will contain the ID of the
524 The environment variable HG_NODE will contain the ID of the
525 changeset being tested. The exit status of the command will be
525 changeset being tested. The exit status of the command will be
526 used to mark revisions as good or bad: status 0 means good, 125
526 used to mark revisions as good or bad: status 0 means good, 125
527 means to skip the revision, 127 (command not found) will abort the
527 means to skip the revision, 127 (command not found) will abort the
528 bisection, and any other non-zero exit status means the revision
528 bisection, and any other non-zero exit status means the revision
529 is bad.
529 is bad.
530
530
531 .. container:: verbose
531 .. container:: verbose
532
532
533 Some examples:
533 Some examples:
534
534
535 - start a bisection with known bad revision 12, and good revision 34::
535 - start a bisection with known bad revision 12, and good revision 34::
536
536
537 hg bisect --bad 34
537 hg bisect --bad 34
538 hg bisect --good 12
538 hg bisect --good 12
539
539
540 - advance the current bisection by marking current revision as good or
540 - advance the current bisection by marking current revision as good or
541 bad::
541 bad::
542
542
543 hg bisect --good
543 hg bisect --good
544 hg bisect --bad
544 hg bisect --bad
545
545
546 - mark the current revision, or a known revision, to be skipped (e.g. if
546 - mark the current revision, or a known revision, to be skipped (e.g. if
547 that revision is not usable because of another issue)::
547 that revision is not usable because of another issue)::
548
548
549 hg bisect --skip
549 hg bisect --skip
550 hg bisect --skip 23
550 hg bisect --skip 23
551
551
552 - skip all revisions that do not touch directories ``foo`` or ``bar``
552 - skip all revisions that do not touch directories ``foo`` or ``bar``
553
553
554 hg bisect --skip '!( file("path:foo") & file("path:bar") )'
554 hg bisect --skip '!( file("path:foo") & file("path:bar") )'
555
555
556 - forget the current bisection::
556 - forget the current bisection::
557
557
558 hg bisect --reset
558 hg bisect --reset
559
559
560 - use 'make && make tests' to automatically find the first broken
560 - use 'make && make tests' to automatically find the first broken
561 revision::
561 revision::
562
562
563 hg bisect --reset
563 hg bisect --reset
564 hg bisect --bad 34
564 hg bisect --bad 34
565 hg bisect --good 12
565 hg bisect --good 12
566 hg bisect --command 'make && make tests'
566 hg bisect --command 'make && make tests'
567
567
568 - see all changesets whose states are already known in the current
568 - see all changesets whose states are already known in the current
569 bisection::
569 bisection::
570
570
571 hg log -r "bisect(pruned)"
571 hg log -r "bisect(pruned)"
572
572
573 - see the changeset currently being bisected (especially useful
573 - see the changeset currently being bisected (especially useful
574 if running with -U/--noupdate)::
574 if running with -U/--noupdate)::
575
575
576 hg log -r "bisect(current)"
576 hg log -r "bisect(current)"
577
577
578 - see all changesets that took part in the current bisection::
578 - see all changesets that took part in the current bisection::
579
579
580 hg log -r "bisect(range)"
580 hg log -r "bisect(range)"
581
581
582 - with the graphlog extension, you can even get a nice graph::
582 - with the graphlog extension, you can even get a nice graph::
583
583
584 hg log --graph -r "bisect(range)"
584 hg log --graph -r "bisect(range)"
585
585
586 See :hg:`help revsets` for more about the `bisect()` keyword.
586 See :hg:`help revsets` for more about the `bisect()` keyword.
587
587
588 Returns 0 on success.
588 Returns 0 on success.
589 """
589 """
590 def extendbisectrange(nodes, good):
590 def extendbisectrange(nodes, good):
591 # bisect is incomplete when it ends on a merge node and
591 # bisect is incomplete when it ends on a merge node and
592 # one of the parent was not checked.
592 # one of the parent was not checked.
593 parents = repo[nodes[0]].parents()
593 parents = repo[nodes[0]].parents()
594 if len(parents) > 1:
594 if len(parents) > 1:
595 side = good and state['bad'] or state['good']
595 side = good and state['bad'] or state['good']
596 num = len(set(i.node() for i in parents) & set(side))
596 num = len(set(i.node() for i in parents) & set(side))
597 if num == 1:
597 if num == 1:
598 return parents[0].ancestor(parents[1])
598 return parents[0].ancestor(parents[1])
599 return None
599 return None
600
600
601 def print_result(nodes, good):
601 def print_result(nodes, good):
602 displayer = cmdutil.show_changeset(ui, repo, {})
602 displayer = cmdutil.show_changeset(ui, repo, {})
603 if len(nodes) == 1:
603 if len(nodes) == 1:
604 # narrowed it down to a single revision
604 # narrowed it down to a single revision
605 if good:
605 if good:
606 ui.write(_("The first good revision is:\n"))
606 ui.write(_("The first good revision is:\n"))
607 else:
607 else:
608 ui.write(_("The first bad revision is:\n"))
608 ui.write(_("The first bad revision is:\n"))
609 displayer.show(repo[nodes[0]])
609 displayer.show(repo[nodes[0]])
610 extendnode = extendbisectrange(nodes, good)
610 extendnode = extendbisectrange(nodes, good)
611 if extendnode is not None:
611 if extendnode is not None:
612 ui.write(_('Not all ancestors of this changeset have been'
612 ui.write(_('Not all ancestors of this changeset have been'
613 ' checked.\nUse bisect --extend to continue the '
613 ' checked.\nUse bisect --extend to continue the '
614 'bisection from\nthe common ancestor, %s.\n')
614 'bisection from\nthe common ancestor, %s.\n')
615 % extendnode)
615 % extendnode)
616 else:
616 else:
617 # multiple possible revisions
617 # multiple possible revisions
618 if good:
618 if good:
619 ui.write(_("Due to skipped revisions, the first "
619 ui.write(_("Due to skipped revisions, the first "
620 "good revision could be any of:\n"))
620 "good revision could be any of:\n"))
621 else:
621 else:
622 ui.write(_("Due to skipped revisions, the first "
622 ui.write(_("Due to skipped revisions, the first "
623 "bad revision could be any of:\n"))
623 "bad revision could be any of:\n"))
624 for n in nodes:
624 for n in nodes:
625 displayer.show(repo[n])
625 displayer.show(repo[n])
626 displayer.close()
626 displayer.close()
627
627
628 def check_state(state, interactive=True):
628 def check_state(state, interactive=True):
629 if not state['good'] or not state['bad']:
629 if not state['good'] or not state['bad']:
630 if (good or bad or skip or reset) and interactive:
630 if (good or bad or skip or reset) and interactive:
631 return
631 return
632 if not state['good']:
632 if not state['good']:
633 raise util.Abort(_('cannot bisect (no known good revisions)'))
633 raise util.Abort(_('cannot bisect (no known good revisions)'))
634 else:
634 else:
635 raise util.Abort(_('cannot bisect (no known bad revisions)'))
635 raise util.Abort(_('cannot bisect (no known bad revisions)'))
636 return True
636 return True
637
637
638 # backward compatibility
638 # backward compatibility
639 if rev in "good bad reset init".split():
639 if rev in "good bad reset init".split():
640 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
640 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
641 cmd, rev, extra = rev, extra, None
641 cmd, rev, extra = rev, extra, None
642 if cmd == "good":
642 if cmd == "good":
643 good = True
643 good = True
644 elif cmd == "bad":
644 elif cmd == "bad":
645 bad = True
645 bad = True
646 else:
646 else:
647 reset = True
647 reset = True
648 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
648 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
649 raise util.Abort(_('incompatible arguments'))
649 raise util.Abort(_('incompatible arguments'))
650
650
651 if reset:
651 if reset:
652 p = repo.join("bisect.state")
652 p = repo.join("bisect.state")
653 if os.path.exists(p):
653 if os.path.exists(p):
654 os.unlink(p)
654 os.unlink(p)
655 return
655 return
656
656
657 state = hbisect.load_state(repo)
657 state = hbisect.load_state(repo)
658
658
659 if command:
659 if command:
660 changesets = 1
660 changesets = 1
661 try:
661 try:
662 node = state['current'][0]
662 node = state['current'][0]
663 except LookupError:
663 except LookupError:
664 if noupdate:
664 if noupdate:
665 raise util.Abort(_('current bisect revision is unknown - '
665 raise util.Abort(_('current bisect revision is unknown - '
666 'start a new bisect to fix'))
666 'start a new bisect to fix'))
667 node, p2 = repo.dirstate.parents()
667 node, p2 = repo.dirstate.parents()
668 if p2 != nullid:
668 if p2 != nullid:
669 raise util.Abort(_('current bisect revision is a merge'))
669 raise util.Abort(_('current bisect revision is a merge'))
670 try:
670 try:
671 while changesets:
671 while changesets:
672 # update state
672 # update state
673 state['current'] = [node]
673 state['current'] = [node]
674 hbisect.save_state(repo, state)
674 hbisect.save_state(repo, state)
675 status = util.system(command,
675 status = util.system(command,
676 environ={'HG_NODE': hex(node)},
676 environ={'HG_NODE': hex(node)},
677 out=ui.fout)
677 out=ui.fout)
678 if status == 125:
678 if status == 125:
679 transition = "skip"
679 transition = "skip"
680 elif status == 0:
680 elif status == 0:
681 transition = "good"
681 transition = "good"
682 # status < 0 means process was killed
682 # status < 0 means process was killed
683 elif status == 127:
683 elif status == 127:
684 raise util.Abort(_("failed to execute %s") % command)
684 raise util.Abort(_("failed to execute %s") % command)
685 elif status < 0:
685 elif status < 0:
686 raise util.Abort(_("%s killed") % command)
686 raise util.Abort(_("%s killed") % command)
687 else:
687 else:
688 transition = "bad"
688 transition = "bad"
689 ctx = scmutil.revsingle(repo, rev, node)
689 ctx = scmutil.revsingle(repo, rev, node)
690 rev = None # clear for future iterations
690 rev = None # clear for future iterations
691 state[transition].append(ctx.node())
691 state[transition].append(ctx.node())
692 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
692 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
693 check_state(state, interactive=False)
693 check_state(state, interactive=False)
694 # bisect
694 # bisect
695 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
695 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
696 # update to next check
696 # update to next check
697 node = nodes[0]
697 node = nodes[0]
698 if not noupdate:
698 if not noupdate:
699 cmdutil.bailifchanged(repo)
699 cmdutil.bailifchanged(repo)
700 hg.clean(repo, node, show_stats=False)
700 hg.clean(repo, node, show_stats=False)
701 finally:
701 finally:
702 state['current'] = [node]
702 state['current'] = [node]
703 hbisect.save_state(repo, state)
703 hbisect.save_state(repo, state)
704 print_result(nodes, good)
704 print_result(nodes, good)
705 return
705 return
706
706
707 # update state
707 # update state
708
708
709 if rev:
709 if rev:
710 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
710 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
711 else:
711 else:
712 nodes = [repo.lookup('.')]
712 nodes = [repo.lookup('.')]
713
713
714 if good or bad or skip:
714 if good or bad or skip:
715 if good:
715 if good:
716 state['good'] += nodes
716 state['good'] += nodes
717 elif bad:
717 elif bad:
718 state['bad'] += nodes
718 state['bad'] += nodes
719 elif skip:
719 elif skip:
720 state['skip'] += nodes
720 state['skip'] += nodes
721 hbisect.save_state(repo, state)
721 hbisect.save_state(repo, state)
722
722
723 if not check_state(state):
723 if not check_state(state):
724 return
724 return
725
725
726 # actually bisect
726 # actually bisect
727 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
727 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
728 if extend:
728 if extend:
729 if not changesets:
729 if not changesets:
730 extendnode = extendbisectrange(nodes, good)
730 extendnode = extendbisectrange(nodes, good)
731 if extendnode is not None:
731 if extendnode is not None:
732 ui.write(_("Extending search to changeset %d:%s\n"
732 ui.write(_("Extending search to changeset %d:%s\n"
733 % (extendnode.rev(), extendnode)))
733 % (extendnode.rev(), extendnode)))
734 state['current'] = [extendnode.node()]
734 state['current'] = [extendnode.node()]
735 hbisect.save_state(repo, state)
735 hbisect.save_state(repo, state)
736 if noupdate:
736 if noupdate:
737 return
737 return
738 cmdutil.bailifchanged(repo)
738 cmdutil.bailifchanged(repo)
739 return hg.clean(repo, extendnode.node())
739 return hg.clean(repo, extendnode.node())
740 raise util.Abort(_("nothing to extend"))
740 raise util.Abort(_("nothing to extend"))
741
741
742 if changesets == 0:
742 if changesets == 0:
743 print_result(nodes, good)
743 print_result(nodes, good)
744 else:
744 else:
745 assert len(nodes) == 1 # only a single node can be tested next
745 assert len(nodes) == 1 # only a single node can be tested next
746 node = nodes[0]
746 node = nodes[0]
747 # compute the approximate number of remaining tests
747 # compute the approximate number of remaining tests
748 tests, size = 0, 2
748 tests, size = 0, 2
749 while size <= changesets:
749 while size <= changesets:
750 tests, size = tests + 1, size * 2
750 tests, size = tests + 1, size * 2
751 rev = repo.changelog.rev(node)
751 rev = repo.changelog.rev(node)
752 ui.write(_("Testing changeset %d:%s "
752 ui.write(_("Testing changeset %d:%s "
753 "(%d changesets remaining, ~%d tests)\n")
753 "(%d changesets remaining, ~%d tests)\n")
754 % (rev, short(node), changesets, tests))
754 % (rev, short(node), changesets, tests))
755 state['current'] = [node]
755 state['current'] = [node]
756 hbisect.save_state(repo, state)
756 hbisect.save_state(repo, state)
757 if not noupdate:
757 if not noupdate:
758 cmdutil.bailifchanged(repo)
758 cmdutil.bailifchanged(repo)
759 return hg.clean(repo, node)
759 return hg.clean(repo, node)
760
760
761 @command('bookmarks',
761 @command('bookmarks',
762 [('f', 'force', False, _('force')),
762 [('f', 'force', False, _('force')),
763 ('r', 'rev', '', _('revision'), _('REV')),
763 ('r', 'rev', '', _('revision'), _('REV')),
764 ('d', 'delete', False, _('delete a given bookmark')),
764 ('d', 'delete', False, _('delete a given bookmark')),
765 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
765 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
766 ('i', 'inactive', False, _('mark a bookmark inactive'))],
766 ('i', 'inactive', False, _('mark a bookmark inactive'))],
767 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
767 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
768 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
768 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
769 rename=None, inactive=False):
769 rename=None, inactive=False):
770 '''track a line of development with movable markers
770 '''track a line of development with movable markers
771
771
772 Bookmarks are pointers to certain commits that move when committing.
772 Bookmarks are pointers to certain commits that move when committing.
773 Bookmarks are local. They can be renamed, copied and deleted. It is
773 Bookmarks are local. They can be renamed, copied and deleted. It is
774 possible to use :hg:`merge NAME` to merge from a given bookmark, and
774 possible to use :hg:`merge NAME` to merge from a given bookmark, and
775 :hg:`update NAME` to update to a given bookmark.
775 :hg:`update NAME` to update to a given bookmark.
776
776
777 You can use :hg:`bookmark NAME` to set a bookmark on the working
777 You can use :hg:`bookmark NAME` to set a bookmark on the working
778 directory's parent revision with the given name. If you specify
778 directory's parent revision with the given name. If you specify
779 a revision using -r REV (where REV may be an existing bookmark),
779 a revision using -r REV (where REV may be an existing bookmark),
780 the bookmark is assigned to that revision.
780 the bookmark is assigned to that revision.
781
781
782 Bookmarks can be pushed and pulled between repositories (see :hg:`help
782 Bookmarks can be pushed and pulled between repositories (see :hg:`help
783 push` and :hg:`help pull`). This requires both the local and remote
783 push` and :hg:`help pull`). This requires both the local and remote
784 repositories to support bookmarks. For versions prior to 1.8, this means
784 repositories to support bookmarks. For versions prior to 1.8, this means
785 the bookmarks extension must be enabled.
785 the bookmarks extension must be enabled.
786
786
787 With -i/--inactive, the new bookmark will not be made the active
787 With -i/--inactive, the new bookmark will not be made the active
788 bookmark. If -r/--rev is given, the new bookmark will not be made
788 bookmark. If -r/--rev is given, the new bookmark will not be made
789 active even if -i/--inactive is not given. If no NAME is given, the
789 active even if -i/--inactive is not given. If no NAME is given, the
790 current active bookmark will be marked inactive.
790 current active bookmark will be marked inactive.
791 '''
791 '''
792 hexfn = ui.debugflag and hex or short
792 hexfn = ui.debugflag and hex or short
793 marks = repo._bookmarks
793 marks = repo._bookmarks
794 cur = repo.changectx('.').node()
794 cur = repo.changectx('.').node()
795
795
796 def checkformat(mark):
796 def checkformat(mark):
797 mark = mark.strip()
797 mark = mark.strip()
798 if not mark:
798 if not mark:
799 raise util.Abort(_("bookmark names cannot consist entirely of "
799 raise util.Abort(_("bookmark names cannot consist entirely of "
800 "whitespace"))
800 "whitespace"))
801 scmutil.checknewlabel(repo, mark, 'bookmark')
801 scmutil.checknewlabel(repo, mark, 'bookmark')
802 return mark
802 return mark
803
803
804 def checkconflict(repo, mark, force=False):
804 def checkconflict(repo, mark, force=False):
805 if mark in marks and not force:
805 if mark in marks and not force:
806 raise util.Abort(_("bookmark '%s' already exists "
806 raise util.Abort(_("bookmark '%s' already exists "
807 "(use -f to force)") % mark)
807 "(use -f to force)") % mark)
808 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
808 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
809 and not force):
809 and not force):
810 raise util.Abort(
810 raise util.Abort(
811 _("a bookmark cannot have the name of an existing branch"))
811 _("a bookmark cannot have the name of an existing branch"))
812
812
813 if delete and rename:
813 if delete and rename:
814 raise util.Abort(_("--delete and --rename are incompatible"))
814 raise util.Abort(_("--delete and --rename are incompatible"))
815 if delete and rev:
815 if delete and rev:
816 raise util.Abort(_("--rev is incompatible with --delete"))
816 raise util.Abort(_("--rev is incompatible with --delete"))
817 if rename and rev:
817 if rename and rev:
818 raise util.Abort(_("--rev is incompatible with --rename"))
818 raise util.Abort(_("--rev is incompatible with --rename"))
819 if mark is None and (delete or rev):
819 if mark is None and (delete or rev):
820 raise util.Abort(_("bookmark name required"))
820 raise util.Abort(_("bookmark name required"))
821
821
822 if delete:
822 if delete:
823 if mark not in marks:
823 if mark not in marks:
824 raise util.Abort(_("bookmark '%s' does not exist") % mark)
824 raise util.Abort(_("bookmark '%s' does not exist") % mark)
825 if mark == repo._bookmarkcurrent:
825 if mark == repo._bookmarkcurrent:
826 bookmarks.setcurrent(repo, None)
826 bookmarks.setcurrent(repo, None)
827 del marks[mark]
827 del marks[mark]
828 marks.write()
828 marks.write()
829
829
830 elif rename:
830 elif rename:
831 if mark is None:
831 if mark is None:
832 raise util.Abort(_("new bookmark name required"))
832 raise util.Abort(_("new bookmark name required"))
833 mark = checkformat(mark)
833 mark = checkformat(mark)
834 if rename not in marks:
834 if rename not in marks:
835 raise util.Abort(_("bookmark '%s' does not exist") % rename)
835 raise util.Abort(_("bookmark '%s' does not exist") % rename)
836 checkconflict(repo, mark, force)
836 checkconflict(repo, mark, force)
837 marks[mark] = marks[rename]
837 marks[mark] = marks[rename]
838 if repo._bookmarkcurrent == rename and not inactive:
838 if repo._bookmarkcurrent == rename and not inactive:
839 bookmarks.setcurrent(repo, mark)
839 bookmarks.setcurrent(repo, mark)
840 del marks[rename]
840 del marks[rename]
841 marks.write()
841 marks.write()
842
842
843 elif mark is not None:
843 elif mark is not None:
844 mark = checkformat(mark)
844 mark = checkformat(mark)
845 if inactive and mark == repo._bookmarkcurrent:
845 if inactive and mark == repo._bookmarkcurrent:
846 bookmarks.setcurrent(repo, None)
846 bookmarks.setcurrent(repo, None)
847 return
847 return
848 checkconflict(repo, mark, force)
848 checkconflict(repo, mark, force)
849 if rev:
849 if rev:
850 marks[mark] = scmutil.revsingle(repo, rev).node()
850 marks[mark] = scmutil.revsingle(repo, rev).node()
851 else:
851 else:
852 marks[mark] = cur
852 marks[mark] = cur
853 if not inactive and cur == marks[mark]:
853 if not inactive and cur == marks[mark]:
854 bookmarks.setcurrent(repo, mark)
854 bookmarks.setcurrent(repo, mark)
855 marks.write()
855 marks.write()
856
856
857 # Same message whether trying to deactivate the current bookmark (-i
857 # Same message whether trying to deactivate the current bookmark (-i
858 # with no NAME) or listing bookmarks
858 # with no NAME) or listing bookmarks
859 elif len(marks) == 0:
859 elif len(marks) == 0:
860 ui.status(_("no bookmarks set\n"))
860 ui.status(_("no bookmarks set\n"))
861
861
862 elif inactive:
862 elif inactive:
863 if not repo._bookmarkcurrent:
863 if not repo._bookmarkcurrent:
864 ui.status(_("no active bookmark\n"))
864 ui.status(_("no active bookmark\n"))
865 else:
865 else:
866 bookmarks.setcurrent(repo, None)
866 bookmarks.setcurrent(repo, None)
867
867
868 else: # show bookmarks
868 else: # show bookmarks
869 for bmark, n in sorted(marks.iteritems()):
869 for bmark, n in sorted(marks.iteritems()):
870 current = repo._bookmarkcurrent
870 current = repo._bookmarkcurrent
871 if bmark == current and n == cur:
871 if bmark == current and n == cur:
872 prefix, label = '*', 'bookmarks.current'
872 prefix, label = '*', 'bookmarks.current'
873 else:
873 else:
874 prefix, label = ' ', ''
874 prefix, label = ' ', ''
875
875
876 if ui.quiet:
876 if ui.quiet:
877 ui.write("%s\n" % bmark, label=label)
877 ui.write("%s\n" % bmark, label=label)
878 else:
878 else:
879 ui.write(" %s %-25s %d:%s\n" % (
879 ui.write(" %s %-25s %d:%s\n" % (
880 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
880 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
881 label=label)
881 label=label)
882
882
883 @command('branch',
883 @command('branch',
884 [('f', 'force', None,
884 [('f', 'force', None,
885 _('set branch name even if it shadows an existing branch')),
885 _('set branch name even if it shadows an existing branch')),
886 ('C', 'clean', None, _('reset branch name to parent branch name'))],
886 ('C', 'clean', None, _('reset branch name to parent branch name'))],
887 _('[-fC] [NAME]'))
887 _('[-fC] [NAME]'))
888 def branch(ui, repo, label=None, **opts):
888 def branch(ui, repo, label=None, **opts):
889 """set or show the current branch name
889 """set or show the current branch name
890
890
891 .. note::
891 .. note::
892 Branch names are permanent and global. Use :hg:`bookmark` to create a
892 Branch names are permanent and global. Use :hg:`bookmark` to create a
893 light-weight bookmark instead. See :hg:`help glossary` for more
893 light-weight bookmark instead. See :hg:`help glossary` for more
894 information about named branches and bookmarks.
894 information about named branches and bookmarks.
895
895
896 With no argument, show the current branch name. With one argument,
896 With no argument, show the current branch name. With one argument,
897 set the working directory branch name (the branch will not exist
897 set the working directory branch name (the branch will not exist
898 in the repository until the next commit). Standard practice
898 in the repository until the next commit). Standard practice
899 recommends that primary development take place on the 'default'
899 recommends that primary development take place on the 'default'
900 branch.
900 branch.
901
901
902 Unless -f/--force is specified, branch will not let you set a
902 Unless -f/--force is specified, branch will not let you set a
903 branch name that already exists, even if it's inactive.
903 branch name that already exists, even if it's inactive.
904
904
905 Use -C/--clean to reset the working directory branch to that of
905 Use -C/--clean to reset the working directory branch to that of
906 the parent of the working directory, negating a previous branch
906 the parent of the working directory, negating a previous branch
907 change.
907 change.
908
908
909 Use the command :hg:`update` to switch to an existing branch. Use
909 Use the command :hg:`update` to switch to an existing branch. Use
910 :hg:`commit --close-branch` to mark this branch as closed.
910 :hg:`commit --close-branch` to mark this branch as closed.
911
911
912 Returns 0 on success.
912 Returns 0 on success.
913 """
913 """
914 if not opts.get('clean') and not label:
914 if not opts.get('clean') and not label:
915 ui.write("%s\n" % repo.dirstate.branch())
915 ui.write("%s\n" % repo.dirstate.branch())
916 return
916 return
917
917
918 wlock = repo.wlock()
918 wlock = repo.wlock()
919 try:
919 try:
920 if opts.get('clean'):
920 if opts.get('clean'):
921 label = repo[None].p1().branch()
921 label = repo[None].p1().branch()
922 repo.dirstate.setbranch(label)
922 repo.dirstate.setbranch(label)
923 ui.status(_('reset working directory to branch %s\n') % label)
923 ui.status(_('reset working directory to branch %s\n') % label)
924 elif label:
924 elif label:
925 if not opts.get('force') and label in repo.branchmap():
925 if not opts.get('force') and label in repo.branchmap():
926 if label not in [p.branch() for p in repo.parents()]:
926 if label not in [p.branch() for p in repo.parents()]:
927 raise util.Abort(_('a branch of the same name already'
927 raise util.Abort(_('a branch of the same name already'
928 ' exists'),
928 ' exists'),
929 # i18n: "it" refers to an existing branch
929 # i18n: "it" refers to an existing branch
930 hint=_("use 'hg update' to switch to it"))
930 hint=_("use 'hg update' to switch to it"))
931 scmutil.checknewlabel(repo, label, 'branch')
931 scmutil.checknewlabel(repo, label, 'branch')
932 repo.dirstate.setbranch(label)
932 repo.dirstate.setbranch(label)
933 ui.status(_('marked working directory as branch %s\n') % label)
933 ui.status(_('marked working directory as branch %s\n') % label)
934 ui.status(_('(branches are permanent and global, '
934 ui.status(_('(branches are permanent and global, '
935 'did you want a bookmark?)\n'))
935 'did you want a bookmark?)\n'))
936 finally:
936 finally:
937 wlock.release()
937 wlock.release()
938
938
939 @command('branches',
939 @command('branches',
940 [('a', 'active', False, _('show only branches that have unmerged heads')),
940 [('a', 'active', False, _('show only branches that have unmerged heads')),
941 ('c', 'closed', False, _('show normal and closed branches'))],
941 ('c', 'closed', False, _('show normal and closed branches'))],
942 _('[-ac]'))
942 _('[-ac]'))
943 def branches(ui, repo, active=False, closed=False):
943 def branches(ui, repo, active=False, closed=False):
944 """list repository named branches
944 """list repository named branches
945
945
946 List the repository's named branches, indicating which ones are
946 List the repository's named branches, indicating which ones are
947 inactive. If -c/--closed is specified, also list branches which have
947 inactive. If -c/--closed is specified, also list branches which have
948 been marked closed (see :hg:`commit --close-branch`).
948 been marked closed (see :hg:`commit --close-branch`).
949
949
950 If -a/--active is specified, only show active branches. A branch
950 If -a/--active is specified, only show active branches. A branch
951 is considered active if it contains repository heads.
951 is considered active if it contains repository heads.
952
952
953 Use the command :hg:`update` to switch to an existing branch.
953 Use the command :hg:`update` to switch to an existing branch.
954
954
955 Returns 0.
955 Returns 0.
956 """
956 """
957
957
958 hexfunc = ui.debugflag and hex or short
958 hexfunc = ui.debugflag and hex or short
959
959
960 activebranches = set([repo[n].branch() for n in repo.heads()])
960 activebranches = set([repo[n].branch() for n in repo.heads()])
961 branches = []
961 branches = []
962 for tag, heads in repo.branchmap().iteritems():
962 for tag, heads in repo.branchmap().iteritems():
963 for h in reversed(heads):
963 for h in reversed(heads):
964 ctx = repo[h]
964 ctx = repo[h]
965 isopen = not ctx.closesbranch()
965 isopen = not ctx.closesbranch()
966 if isopen:
966 if isopen:
967 tip = ctx
967 tip = ctx
968 break
968 break
969 else:
969 else:
970 tip = repo[heads[-1]]
970 tip = repo[heads[-1]]
971 isactive = tag in activebranches and isopen
971 isactive = tag in activebranches and isopen
972 branches.append((tip, isactive, isopen))
972 branches.append((tip, isactive, isopen))
973 branches.sort(key=lambda i: (i[1], i[0].rev(), i[0].branch(), i[2]),
973 branches.sort(key=lambda i: (i[1], i[0].rev(), i[0].branch(), i[2]),
974 reverse=True)
974 reverse=True)
975
975
976 for ctx, isactive, isopen in branches:
976 for ctx, isactive, isopen in branches:
977 if (not active) or isactive:
977 if (not active) or isactive:
978 if isactive:
978 if isactive:
979 label = 'branches.active'
979 label = 'branches.active'
980 notice = ''
980 notice = ''
981 elif not isopen:
981 elif not isopen:
982 if not closed:
982 if not closed:
983 continue
983 continue
984 label = 'branches.closed'
984 label = 'branches.closed'
985 notice = _(' (closed)')
985 notice = _(' (closed)')
986 else:
986 else:
987 label = 'branches.inactive'
987 label = 'branches.inactive'
988 notice = _(' (inactive)')
988 notice = _(' (inactive)')
989 if ctx.branch() == repo.dirstate.branch():
989 if ctx.branch() == repo.dirstate.branch():
990 label = 'branches.current'
990 label = 'branches.current'
991 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(ctx.branch()))
991 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(ctx.branch()))
992 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
992 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
993 'log.changeset changeset.%s' % ctx.phasestr())
993 'log.changeset changeset.%s' % ctx.phasestr())
994 tag = ui.label(ctx.branch(), label)
994 tag = ui.label(ctx.branch(), label)
995 if ui.quiet:
995 if ui.quiet:
996 ui.write("%s\n" % tag)
996 ui.write("%s\n" % tag)
997 else:
997 else:
998 ui.write("%s %s%s\n" % (tag, rev, notice))
998 ui.write("%s %s%s\n" % (tag, rev, notice))
999
999
1000 @command('bundle',
1000 @command('bundle',
1001 [('f', 'force', None, _('run even when the destination is unrelated')),
1001 [('f', 'force', None, _('run even when the destination is unrelated')),
1002 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1002 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1003 _('REV')),
1003 _('REV')),
1004 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1004 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1005 _('BRANCH')),
1005 _('BRANCH')),
1006 ('', 'base', [],
1006 ('', 'base', [],
1007 _('a base changeset assumed to be available at the destination'),
1007 _('a base changeset assumed to be available at the destination'),
1008 _('REV')),
1008 _('REV')),
1009 ('a', 'all', None, _('bundle all changesets in the repository')),
1009 ('a', 'all', None, _('bundle all changesets in the repository')),
1010 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1010 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1011 ] + remoteopts,
1011 ] + remoteopts,
1012 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1012 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1013 def bundle(ui, repo, fname, dest=None, **opts):
1013 def bundle(ui, repo, fname, dest=None, **opts):
1014 """create a changegroup file
1014 """create a changegroup file
1015
1015
1016 Generate a compressed changegroup file collecting changesets not
1016 Generate a compressed changegroup file collecting changesets not
1017 known to be in another repository.
1017 known to be in another repository.
1018
1018
1019 If you omit the destination repository, then hg assumes the
1019 If you omit the destination repository, then hg assumes the
1020 destination will have all the nodes you specify with --base
1020 destination will have all the nodes you specify with --base
1021 parameters. To create a bundle containing all changesets, use
1021 parameters. To create a bundle containing all changesets, use
1022 -a/--all (or --base null).
1022 -a/--all (or --base null).
1023
1023
1024 You can change compression method with the -t/--type option.
1024 You can change compression method with the -t/--type option.
1025 The available compression methods are: none, bzip2, and
1025 The available compression methods are: none, bzip2, and
1026 gzip (by default, bundles are compressed using bzip2).
1026 gzip (by default, bundles are compressed using bzip2).
1027
1027
1028 The bundle file can then be transferred using conventional means
1028 The bundle file can then be transferred using conventional means
1029 and applied to another repository with the unbundle or pull
1029 and applied to another repository with the unbundle or pull
1030 command. This is useful when direct push and pull are not
1030 command. This is useful when direct push and pull are not
1031 available or when exporting an entire repository is undesirable.
1031 available or when exporting an entire repository is undesirable.
1032
1032
1033 Applying bundles preserves all changeset contents including
1033 Applying bundles preserves all changeset contents including
1034 permissions, copy/rename information, and revision history.
1034 permissions, copy/rename information, and revision history.
1035
1035
1036 Returns 0 on success, 1 if no changes found.
1036 Returns 0 on success, 1 if no changes found.
1037 """
1037 """
1038 revs = None
1038 revs = None
1039 if 'rev' in opts:
1039 if 'rev' in opts:
1040 revs = scmutil.revrange(repo, opts['rev'])
1040 revs = scmutil.revrange(repo, opts['rev'])
1041
1041
1042 bundletype = opts.get('type', 'bzip2').lower()
1042 bundletype = opts.get('type', 'bzip2').lower()
1043 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1043 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1044 bundletype = btypes.get(bundletype)
1044 bundletype = btypes.get(bundletype)
1045 if bundletype not in changegroup.bundletypes:
1045 if bundletype not in changegroup.bundletypes:
1046 raise util.Abort(_('unknown bundle type specified with --type'))
1046 raise util.Abort(_('unknown bundle type specified with --type'))
1047
1047
1048 if opts.get('all'):
1048 if opts.get('all'):
1049 base = ['null']
1049 base = ['null']
1050 else:
1050 else:
1051 base = scmutil.revrange(repo, opts.get('base'))
1051 base = scmutil.revrange(repo, opts.get('base'))
1052 if base:
1052 if base:
1053 if dest:
1053 if dest:
1054 raise util.Abort(_("--base is incompatible with specifying "
1054 raise util.Abort(_("--base is incompatible with specifying "
1055 "a destination"))
1055 "a destination"))
1056 common = [repo.lookup(rev) for rev in base]
1056 common = [repo.lookup(rev) for rev in base]
1057 heads = revs and map(repo.lookup, revs) or revs
1057 heads = revs and map(repo.lookup, revs) or revs
1058 cg = repo.getbundle('bundle', heads=heads, common=common)
1058 cg = repo.getbundle('bundle', heads=heads, common=common)
1059 outgoing = None
1059 outgoing = None
1060 else:
1060 else:
1061 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1061 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1062 dest, branches = hg.parseurl(dest, opts.get('branch'))
1062 dest, branches = hg.parseurl(dest, opts.get('branch'))
1063 other = hg.peer(repo, opts, dest)
1063 other = hg.peer(repo, opts, dest)
1064 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1064 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
1065 heads = revs and map(repo.lookup, revs) or revs
1065 heads = revs and map(repo.lookup, revs) or revs
1066 outgoing = discovery.findcommonoutgoing(repo, other,
1066 outgoing = discovery.findcommonoutgoing(repo, other,
1067 onlyheads=heads,
1067 onlyheads=heads,
1068 force=opts.get('force'),
1068 force=opts.get('force'),
1069 portable=True)
1069 portable=True)
1070 cg = repo.getlocalbundle('bundle', outgoing)
1070 cg = repo.getlocalbundle('bundle', outgoing)
1071 if not cg:
1071 if not cg:
1072 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1072 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1073 return 1
1073 return 1
1074
1074
1075 changegroup.writebundle(cg, fname, bundletype)
1075 changegroup.writebundle(cg, fname, bundletype)
1076
1076
1077 @command('cat',
1077 @command('cat',
1078 [('o', 'output', '',
1078 [('o', 'output', '',
1079 _('print output to file with formatted name'), _('FORMAT')),
1079 _('print output to file with formatted name'), _('FORMAT')),
1080 ('r', 'rev', '', _('print the given revision'), _('REV')),
1080 ('r', 'rev', '', _('print the given revision'), _('REV')),
1081 ('', 'decode', None, _('apply any matching decode filter')),
1081 ('', 'decode', None, _('apply any matching decode filter')),
1082 ] + walkopts,
1082 ] + walkopts,
1083 _('[OPTION]... FILE...'))
1083 _('[OPTION]... FILE...'))
1084 def cat(ui, repo, file1, *pats, **opts):
1084 def cat(ui, repo, file1, *pats, **opts):
1085 """output the current or given revision of files
1085 """output the current or given revision of files
1086
1086
1087 Print the specified files as they were at the given revision. If
1087 Print the specified files as they were at the given revision. If
1088 no revision is given, the parent of the working directory is used,
1088 no revision is given, the parent of the working directory is used,
1089 or tip if no revision is checked out.
1089 or tip if no revision is checked out.
1090
1090
1091 Output may be to a file, in which case the name of the file is
1091 Output may be to a file, in which case the name of the file is
1092 given using a format string. The formatting rules are the same as
1092 given using a format string. The formatting rules are the same as
1093 for the export command, with the following additions:
1093 for the export command, with the following additions:
1094
1094
1095 :``%s``: basename of file being printed
1095 :``%s``: basename of file being printed
1096 :``%d``: dirname of file being printed, or '.' if in repository root
1096 :``%d``: dirname of file being printed, or '.' if in repository root
1097 :``%p``: root-relative path name of file being printed
1097 :``%p``: root-relative path name of file being printed
1098
1098
1099 Returns 0 on success.
1099 Returns 0 on success.
1100 """
1100 """
1101 ctx = scmutil.revsingle(repo, opts.get('rev'))
1101 ctx = scmutil.revsingle(repo, opts.get('rev'))
1102 err = 1
1102 err = 1
1103 m = scmutil.match(ctx, (file1,) + pats, opts)
1103 m = scmutil.match(ctx, (file1,) + pats, opts)
1104 for abs in ctx.walk(m):
1104 for abs in ctx.walk(m):
1105 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1105 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1106 pathname=abs)
1106 pathname=abs)
1107 data = ctx[abs].data()
1107 data = ctx[abs].data()
1108 if opts.get('decode'):
1108 if opts.get('decode'):
1109 data = repo.wwritedata(abs, data)
1109 data = repo.wwritedata(abs, data)
1110 fp.write(data)
1110 fp.write(data)
1111 fp.close()
1111 fp.close()
1112 err = 0
1112 err = 0
1113 return err
1113 return err
1114
1114
1115 @command('^clone',
1115 @command('^clone',
1116 [('U', 'noupdate', None,
1116 [('U', 'noupdate', None,
1117 _('the clone will include an empty working copy (only a repository)')),
1117 _('the clone will include an empty working copy (only a repository)')),
1118 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1118 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1119 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1119 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1120 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1120 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1121 ('', 'pull', None, _('use pull protocol to copy metadata')),
1121 ('', 'pull', None, _('use pull protocol to copy metadata')),
1122 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1122 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1123 ] + remoteopts,
1123 ] + remoteopts,
1124 _('[OPTION]... SOURCE [DEST]'))
1124 _('[OPTION]... SOURCE [DEST]'))
1125 def clone(ui, source, dest=None, **opts):
1125 def clone(ui, source, dest=None, **opts):
1126 """make a copy of an existing repository
1126 """make a copy of an existing repository
1127
1127
1128 Create a copy of an existing repository in a new directory.
1128 Create a copy of an existing repository in a new directory.
1129
1129
1130 If no destination directory name is specified, it defaults to the
1130 If no destination directory name is specified, it defaults to the
1131 basename of the source.
1131 basename of the source.
1132
1132
1133 The location of the source is added to the new repository's
1133 The location of the source is added to the new repository's
1134 ``.hg/hgrc`` file, as the default to be used for future pulls.
1134 ``.hg/hgrc`` file, as the default to be used for future pulls.
1135
1135
1136 Only local paths and ``ssh://`` URLs are supported as
1136 Only local paths and ``ssh://`` URLs are supported as
1137 destinations. For ``ssh://`` destinations, no working directory or
1137 destinations. For ``ssh://`` destinations, no working directory or
1138 ``.hg/hgrc`` will be created on the remote side.
1138 ``.hg/hgrc`` will be created on the remote side.
1139
1139
1140 To pull only a subset of changesets, specify one or more revisions
1140 To pull only a subset of changesets, specify one or more revisions
1141 identifiers with -r/--rev or branches with -b/--branch. The
1141 identifiers with -r/--rev or branches with -b/--branch. The
1142 resulting clone will contain only the specified changesets and
1142 resulting clone will contain only the specified changesets and
1143 their ancestors. These options (or 'clone src#rev dest') imply
1143 their ancestors. These options (or 'clone src#rev dest') imply
1144 --pull, even for local source repositories. Note that specifying a
1144 --pull, even for local source repositories. Note that specifying a
1145 tag will include the tagged changeset but not the changeset
1145 tag will include the tagged changeset but not the changeset
1146 containing the tag.
1146 containing the tag.
1147
1147
1148 To check out a particular version, use -u/--update, or
1148 To check out a particular version, use -u/--update, or
1149 -U/--noupdate to create a clone with no working directory.
1149 -U/--noupdate to create a clone with no working directory.
1150
1150
1151 .. container:: verbose
1151 .. container:: verbose
1152
1152
1153 For efficiency, hardlinks are used for cloning whenever the
1153 For efficiency, hardlinks are used for cloning whenever the
1154 source and destination are on the same filesystem (note this
1154 source and destination are on the same filesystem (note this
1155 applies only to the repository data, not to the working
1155 applies only to the repository data, not to the working
1156 directory). Some filesystems, such as AFS, implement hardlinking
1156 directory). Some filesystems, such as AFS, implement hardlinking
1157 incorrectly, but do not report errors. In these cases, use the
1157 incorrectly, but do not report errors. In these cases, use the
1158 --pull option to avoid hardlinking.
1158 --pull option to avoid hardlinking.
1159
1159
1160 In some cases, you can clone repositories and the working
1160 In some cases, you can clone repositories and the working
1161 directory using full hardlinks with ::
1161 directory using full hardlinks with ::
1162
1162
1163 $ cp -al REPO REPOCLONE
1163 $ cp -al REPO REPOCLONE
1164
1164
1165 This is the fastest way to clone, but it is not always safe. The
1165 This is the fastest way to clone, but it is not always safe. The
1166 operation is not atomic (making sure REPO is not modified during
1166 operation is not atomic (making sure REPO is not modified during
1167 the operation is up to you) and you have to make sure your
1167 the operation is up to you) and you have to make sure your
1168 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1168 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1169 so). Also, this is not compatible with certain extensions that
1169 so). Also, this is not compatible with certain extensions that
1170 place their metadata under the .hg directory, such as mq.
1170 place their metadata under the .hg directory, such as mq.
1171
1171
1172 Mercurial will update the working directory to the first applicable
1172 Mercurial will update the working directory to the first applicable
1173 revision from this list:
1173 revision from this list:
1174
1174
1175 a) null if -U or the source repository has no changesets
1175 a) null if -U or the source repository has no changesets
1176 b) if -u . and the source repository is local, the first parent of
1176 b) if -u . and the source repository is local, the first parent of
1177 the source repository's working directory
1177 the source repository's working directory
1178 c) the changeset specified with -u (if a branch name, this means the
1178 c) the changeset specified with -u (if a branch name, this means the
1179 latest head of that branch)
1179 latest head of that branch)
1180 d) the changeset specified with -r
1180 d) the changeset specified with -r
1181 e) the tipmost head specified with -b
1181 e) the tipmost head specified with -b
1182 f) the tipmost head specified with the url#branch source syntax
1182 f) the tipmost head specified with the url#branch source syntax
1183 g) the tipmost head of the default branch
1183 g) the tipmost head of the default branch
1184 h) tip
1184 h) tip
1185
1185
1186 Examples:
1186 Examples:
1187
1187
1188 - clone a remote repository to a new directory named hg/::
1188 - clone a remote repository to a new directory named hg/::
1189
1189
1190 hg clone http://selenic.com/hg
1190 hg clone http://selenic.com/hg
1191
1191
1192 - create a lightweight local clone::
1192 - create a lightweight local clone::
1193
1193
1194 hg clone project/ project-feature/
1194 hg clone project/ project-feature/
1195
1195
1196 - clone from an absolute path on an ssh server (note double-slash)::
1196 - clone from an absolute path on an ssh server (note double-slash)::
1197
1197
1198 hg clone ssh://user@server//home/projects/alpha/
1198 hg clone ssh://user@server//home/projects/alpha/
1199
1199
1200 - do a high-speed clone over a LAN while checking out a
1200 - do a high-speed clone over a LAN while checking out a
1201 specified version::
1201 specified version::
1202
1202
1203 hg clone --uncompressed http://server/repo -u 1.5
1203 hg clone --uncompressed http://server/repo -u 1.5
1204
1204
1205 - create a repository without changesets after a particular revision::
1205 - create a repository without changesets after a particular revision::
1206
1206
1207 hg clone -r 04e544 experimental/ good/
1207 hg clone -r 04e544 experimental/ good/
1208
1208
1209 - clone (and track) a particular named branch::
1209 - clone (and track) a particular named branch::
1210
1210
1211 hg clone http://selenic.com/hg#stable
1211 hg clone http://selenic.com/hg#stable
1212
1212
1213 See :hg:`help urls` for details on specifying URLs.
1213 See :hg:`help urls` for details on specifying URLs.
1214
1214
1215 Returns 0 on success.
1215 Returns 0 on success.
1216 """
1216 """
1217 if opts.get('noupdate') and opts.get('updaterev'):
1217 if opts.get('noupdate') and opts.get('updaterev'):
1218 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1218 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1219
1219
1220 r = hg.clone(ui, opts, source, dest,
1220 r = hg.clone(ui, opts, source, dest,
1221 pull=opts.get('pull'),
1221 pull=opts.get('pull'),
1222 stream=opts.get('uncompressed'),
1222 stream=opts.get('uncompressed'),
1223 rev=opts.get('rev'),
1223 rev=opts.get('rev'),
1224 update=opts.get('updaterev') or not opts.get('noupdate'),
1224 update=opts.get('updaterev') or not opts.get('noupdate'),
1225 branch=opts.get('branch'))
1225 branch=opts.get('branch'))
1226
1226
1227 return r is None
1227 return r is None
1228
1228
1229 @command('^commit|ci',
1229 @command('^commit|ci',
1230 [('A', 'addremove', None,
1230 [('A', 'addremove', None,
1231 _('mark new/missing files as added/removed before committing')),
1231 _('mark new/missing files as added/removed before committing')),
1232 ('', 'close-branch', None,
1232 ('', 'close-branch', None,
1233 _('mark a branch as closed, hiding it from the branch list')),
1233 _('mark a branch as closed, hiding it from the branch list')),
1234 ('', 'amend', None, _('amend the parent of the working dir')),
1234 ('', 'amend', None, _('amend the parent of the working dir')),
1235 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1235 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1236 _('[OPTION]... [FILE]...'))
1236 _('[OPTION]... [FILE]...'))
1237 def commit(ui, repo, *pats, **opts):
1237 def commit(ui, repo, *pats, **opts):
1238 """commit the specified files or all outstanding changes
1238 """commit the specified files or all outstanding changes
1239
1239
1240 Commit changes to the given files into the repository. Unlike a
1240 Commit changes to the given files into the repository. Unlike a
1241 centralized SCM, this operation is a local operation. See
1241 centralized SCM, this operation is a local operation. See
1242 :hg:`push` for a way to actively distribute your changes.
1242 :hg:`push` for a way to actively distribute your changes.
1243
1243
1244 If a list of files is omitted, all changes reported by :hg:`status`
1244 If a list of files is omitted, all changes reported by :hg:`status`
1245 will be committed.
1245 will be committed.
1246
1246
1247 If you are committing the result of a merge, do not provide any
1247 If you are committing the result of a merge, do not provide any
1248 filenames or -I/-X filters.
1248 filenames or -I/-X filters.
1249
1249
1250 If no commit message is specified, Mercurial starts your
1250 If no commit message is specified, Mercurial starts your
1251 configured editor where you can enter a message. In case your
1251 configured editor where you can enter a message. In case your
1252 commit fails, you will find a backup of your message in
1252 commit fails, you will find a backup of your message in
1253 ``.hg/last-message.txt``.
1253 ``.hg/last-message.txt``.
1254
1254
1255 The --amend flag can be used to amend the parent of the
1255 The --amend flag can be used to amend the parent of the
1256 working directory with a new commit that contains the changes
1256 working directory with a new commit that contains the changes
1257 in the parent in addition to those currently reported by :hg:`status`,
1257 in the parent in addition to those currently reported by :hg:`status`,
1258 if there are any. The old commit is stored in a backup bundle in
1258 if there are any. The old commit is stored in a backup bundle in
1259 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1259 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1260 on how to restore it).
1260 on how to restore it).
1261
1261
1262 Message, user and date are taken from the amended commit unless
1262 Message, user and date are taken from the amended commit unless
1263 specified. When a message isn't specified on the command line,
1263 specified. When a message isn't specified on the command line,
1264 the editor will open with the message of the amended commit.
1264 the editor will open with the message of the amended commit.
1265
1265
1266 It is not possible to amend public changesets (see :hg:`help phases`)
1266 It is not possible to amend public changesets (see :hg:`help phases`)
1267 or changesets that have children.
1267 or changesets that have children.
1268
1268
1269 See :hg:`help dates` for a list of formats valid for -d/--date.
1269 See :hg:`help dates` for a list of formats valid for -d/--date.
1270
1270
1271 Returns 0 on success, 1 if nothing changed.
1271 Returns 0 on success, 1 if nothing changed.
1272 """
1272 """
1273 if opts.get('subrepos'):
1273 if opts.get('subrepos'):
1274 # Let --subrepos on the command line override config setting.
1274 # Let --subrepos on the command line override config setting.
1275 ui.setconfig('ui', 'commitsubrepos', True)
1275 ui.setconfig('ui', 'commitsubrepos', True)
1276
1276
1277 extra = {}
1277 extra = {}
1278 if opts.get('close_branch'):
1278 if opts.get('close_branch'):
1279 if repo['.'].node() not in repo.branchheads():
1279 if repo['.'].node() not in repo.branchheads():
1280 # The topo heads set is included in the branch heads set of the
1280 # The topo heads set is included in the branch heads set of the
1281 # current branch, so it's sufficient to test branchheads
1281 # current branch, so it's sufficient to test branchheads
1282 raise util.Abort(_('can only close branch heads'))
1282 raise util.Abort(_('can only close branch heads'))
1283 extra['close'] = 1
1283 extra['close'] = 1
1284
1284
1285 branch = repo[None].branch()
1285 branch = repo[None].branch()
1286 bheads = repo.branchheads(branch)
1286 bheads = repo.branchheads(branch)
1287
1287
1288 if opts.get('amend'):
1288 if opts.get('amend'):
1289 if ui.configbool('ui', 'commitsubrepos'):
1289 if ui.configbool('ui', 'commitsubrepos'):
1290 raise util.Abort(_('cannot amend recursively'))
1290 raise util.Abort(_('cannot amend recursively'))
1291
1291
1292 old = repo['.']
1292 old = repo['.']
1293 if old.phase() == phases.public:
1293 if old.phase() == phases.public:
1294 raise util.Abort(_('cannot amend public changesets'))
1294 raise util.Abort(_('cannot amend public changesets'))
1295 if len(old.parents()) > 1:
1295 if len(old.parents()) > 1:
1296 raise util.Abort(_('cannot amend merge changesets'))
1296 raise util.Abort(_('cannot amend merge changesets'))
1297 if len(repo[None].parents()) > 1:
1297 if len(repo[None].parents()) > 1:
1298 raise util.Abort(_('cannot amend while merging'))
1298 raise util.Abort(_('cannot amend while merging'))
1299 if old.children():
1299 if old.children():
1300 raise util.Abort(_('cannot amend changeset with children'))
1300 raise util.Abort(_('cannot amend changeset with children'))
1301
1301
1302 e = cmdutil.commiteditor
1302 e = cmdutil.commiteditor
1303 if opts.get('force_editor'):
1303 if opts.get('force_editor'):
1304 e = cmdutil.commitforceeditor
1304 e = cmdutil.commitforceeditor
1305
1305
1306 def commitfunc(ui, repo, message, match, opts):
1306 def commitfunc(ui, repo, message, match, opts):
1307 editor = e
1307 editor = e
1308 # message contains text from -m or -l, if it's empty,
1308 # message contains text from -m or -l, if it's empty,
1309 # open the editor with the old message
1309 # open the editor with the old message
1310 if not message:
1310 if not message:
1311 message = old.description()
1311 message = old.description()
1312 editor = cmdutil.commitforceeditor
1312 editor = cmdutil.commitforceeditor
1313 return repo.commit(message,
1313 return repo.commit(message,
1314 opts.get('user') or old.user(),
1314 opts.get('user') or old.user(),
1315 opts.get('date') or old.date(),
1315 opts.get('date') or old.date(),
1316 match,
1316 match,
1317 editor=editor,
1317 editor=editor,
1318 extra=extra)
1318 extra=extra)
1319
1319
1320 current = repo._bookmarkcurrent
1320 current = repo._bookmarkcurrent
1321 marks = old.bookmarks()
1321 marks = old.bookmarks()
1322 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1322 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1323 if node == old.node():
1323 if node == old.node():
1324 ui.status(_("nothing changed\n"))
1324 ui.status(_("nothing changed\n"))
1325 return 1
1325 return 1
1326 elif marks:
1326 elif marks:
1327 ui.debug('moving bookmarks %r from %s to %s\n' %
1327 ui.debug('moving bookmarks %r from %s to %s\n' %
1328 (marks, old.hex(), hex(node)))
1328 (marks, old.hex(), hex(node)))
1329 newmarks = repo._bookmarks
1329 newmarks = repo._bookmarks
1330 for bm in marks:
1330 for bm in marks:
1331 newmarks[bm] = node
1331 newmarks[bm] = node
1332 if bm == current:
1332 if bm == current:
1333 bookmarks.setcurrent(repo, bm)
1333 bookmarks.setcurrent(repo, bm)
1334 newmarks.write()
1334 newmarks.write()
1335 else:
1335 else:
1336 e = cmdutil.commiteditor
1336 e = cmdutil.commiteditor
1337 if opts.get('force_editor'):
1337 if opts.get('force_editor'):
1338 e = cmdutil.commitforceeditor
1338 e = cmdutil.commitforceeditor
1339
1339
1340 def commitfunc(ui, repo, message, match, opts):
1340 def commitfunc(ui, repo, message, match, opts):
1341 return repo.commit(message, opts.get('user'), opts.get('date'),
1341 return repo.commit(message, opts.get('user'), opts.get('date'),
1342 match, editor=e, extra=extra)
1342 match, editor=e, extra=extra)
1343
1343
1344 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1344 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1345
1345
1346 if not node:
1346 if not node:
1347 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1347 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1348 if stat[3]:
1348 if stat[3]:
1349 ui.status(_("nothing changed (%d missing files, see "
1349 ui.status(_("nothing changed (%d missing files, see "
1350 "'hg status')\n") % len(stat[3]))
1350 "'hg status')\n") % len(stat[3]))
1351 else:
1351 else:
1352 ui.status(_("nothing changed\n"))
1352 ui.status(_("nothing changed\n"))
1353 return 1
1353 return 1
1354
1354
1355 ctx = repo[node]
1355 ctx = repo[node]
1356 parents = ctx.parents()
1356 parents = ctx.parents()
1357
1357
1358 if (not opts.get('amend') and bheads and node not in bheads and not
1358 if (not opts.get('amend') and bheads and node not in bheads and not
1359 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1359 [x for x in parents if x.node() in bheads and x.branch() == branch]):
1360 ui.status(_('created new head\n'))
1360 ui.status(_('created new head\n'))
1361 # The message is not printed for initial roots. For the other
1361 # The message is not printed for initial roots. For the other
1362 # changesets, it is printed in the following situations:
1362 # changesets, it is printed in the following situations:
1363 #
1363 #
1364 # Par column: for the 2 parents with ...
1364 # Par column: for the 2 parents with ...
1365 # N: null or no parent
1365 # N: null or no parent
1366 # B: parent is on another named branch
1366 # B: parent is on another named branch
1367 # C: parent is a regular non head changeset
1367 # C: parent is a regular non head changeset
1368 # H: parent was a branch head of the current branch
1368 # H: parent was a branch head of the current branch
1369 # Msg column: whether we print "created new head" message
1369 # Msg column: whether we print "created new head" message
1370 # In the following, it is assumed that there already exists some
1370 # In the following, it is assumed that there already exists some
1371 # initial branch heads of the current branch, otherwise nothing is
1371 # initial branch heads of the current branch, otherwise nothing is
1372 # printed anyway.
1372 # printed anyway.
1373 #
1373 #
1374 # Par Msg Comment
1374 # Par Msg Comment
1375 # N N y additional topo root
1375 # N N y additional topo root
1376 #
1376 #
1377 # B N y additional branch root
1377 # B N y additional branch root
1378 # C N y additional topo head
1378 # C N y additional topo head
1379 # H N n usual case
1379 # H N n usual case
1380 #
1380 #
1381 # B B y weird additional branch root
1381 # B B y weird additional branch root
1382 # C B y branch merge
1382 # C B y branch merge
1383 # H B n merge with named branch
1383 # H B n merge with named branch
1384 #
1384 #
1385 # C C y additional head from merge
1385 # C C y additional head from merge
1386 # C H n merge with a head
1386 # C H n merge with a head
1387 #
1387 #
1388 # H H n head merge: head count decreases
1388 # H H n head merge: head count decreases
1389
1389
1390 if not opts.get('close_branch'):
1390 if not opts.get('close_branch'):
1391 for r in parents:
1391 for r in parents:
1392 if r.closesbranch() and r.branch() == branch:
1392 if r.closesbranch() and r.branch() == branch:
1393 ui.status(_('reopening closed branch head %d\n') % r)
1393 ui.status(_('reopening closed branch head %d\n') % r)
1394
1394
1395 if ui.debugflag:
1395 if ui.debugflag:
1396 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1396 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1397 elif ui.verbose:
1397 elif ui.verbose:
1398 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1398 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1399
1399
1400 @command('copy|cp',
1400 @command('copy|cp',
1401 [('A', 'after', None, _('record a copy that has already occurred')),
1401 [('A', 'after', None, _('record a copy that has already occurred')),
1402 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1402 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1403 ] + walkopts + dryrunopts,
1403 ] + walkopts + dryrunopts,
1404 _('[OPTION]... [SOURCE]... DEST'))
1404 _('[OPTION]... [SOURCE]... DEST'))
1405 def copy(ui, repo, *pats, **opts):
1405 def copy(ui, repo, *pats, **opts):
1406 """mark files as copied for the next commit
1406 """mark files as copied for the next commit
1407
1407
1408 Mark dest as having copies of source files. If dest is a
1408 Mark dest as having copies of source files. If dest is a
1409 directory, copies are put in that directory. If dest is a file,
1409 directory, copies are put in that directory. If dest is a file,
1410 the source must be a single file.
1410 the source must be a single file.
1411
1411
1412 By default, this command copies the contents of files as they
1412 By default, this command copies the contents of files as they
1413 exist in the working directory. If invoked with -A/--after, the
1413 exist in the working directory. If invoked with -A/--after, the
1414 operation is recorded, but no copying is performed.
1414 operation is recorded, but no copying is performed.
1415
1415
1416 This command takes effect with the next commit. To undo a copy
1416 This command takes effect with the next commit. To undo a copy
1417 before that, see :hg:`revert`.
1417 before that, see :hg:`revert`.
1418
1418
1419 Returns 0 on success, 1 if errors are encountered.
1419 Returns 0 on success, 1 if errors are encountered.
1420 """
1420 """
1421 wlock = repo.wlock(False)
1421 wlock = repo.wlock(False)
1422 try:
1422 try:
1423 return cmdutil.copy(ui, repo, pats, opts)
1423 return cmdutil.copy(ui, repo, pats, opts)
1424 finally:
1424 finally:
1425 wlock.release()
1425 wlock.release()
1426
1426
1427 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1427 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1428 def debugancestor(ui, repo, *args):
1428 def debugancestor(ui, repo, *args):
1429 """find the ancestor revision of two revisions in a given index"""
1429 """find the ancestor revision of two revisions in a given index"""
1430 if len(args) == 3:
1430 if len(args) == 3:
1431 index, rev1, rev2 = args
1431 index, rev1, rev2 = args
1432 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1432 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1433 lookup = r.lookup
1433 lookup = r.lookup
1434 elif len(args) == 2:
1434 elif len(args) == 2:
1435 if not repo:
1435 if not repo:
1436 raise util.Abort(_("there is no Mercurial repository here "
1436 raise util.Abort(_("there is no Mercurial repository here "
1437 "(.hg not found)"))
1437 "(.hg not found)"))
1438 rev1, rev2 = args
1438 rev1, rev2 = args
1439 r = repo.changelog
1439 r = repo.changelog
1440 lookup = repo.lookup
1440 lookup = repo.lookup
1441 else:
1441 else:
1442 raise util.Abort(_('either two or three arguments required'))
1442 raise util.Abort(_('either two or three arguments required'))
1443 a = r.ancestor(lookup(rev1), lookup(rev2))
1443 a = r.ancestor(lookup(rev1), lookup(rev2))
1444 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1444 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1445
1445
1446 @command('debugbuilddag',
1446 @command('debugbuilddag',
1447 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1447 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1448 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1448 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1449 ('n', 'new-file', None, _('add new file at each rev'))],
1449 ('n', 'new-file', None, _('add new file at each rev'))],
1450 _('[OPTION]... [TEXT]'))
1450 _('[OPTION]... [TEXT]'))
1451 def debugbuilddag(ui, repo, text=None,
1451 def debugbuilddag(ui, repo, text=None,
1452 mergeable_file=False,
1452 mergeable_file=False,
1453 overwritten_file=False,
1453 overwritten_file=False,
1454 new_file=False):
1454 new_file=False):
1455 """builds a repo with a given DAG from scratch in the current empty repo
1455 """builds a repo with a given DAG from scratch in the current empty repo
1456
1456
1457 The description of the DAG is read from stdin if not given on the
1457 The description of the DAG is read from stdin if not given on the
1458 command line.
1458 command line.
1459
1459
1460 Elements:
1460 Elements:
1461
1461
1462 - "+n" is a linear run of n nodes based on the current default parent
1462 - "+n" is a linear run of n nodes based on the current default parent
1463 - "." is a single node based on the current default parent
1463 - "." is a single node based on the current default parent
1464 - "$" resets the default parent to null (implied at the start);
1464 - "$" resets the default parent to null (implied at the start);
1465 otherwise the default parent is always the last node created
1465 otherwise the default parent is always the last node created
1466 - "<p" sets the default parent to the backref p
1466 - "<p" sets the default parent to the backref p
1467 - "*p" is a fork at parent p, which is a backref
1467 - "*p" is a fork at parent p, which is a backref
1468 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1468 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1469 - "/p2" is a merge of the preceding node and p2
1469 - "/p2" is a merge of the preceding node and p2
1470 - ":tag" defines a local tag for the preceding node
1470 - ":tag" defines a local tag for the preceding node
1471 - "@branch" sets the named branch for subsequent nodes
1471 - "@branch" sets the named branch for subsequent nodes
1472 - "#...\\n" is a comment up to the end of the line
1472 - "#...\\n" is a comment up to the end of the line
1473
1473
1474 Whitespace between the above elements is ignored.
1474 Whitespace between the above elements is ignored.
1475
1475
1476 A backref is either
1476 A backref is either
1477
1477
1478 - a number n, which references the node curr-n, where curr is the current
1478 - a number n, which references the node curr-n, where curr is the current
1479 node, or
1479 node, or
1480 - the name of a local tag you placed earlier using ":tag", or
1480 - the name of a local tag you placed earlier using ":tag", or
1481 - empty to denote the default parent.
1481 - empty to denote the default parent.
1482
1482
1483 All string valued-elements are either strictly alphanumeric, or must
1483 All string valued-elements are either strictly alphanumeric, or must
1484 be enclosed in double quotes ("..."), with "\\" as escape character.
1484 be enclosed in double quotes ("..."), with "\\" as escape character.
1485 """
1485 """
1486
1486
1487 if text is None:
1487 if text is None:
1488 ui.status(_("reading DAG from stdin\n"))
1488 ui.status(_("reading DAG from stdin\n"))
1489 text = ui.fin.read()
1489 text = ui.fin.read()
1490
1490
1491 cl = repo.changelog
1491 cl = repo.changelog
1492 if len(cl) > 0:
1492 if len(cl) > 0:
1493 raise util.Abort(_('repository is not empty'))
1493 raise util.Abort(_('repository is not empty'))
1494
1494
1495 # determine number of revs in DAG
1495 # determine number of revs in DAG
1496 total = 0
1496 total = 0
1497 for type, data in dagparser.parsedag(text):
1497 for type, data in dagparser.parsedag(text):
1498 if type == 'n':
1498 if type == 'n':
1499 total += 1
1499 total += 1
1500
1500
1501 if mergeable_file:
1501 if mergeable_file:
1502 linesperrev = 2
1502 linesperrev = 2
1503 # make a file with k lines per rev
1503 # make a file with k lines per rev
1504 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1504 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1505 initialmergedlines.append("")
1505 initialmergedlines.append("")
1506
1506
1507 tags = []
1507 tags = []
1508
1508
1509 lock = tr = None
1509 lock = tr = None
1510 try:
1510 try:
1511 lock = repo.lock()
1511 lock = repo.lock()
1512 tr = repo.transaction("builddag")
1512 tr = repo.transaction("builddag")
1513
1513
1514 at = -1
1514 at = -1
1515 atbranch = 'default'
1515 atbranch = 'default'
1516 nodeids = []
1516 nodeids = []
1517 id = 0
1517 id = 0
1518 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1518 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1519 for type, data in dagparser.parsedag(text):
1519 for type, data in dagparser.parsedag(text):
1520 if type == 'n':
1520 if type == 'n':
1521 ui.note(('node %s\n' % str(data)))
1521 ui.note(('node %s\n' % str(data)))
1522 id, ps = data
1522 id, ps = data
1523
1523
1524 files = []
1524 files = []
1525 fctxs = {}
1525 fctxs = {}
1526
1526
1527 p2 = None
1527 p2 = None
1528 if mergeable_file:
1528 if mergeable_file:
1529 fn = "mf"
1529 fn = "mf"
1530 p1 = repo[ps[0]]
1530 p1 = repo[ps[0]]
1531 if len(ps) > 1:
1531 if len(ps) > 1:
1532 p2 = repo[ps[1]]
1532 p2 = repo[ps[1]]
1533 pa = p1.ancestor(p2)
1533 pa = p1.ancestor(p2)
1534 base, local, other = [x[fn].data() for x in pa, p1, p2]
1534 base, local, other = [x[fn].data() for x in pa, p1, p2]
1535 m3 = simplemerge.Merge3Text(base, local, other)
1535 m3 = simplemerge.Merge3Text(base, local, other)
1536 ml = [l.strip() for l in m3.merge_lines()]
1536 ml = [l.strip() for l in m3.merge_lines()]
1537 ml.append("")
1537 ml.append("")
1538 elif at > 0:
1538 elif at > 0:
1539 ml = p1[fn].data().split("\n")
1539 ml = p1[fn].data().split("\n")
1540 else:
1540 else:
1541 ml = initialmergedlines
1541 ml = initialmergedlines
1542 ml[id * linesperrev] += " r%i" % id
1542 ml[id * linesperrev] += " r%i" % id
1543 mergedtext = "\n".join(ml)
1543 mergedtext = "\n".join(ml)
1544 files.append(fn)
1544 files.append(fn)
1545 fctxs[fn] = context.memfilectx(fn, mergedtext)
1545 fctxs[fn] = context.memfilectx(fn, mergedtext)
1546
1546
1547 if overwritten_file:
1547 if overwritten_file:
1548 fn = "of"
1548 fn = "of"
1549 files.append(fn)
1549 files.append(fn)
1550 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1550 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1551
1551
1552 if new_file:
1552 if new_file:
1553 fn = "nf%i" % id
1553 fn = "nf%i" % id
1554 files.append(fn)
1554 files.append(fn)
1555 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1555 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1556 if len(ps) > 1:
1556 if len(ps) > 1:
1557 if not p2:
1557 if not p2:
1558 p2 = repo[ps[1]]
1558 p2 = repo[ps[1]]
1559 for fn in p2:
1559 for fn in p2:
1560 if fn.startswith("nf"):
1560 if fn.startswith("nf"):
1561 files.append(fn)
1561 files.append(fn)
1562 fctxs[fn] = p2[fn]
1562 fctxs[fn] = p2[fn]
1563
1563
1564 def fctxfn(repo, cx, path):
1564 def fctxfn(repo, cx, path):
1565 return fctxs.get(path)
1565 return fctxs.get(path)
1566
1566
1567 if len(ps) == 0 or ps[0] < 0:
1567 if len(ps) == 0 or ps[0] < 0:
1568 pars = [None, None]
1568 pars = [None, None]
1569 elif len(ps) == 1:
1569 elif len(ps) == 1:
1570 pars = [nodeids[ps[0]], None]
1570 pars = [nodeids[ps[0]], None]
1571 else:
1571 else:
1572 pars = [nodeids[p] for p in ps]
1572 pars = [nodeids[p] for p in ps]
1573 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1573 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1574 date=(id, 0),
1574 date=(id, 0),
1575 user="debugbuilddag",
1575 user="debugbuilddag",
1576 extra={'branch': atbranch})
1576 extra={'branch': atbranch})
1577 nodeid = repo.commitctx(cx)
1577 nodeid = repo.commitctx(cx)
1578 nodeids.append(nodeid)
1578 nodeids.append(nodeid)
1579 at = id
1579 at = id
1580 elif type == 'l':
1580 elif type == 'l':
1581 id, name = data
1581 id, name = data
1582 ui.note(('tag %s\n' % name))
1582 ui.note(('tag %s\n' % name))
1583 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1583 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1584 elif type == 'a':
1584 elif type == 'a':
1585 ui.note(('branch %s\n' % data))
1585 ui.note(('branch %s\n' % data))
1586 atbranch = data
1586 atbranch = data
1587 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1587 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1588 tr.close()
1588 tr.close()
1589
1589
1590 if tags:
1590 if tags:
1591 repo.opener.write("localtags", "".join(tags))
1591 repo.opener.write("localtags", "".join(tags))
1592 finally:
1592 finally:
1593 ui.progress(_('building'), None)
1593 ui.progress(_('building'), None)
1594 release(tr, lock)
1594 release(tr, lock)
1595
1595
1596 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1596 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1597 def debugbundle(ui, bundlepath, all=None, **opts):
1597 def debugbundle(ui, bundlepath, all=None, **opts):
1598 """lists the contents of a bundle"""
1598 """lists the contents of a bundle"""
1599 f = hg.openpath(ui, bundlepath)
1599 f = hg.openpath(ui, bundlepath)
1600 try:
1600 try:
1601 gen = changegroup.readbundle(f, bundlepath)
1601 gen = changegroup.readbundle(f, bundlepath)
1602 if all:
1602 if all:
1603 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1603 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1604
1604
1605 def showchunks(named):
1605 def showchunks(named):
1606 ui.write("\n%s\n" % named)
1606 ui.write("\n%s\n" % named)
1607 chain = None
1607 chain = None
1608 while True:
1608 while True:
1609 chunkdata = gen.deltachunk(chain)
1609 chunkdata = gen.deltachunk(chain)
1610 if not chunkdata:
1610 if not chunkdata:
1611 break
1611 break
1612 node = chunkdata['node']
1612 node = chunkdata['node']
1613 p1 = chunkdata['p1']
1613 p1 = chunkdata['p1']
1614 p2 = chunkdata['p2']
1614 p2 = chunkdata['p2']
1615 cs = chunkdata['cs']
1615 cs = chunkdata['cs']
1616 deltabase = chunkdata['deltabase']
1616 deltabase = chunkdata['deltabase']
1617 delta = chunkdata['delta']
1617 delta = chunkdata['delta']
1618 ui.write("%s %s %s %s %s %s\n" %
1618 ui.write("%s %s %s %s %s %s\n" %
1619 (hex(node), hex(p1), hex(p2),
1619 (hex(node), hex(p1), hex(p2),
1620 hex(cs), hex(deltabase), len(delta)))
1620 hex(cs), hex(deltabase), len(delta)))
1621 chain = node
1621 chain = node
1622
1622
1623 chunkdata = gen.changelogheader()
1623 chunkdata = gen.changelogheader()
1624 showchunks("changelog")
1624 showchunks("changelog")
1625 chunkdata = gen.manifestheader()
1625 chunkdata = gen.manifestheader()
1626 showchunks("manifest")
1626 showchunks("manifest")
1627 while True:
1627 while True:
1628 chunkdata = gen.filelogheader()
1628 chunkdata = gen.filelogheader()
1629 if not chunkdata:
1629 if not chunkdata:
1630 break
1630 break
1631 fname = chunkdata['filename']
1631 fname = chunkdata['filename']
1632 showchunks(fname)
1632 showchunks(fname)
1633 else:
1633 else:
1634 chunkdata = gen.changelogheader()
1634 chunkdata = gen.changelogheader()
1635 chain = None
1635 chain = None
1636 while True:
1636 while True:
1637 chunkdata = gen.deltachunk(chain)
1637 chunkdata = gen.deltachunk(chain)
1638 if not chunkdata:
1638 if not chunkdata:
1639 break
1639 break
1640 node = chunkdata['node']
1640 node = chunkdata['node']
1641 ui.write("%s\n" % hex(node))
1641 ui.write("%s\n" % hex(node))
1642 chain = node
1642 chain = node
1643 finally:
1643 finally:
1644 f.close()
1644 f.close()
1645
1645
1646 @command('debugcheckstate', [], '')
1646 @command('debugcheckstate', [], '')
1647 def debugcheckstate(ui, repo):
1647 def debugcheckstate(ui, repo):
1648 """validate the correctness of the current dirstate"""
1648 """validate the correctness of the current dirstate"""
1649 parent1, parent2 = repo.dirstate.parents()
1649 parent1, parent2 = repo.dirstate.parents()
1650 m1 = repo[parent1].manifest()
1650 m1 = repo[parent1].manifest()
1651 m2 = repo[parent2].manifest()
1651 m2 = repo[parent2].manifest()
1652 errors = 0
1652 errors = 0
1653 for f in repo.dirstate:
1653 for f in repo.dirstate:
1654 state = repo.dirstate[f]
1654 state = repo.dirstate[f]
1655 if state in "nr" and f not in m1:
1655 if state in "nr" and f not in m1:
1656 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1656 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1657 errors += 1
1657 errors += 1
1658 if state in "a" and f in m1:
1658 if state in "a" and f in m1:
1659 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1659 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1660 errors += 1
1660 errors += 1
1661 if state in "m" and f not in m1 and f not in m2:
1661 if state in "m" and f not in m1 and f not in m2:
1662 ui.warn(_("%s in state %s, but not in either manifest\n") %
1662 ui.warn(_("%s in state %s, but not in either manifest\n") %
1663 (f, state))
1663 (f, state))
1664 errors += 1
1664 errors += 1
1665 for f in m1:
1665 for f in m1:
1666 state = repo.dirstate[f]
1666 state = repo.dirstate[f]
1667 if state not in "nrm":
1667 if state not in "nrm":
1668 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1668 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1669 errors += 1
1669 errors += 1
1670 if errors:
1670 if errors:
1671 error = _(".hg/dirstate inconsistent with current parent's manifest")
1671 error = _(".hg/dirstate inconsistent with current parent's manifest")
1672 raise util.Abort(error)
1672 raise util.Abort(error)
1673
1673
1674 @command('debugcommands', [], _('[COMMAND]'))
1674 @command('debugcommands', [], _('[COMMAND]'))
1675 def debugcommands(ui, cmd='', *args):
1675 def debugcommands(ui, cmd='', *args):
1676 """list all available commands and options"""
1676 """list all available commands and options"""
1677 for cmd, vals in sorted(table.iteritems()):
1677 for cmd, vals in sorted(table.iteritems()):
1678 cmd = cmd.split('|')[0].strip('^')
1678 cmd = cmd.split('|')[0].strip('^')
1679 opts = ', '.join([i[1] for i in vals[1]])
1679 opts = ', '.join([i[1] for i in vals[1]])
1680 ui.write('%s: %s\n' % (cmd, opts))
1680 ui.write('%s: %s\n' % (cmd, opts))
1681
1681
1682 @command('debugcomplete',
1682 @command('debugcomplete',
1683 [('o', 'options', None, _('show the command options'))],
1683 [('o', 'options', None, _('show the command options'))],
1684 _('[-o] CMD'))
1684 _('[-o] CMD'))
1685 def debugcomplete(ui, cmd='', **opts):
1685 def debugcomplete(ui, cmd='', **opts):
1686 """returns the completion list associated with the given command"""
1686 """returns the completion list associated with the given command"""
1687
1687
1688 if opts.get('options'):
1688 if opts.get('options'):
1689 options = []
1689 options = []
1690 otables = [globalopts]
1690 otables = [globalopts]
1691 if cmd:
1691 if cmd:
1692 aliases, entry = cmdutil.findcmd(cmd, table, False)
1692 aliases, entry = cmdutil.findcmd(cmd, table, False)
1693 otables.append(entry[1])
1693 otables.append(entry[1])
1694 for t in otables:
1694 for t in otables:
1695 for o in t:
1695 for o in t:
1696 if "(DEPRECATED)" in o[3]:
1696 if "(DEPRECATED)" in o[3]:
1697 continue
1697 continue
1698 if o[0]:
1698 if o[0]:
1699 options.append('-%s' % o[0])
1699 options.append('-%s' % o[0])
1700 options.append('--%s' % o[1])
1700 options.append('--%s' % o[1])
1701 ui.write("%s\n" % "\n".join(options))
1701 ui.write("%s\n" % "\n".join(options))
1702 return
1702 return
1703
1703
1704 cmdlist = cmdutil.findpossible(cmd, table)
1704 cmdlist = cmdutil.findpossible(cmd, table)
1705 if ui.verbose:
1705 if ui.verbose:
1706 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1706 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1707 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1707 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1708
1708
1709 @command('debugdag',
1709 @command('debugdag',
1710 [('t', 'tags', None, _('use tags as labels')),
1710 [('t', 'tags', None, _('use tags as labels')),
1711 ('b', 'branches', None, _('annotate with branch names')),
1711 ('b', 'branches', None, _('annotate with branch names')),
1712 ('', 'dots', None, _('use dots for runs')),
1712 ('', 'dots', None, _('use dots for runs')),
1713 ('s', 'spaces', None, _('separate elements by spaces'))],
1713 ('s', 'spaces', None, _('separate elements by spaces'))],
1714 _('[OPTION]... [FILE [REV]...]'))
1714 _('[OPTION]... [FILE [REV]...]'))
1715 def debugdag(ui, repo, file_=None, *revs, **opts):
1715 def debugdag(ui, repo, file_=None, *revs, **opts):
1716 """format the changelog or an index DAG as a concise textual description
1716 """format the changelog or an index DAG as a concise textual description
1717
1717
1718 If you pass a revlog index, the revlog's DAG is emitted. If you list
1718 If you pass a revlog index, the revlog's DAG is emitted. If you list
1719 revision numbers, they get labeled in the output as rN.
1719 revision numbers, they get labeled in the output as rN.
1720
1720
1721 Otherwise, the changelog DAG of the current repo is emitted.
1721 Otherwise, the changelog DAG of the current repo is emitted.
1722 """
1722 """
1723 spaces = opts.get('spaces')
1723 spaces = opts.get('spaces')
1724 dots = opts.get('dots')
1724 dots = opts.get('dots')
1725 if file_:
1725 if file_:
1726 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1726 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1727 revs = set((int(r) for r in revs))
1727 revs = set((int(r) for r in revs))
1728 def events():
1728 def events():
1729 for r in rlog:
1729 for r in rlog:
1730 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1730 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1731 if p != -1)))
1731 if p != -1)))
1732 if r in revs:
1732 if r in revs:
1733 yield 'l', (r, "r%i" % r)
1733 yield 'l', (r, "r%i" % r)
1734 elif repo:
1734 elif repo:
1735 cl = repo.changelog
1735 cl = repo.changelog
1736 tags = opts.get('tags')
1736 tags = opts.get('tags')
1737 branches = opts.get('branches')
1737 branches = opts.get('branches')
1738 if tags:
1738 if tags:
1739 labels = {}
1739 labels = {}
1740 for l, n in repo.tags().items():
1740 for l, n in repo.tags().items():
1741 labels.setdefault(cl.rev(n), []).append(l)
1741 labels.setdefault(cl.rev(n), []).append(l)
1742 def events():
1742 def events():
1743 b = "default"
1743 b = "default"
1744 for r in cl:
1744 for r in cl:
1745 if branches:
1745 if branches:
1746 newb = cl.read(cl.node(r))[5]['branch']
1746 newb = cl.read(cl.node(r))[5]['branch']
1747 if newb != b:
1747 if newb != b:
1748 yield 'a', newb
1748 yield 'a', newb
1749 b = newb
1749 b = newb
1750 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1750 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1751 if p != -1)))
1751 if p != -1)))
1752 if tags:
1752 if tags:
1753 ls = labels.get(r)
1753 ls = labels.get(r)
1754 if ls:
1754 if ls:
1755 for l in ls:
1755 for l in ls:
1756 yield 'l', (r, l)
1756 yield 'l', (r, l)
1757 else:
1757 else:
1758 raise util.Abort(_('need repo for changelog dag'))
1758 raise util.Abort(_('need repo for changelog dag'))
1759
1759
1760 for line in dagparser.dagtextlines(events(),
1760 for line in dagparser.dagtextlines(events(),
1761 addspaces=spaces,
1761 addspaces=spaces,
1762 wraplabels=True,
1762 wraplabels=True,
1763 wrapannotations=True,
1763 wrapannotations=True,
1764 wrapnonlinear=dots,
1764 wrapnonlinear=dots,
1765 usedots=dots,
1765 usedots=dots,
1766 maxlinewidth=70):
1766 maxlinewidth=70):
1767 ui.write(line)
1767 ui.write(line)
1768 ui.write("\n")
1768 ui.write("\n")
1769
1769
1770 @command('debugdata',
1770 @command('debugdata',
1771 [('c', 'changelog', False, _('open changelog')),
1771 [('c', 'changelog', False, _('open changelog')),
1772 ('m', 'manifest', False, _('open manifest'))],
1772 ('m', 'manifest', False, _('open manifest'))],
1773 _('-c|-m|FILE REV'))
1773 _('-c|-m|FILE REV'))
1774 def debugdata(ui, repo, file_, rev = None, **opts):
1774 def debugdata(ui, repo, file_, rev = None, **opts):
1775 """dump the contents of a data file revision"""
1775 """dump the contents of a data file revision"""
1776 if opts.get('changelog') or opts.get('manifest'):
1776 if opts.get('changelog') or opts.get('manifest'):
1777 file_, rev = None, file_
1777 file_, rev = None, file_
1778 elif rev is None:
1778 elif rev is None:
1779 raise error.CommandError('debugdata', _('invalid arguments'))
1779 raise error.CommandError('debugdata', _('invalid arguments'))
1780 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1780 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1781 try:
1781 try:
1782 ui.write(r.revision(r.lookup(rev)))
1782 ui.write(r.revision(r.lookup(rev)))
1783 except KeyError:
1783 except KeyError:
1784 raise util.Abort(_('invalid revision identifier %s') % rev)
1784 raise util.Abort(_('invalid revision identifier %s') % rev)
1785
1785
1786 @command('debugdate',
1786 @command('debugdate',
1787 [('e', 'extended', None, _('try extended date formats'))],
1787 [('e', 'extended', None, _('try extended date formats'))],
1788 _('[-e] DATE [RANGE]'))
1788 _('[-e] DATE [RANGE]'))
1789 def debugdate(ui, date, range=None, **opts):
1789 def debugdate(ui, date, range=None, **opts):
1790 """parse and display a date"""
1790 """parse and display a date"""
1791 if opts["extended"]:
1791 if opts["extended"]:
1792 d = util.parsedate(date, util.extendeddateformats)
1792 d = util.parsedate(date, util.extendeddateformats)
1793 else:
1793 else:
1794 d = util.parsedate(date)
1794 d = util.parsedate(date)
1795 ui.write(("internal: %s %s\n") % d)
1795 ui.write(("internal: %s %s\n") % d)
1796 ui.write(("standard: %s\n") % util.datestr(d))
1796 ui.write(("standard: %s\n") % util.datestr(d))
1797 if range:
1797 if range:
1798 m = util.matchdate(range)
1798 m = util.matchdate(range)
1799 ui.write(("match: %s\n") % m(d[0]))
1799 ui.write(("match: %s\n") % m(d[0]))
1800
1800
1801 @command('debugdiscovery',
1801 @command('debugdiscovery',
1802 [('', 'old', None, _('use old-style discovery')),
1802 [('', 'old', None, _('use old-style discovery')),
1803 ('', 'nonheads', None,
1803 ('', 'nonheads', None,
1804 _('use old-style discovery with non-heads included')),
1804 _('use old-style discovery with non-heads included')),
1805 ] + remoteopts,
1805 ] + remoteopts,
1806 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1806 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1807 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1807 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1808 """runs the changeset discovery protocol in isolation"""
1808 """runs the changeset discovery protocol in isolation"""
1809 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1809 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1810 opts.get('branch'))
1810 opts.get('branch'))
1811 remote = hg.peer(repo, opts, remoteurl)
1811 remote = hg.peer(repo, opts, remoteurl)
1812 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1812 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1813
1813
1814 # make sure tests are repeatable
1814 # make sure tests are repeatable
1815 random.seed(12323)
1815 random.seed(12323)
1816
1816
1817 def doit(localheads, remoteheads, remote=remote):
1817 def doit(localheads, remoteheads, remote=remote):
1818 if opts.get('old'):
1818 if opts.get('old'):
1819 if localheads:
1819 if localheads:
1820 raise util.Abort('cannot use localheads with old style '
1820 raise util.Abort('cannot use localheads with old style '
1821 'discovery')
1821 'discovery')
1822 if not util.safehasattr(remote, 'branches'):
1822 if not util.safehasattr(remote, 'branches'):
1823 # enable in-client legacy support
1823 # enable in-client legacy support
1824 remote = localrepo.locallegacypeer(remote.local())
1824 remote = localrepo.locallegacypeer(remote.local())
1825 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1825 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1826 force=True)
1826 force=True)
1827 common = set(common)
1827 common = set(common)
1828 if not opts.get('nonheads'):
1828 if not opts.get('nonheads'):
1829 ui.write(("unpruned common: %s\n") % " ".join([short(n)
1829 ui.write(("unpruned common: %s\n") % " ".join([short(n)
1830 for n in common]))
1830 for n in common]))
1831 dag = dagutil.revlogdag(repo.changelog)
1831 dag = dagutil.revlogdag(repo.changelog)
1832 all = dag.ancestorset(dag.internalizeall(common))
1832 all = dag.ancestorset(dag.internalizeall(common))
1833 common = dag.externalizeall(dag.headsetofconnecteds(all))
1833 common = dag.externalizeall(dag.headsetofconnecteds(all))
1834 else:
1834 else:
1835 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1835 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1836 common = set(common)
1836 common = set(common)
1837 rheads = set(hds)
1837 rheads = set(hds)
1838 lheads = set(repo.heads())
1838 lheads = set(repo.heads())
1839 ui.write(("common heads: %s\n") % " ".join([short(n) for n in common]))
1839 ui.write(("common heads: %s\n") % " ".join([short(n) for n in common]))
1840 if lheads <= common:
1840 if lheads <= common:
1841 ui.write(("local is subset\n"))
1841 ui.write(("local is subset\n"))
1842 elif rheads <= common:
1842 elif rheads <= common:
1843 ui.write(("remote is subset\n"))
1843 ui.write(("remote is subset\n"))
1844
1844
1845 serverlogs = opts.get('serverlog')
1845 serverlogs = opts.get('serverlog')
1846 if serverlogs:
1846 if serverlogs:
1847 for filename in serverlogs:
1847 for filename in serverlogs:
1848 logfile = open(filename, 'r')
1848 logfile = open(filename, 'r')
1849 try:
1849 try:
1850 line = logfile.readline()
1850 line = logfile.readline()
1851 while line:
1851 while line:
1852 parts = line.strip().split(';')
1852 parts = line.strip().split(';')
1853 op = parts[1]
1853 op = parts[1]
1854 if op == 'cg':
1854 if op == 'cg':
1855 pass
1855 pass
1856 elif op == 'cgss':
1856 elif op == 'cgss':
1857 doit(parts[2].split(' '), parts[3].split(' '))
1857 doit(parts[2].split(' '), parts[3].split(' '))
1858 elif op == 'unb':
1858 elif op == 'unb':
1859 doit(parts[3].split(' '), parts[2].split(' '))
1859 doit(parts[3].split(' '), parts[2].split(' '))
1860 line = logfile.readline()
1860 line = logfile.readline()
1861 finally:
1861 finally:
1862 logfile.close()
1862 logfile.close()
1863
1863
1864 else:
1864 else:
1865 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1865 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1866 opts.get('remote_head'))
1866 opts.get('remote_head'))
1867 localrevs = opts.get('local_head')
1867 localrevs = opts.get('local_head')
1868 doit(localrevs, remoterevs)
1868 doit(localrevs, remoterevs)
1869
1869
1870 @command('debugfileset',
1870 @command('debugfileset',
1871 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1871 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
1872 _('[-r REV] FILESPEC'))
1872 _('[-r REV] FILESPEC'))
1873 def debugfileset(ui, repo, expr, **opts):
1873 def debugfileset(ui, repo, expr, **opts):
1874 '''parse and apply a fileset specification'''
1874 '''parse and apply a fileset specification'''
1875 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1875 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
1876 if ui.verbose:
1876 if ui.verbose:
1877 tree = fileset.parse(expr)[0]
1877 tree = fileset.parse(expr)[0]
1878 ui.note(tree, "\n")
1878 ui.note(tree, "\n")
1879
1879
1880 for f in fileset.getfileset(ctx, expr):
1880 for f in fileset.getfileset(ctx, expr):
1881 ui.write("%s\n" % f)
1881 ui.write("%s\n" % f)
1882
1882
1883 @command('debugfsinfo', [], _('[PATH]'))
1883 @command('debugfsinfo', [], _('[PATH]'))
1884 def debugfsinfo(ui, path = "."):
1884 def debugfsinfo(ui, path = "."):
1885 """show information detected about current filesystem"""
1885 """show information detected about current filesystem"""
1886 util.writefile('.debugfsinfo', '')
1886 util.writefile('.debugfsinfo', '')
1887 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1887 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
1888 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1888 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
1889 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
1889 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
1890 and 'yes' or 'no'))
1890 and 'yes' or 'no'))
1891 os.unlink('.debugfsinfo')
1891 os.unlink('.debugfsinfo')
1892
1892
1893 @command('debuggetbundle',
1893 @command('debuggetbundle',
1894 [('H', 'head', [], _('id of head node'), _('ID')),
1894 [('H', 'head', [], _('id of head node'), _('ID')),
1895 ('C', 'common', [], _('id of common node'), _('ID')),
1895 ('C', 'common', [], _('id of common node'), _('ID')),
1896 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1896 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1897 _('REPO FILE [-H|-C ID]...'))
1897 _('REPO FILE [-H|-C ID]...'))
1898 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1898 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1899 """retrieves a bundle from a repo
1899 """retrieves a bundle from a repo
1900
1900
1901 Every ID must be a full-length hex node id string. Saves the bundle to the
1901 Every ID must be a full-length hex node id string. Saves the bundle to the
1902 given file.
1902 given file.
1903 """
1903 """
1904 repo = hg.peer(ui, opts, repopath)
1904 repo = hg.peer(ui, opts, repopath)
1905 if not repo.capable('getbundle'):
1905 if not repo.capable('getbundle'):
1906 raise util.Abort("getbundle() not supported by target repository")
1906 raise util.Abort("getbundle() not supported by target repository")
1907 args = {}
1907 args = {}
1908 if common:
1908 if common:
1909 args['common'] = [bin(s) for s in common]
1909 args['common'] = [bin(s) for s in common]
1910 if head:
1910 if head:
1911 args['heads'] = [bin(s) for s in head]
1911 args['heads'] = [bin(s) for s in head]
1912 bundle = repo.getbundle('debug', **args)
1912 bundle = repo.getbundle('debug', **args)
1913
1913
1914 bundletype = opts.get('type', 'bzip2').lower()
1914 bundletype = opts.get('type', 'bzip2').lower()
1915 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1915 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1916 bundletype = btypes.get(bundletype)
1916 bundletype = btypes.get(bundletype)
1917 if bundletype not in changegroup.bundletypes:
1917 if bundletype not in changegroup.bundletypes:
1918 raise util.Abort(_('unknown bundle type specified with --type'))
1918 raise util.Abort(_('unknown bundle type specified with --type'))
1919 changegroup.writebundle(bundle, bundlepath, bundletype)
1919 changegroup.writebundle(bundle, bundlepath, bundletype)
1920
1920
1921 @command('debugignore', [], '')
1921 @command('debugignore', [], '')
1922 def debugignore(ui, repo, *values, **opts):
1922 def debugignore(ui, repo, *values, **opts):
1923 """display the combined ignore pattern"""
1923 """display the combined ignore pattern"""
1924 ignore = repo.dirstate._ignore
1924 ignore = repo.dirstate._ignore
1925 includepat = getattr(ignore, 'includepat', None)
1925 includepat = getattr(ignore, 'includepat', None)
1926 if includepat is not None:
1926 if includepat is not None:
1927 ui.write("%s\n" % includepat)
1927 ui.write("%s\n" % includepat)
1928 else:
1928 else:
1929 raise util.Abort(_("no ignore patterns found"))
1929 raise util.Abort(_("no ignore patterns found"))
1930
1930
1931 @command('debugindex',
1931 @command('debugindex',
1932 [('c', 'changelog', False, _('open changelog')),
1932 [('c', 'changelog', False, _('open changelog')),
1933 ('m', 'manifest', False, _('open manifest')),
1933 ('m', 'manifest', False, _('open manifest')),
1934 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1934 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1935 _('[-f FORMAT] -c|-m|FILE'))
1935 _('[-f FORMAT] -c|-m|FILE'))
1936 def debugindex(ui, repo, file_ = None, **opts):
1936 def debugindex(ui, repo, file_ = None, **opts):
1937 """dump the contents of an index file"""
1937 """dump the contents of an index file"""
1938 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1938 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1939 format = opts.get('format', 0)
1939 format = opts.get('format', 0)
1940 if format not in (0, 1):
1940 if format not in (0, 1):
1941 raise util.Abort(_("unknown format %d") % format)
1941 raise util.Abort(_("unknown format %d") % format)
1942
1942
1943 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1943 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1944 if generaldelta:
1944 if generaldelta:
1945 basehdr = ' delta'
1945 basehdr = ' delta'
1946 else:
1946 else:
1947 basehdr = ' base'
1947 basehdr = ' base'
1948
1948
1949 if format == 0:
1949 if format == 0:
1950 ui.write(" rev offset length " + basehdr + " linkrev"
1950 ui.write(" rev offset length " + basehdr + " linkrev"
1951 " nodeid p1 p2\n")
1951 " nodeid p1 p2\n")
1952 elif format == 1:
1952 elif format == 1:
1953 ui.write(" rev flag offset length"
1953 ui.write(" rev flag offset length"
1954 " size " + basehdr + " link p1 p2"
1954 " size " + basehdr + " link p1 p2"
1955 " nodeid\n")
1955 " nodeid\n")
1956
1956
1957 for i in r:
1957 for i in r:
1958 node = r.node(i)
1958 node = r.node(i)
1959 if generaldelta:
1959 if generaldelta:
1960 base = r.deltaparent(i)
1960 base = r.deltaparent(i)
1961 else:
1961 else:
1962 base = r.chainbase(i)
1962 base = r.chainbase(i)
1963 if format == 0:
1963 if format == 0:
1964 try:
1964 try:
1965 pp = r.parents(node)
1965 pp = r.parents(node)
1966 except Exception:
1966 except Exception:
1967 pp = [nullid, nullid]
1967 pp = [nullid, nullid]
1968 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1968 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1969 i, r.start(i), r.length(i), base, r.linkrev(i),
1969 i, r.start(i), r.length(i), base, r.linkrev(i),
1970 short(node), short(pp[0]), short(pp[1])))
1970 short(node), short(pp[0]), short(pp[1])))
1971 elif format == 1:
1971 elif format == 1:
1972 pr = r.parentrevs(i)
1972 pr = r.parentrevs(i)
1973 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1973 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1974 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1974 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1975 base, r.linkrev(i), pr[0], pr[1], short(node)))
1975 base, r.linkrev(i), pr[0], pr[1], short(node)))
1976
1976
1977 @command('debugindexdot', [], _('FILE'))
1977 @command('debugindexdot', [], _('FILE'))
1978 def debugindexdot(ui, repo, file_):
1978 def debugindexdot(ui, repo, file_):
1979 """dump an index DAG as a graphviz dot file"""
1979 """dump an index DAG as a graphviz dot file"""
1980 r = None
1980 r = None
1981 if repo:
1981 if repo:
1982 filelog = repo.file(file_)
1982 filelog = repo.file(file_)
1983 if len(filelog):
1983 if len(filelog):
1984 r = filelog
1984 r = filelog
1985 if not r:
1985 if not r:
1986 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1986 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1987 ui.write(("digraph G {\n"))
1987 ui.write(("digraph G {\n"))
1988 for i in r:
1988 for i in r:
1989 node = r.node(i)
1989 node = r.node(i)
1990 pp = r.parents(node)
1990 pp = r.parents(node)
1991 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1991 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1992 if pp[1] != nullid:
1992 if pp[1] != nullid:
1993 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1993 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1994 ui.write("}\n")
1994 ui.write("}\n")
1995
1995
1996 @command('debuginstall', [], '')
1996 @command('debuginstall', [], '')
1997 def debuginstall(ui):
1997 def debuginstall(ui):
1998 '''test Mercurial installation
1998 '''test Mercurial installation
1999
1999
2000 Returns 0 on success.
2000 Returns 0 on success.
2001 '''
2001 '''
2002
2002
2003 def writetemp(contents):
2003 def writetemp(contents):
2004 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2004 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2005 f = os.fdopen(fd, "wb")
2005 f = os.fdopen(fd, "wb")
2006 f.write(contents)
2006 f.write(contents)
2007 f.close()
2007 f.close()
2008 return name
2008 return name
2009
2009
2010 problems = 0
2010 problems = 0
2011
2011
2012 # encoding
2012 # encoding
2013 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2013 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2014 try:
2014 try:
2015 encoding.fromlocal("test")
2015 encoding.fromlocal("test")
2016 except util.Abort, inst:
2016 except util.Abort, inst:
2017 ui.write(" %s\n" % inst)
2017 ui.write(" %s\n" % inst)
2018 ui.write(_(" (check that your locale is properly set)\n"))
2018 ui.write(_(" (check that your locale is properly set)\n"))
2019 problems += 1
2019 problems += 1
2020
2020
2021 # Python lib
2021 # Python lib
2022 ui.status(_("checking Python lib (%s)...\n")
2022 ui.status(_("checking Python lib (%s)...\n")
2023 % os.path.dirname(os.__file__))
2023 % os.path.dirname(os.__file__))
2024
2024
2025 # compiled modules
2025 # compiled modules
2026 ui.status(_("checking installed modules (%s)...\n")
2026 ui.status(_("checking installed modules (%s)...\n")
2027 % os.path.dirname(__file__))
2027 % os.path.dirname(__file__))
2028 try:
2028 try:
2029 import bdiff, mpatch, base85, osutil
2029 import bdiff, mpatch, base85, osutil
2030 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2030 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2031 except Exception, inst:
2031 except Exception, inst:
2032 ui.write(" %s\n" % inst)
2032 ui.write(" %s\n" % inst)
2033 ui.write(_(" One or more extensions could not be found"))
2033 ui.write(_(" One or more extensions could not be found"))
2034 ui.write(_(" (check that you compiled the extensions)\n"))
2034 ui.write(_(" (check that you compiled the extensions)\n"))
2035 problems += 1
2035 problems += 1
2036
2036
2037 # templates
2037 # templates
2038 import templater
2038 import templater
2039 p = templater.templatepath()
2039 p = templater.templatepath()
2040 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2040 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2041 try:
2041 try:
2042 templater.templater(templater.templatepath("map-cmdline.default"))
2042 templater.templater(templater.templatepath("map-cmdline.default"))
2043 except Exception, inst:
2043 except Exception, inst:
2044 ui.write(" %s\n" % inst)
2044 ui.write(" %s\n" % inst)
2045 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2045 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2046 problems += 1
2046 problems += 1
2047
2047
2048 # editor
2048 # editor
2049 ui.status(_("checking commit editor...\n"))
2049 ui.status(_("checking commit editor...\n"))
2050 editor = ui.geteditor()
2050 editor = ui.geteditor()
2051 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2051 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2052 if not cmdpath:
2052 if not cmdpath:
2053 if editor == 'vi':
2053 if editor == 'vi':
2054 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2054 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2055 ui.write(_(" (specify a commit editor in your configuration"
2055 ui.write(_(" (specify a commit editor in your configuration"
2056 " file)\n"))
2056 " file)\n"))
2057 else:
2057 else:
2058 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2058 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2059 ui.write(_(" (specify a commit editor in your configuration"
2059 ui.write(_(" (specify a commit editor in your configuration"
2060 " file)\n"))
2060 " file)\n"))
2061 problems += 1
2061 problems += 1
2062
2062
2063 # check username
2063 # check username
2064 ui.status(_("checking username...\n"))
2064 ui.status(_("checking username...\n"))
2065 try:
2065 try:
2066 ui.username()
2066 ui.username()
2067 except util.Abort, e:
2067 except util.Abort, e:
2068 ui.write(" %s\n" % e)
2068 ui.write(" %s\n" % e)
2069 ui.write(_(" (specify a username in your configuration file)\n"))
2069 ui.write(_(" (specify a username in your configuration file)\n"))
2070 problems += 1
2070 problems += 1
2071
2071
2072 if not problems:
2072 if not problems:
2073 ui.status(_("no problems detected\n"))
2073 ui.status(_("no problems detected\n"))
2074 else:
2074 else:
2075 ui.write(_("%s problems detected,"
2075 ui.write(_("%s problems detected,"
2076 " please check your install!\n") % problems)
2076 " please check your install!\n") % problems)
2077
2077
2078 return problems
2078 return problems
2079
2079
2080 @command('debugknown', [], _('REPO ID...'))
2080 @command('debugknown', [], _('REPO ID...'))
2081 def debugknown(ui, repopath, *ids, **opts):
2081 def debugknown(ui, repopath, *ids, **opts):
2082 """test whether node ids are known to a repo
2082 """test whether node ids are known to a repo
2083
2083
2084 Every ID must be a full-length hex node id string. Returns a list of 0s
2084 Every ID must be a full-length hex node id string. Returns a list of 0s
2085 and 1s indicating unknown/known.
2085 and 1s indicating unknown/known.
2086 """
2086 """
2087 repo = hg.peer(ui, opts, repopath)
2087 repo = hg.peer(ui, opts, repopath)
2088 if not repo.capable('known'):
2088 if not repo.capable('known'):
2089 raise util.Abort("known() not supported by target repository")
2089 raise util.Abort("known() not supported by target repository")
2090 flags = repo.known([bin(s) for s in ids])
2090 flags = repo.known([bin(s) for s in ids])
2091 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2091 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2092
2092
2093 @command('debugobsolete',
2093 @command('debugobsolete',
2094 [('', 'flags', 0, _('markers flag')),
2094 [('', 'flags', 0, _('markers flag')),
2095 ] + commitopts2,
2095 ] + commitopts2,
2096 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2096 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2097 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2097 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2098 """create arbitrary obsolete marker"""
2098 """create arbitrary obsolete marker"""
2099 def parsenodeid(s):
2099 def parsenodeid(s):
2100 try:
2100 try:
2101 # We do not use revsingle/revrange functions here to accept
2101 # We do not use revsingle/revrange functions here to accept
2102 # arbitrary node identifiers, possibly not present in the
2102 # arbitrary node identifiers, possibly not present in the
2103 # local repository.
2103 # local repository.
2104 n = bin(s)
2104 n = bin(s)
2105 if len(n) != len(nullid):
2105 if len(n) != len(nullid):
2106 raise TypeError()
2106 raise TypeError()
2107 return n
2107 return n
2108 except TypeError:
2108 except TypeError:
2109 raise util.Abort('changeset references must be full hexadecimal '
2109 raise util.Abort('changeset references must be full hexadecimal '
2110 'node identifiers')
2110 'node identifiers')
2111
2111
2112 if precursor is not None:
2112 if precursor is not None:
2113 metadata = {}
2113 metadata = {}
2114 if 'date' in opts:
2114 if 'date' in opts:
2115 metadata['date'] = opts['date']
2115 metadata['date'] = opts['date']
2116 metadata['user'] = opts['user'] or ui.username()
2116 metadata['user'] = opts['user'] or ui.username()
2117 succs = tuple(parsenodeid(succ) for succ in successors)
2117 succs = tuple(parsenodeid(succ) for succ in successors)
2118 l = repo.lock()
2118 l = repo.lock()
2119 try:
2119 try:
2120 tr = repo.transaction('debugobsolete')
2120 tr = repo.transaction('debugobsolete')
2121 try:
2121 try:
2122 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2122 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2123 opts['flags'], metadata)
2123 opts['flags'], metadata)
2124 tr.close()
2124 tr.close()
2125 finally:
2125 finally:
2126 tr.release()
2126 tr.release()
2127 finally:
2127 finally:
2128 l.release()
2128 l.release()
2129 else:
2129 else:
2130 for m in obsolete.allmarkers(repo):
2130 for m in obsolete.allmarkers(repo):
2131 ui.write(hex(m.precnode()))
2131 ui.write(hex(m.precnode()))
2132 for repl in m.succnodes():
2132 for repl in m.succnodes():
2133 ui.write(' ')
2133 ui.write(' ')
2134 ui.write(hex(repl))
2134 ui.write(hex(repl))
2135 ui.write(' %X ' % m._data[2])
2135 ui.write(' %X ' % m._data[2])
2136 ui.write(m.metadata())
2136 ui.write(m.metadata())
2137 ui.write('\n')
2137 ui.write('\n')
2138
2138
2139 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2139 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2140 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2140 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2141 '''access the pushkey key/value protocol
2141 '''access the pushkey key/value protocol
2142
2142
2143 With two args, list the keys in the given namespace.
2143 With two args, list the keys in the given namespace.
2144
2144
2145 With five args, set a key to new if it currently is set to old.
2145 With five args, set a key to new if it currently is set to old.
2146 Reports success or failure.
2146 Reports success or failure.
2147 '''
2147 '''
2148
2148
2149 target = hg.peer(ui, {}, repopath)
2149 target = hg.peer(ui, {}, repopath)
2150 if keyinfo:
2150 if keyinfo:
2151 key, old, new = keyinfo
2151 key, old, new = keyinfo
2152 r = target.pushkey(namespace, key, old, new)
2152 r = target.pushkey(namespace, key, old, new)
2153 ui.status(str(r) + '\n')
2153 ui.status(str(r) + '\n')
2154 return not r
2154 return not r
2155 else:
2155 else:
2156 for k, v in target.listkeys(namespace).iteritems():
2156 for k, v in target.listkeys(namespace).iteritems():
2157 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2157 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2158 v.encode('string-escape')))
2158 v.encode('string-escape')))
2159
2159
2160 @command('debugpvec', [], _('A B'))
2160 @command('debugpvec', [], _('A B'))
2161 def debugpvec(ui, repo, a, b=None):
2161 def debugpvec(ui, repo, a, b=None):
2162 ca = scmutil.revsingle(repo, a)
2162 ca = scmutil.revsingle(repo, a)
2163 cb = scmutil.revsingle(repo, b)
2163 cb = scmutil.revsingle(repo, b)
2164 pa = pvec.ctxpvec(ca)
2164 pa = pvec.ctxpvec(ca)
2165 pb = pvec.ctxpvec(cb)
2165 pb = pvec.ctxpvec(cb)
2166 if pa == pb:
2166 if pa == pb:
2167 rel = "="
2167 rel = "="
2168 elif pa > pb:
2168 elif pa > pb:
2169 rel = ">"
2169 rel = ">"
2170 elif pa < pb:
2170 elif pa < pb:
2171 rel = "<"
2171 rel = "<"
2172 elif pa | pb:
2172 elif pa | pb:
2173 rel = "|"
2173 rel = "|"
2174 ui.write(_("a: %s\n") % pa)
2174 ui.write(_("a: %s\n") % pa)
2175 ui.write(_("b: %s\n") % pb)
2175 ui.write(_("b: %s\n") % pb)
2176 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2176 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2177 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2177 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2178 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2178 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2179 pa.distance(pb), rel))
2179 pa.distance(pb), rel))
2180
2180
2181 @command('debugrebuildstate',
2181 @command('debugrebuildstate',
2182 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2182 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2183 _('[-r REV] [REV]'))
2183 _('[-r REV] [REV]'))
2184 def debugrebuildstate(ui, repo, rev="tip"):
2184 def debugrebuildstate(ui, repo, rev="tip"):
2185 """rebuild the dirstate as it would look like for the given revision"""
2185 """rebuild the dirstate as it would look like for the given revision"""
2186 ctx = scmutil.revsingle(repo, rev)
2186 ctx = scmutil.revsingle(repo, rev)
2187 wlock = repo.wlock()
2187 wlock = repo.wlock()
2188 try:
2188 try:
2189 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2189 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2190 finally:
2190 finally:
2191 wlock.release()
2191 wlock.release()
2192
2192
2193 @command('debugrename',
2193 @command('debugrename',
2194 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2194 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2195 _('[-r REV] FILE'))
2195 _('[-r REV] FILE'))
2196 def debugrename(ui, repo, file1, *pats, **opts):
2196 def debugrename(ui, repo, file1, *pats, **opts):
2197 """dump rename information"""
2197 """dump rename information"""
2198
2198
2199 ctx = scmutil.revsingle(repo, opts.get('rev'))
2199 ctx = scmutil.revsingle(repo, opts.get('rev'))
2200 m = scmutil.match(ctx, (file1,) + pats, opts)
2200 m = scmutil.match(ctx, (file1,) + pats, opts)
2201 for abs in ctx.walk(m):
2201 for abs in ctx.walk(m):
2202 fctx = ctx[abs]
2202 fctx = ctx[abs]
2203 o = fctx.filelog().renamed(fctx.filenode())
2203 o = fctx.filelog().renamed(fctx.filenode())
2204 rel = m.rel(abs)
2204 rel = m.rel(abs)
2205 if o:
2205 if o:
2206 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2206 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2207 else:
2207 else:
2208 ui.write(_("%s not renamed\n") % rel)
2208 ui.write(_("%s not renamed\n") % rel)
2209
2209
2210 @command('debugrevlog',
2210 @command('debugrevlog',
2211 [('c', 'changelog', False, _('open changelog')),
2211 [('c', 'changelog', False, _('open changelog')),
2212 ('m', 'manifest', False, _('open manifest')),
2212 ('m', 'manifest', False, _('open manifest')),
2213 ('d', 'dump', False, _('dump index data'))],
2213 ('d', 'dump', False, _('dump index data'))],
2214 _('-c|-m|FILE'))
2214 _('-c|-m|FILE'))
2215 def debugrevlog(ui, repo, file_ = None, **opts):
2215 def debugrevlog(ui, repo, file_ = None, **opts):
2216 """show data and statistics about a revlog"""
2216 """show data and statistics about a revlog"""
2217 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2217 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2218
2218
2219 if opts.get("dump"):
2219 if opts.get("dump"):
2220 numrevs = len(r)
2220 numrevs = len(r)
2221 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2221 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2222 " rawsize totalsize compression heads\n")
2222 " rawsize totalsize compression heads\n")
2223 ts = 0
2223 ts = 0
2224 heads = set()
2224 heads = set()
2225 for rev in xrange(numrevs):
2225 for rev in xrange(numrevs):
2226 dbase = r.deltaparent(rev)
2226 dbase = r.deltaparent(rev)
2227 if dbase == -1:
2227 if dbase == -1:
2228 dbase = rev
2228 dbase = rev
2229 cbase = r.chainbase(rev)
2229 cbase = r.chainbase(rev)
2230 p1, p2 = r.parentrevs(rev)
2230 p1, p2 = r.parentrevs(rev)
2231 rs = r.rawsize(rev)
2231 rs = r.rawsize(rev)
2232 ts = ts + rs
2232 ts = ts + rs
2233 heads -= set(r.parentrevs(rev))
2233 heads -= set(r.parentrevs(rev))
2234 heads.add(rev)
2234 heads.add(rev)
2235 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2235 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2236 (rev, p1, p2, r.start(rev), r.end(rev),
2236 (rev, p1, p2, r.start(rev), r.end(rev),
2237 r.start(dbase), r.start(cbase),
2237 r.start(dbase), r.start(cbase),
2238 r.start(p1), r.start(p2),
2238 r.start(p1), r.start(p2),
2239 rs, ts, ts / r.end(rev), len(heads)))
2239 rs, ts, ts / r.end(rev), len(heads)))
2240 return 0
2240 return 0
2241
2241
2242 v = r.version
2242 v = r.version
2243 format = v & 0xFFFF
2243 format = v & 0xFFFF
2244 flags = []
2244 flags = []
2245 gdelta = False
2245 gdelta = False
2246 if v & revlog.REVLOGNGINLINEDATA:
2246 if v & revlog.REVLOGNGINLINEDATA:
2247 flags.append('inline')
2247 flags.append('inline')
2248 if v & revlog.REVLOGGENERALDELTA:
2248 if v & revlog.REVLOGGENERALDELTA:
2249 gdelta = True
2249 gdelta = True
2250 flags.append('generaldelta')
2250 flags.append('generaldelta')
2251 if not flags:
2251 if not flags:
2252 flags = ['(none)']
2252 flags = ['(none)']
2253
2253
2254 nummerges = 0
2254 nummerges = 0
2255 numfull = 0
2255 numfull = 0
2256 numprev = 0
2256 numprev = 0
2257 nump1 = 0
2257 nump1 = 0
2258 nump2 = 0
2258 nump2 = 0
2259 numother = 0
2259 numother = 0
2260 nump1prev = 0
2260 nump1prev = 0
2261 nump2prev = 0
2261 nump2prev = 0
2262 chainlengths = []
2262 chainlengths = []
2263
2263
2264 datasize = [None, 0, 0L]
2264 datasize = [None, 0, 0L]
2265 fullsize = [None, 0, 0L]
2265 fullsize = [None, 0, 0L]
2266 deltasize = [None, 0, 0L]
2266 deltasize = [None, 0, 0L]
2267
2267
2268 def addsize(size, l):
2268 def addsize(size, l):
2269 if l[0] is None or size < l[0]:
2269 if l[0] is None or size < l[0]:
2270 l[0] = size
2270 l[0] = size
2271 if size > l[1]:
2271 if size > l[1]:
2272 l[1] = size
2272 l[1] = size
2273 l[2] += size
2273 l[2] += size
2274
2274
2275 numrevs = len(r)
2275 numrevs = len(r)
2276 for rev in xrange(numrevs):
2276 for rev in xrange(numrevs):
2277 p1, p2 = r.parentrevs(rev)
2277 p1, p2 = r.parentrevs(rev)
2278 delta = r.deltaparent(rev)
2278 delta = r.deltaparent(rev)
2279 if format > 0:
2279 if format > 0:
2280 addsize(r.rawsize(rev), datasize)
2280 addsize(r.rawsize(rev), datasize)
2281 if p2 != nullrev:
2281 if p2 != nullrev:
2282 nummerges += 1
2282 nummerges += 1
2283 size = r.length(rev)
2283 size = r.length(rev)
2284 if delta == nullrev:
2284 if delta == nullrev:
2285 chainlengths.append(0)
2285 chainlengths.append(0)
2286 numfull += 1
2286 numfull += 1
2287 addsize(size, fullsize)
2287 addsize(size, fullsize)
2288 else:
2288 else:
2289 chainlengths.append(chainlengths[delta] + 1)
2289 chainlengths.append(chainlengths[delta] + 1)
2290 addsize(size, deltasize)
2290 addsize(size, deltasize)
2291 if delta == rev - 1:
2291 if delta == rev - 1:
2292 numprev += 1
2292 numprev += 1
2293 if delta == p1:
2293 if delta == p1:
2294 nump1prev += 1
2294 nump1prev += 1
2295 elif delta == p2:
2295 elif delta == p2:
2296 nump2prev += 1
2296 nump2prev += 1
2297 elif delta == p1:
2297 elif delta == p1:
2298 nump1 += 1
2298 nump1 += 1
2299 elif delta == p2:
2299 elif delta == p2:
2300 nump2 += 1
2300 nump2 += 1
2301 elif delta != nullrev:
2301 elif delta != nullrev:
2302 numother += 1
2302 numother += 1
2303
2303
2304 # Adjust size min value for empty cases
2304 # Adjust size min value for empty cases
2305 for size in (datasize, fullsize, deltasize):
2305 for size in (datasize, fullsize, deltasize):
2306 if size[0] is None:
2306 if size[0] is None:
2307 size[0] = 0
2307 size[0] = 0
2308
2308
2309 numdeltas = numrevs - numfull
2309 numdeltas = numrevs - numfull
2310 numoprev = numprev - nump1prev - nump2prev
2310 numoprev = numprev - nump1prev - nump2prev
2311 totalrawsize = datasize[2]
2311 totalrawsize = datasize[2]
2312 datasize[2] /= numrevs
2312 datasize[2] /= numrevs
2313 fulltotal = fullsize[2]
2313 fulltotal = fullsize[2]
2314 fullsize[2] /= numfull
2314 fullsize[2] /= numfull
2315 deltatotal = deltasize[2]
2315 deltatotal = deltasize[2]
2316 if numrevs - numfull > 0:
2316 if numrevs - numfull > 0:
2317 deltasize[2] /= numrevs - numfull
2317 deltasize[2] /= numrevs - numfull
2318 totalsize = fulltotal + deltatotal
2318 totalsize = fulltotal + deltatotal
2319 avgchainlen = sum(chainlengths) / numrevs
2319 avgchainlen = sum(chainlengths) / numrevs
2320 compratio = totalrawsize / totalsize
2320 compratio = totalrawsize / totalsize
2321
2321
2322 basedfmtstr = '%%%dd\n'
2322 basedfmtstr = '%%%dd\n'
2323 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2323 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2324
2324
2325 def dfmtstr(max):
2325 def dfmtstr(max):
2326 return basedfmtstr % len(str(max))
2326 return basedfmtstr % len(str(max))
2327 def pcfmtstr(max, padding=0):
2327 def pcfmtstr(max, padding=0):
2328 return basepcfmtstr % (len(str(max)), ' ' * padding)
2328 return basepcfmtstr % (len(str(max)), ' ' * padding)
2329
2329
2330 def pcfmt(value, total):
2330 def pcfmt(value, total):
2331 return (value, 100 * float(value) / total)
2331 return (value, 100 * float(value) / total)
2332
2332
2333 ui.write(('format : %d\n') % format)
2333 ui.write(('format : %d\n') % format)
2334 ui.write(('flags : %s\n') % ', '.join(flags))
2334 ui.write(('flags : %s\n') % ', '.join(flags))
2335
2335
2336 ui.write('\n')
2336 ui.write('\n')
2337 fmt = pcfmtstr(totalsize)
2337 fmt = pcfmtstr(totalsize)
2338 fmt2 = dfmtstr(totalsize)
2338 fmt2 = dfmtstr(totalsize)
2339 ui.write(('revisions : ') + fmt2 % numrevs)
2339 ui.write(('revisions : ') + fmt2 % numrevs)
2340 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2340 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2341 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2341 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2342 ui.write(('revisions : ') + fmt2 % numrevs)
2342 ui.write(('revisions : ') + fmt2 % numrevs)
2343 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2343 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2344 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2344 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2345 ui.write(('revision size : ') + fmt2 % totalsize)
2345 ui.write(('revision size : ') + fmt2 % totalsize)
2346 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2346 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2347 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2347 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2348
2348
2349 ui.write('\n')
2349 ui.write('\n')
2350 fmt = dfmtstr(max(avgchainlen, compratio))
2350 fmt = dfmtstr(max(avgchainlen, compratio))
2351 ui.write(('avg chain length : ') + fmt % avgchainlen)
2351 ui.write(('avg chain length : ') + fmt % avgchainlen)
2352 ui.write(('compression ratio : ') + fmt % compratio)
2352 ui.write(('compression ratio : ') + fmt % compratio)
2353
2353
2354 if format > 0:
2354 if format > 0:
2355 ui.write('\n')
2355 ui.write('\n')
2356 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2356 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2357 % tuple(datasize))
2357 % tuple(datasize))
2358 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2358 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2359 % tuple(fullsize))
2359 % tuple(fullsize))
2360 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2360 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2361 % tuple(deltasize))
2361 % tuple(deltasize))
2362
2362
2363 if numdeltas > 0:
2363 if numdeltas > 0:
2364 ui.write('\n')
2364 ui.write('\n')
2365 fmt = pcfmtstr(numdeltas)
2365 fmt = pcfmtstr(numdeltas)
2366 fmt2 = pcfmtstr(numdeltas, 4)
2366 fmt2 = pcfmtstr(numdeltas, 4)
2367 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2367 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2368 if numprev > 0:
2368 if numprev > 0:
2369 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2369 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2370 numprev))
2370 numprev))
2371 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2371 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2372 numprev))
2372 numprev))
2373 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2373 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2374 numprev))
2374 numprev))
2375 if gdelta:
2375 if gdelta:
2376 ui.write(('deltas against p1 : ')
2376 ui.write(('deltas against p1 : ')
2377 + fmt % pcfmt(nump1, numdeltas))
2377 + fmt % pcfmt(nump1, numdeltas))
2378 ui.write(('deltas against p2 : ')
2378 ui.write(('deltas against p2 : ')
2379 + fmt % pcfmt(nump2, numdeltas))
2379 + fmt % pcfmt(nump2, numdeltas))
2380 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2380 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2381 numdeltas))
2381 numdeltas))
2382
2382
2383 @command('debugrevspec', [], ('REVSPEC'))
2383 @command('debugrevspec', [], ('REVSPEC'))
2384 def debugrevspec(ui, repo, expr):
2384 def debugrevspec(ui, repo, expr):
2385 """parse and apply a revision specification
2385 """parse and apply a revision specification
2386
2386
2387 Use --verbose to print the parsed tree before and after aliases
2387 Use --verbose to print the parsed tree before and after aliases
2388 expansion.
2388 expansion.
2389 """
2389 """
2390 if ui.verbose:
2390 if ui.verbose:
2391 tree = revset.parse(expr)[0]
2391 tree = revset.parse(expr)[0]
2392 ui.note(revset.prettyformat(tree), "\n")
2392 ui.note(revset.prettyformat(tree), "\n")
2393 newtree = revset.findaliases(ui, tree)
2393 newtree = revset.findaliases(ui, tree)
2394 if newtree != tree:
2394 if newtree != tree:
2395 ui.note(revset.prettyformat(newtree), "\n")
2395 ui.note(revset.prettyformat(newtree), "\n")
2396 func = revset.match(ui, expr)
2396 func = revset.match(ui, expr)
2397 for c in func(repo, range(len(repo))):
2397 for c in func(repo, range(len(repo))):
2398 ui.write("%s\n" % c)
2398 ui.write("%s\n" % c)
2399
2399
2400 @command('debugsetparents', [], _('REV1 [REV2]'))
2400 @command('debugsetparents', [], _('REV1 [REV2]'))
2401 def debugsetparents(ui, repo, rev1, rev2=None):
2401 def debugsetparents(ui, repo, rev1, rev2=None):
2402 """manually set the parents of the current working directory
2402 """manually set the parents of the current working directory
2403
2403
2404 This is useful for writing repository conversion tools, but should
2404 This is useful for writing repository conversion tools, but should
2405 be used with care.
2405 be used with care.
2406
2406
2407 Returns 0 on success.
2407 Returns 0 on success.
2408 """
2408 """
2409
2409
2410 r1 = scmutil.revsingle(repo, rev1).node()
2410 r1 = scmutil.revsingle(repo, rev1).node()
2411 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2411 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2412
2412
2413 wlock = repo.wlock()
2413 wlock = repo.wlock()
2414 try:
2414 try:
2415 repo.setparents(r1, r2)
2415 repo.setparents(r1, r2)
2416 finally:
2416 finally:
2417 wlock.release()
2417 wlock.release()
2418
2418
2419 @command('debugstate',
2419 @command('debugstate',
2420 [('', 'nodates', None, _('do not display the saved mtime')),
2420 [('', 'nodates', None, _('do not display the saved mtime')),
2421 ('', 'datesort', None, _('sort by saved mtime'))],
2421 ('', 'datesort', None, _('sort by saved mtime'))],
2422 _('[OPTION]...'))
2422 _('[OPTION]...'))
2423 def debugstate(ui, repo, nodates=None, datesort=None):
2423 def debugstate(ui, repo, nodates=None, datesort=None):
2424 """show the contents of the current dirstate"""
2424 """show the contents of the current dirstate"""
2425 timestr = ""
2425 timestr = ""
2426 showdate = not nodates
2426 showdate = not nodates
2427 if datesort:
2427 if datesort:
2428 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2428 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2429 else:
2429 else:
2430 keyfunc = None # sort by filename
2430 keyfunc = None # sort by filename
2431 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2431 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2432 if showdate:
2432 if showdate:
2433 if ent[3] == -1:
2433 if ent[3] == -1:
2434 # Pad or slice to locale representation
2434 # Pad or slice to locale representation
2435 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2435 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2436 time.localtime(0)))
2436 time.localtime(0)))
2437 timestr = 'unset'
2437 timestr = 'unset'
2438 timestr = (timestr[:locale_len] +
2438 timestr = (timestr[:locale_len] +
2439 ' ' * (locale_len - len(timestr)))
2439 ' ' * (locale_len - len(timestr)))
2440 else:
2440 else:
2441 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2441 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2442 time.localtime(ent[3]))
2442 time.localtime(ent[3]))
2443 if ent[1] & 020000:
2443 if ent[1] & 020000:
2444 mode = 'lnk'
2444 mode = 'lnk'
2445 else:
2445 else:
2446 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2446 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2447 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2447 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2448 for f in repo.dirstate.copies():
2448 for f in repo.dirstate.copies():
2449 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2449 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2450
2450
2451 @command('debugsub',
2451 @command('debugsub',
2452 [('r', 'rev', '',
2452 [('r', 'rev', '',
2453 _('revision to check'), _('REV'))],
2453 _('revision to check'), _('REV'))],
2454 _('[-r REV] [REV]'))
2454 _('[-r REV] [REV]'))
2455 def debugsub(ui, repo, rev=None):
2455 def debugsub(ui, repo, rev=None):
2456 ctx = scmutil.revsingle(repo, rev, None)
2456 ctx = scmutil.revsingle(repo, rev, None)
2457 for k, v in sorted(ctx.substate.items()):
2457 for k, v in sorted(ctx.substate.items()):
2458 ui.write(('path %s\n') % k)
2458 ui.write(('path %s\n') % k)
2459 ui.write((' source %s\n') % v[0])
2459 ui.write((' source %s\n') % v[0])
2460 ui.write((' revision %s\n') % v[1])
2460 ui.write((' revision %s\n') % v[1])
2461
2461
2462 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2462 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2463 def debugwalk(ui, repo, *pats, **opts):
2463 def debugwalk(ui, repo, *pats, **opts):
2464 """show how files match on given patterns"""
2464 """show how files match on given patterns"""
2465 m = scmutil.match(repo[None], pats, opts)
2465 m = scmutil.match(repo[None], pats, opts)
2466 items = list(repo.walk(m))
2466 items = list(repo.walk(m))
2467 if not items:
2467 if not items:
2468 return
2468 return
2469 f = lambda fn: fn
2469 f = lambda fn: fn
2470 if ui.configbool('ui', 'slash') and os.sep != '/':
2470 if ui.configbool('ui', 'slash') and os.sep != '/':
2471 f = lambda fn: util.normpath(fn)
2471 f = lambda fn: util.normpath(fn)
2472 fmt = 'f %%-%ds %%-%ds %%s' % (
2472 fmt = 'f %%-%ds %%-%ds %%s' % (
2473 max([len(abs) for abs in items]),
2473 max([len(abs) for abs in items]),
2474 max([len(m.rel(abs)) for abs in items]))
2474 max([len(m.rel(abs)) for abs in items]))
2475 for abs in items:
2475 for abs in items:
2476 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2476 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2477 ui.write("%s\n" % line.rstrip())
2477 ui.write("%s\n" % line.rstrip())
2478
2478
2479 @command('debugwireargs',
2479 @command('debugwireargs',
2480 [('', 'three', '', 'three'),
2480 [('', 'three', '', 'three'),
2481 ('', 'four', '', 'four'),
2481 ('', 'four', '', 'four'),
2482 ('', 'five', '', 'five'),
2482 ('', 'five', '', 'five'),
2483 ] + remoteopts,
2483 ] + remoteopts,
2484 _('REPO [OPTIONS]... [ONE [TWO]]'))
2484 _('REPO [OPTIONS]... [ONE [TWO]]'))
2485 def debugwireargs(ui, repopath, *vals, **opts):
2485 def debugwireargs(ui, repopath, *vals, **opts):
2486 repo = hg.peer(ui, opts, repopath)
2486 repo = hg.peer(ui, opts, repopath)
2487 for opt in remoteopts:
2487 for opt in remoteopts:
2488 del opts[opt[1]]
2488 del opts[opt[1]]
2489 args = {}
2489 args = {}
2490 for k, v in opts.iteritems():
2490 for k, v in opts.iteritems():
2491 if v:
2491 if v:
2492 args[k] = v
2492 args[k] = v
2493 # run twice to check that we don't mess up the stream for the next command
2493 # run twice to check that we don't mess up the stream for the next command
2494 res1 = repo.debugwireargs(*vals, **args)
2494 res1 = repo.debugwireargs(*vals, **args)
2495 res2 = repo.debugwireargs(*vals, **args)
2495 res2 = repo.debugwireargs(*vals, **args)
2496 ui.write("%s\n" % res1)
2496 ui.write("%s\n" % res1)
2497 if res1 != res2:
2497 if res1 != res2:
2498 ui.warn("%s\n" % res2)
2498 ui.warn("%s\n" % res2)
2499
2499
2500 @command('^diff',
2500 @command('^diff',
2501 [('r', 'rev', [], _('revision'), _('REV')),
2501 [('r', 'rev', [], _('revision'), _('REV')),
2502 ('c', 'change', '', _('change made by revision'), _('REV'))
2502 ('c', 'change', '', _('change made by revision'), _('REV'))
2503 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2503 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2504 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2504 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2505 def diff(ui, repo, *pats, **opts):
2505 def diff(ui, repo, *pats, **opts):
2506 """diff repository (or selected files)
2506 """diff repository (or selected files)
2507
2507
2508 Show differences between revisions for the specified files.
2508 Show differences between revisions for the specified files.
2509
2509
2510 Differences between files are shown using the unified diff format.
2510 Differences between files are shown using the unified diff format.
2511
2511
2512 .. note::
2512 .. note::
2513 diff may generate unexpected results for merges, as it will
2513 diff may generate unexpected results for merges, as it will
2514 default to comparing against the working directory's first
2514 default to comparing against the working directory's first
2515 parent changeset if no revisions are specified.
2515 parent changeset if no revisions are specified.
2516
2516
2517 When two revision arguments are given, then changes are shown
2517 When two revision arguments are given, then changes are shown
2518 between those revisions. If only one revision is specified then
2518 between those revisions. If only one revision is specified then
2519 that revision is compared to the working directory, and, when no
2519 that revision is compared to the working directory, and, when no
2520 revisions are specified, the working directory files are compared
2520 revisions are specified, the working directory files are compared
2521 to its parent.
2521 to its parent.
2522
2522
2523 Alternatively you can specify -c/--change with a revision to see
2523 Alternatively you can specify -c/--change with a revision to see
2524 the changes in that changeset relative to its first parent.
2524 the changes in that changeset relative to its first parent.
2525
2525
2526 Without the -a/--text option, diff will avoid generating diffs of
2526 Without the -a/--text option, diff will avoid generating diffs of
2527 files it detects as binary. With -a, diff will generate a diff
2527 files it detects as binary. With -a, diff will generate a diff
2528 anyway, probably with undesirable results.
2528 anyway, probably with undesirable results.
2529
2529
2530 Use the -g/--git option to generate diffs in the git extended diff
2530 Use the -g/--git option to generate diffs in the git extended diff
2531 format. For more information, read :hg:`help diffs`.
2531 format. For more information, read :hg:`help diffs`.
2532
2532
2533 .. container:: verbose
2533 .. container:: verbose
2534
2534
2535 Examples:
2535 Examples:
2536
2536
2537 - compare a file in the current working directory to its parent::
2537 - compare a file in the current working directory to its parent::
2538
2538
2539 hg diff foo.c
2539 hg diff foo.c
2540
2540
2541 - compare two historical versions of a directory, with rename info::
2541 - compare two historical versions of a directory, with rename info::
2542
2542
2543 hg diff --git -r 1.0:1.2 lib/
2543 hg diff --git -r 1.0:1.2 lib/
2544
2544
2545 - get change stats relative to the last change on some date::
2545 - get change stats relative to the last change on some date::
2546
2546
2547 hg diff --stat -r "date('may 2')"
2547 hg diff --stat -r "date('may 2')"
2548
2548
2549 - diff all newly-added files that contain a keyword::
2549 - diff all newly-added files that contain a keyword::
2550
2550
2551 hg diff "set:added() and grep(GNU)"
2551 hg diff "set:added() and grep(GNU)"
2552
2552
2553 - compare a revision and its parents::
2553 - compare a revision and its parents::
2554
2554
2555 hg diff -c 9353 # compare against first parent
2555 hg diff -c 9353 # compare against first parent
2556 hg diff -r 9353^:9353 # same using revset syntax
2556 hg diff -r 9353^:9353 # same using revset syntax
2557 hg diff -r 9353^2:9353 # compare against the second parent
2557 hg diff -r 9353^2:9353 # compare against the second parent
2558
2558
2559 Returns 0 on success.
2559 Returns 0 on success.
2560 """
2560 """
2561
2561
2562 revs = opts.get('rev')
2562 revs = opts.get('rev')
2563 change = opts.get('change')
2563 change = opts.get('change')
2564 stat = opts.get('stat')
2564 stat = opts.get('stat')
2565 reverse = opts.get('reverse')
2565 reverse = opts.get('reverse')
2566
2566
2567 if revs and change:
2567 if revs and change:
2568 msg = _('cannot specify --rev and --change at the same time')
2568 msg = _('cannot specify --rev and --change at the same time')
2569 raise util.Abort(msg)
2569 raise util.Abort(msg)
2570 elif change:
2570 elif change:
2571 node2 = scmutil.revsingle(repo, change, None).node()
2571 node2 = scmutil.revsingle(repo, change, None).node()
2572 node1 = repo[node2].p1().node()
2572 node1 = repo[node2].p1().node()
2573 else:
2573 else:
2574 node1, node2 = scmutil.revpair(repo, revs)
2574 node1, node2 = scmutil.revpair(repo, revs)
2575
2575
2576 if reverse:
2576 if reverse:
2577 node1, node2 = node2, node1
2577 node1, node2 = node2, node1
2578
2578
2579 diffopts = patch.diffopts(ui, opts)
2579 diffopts = patch.diffopts(ui, opts)
2580 m = scmutil.match(repo[node2], pats, opts)
2580 m = scmutil.match(repo[node2], pats, opts)
2581 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2581 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2582 listsubrepos=opts.get('subrepos'))
2582 listsubrepos=opts.get('subrepos'))
2583
2583
2584 @command('^export',
2584 @command('^export',
2585 [('o', 'output', '',
2585 [('o', 'output', '',
2586 _('print output to file with formatted name'), _('FORMAT')),
2586 _('print output to file with formatted name'), _('FORMAT')),
2587 ('', 'switch-parent', None, _('diff against the second parent')),
2587 ('', 'switch-parent', None, _('diff against the second parent')),
2588 ('r', 'rev', [], _('revisions to export'), _('REV')),
2588 ('r', 'rev', [], _('revisions to export'), _('REV')),
2589 ] + diffopts,
2589 ] + diffopts,
2590 _('[OPTION]... [-o OUTFILESPEC] [-r] REV...'))
2590 _('[OPTION]... [-o OUTFILESPEC] [-r] REV...'))
2591 def export(ui, repo, *changesets, **opts):
2591 def export(ui, repo, *changesets, **opts):
2592 """dump the header and diffs for one or more changesets
2592 """dump the header and diffs for one or more changesets
2593
2593
2594 Print the changeset header and diffs for one or more revisions.
2594 Print the changeset header and diffs for one or more revisions.
2595
2595
2596 The information shown in the changeset header is: author, date,
2596 The information shown in the changeset header is: author, date,
2597 branch name (if non-default), changeset hash, parent(s) and commit
2597 branch name (if non-default), changeset hash, parent(s) and commit
2598 comment.
2598 comment.
2599
2599
2600 .. note::
2600 .. note::
2601 export may generate unexpected diff output for merge
2601 export may generate unexpected diff output for merge
2602 changesets, as it will compare the merge changeset against its
2602 changesets, as it will compare the merge changeset against its
2603 first parent only.
2603 first parent only.
2604
2604
2605 Output may be to a file, in which case the name of the file is
2605 Output may be to a file, in which case the name of the file is
2606 given using a format string. The formatting rules are as follows:
2606 given using a format string. The formatting rules are as follows:
2607
2607
2608 :``%%``: literal "%" character
2608 :``%%``: literal "%" character
2609 :``%H``: changeset hash (40 hexadecimal digits)
2609 :``%H``: changeset hash (40 hexadecimal digits)
2610 :``%N``: number of patches being generated
2610 :``%N``: number of patches being generated
2611 :``%R``: changeset revision number
2611 :``%R``: changeset revision number
2612 :``%b``: basename of the exporting repository
2612 :``%b``: basename of the exporting repository
2613 :``%h``: short-form changeset hash (12 hexadecimal digits)
2613 :``%h``: short-form changeset hash (12 hexadecimal digits)
2614 :``%m``: first line of the commit message (only alphanumeric characters)
2614 :``%m``: first line of the commit message (only alphanumeric characters)
2615 :``%n``: zero-padded sequence number, starting at 1
2615 :``%n``: zero-padded sequence number, starting at 1
2616 :``%r``: zero-padded changeset revision number
2616 :``%r``: zero-padded changeset revision number
2617
2617
2618 Without the -a/--text option, export will avoid generating diffs
2618 Without the -a/--text option, export will avoid generating diffs
2619 of files it detects as binary. With -a, export will generate a
2619 of files it detects as binary. With -a, export will generate a
2620 diff anyway, probably with undesirable results.
2620 diff anyway, probably with undesirable results.
2621
2621
2622 Use the -g/--git option to generate diffs in the git extended diff
2622 Use the -g/--git option to generate diffs in the git extended diff
2623 format. See :hg:`help diffs` for more information.
2623 format. See :hg:`help diffs` for more information.
2624
2624
2625 With the --switch-parent option, the diff will be against the
2625 With the --switch-parent option, the diff will be against the
2626 second parent. It can be useful to review a merge.
2626 second parent. It can be useful to review a merge.
2627
2627
2628 .. container:: verbose
2628 .. container:: verbose
2629
2629
2630 Examples:
2630 Examples:
2631
2631
2632 - use export and import to transplant a bugfix to the current
2632 - use export and import to transplant a bugfix to the current
2633 branch::
2633 branch::
2634
2634
2635 hg export -r 9353 | hg import -
2635 hg export -r 9353 | hg import -
2636
2636
2637 - export all the changesets between two revisions to a file with
2637 - export all the changesets between two revisions to a file with
2638 rename information::
2638 rename information::
2639
2639
2640 hg export --git -r 123:150 > changes.txt
2640 hg export --git -r 123:150 > changes.txt
2641
2641
2642 - split outgoing changes into a series of patches with
2642 - split outgoing changes into a series of patches with
2643 descriptive names::
2643 descriptive names::
2644
2644
2645 hg export -r "outgoing()" -o "%n-%m.patch"
2645 hg export -r "outgoing()" -o "%n-%m.patch"
2646
2646
2647 Returns 0 on success.
2647 Returns 0 on success.
2648 """
2648 """
2649 changesets += tuple(opts.get('rev', []))
2649 changesets += tuple(opts.get('rev', []))
2650 revs = scmutil.revrange(repo, changesets)
2650 revs = scmutil.revrange(repo, changesets)
2651 if not revs:
2651 if not revs:
2652 raise util.Abort(_("export requires at least one changeset"))
2652 raise util.Abort(_("export requires at least one changeset"))
2653 if len(revs) > 1:
2653 if len(revs) > 1:
2654 ui.note(_('exporting patches:\n'))
2654 ui.note(_('exporting patches:\n'))
2655 else:
2655 else:
2656 ui.note(_('exporting patch:\n'))
2656 ui.note(_('exporting patch:\n'))
2657 cmdutil.export(repo, revs, template=opts.get('output'),
2657 cmdutil.export(repo, revs, template=opts.get('output'),
2658 switch_parent=opts.get('switch_parent'),
2658 switch_parent=opts.get('switch_parent'),
2659 opts=patch.diffopts(ui, opts))
2659 opts=patch.diffopts(ui, opts))
2660
2660
2661 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2661 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2662 def forget(ui, repo, *pats, **opts):
2662 def forget(ui, repo, *pats, **opts):
2663 """forget the specified files on the next commit
2663 """forget the specified files on the next commit
2664
2664
2665 Mark the specified files so they will no longer be tracked
2665 Mark the specified files so they will no longer be tracked
2666 after the next commit.
2666 after the next commit.
2667
2667
2668 This only removes files from the current branch, not from the
2668 This only removes files from the current branch, not from the
2669 entire project history, and it does not delete them from the
2669 entire project history, and it does not delete them from the
2670 working directory.
2670 working directory.
2671
2671
2672 To undo a forget before the next commit, see :hg:`add`.
2672 To undo a forget before the next commit, see :hg:`add`.
2673
2673
2674 .. container:: verbose
2674 .. container:: verbose
2675
2675
2676 Examples:
2676 Examples:
2677
2677
2678 - forget newly-added binary files::
2678 - forget newly-added binary files::
2679
2679
2680 hg forget "set:added() and binary()"
2680 hg forget "set:added() and binary()"
2681
2681
2682 - forget files that would be excluded by .hgignore::
2682 - forget files that would be excluded by .hgignore::
2683
2683
2684 hg forget "set:hgignore()"
2684 hg forget "set:hgignore()"
2685
2685
2686 Returns 0 on success.
2686 Returns 0 on success.
2687 """
2687 """
2688
2688
2689 if not pats:
2689 if not pats:
2690 raise util.Abort(_('no files specified'))
2690 raise util.Abort(_('no files specified'))
2691
2691
2692 m = scmutil.match(repo[None], pats, opts)
2692 m = scmutil.match(repo[None], pats, opts)
2693 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2693 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
2694 return rejected and 1 or 0
2694 return rejected and 1 or 0
2695
2695
2696 @command(
2696 @command(
2697 'graft',
2697 'graft',
2698 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2698 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2699 ('c', 'continue', False, _('resume interrupted graft')),
2699 ('c', 'continue', False, _('resume interrupted graft')),
2700 ('e', 'edit', False, _('invoke editor on commit messages')),
2700 ('e', 'edit', False, _('invoke editor on commit messages')),
2701 ('', 'log', None, _('append graft info to log message')),
2701 ('', 'log', None, _('append graft info to log message')),
2702 ('D', 'currentdate', False,
2702 ('D', 'currentdate', False,
2703 _('record the current date as commit date')),
2703 _('record the current date as commit date')),
2704 ('U', 'currentuser', False,
2704 ('U', 'currentuser', False,
2705 _('record the current user as committer'), _('DATE'))]
2705 _('record the current user as committer'), _('DATE'))]
2706 + commitopts2 + mergetoolopts + dryrunopts,
2706 + commitopts2 + mergetoolopts + dryrunopts,
2707 _('[OPTION]... [-r] REV...'))
2707 _('[OPTION]... [-r] REV...'))
2708 def graft(ui, repo, *revs, **opts):
2708 def graft(ui, repo, *revs, **opts):
2709 '''copy changes from other branches onto the current branch
2709 '''copy changes from other branches onto the current branch
2710
2710
2711 This command uses Mercurial's merge logic to copy individual
2711 This command uses Mercurial's merge logic to copy individual
2712 changes from other branches without merging branches in the
2712 changes from other branches without merging branches in the
2713 history graph. This is sometimes known as 'backporting' or
2713 history graph. This is sometimes known as 'backporting' or
2714 'cherry-picking'. By default, graft will copy user, date, and
2714 'cherry-picking'. By default, graft will copy user, date, and
2715 description from the source changesets.
2715 description from the source changesets.
2716
2716
2717 Changesets that are ancestors of the current revision, that have
2717 Changesets that are ancestors of the current revision, that have
2718 already been grafted, or that are merges will be skipped.
2718 already been grafted, or that are merges will be skipped.
2719
2719
2720 If --log is specified, log messages will have a comment appended
2720 If --log is specified, log messages will have a comment appended
2721 of the form::
2721 of the form::
2722
2722
2723 (grafted from CHANGESETHASH)
2723 (grafted from CHANGESETHASH)
2724
2724
2725 If a graft merge results in conflicts, the graft process is
2725 If a graft merge results in conflicts, the graft process is
2726 interrupted so that the current merge can be manually resolved.
2726 interrupted so that the current merge can be manually resolved.
2727 Once all conflicts are addressed, the graft process can be
2727 Once all conflicts are addressed, the graft process can be
2728 continued with the -c/--continue option.
2728 continued with the -c/--continue option.
2729
2729
2730 .. note::
2730 .. note::
2731 The -c/--continue option does not reapply earlier options.
2731 The -c/--continue option does not reapply earlier options.
2732
2732
2733 .. container:: verbose
2733 .. container:: verbose
2734
2734
2735 Examples:
2735 Examples:
2736
2736
2737 - copy a single change to the stable branch and edit its description::
2737 - copy a single change to the stable branch and edit its description::
2738
2738
2739 hg update stable
2739 hg update stable
2740 hg graft --edit 9393
2740 hg graft --edit 9393
2741
2741
2742 - graft a range of changesets with one exception, updating dates::
2742 - graft a range of changesets with one exception, updating dates::
2743
2743
2744 hg graft -D "2085::2093 and not 2091"
2744 hg graft -D "2085::2093 and not 2091"
2745
2745
2746 - continue a graft after resolving conflicts::
2746 - continue a graft after resolving conflicts::
2747
2747
2748 hg graft -c
2748 hg graft -c
2749
2749
2750 - show the source of a grafted changeset::
2750 - show the source of a grafted changeset::
2751
2751
2752 hg log --debug -r tip
2752 hg log --debug -r tip
2753
2753
2754 Returns 0 on successful completion.
2754 Returns 0 on successful completion.
2755 '''
2755 '''
2756
2756
2757 revs = list(revs)
2757 revs = list(revs)
2758 revs.extend(opts['rev'])
2758 revs.extend(opts['rev'])
2759
2759
2760 if not opts.get('user') and opts.get('currentuser'):
2760 if not opts.get('user') and opts.get('currentuser'):
2761 opts['user'] = ui.username()
2761 opts['user'] = ui.username()
2762 if not opts.get('date') and opts.get('currentdate'):
2762 if not opts.get('date') and opts.get('currentdate'):
2763 opts['date'] = "%d %d" % util.makedate()
2763 opts['date'] = "%d %d" % util.makedate()
2764
2764
2765 editor = None
2765 editor = None
2766 if opts.get('edit'):
2766 if opts.get('edit'):
2767 editor = cmdutil.commitforceeditor
2767 editor = cmdutil.commitforceeditor
2768
2768
2769 cont = False
2769 cont = False
2770 if opts['continue']:
2770 if opts['continue']:
2771 cont = True
2771 cont = True
2772 if revs:
2772 if revs:
2773 raise util.Abort(_("can't specify --continue and revisions"))
2773 raise util.Abort(_("can't specify --continue and revisions"))
2774 # read in unfinished revisions
2774 # read in unfinished revisions
2775 try:
2775 try:
2776 nodes = repo.opener.read('graftstate').splitlines()
2776 nodes = repo.opener.read('graftstate').splitlines()
2777 revs = [repo[node].rev() for node in nodes]
2777 revs = [repo[node].rev() for node in nodes]
2778 except IOError, inst:
2778 except IOError, inst:
2779 if inst.errno != errno.ENOENT:
2779 if inst.errno != errno.ENOENT:
2780 raise
2780 raise
2781 raise util.Abort(_("no graft state found, can't continue"))
2781 raise util.Abort(_("no graft state found, can't continue"))
2782 else:
2782 else:
2783 cmdutil.bailifchanged(repo)
2783 cmdutil.bailifchanged(repo)
2784 if not revs:
2784 if not revs:
2785 raise util.Abort(_('no revisions specified'))
2785 raise util.Abort(_('no revisions specified'))
2786 revs = scmutil.revrange(repo, revs)
2786 revs = scmutil.revrange(repo, revs)
2787
2787
2788 # check for merges
2788 # check for merges
2789 for rev in repo.revs('%ld and merge()', revs):
2789 for rev in repo.revs('%ld and merge()', revs):
2790 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2790 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
2791 revs.remove(rev)
2791 revs.remove(rev)
2792 if not revs:
2792 if not revs:
2793 return -1
2793 return -1
2794
2794
2795 # check for ancestors of dest branch
2795 # check for ancestors of dest branch
2796 for rev in repo.revs('::. and %ld', revs):
2796 for rev in repo.revs('::. and %ld', revs):
2797 ui.warn(_('skipping ancestor revision %s\n') % rev)
2797 ui.warn(_('skipping ancestor revision %s\n') % rev)
2798 revs.remove(rev)
2798 revs.remove(rev)
2799 if not revs:
2799 if not revs:
2800 return -1
2800 return -1
2801
2801
2802 # analyze revs for earlier grafts
2802 # analyze revs for earlier grafts
2803 ids = {}
2803 ids = {}
2804 for ctx in repo.set("%ld", revs):
2804 for ctx in repo.set("%ld", revs):
2805 ids[ctx.hex()] = ctx.rev()
2805 ids[ctx.hex()] = ctx.rev()
2806 n = ctx.extra().get('source')
2806 n = ctx.extra().get('source')
2807 if n:
2807 if n:
2808 ids[n] = ctx.rev()
2808 ids[n] = ctx.rev()
2809
2809
2810 # check ancestors for earlier grafts
2810 # check ancestors for earlier grafts
2811 ui.debug('scanning for duplicate grafts\n')
2811 ui.debug('scanning for duplicate grafts\n')
2812 for ctx in repo.set("::. - ::%ld", revs):
2812 for ctx in repo.set("::. - ::%ld", revs):
2813 n = ctx.extra().get('source')
2813 n = ctx.extra().get('source')
2814 if n in ids:
2814 if n in ids:
2815 r = repo[n].rev()
2815 r = repo[n].rev()
2816 if r in revs:
2816 if r in revs:
2817 ui.warn(_('skipping already grafted revision %s\n') % r)
2817 ui.warn(_('skipping already grafted revision %s\n') % r)
2818 revs.remove(r)
2818 revs.remove(r)
2819 elif ids[n] in revs:
2819 elif ids[n] in revs:
2820 ui.warn(_('skipping already grafted revision %s '
2820 ui.warn(_('skipping already grafted revision %s '
2821 '(same origin %d)\n') % (ids[n], r))
2821 '(same origin %d)\n') % (ids[n], r))
2822 revs.remove(ids[n])
2822 revs.remove(ids[n])
2823 elif ctx.hex() in ids:
2823 elif ctx.hex() in ids:
2824 r = ids[ctx.hex()]
2824 r = ids[ctx.hex()]
2825 ui.warn(_('skipping already grafted revision %s '
2825 ui.warn(_('skipping already grafted revision %s '
2826 '(was grafted from %d)\n') % (r, ctx.rev()))
2826 '(was grafted from %d)\n') % (r, ctx.rev()))
2827 revs.remove(r)
2827 revs.remove(r)
2828 if not revs:
2828 if not revs:
2829 return -1
2829 return -1
2830
2830
2831 wlock = repo.wlock()
2831 wlock = repo.wlock()
2832 try:
2832 try:
2833 current = repo['.']
2833 current = repo['.']
2834 for pos, ctx in enumerate(repo.set("%ld", revs)):
2834 for pos, ctx in enumerate(repo.set("%ld", revs)):
2835
2835
2836 ui.status(_('grafting revision %s\n') % ctx.rev())
2836 ui.status(_('grafting revision %s\n') % ctx.rev())
2837 if opts.get('dry_run'):
2837 if opts.get('dry_run'):
2838 continue
2838 continue
2839
2839
2840 source = ctx.extra().get('source')
2840 source = ctx.extra().get('source')
2841 if not source:
2841 if not source:
2842 source = ctx.hex()
2842 source = ctx.hex()
2843 extra = {'source': source}
2843 extra = {'source': source}
2844 user = ctx.user()
2844 user = ctx.user()
2845 if opts.get('user'):
2845 if opts.get('user'):
2846 user = opts['user']
2846 user = opts['user']
2847 date = ctx.date()
2847 date = ctx.date()
2848 if opts.get('date'):
2848 if opts.get('date'):
2849 date = opts['date']
2849 date = opts['date']
2850 message = ctx.description()
2850 message = ctx.description()
2851 if opts.get('log'):
2851 if opts.get('log'):
2852 message += '\n(grafted from %s)' % ctx.hex()
2852 message += '\n(grafted from %s)' % ctx.hex()
2853
2853
2854 # we don't merge the first commit when continuing
2854 # we don't merge the first commit when continuing
2855 if not cont:
2855 if not cont:
2856 # perform the graft merge with p1(rev) as 'ancestor'
2856 # perform the graft merge with p1(rev) as 'ancestor'
2857 try:
2857 try:
2858 # ui.forcemerge is an internal variable, do not document
2858 # ui.forcemerge is an internal variable, do not document
2859 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2859 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
2860 stats = mergemod.update(repo, ctx.node(), True, True, False,
2860 stats = mergemod.update(repo, ctx.node(), True, True, False,
2861 ctx.p1().node())
2861 ctx.p1().node())
2862 finally:
2862 finally:
2863 repo.ui.setconfig('ui', 'forcemerge', '')
2863 repo.ui.setconfig('ui', 'forcemerge', '')
2864 # report any conflicts
2864 # report any conflicts
2865 if stats and stats[3] > 0:
2865 if stats and stats[3] > 0:
2866 # write out state for --continue
2866 # write out state for --continue
2867 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2867 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
2868 repo.opener.write('graftstate', ''.join(nodelines))
2868 repo.opener.write('graftstate', ''.join(nodelines))
2869 raise util.Abort(
2869 raise util.Abort(
2870 _("unresolved conflicts, can't continue"),
2870 _("unresolved conflicts, can't continue"),
2871 hint=_('use hg resolve and hg graft --continue'))
2871 hint=_('use hg resolve and hg graft --continue'))
2872 else:
2872 else:
2873 cont = False
2873 cont = False
2874
2874
2875 # drop the second merge parent
2875 # drop the second merge parent
2876 repo.setparents(current.node(), nullid)
2876 repo.setparents(current.node(), nullid)
2877 repo.dirstate.write()
2877 repo.dirstate.write()
2878 # fix up dirstate for copies and renames
2878 # fix up dirstate for copies and renames
2879 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2879 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
2880
2880
2881 # commit
2881 # commit
2882 node = repo.commit(text=message, user=user,
2882 node = repo.commit(text=message, user=user,
2883 date=date, extra=extra, editor=editor)
2883 date=date, extra=extra, editor=editor)
2884 if node is None:
2884 if node is None:
2885 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2885 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
2886 else:
2886 else:
2887 current = repo[node]
2887 current = repo[node]
2888 finally:
2888 finally:
2889 wlock.release()
2889 wlock.release()
2890
2890
2891 # remove state when we complete successfully
2891 # remove state when we complete successfully
2892 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2892 if not opts.get('dry_run') and os.path.exists(repo.join('graftstate')):
2893 util.unlinkpath(repo.join('graftstate'))
2893 util.unlinkpath(repo.join('graftstate'))
2894
2894
2895 return 0
2895 return 0
2896
2896
2897 @command('grep',
2897 @command('grep',
2898 [('0', 'print0', None, _('end fields with NUL')),
2898 [('0', 'print0', None, _('end fields with NUL')),
2899 ('', 'all', None, _('print all revisions that match')),
2899 ('', 'all', None, _('print all revisions that match')),
2900 ('a', 'text', None, _('treat all files as text')),
2900 ('a', 'text', None, _('treat all files as text')),
2901 ('f', 'follow', None,
2901 ('f', 'follow', None,
2902 _('follow changeset history,'
2902 _('follow changeset history,'
2903 ' or file history across copies and renames')),
2903 ' or file history across copies and renames')),
2904 ('i', 'ignore-case', None, _('ignore case when matching')),
2904 ('i', 'ignore-case', None, _('ignore case when matching')),
2905 ('l', 'files-with-matches', None,
2905 ('l', 'files-with-matches', None,
2906 _('print only filenames and revisions that match')),
2906 _('print only filenames and revisions that match')),
2907 ('n', 'line-number', None, _('print matching line numbers')),
2907 ('n', 'line-number', None, _('print matching line numbers')),
2908 ('r', 'rev', [],
2908 ('r', 'rev', [],
2909 _('only search files changed within revision range'), _('REV')),
2909 _('only search files changed within revision range'), _('REV')),
2910 ('u', 'user', None, _('list the author (long with -v)')),
2910 ('u', 'user', None, _('list the author (long with -v)')),
2911 ('d', 'date', None, _('list the date (short with -q)')),
2911 ('d', 'date', None, _('list the date (short with -q)')),
2912 ] + walkopts,
2912 ] + walkopts,
2913 _('[OPTION]... PATTERN [FILE]...'))
2913 _('[OPTION]... PATTERN [FILE]...'))
2914 def grep(ui, repo, pattern, *pats, **opts):
2914 def grep(ui, repo, pattern, *pats, **opts):
2915 """search for a pattern in specified files and revisions
2915 """search for a pattern in specified files and revisions
2916
2916
2917 Search revisions of files for a regular expression.
2917 Search revisions of files for a regular expression.
2918
2918
2919 This command behaves differently than Unix grep. It only accepts
2919 This command behaves differently than Unix grep. It only accepts
2920 Python/Perl regexps. It searches repository history, not the
2920 Python/Perl regexps. It searches repository history, not the
2921 working directory. It always prints the revision number in which a
2921 working directory. It always prints the revision number in which a
2922 match appears.
2922 match appears.
2923
2923
2924 By default, grep only prints output for the first revision of a
2924 By default, grep only prints output for the first revision of a
2925 file in which it finds a match. To get it to print every revision
2925 file in which it finds a match. To get it to print every revision
2926 that contains a change in match status ("-" for a match that
2926 that contains a change in match status ("-" for a match that
2927 becomes a non-match, or "+" for a non-match that becomes a match),
2927 becomes a non-match, or "+" for a non-match that becomes a match),
2928 use the --all flag.
2928 use the --all flag.
2929
2929
2930 Returns 0 if a match is found, 1 otherwise.
2930 Returns 0 if a match is found, 1 otherwise.
2931 """
2931 """
2932 reflags = re.M
2932 reflags = re.M
2933 if opts.get('ignore_case'):
2933 if opts.get('ignore_case'):
2934 reflags |= re.I
2934 reflags |= re.I
2935 try:
2935 try:
2936 regexp = re.compile(pattern, reflags)
2936 regexp = re.compile(pattern, reflags)
2937 except re.error, inst:
2937 except re.error, inst:
2938 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2938 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2939 return 1
2939 return 1
2940 sep, eol = ':', '\n'
2940 sep, eol = ':', '\n'
2941 if opts.get('print0'):
2941 if opts.get('print0'):
2942 sep = eol = '\0'
2942 sep = eol = '\0'
2943
2943
2944 getfile = util.lrucachefunc(repo.file)
2944 getfile = util.lrucachefunc(repo.file)
2945
2945
2946 def matchlines(body):
2946 def matchlines(body):
2947 begin = 0
2947 begin = 0
2948 linenum = 0
2948 linenum = 0
2949 while begin < len(body):
2949 while begin < len(body):
2950 match = regexp.search(body, begin)
2950 match = regexp.search(body, begin)
2951 if not match:
2951 if not match:
2952 break
2952 break
2953 mstart, mend = match.span()
2953 mstart, mend = match.span()
2954 linenum += body.count('\n', begin, mstart) + 1
2954 linenum += body.count('\n', begin, mstart) + 1
2955 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2955 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2956 begin = body.find('\n', mend) + 1 or len(body) + 1
2956 begin = body.find('\n', mend) + 1 or len(body) + 1
2957 lend = begin - 1
2957 lend = begin - 1
2958 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2958 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2959
2959
2960 class linestate(object):
2960 class linestate(object):
2961 def __init__(self, line, linenum, colstart, colend):
2961 def __init__(self, line, linenum, colstart, colend):
2962 self.line = line
2962 self.line = line
2963 self.linenum = linenum
2963 self.linenum = linenum
2964 self.colstart = colstart
2964 self.colstart = colstart
2965 self.colend = colend
2965 self.colend = colend
2966
2966
2967 def __hash__(self):
2967 def __hash__(self):
2968 return hash((self.linenum, self.line))
2968 return hash((self.linenum, self.line))
2969
2969
2970 def __eq__(self, other):
2970 def __eq__(self, other):
2971 return self.line == other.line
2971 return self.line == other.line
2972
2972
2973 matches = {}
2973 matches = {}
2974 copies = {}
2974 copies = {}
2975 def grepbody(fn, rev, body):
2975 def grepbody(fn, rev, body):
2976 matches[rev].setdefault(fn, [])
2976 matches[rev].setdefault(fn, [])
2977 m = matches[rev][fn]
2977 m = matches[rev][fn]
2978 for lnum, cstart, cend, line in matchlines(body):
2978 for lnum, cstart, cend, line in matchlines(body):
2979 s = linestate(line, lnum, cstart, cend)
2979 s = linestate(line, lnum, cstart, cend)
2980 m.append(s)
2980 m.append(s)
2981
2981
2982 def difflinestates(a, b):
2982 def difflinestates(a, b):
2983 sm = difflib.SequenceMatcher(None, a, b)
2983 sm = difflib.SequenceMatcher(None, a, b)
2984 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2984 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2985 if tag == 'insert':
2985 if tag == 'insert':
2986 for i in xrange(blo, bhi):
2986 for i in xrange(blo, bhi):
2987 yield ('+', b[i])
2987 yield ('+', b[i])
2988 elif tag == 'delete':
2988 elif tag == 'delete':
2989 for i in xrange(alo, ahi):
2989 for i in xrange(alo, ahi):
2990 yield ('-', a[i])
2990 yield ('-', a[i])
2991 elif tag == 'replace':
2991 elif tag == 'replace':
2992 for i in xrange(alo, ahi):
2992 for i in xrange(alo, ahi):
2993 yield ('-', a[i])
2993 yield ('-', a[i])
2994 for i in xrange(blo, bhi):
2994 for i in xrange(blo, bhi):
2995 yield ('+', b[i])
2995 yield ('+', b[i])
2996
2996
2997 def display(fn, ctx, pstates, states):
2997 def display(fn, ctx, pstates, states):
2998 rev = ctx.rev()
2998 rev = ctx.rev()
2999 datefunc = ui.quiet and util.shortdate or util.datestr
2999 datefunc = ui.quiet and util.shortdate or util.datestr
3000 found = False
3000 found = False
3001 filerevmatches = {}
3001 filerevmatches = {}
3002 def binary():
3002 def binary():
3003 flog = getfile(fn)
3003 flog = getfile(fn)
3004 return util.binary(flog.read(ctx.filenode(fn)))
3004 return util.binary(flog.read(ctx.filenode(fn)))
3005
3005
3006 if opts.get('all'):
3006 if opts.get('all'):
3007 iter = difflinestates(pstates, states)
3007 iter = difflinestates(pstates, states)
3008 else:
3008 else:
3009 iter = [('', l) for l in states]
3009 iter = [('', l) for l in states]
3010 for change, l in iter:
3010 for change, l in iter:
3011 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3011 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3012 before, match, after = None, None, None
3012 before, match, after = None, None, None
3013
3013
3014 if opts.get('line_number'):
3014 if opts.get('line_number'):
3015 cols.append((str(l.linenum), 'grep.linenumber'))
3015 cols.append((str(l.linenum), 'grep.linenumber'))
3016 if opts.get('all'):
3016 if opts.get('all'):
3017 cols.append((change, 'grep.change'))
3017 cols.append((change, 'grep.change'))
3018 if opts.get('user'):
3018 if opts.get('user'):
3019 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3019 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3020 if opts.get('date'):
3020 if opts.get('date'):
3021 cols.append((datefunc(ctx.date()), 'grep.date'))
3021 cols.append((datefunc(ctx.date()), 'grep.date'))
3022 if opts.get('files_with_matches'):
3022 if opts.get('files_with_matches'):
3023 c = (fn, rev)
3023 c = (fn, rev)
3024 if c in filerevmatches:
3024 if c in filerevmatches:
3025 continue
3025 continue
3026 filerevmatches[c] = 1
3026 filerevmatches[c] = 1
3027 else:
3027 else:
3028 before = l.line[:l.colstart]
3028 before = l.line[:l.colstart]
3029 match = l.line[l.colstart:l.colend]
3029 match = l.line[l.colstart:l.colend]
3030 after = l.line[l.colend:]
3030 after = l.line[l.colend:]
3031 for col, label in cols[:-1]:
3031 for col, label in cols[:-1]:
3032 ui.write(col, label=label)
3032 ui.write(col, label=label)
3033 ui.write(sep, label='grep.sep')
3033 ui.write(sep, label='grep.sep')
3034 ui.write(cols[-1][0], label=cols[-1][1])
3034 ui.write(cols[-1][0], label=cols[-1][1])
3035 if before is not None:
3035 if before is not None:
3036 ui.write(sep, label='grep.sep')
3036 ui.write(sep, label='grep.sep')
3037 if not opts.get('text') and binary():
3037 if not opts.get('text') and binary():
3038 ui.write(" Binary file matches")
3038 ui.write(" Binary file matches")
3039 else:
3039 else:
3040 ui.write(before)
3040 ui.write(before)
3041 ui.write(match, label='grep.match')
3041 ui.write(match, label='grep.match')
3042 ui.write(after)
3042 ui.write(after)
3043 ui.write(eol)
3043 ui.write(eol)
3044 found = True
3044 found = True
3045 return found
3045 return found
3046
3046
3047 skip = {}
3047 skip = {}
3048 revfiles = {}
3048 revfiles = {}
3049 matchfn = scmutil.match(repo[None], pats, opts)
3049 matchfn = scmutil.match(repo[None], pats, opts)
3050 found = False
3050 found = False
3051 follow = opts.get('follow')
3051 follow = opts.get('follow')
3052
3052
3053 def prep(ctx, fns):
3053 def prep(ctx, fns):
3054 rev = ctx.rev()
3054 rev = ctx.rev()
3055 pctx = ctx.p1()
3055 pctx = ctx.p1()
3056 parent = pctx.rev()
3056 parent = pctx.rev()
3057 matches.setdefault(rev, {})
3057 matches.setdefault(rev, {})
3058 matches.setdefault(parent, {})
3058 matches.setdefault(parent, {})
3059 files = revfiles.setdefault(rev, [])
3059 files = revfiles.setdefault(rev, [])
3060 for fn in fns:
3060 for fn in fns:
3061 flog = getfile(fn)
3061 flog = getfile(fn)
3062 try:
3062 try:
3063 fnode = ctx.filenode(fn)
3063 fnode = ctx.filenode(fn)
3064 except error.LookupError:
3064 except error.LookupError:
3065 continue
3065 continue
3066
3066
3067 copied = flog.renamed(fnode)
3067 copied = flog.renamed(fnode)
3068 copy = follow and copied and copied[0]
3068 copy = follow and copied and copied[0]
3069 if copy:
3069 if copy:
3070 copies.setdefault(rev, {})[fn] = copy
3070 copies.setdefault(rev, {})[fn] = copy
3071 if fn in skip:
3071 if fn in skip:
3072 if copy:
3072 if copy:
3073 skip[copy] = True
3073 skip[copy] = True
3074 continue
3074 continue
3075 files.append(fn)
3075 files.append(fn)
3076
3076
3077 if fn not in matches[rev]:
3077 if fn not in matches[rev]:
3078 grepbody(fn, rev, flog.read(fnode))
3078 grepbody(fn, rev, flog.read(fnode))
3079
3079
3080 pfn = copy or fn
3080 pfn = copy or fn
3081 if pfn not in matches[parent]:
3081 if pfn not in matches[parent]:
3082 try:
3082 try:
3083 fnode = pctx.filenode(pfn)
3083 fnode = pctx.filenode(pfn)
3084 grepbody(pfn, parent, flog.read(fnode))
3084 grepbody(pfn, parent, flog.read(fnode))
3085 except error.LookupError:
3085 except error.LookupError:
3086 pass
3086 pass
3087
3087
3088 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3088 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3089 rev = ctx.rev()
3089 rev = ctx.rev()
3090 parent = ctx.p1().rev()
3090 parent = ctx.p1().rev()
3091 for fn in sorted(revfiles.get(rev, [])):
3091 for fn in sorted(revfiles.get(rev, [])):
3092 states = matches[rev][fn]
3092 states = matches[rev][fn]
3093 copy = copies.get(rev, {}).get(fn)
3093 copy = copies.get(rev, {}).get(fn)
3094 if fn in skip:
3094 if fn in skip:
3095 if copy:
3095 if copy:
3096 skip[copy] = True
3096 skip[copy] = True
3097 continue
3097 continue
3098 pstates = matches.get(parent, {}).get(copy or fn, [])
3098 pstates = matches.get(parent, {}).get(copy or fn, [])
3099 if pstates or states:
3099 if pstates or states:
3100 r = display(fn, ctx, pstates, states)
3100 r = display(fn, ctx, pstates, states)
3101 found = found or r
3101 found = found or r
3102 if r and not opts.get('all'):
3102 if r and not opts.get('all'):
3103 skip[fn] = True
3103 skip[fn] = True
3104 if copy:
3104 if copy:
3105 skip[copy] = True
3105 skip[copy] = True
3106 del matches[rev]
3106 del matches[rev]
3107 del revfiles[rev]
3107 del revfiles[rev]
3108
3108
3109 return not found
3109 return not found
3110
3110
3111 @command('heads',
3111 @command('heads',
3112 [('r', 'rev', '',
3112 [('r', 'rev', '',
3113 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3113 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3114 ('t', 'topo', False, _('show topological heads only')),
3114 ('t', 'topo', False, _('show topological heads only')),
3115 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3115 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3116 ('c', 'closed', False, _('show normal and closed branch heads')),
3116 ('c', 'closed', False, _('show normal and closed branch heads')),
3117 ] + templateopts,
3117 ] + templateopts,
3118 _('[-ct] [-r STARTREV] [REV]...'))
3118 _('[-ct] [-r STARTREV] [REV]...'))
3119 def heads(ui, repo, *branchrevs, **opts):
3119 def heads(ui, repo, *branchrevs, **opts):
3120 """show current repository heads or show branch heads
3120 """show current repository heads or show branch heads
3121
3121
3122 With no arguments, show all repository branch heads.
3122 With no arguments, show all repository branch heads.
3123
3123
3124 Repository "heads" are changesets with no child changesets. They are
3124 Repository "heads" are changesets with no child changesets. They are
3125 where development generally takes place and are the usual targets
3125 where development generally takes place and are the usual targets
3126 for update and merge operations. Branch heads are changesets that have
3126 for update and merge operations. Branch heads are changesets that have
3127 no child changeset on the same branch.
3127 no child changeset on the same branch.
3128
3128
3129 If one or more REVs are given, only branch heads on the branches
3129 If one or more REVs are given, only branch heads on the branches
3130 associated with the specified changesets are shown. This means
3130 associated with the specified changesets are shown. This means
3131 that you can use :hg:`heads foo` to see the heads on a branch
3131 that you can use :hg:`heads foo` to see the heads on a branch
3132 named ``foo``.
3132 named ``foo``.
3133
3133
3134 If -c/--closed is specified, also show branch heads marked closed
3134 If -c/--closed is specified, also show branch heads marked closed
3135 (see :hg:`commit --close-branch`).
3135 (see :hg:`commit --close-branch`).
3136
3136
3137 If STARTREV is specified, only those heads that are descendants of
3137 If STARTREV is specified, only those heads that are descendants of
3138 STARTREV will be displayed.
3138 STARTREV will be displayed.
3139
3139
3140 If -t/--topo is specified, named branch mechanics will be ignored and only
3140 If -t/--topo is specified, named branch mechanics will be ignored and only
3141 changesets without children will be shown.
3141 changesets without children will be shown.
3142
3142
3143 Returns 0 if matching heads are found, 1 if not.
3143 Returns 0 if matching heads are found, 1 if not.
3144 """
3144 """
3145
3145
3146 start = None
3146 start = None
3147 if 'rev' in opts:
3147 if 'rev' in opts:
3148 start = scmutil.revsingle(repo, opts['rev'], None).node()
3148 start = scmutil.revsingle(repo, opts['rev'], None).node()
3149
3149
3150 if opts.get('topo'):
3150 if opts.get('topo'):
3151 heads = [repo[h] for h in repo.heads(start)]
3151 heads = [repo[h] for h in repo.heads(start)]
3152 else:
3152 else:
3153 heads = []
3153 heads = []
3154 for branch in repo.branchmap():
3154 for branch in repo.branchmap():
3155 heads += repo.branchheads(branch, start, opts.get('closed'))
3155 heads += repo.branchheads(branch, start, opts.get('closed'))
3156 heads = [repo[h] for h in heads]
3156 heads = [repo[h] for h in heads]
3157
3157
3158 if branchrevs:
3158 if branchrevs:
3159 branches = set(repo[br].branch() for br in branchrevs)
3159 branches = set(repo[br].branch() for br in branchrevs)
3160 heads = [h for h in heads if h.branch() in branches]
3160 heads = [h for h in heads if h.branch() in branches]
3161
3161
3162 if opts.get('active') and branchrevs:
3162 if opts.get('active') and branchrevs:
3163 dagheads = repo.heads(start)
3163 dagheads = repo.heads(start)
3164 heads = [h for h in heads if h.node() in dagheads]
3164 heads = [h for h in heads if h.node() in dagheads]
3165
3165
3166 if branchrevs:
3166 if branchrevs:
3167 haveheads = set(h.branch() for h in heads)
3167 haveheads = set(h.branch() for h in heads)
3168 if branches - haveheads:
3168 if branches - haveheads:
3169 headless = ', '.join(b for b in branches - haveheads)
3169 headless = ', '.join(b for b in branches - haveheads)
3170 msg = _('no open branch heads found on branches %s')
3170 msg = _('no open branch heads found on branches %s')
3171 if opts.get('rev'):
3171 if opts.get('rev'):
3172 msg += _(' (started at %s)') % opts['rev']
3172 msg += _(' (started at %s)') % opts['rev']
3173 ui.warn((msg + '\n') % headless)
3173 ui.warn((msg + '\n') % headless)
3174
3174
3175 if not heads:
3175 if not heads:
3176 return 1
3176 return 1
3177
3177
3178 heads = sorted(heads, key=lambda x: -x.rev())
3178 heads = sorted(heads, key=lambda x: -x.rev())
3179 displayer = cmdutil.show_changeset(ui, repo, opts)
3179 displayer = cmdutil.show_changeset(ui, repo, opts)
3180 for ctx in heads:
3180 for ctx in heads:
3181 displayer.show(ctx)
3181 displayer.show(ctx)
3182 displayer.close()
3182 displayer.close()
3183
3183
3184 @command('help',
3184 @command('help',
3185 [('e', 'extension', None, _('show only help for extensions')),
3185 [('e', 'extension', None, _('show only help for extensions')),
3186 ('c', 'command', None, _('show only help for commands')),
3186 ('c', 'command', None, _('show only help for commands')),
3187 ('k', 'keyword', '', _('show topics matching keyword')),
3187 ('k', 'keyword', '', _('show topics matching keyword')),
3188 ],
3188 ],
3189 _('[-ec] [TOPIC]'))
3189 _('[-ec] [TOPIC]'))
3190 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3190 def help_(ui, name=None, unknowncmd=False, full=True, **opts):
3191 """show help for a given topic or a help overview
3191 """show help for a given topic or a help overview
3192
3192
3193 With no arguments, print a list of commands with short help messages.
3193 With no arguments, print a list of commands with short help messages.
3194
3194
3195 Given a topic, extension, or command name, print help for that
3195 Given a topic, extension, or command name, print help for that
3196 topic.
3196 topic.
3197
3197
3198 Returns 0 if successful.
3198 Returns 0 if successful.
3199 """
3199 """
3200
3200
3201 textwidth = min(ui.termwidth(), 80) - 2
3201 textwidth = min(ui.termwidth(), 80) - 2
3202
3202
3203 def helpcmd(name):
3203 def helpcmd(name):
3204 try:
3204 try:
3205 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3205 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
3206 except error.AmbiguousCommand, inst:
3206 except error.AmbiguousCommand, inst:
3207 # py3k fix: except vars can't be used outside the scope of the
3207 # py3k fix: except vars can't be used outside the scope of the
3208 # except block, nor can be used inside a lambda. python issue4617
3208 # except block, nor can be used inside a lambda. python issue4617
3209 prefix = inst.args[0]
3209 prefix = inst.args[0]
3210 select = lambda c: c.lstrip('^').startswith(prefix)
3210 select = lambda c: c.lstrip('^').startswith(prefix)
3211 rst = helplist(select)
3211 rst = helplist(select)
3212 return rst
3212 return rst
3213
3213
3214 rst = []
3214 rst = []
3215
3215
3216 # check if it's an invalid alias and display its error if it is
3216 # check if it's an invalid alias and display its error if it is
3217 if getattr(entry[0], 'badalias', False):
3217 if getattr(entry[0], 'badalias', False):
3218 if not unknowncmd:
3218 if not unknowncmd:
3219 ui.pushbuffer()
3219 ui.pushbuffer()
3220 entry[0](ui)
3220 entry[0](ui)
3221 rst.append(ui.popbuffer())
3221 rst.append(ui.popbuffer())
3222 return rst
3222 return rst
3223
3223
3224 # synopsis
3224 # synopsis
3225 if len(entry) > 2:
3225 if len(entry) > 2:
3226 if entry[2].startswith('hg'):
3226 if entry[2].startswith('hg'):
3227 rst.append("%s\n" % entry[2])
3227 rst.append("%s\n" % entry[2])
3228 else:
3228 else:
3229 rst.append('hg %s %s\n' % (aliases[0], entry[2]))
3229 rst.append('hg %s %s\n' % (aliases[0], entry[2]))
3230 else:
3230 else:
3231 rst.append('hg %s\n' % aliases[0])
3231 rst.append('hg %s\n' % aliases[0])
3232 # aliases
3232 # aliases
3233 if full and not ui.quiet and len(aliases) > 1:
3233 if full and not ui.quiet and len(aliases) > 1:
3234 rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
3234 rst.append(_("\naliases: %s\n") % ', '.join(aliases[1:]))
3235 rst.append('\n')
3235 rst.append('\n')
3236
3236
3237 # description
3237 # description
3238 doc = gettext(entry[0].__doc__)
3238 doc = gettext(entry[0].__doc__)
3239 if not doc:
3239 if not doc:
3240 doc = _("(no help text available)")
3240 doc = _("(no help text available)")
3241 if util.safehasattr(entry[0], 'definition'): # aliased command
3241 if util.safehasattr(entry[0], 'definition'): # aliased command
3242 if entry[0].definition.startswith('!'): # shell alias
3242 if entry[0].definition.startswith('!'): # shell alias
3243 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3243 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
3244 else:
3244 else:
3245 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3245 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
3246 doc = doc.splitlines(True)
3246 doc = doc.splitlines(True)
3247 if ui.quiet or not full:
3247 if ui.quiet or not full:
3248 rst.append(doc[0])
3248 rst.append(doc[0])
3249 else:
3249 else:
3250 rst.extend(doc)
3250 rst.extend(doc)
3251 rst.append('\n')
3251 rst.append('\n')
3252
3252
3253 # check if this command shadows a non-trivial (multi-line)
3253 # check if this command shadows a non-trivial (multi-line)
3254 # extension help text
3254 # extension help text
3255 try:
3255 try:
3256 mod = extensions.find(name)
3256 mod = extensions.find(name)
3257 doc = gettext(mod.__doc__) or ''
3257 doc = gettext(mod.__doc__) or ''
3258 if '\n' in doc.strip():
3258 if '\n' in doc.strip():
3259 msg = _('use "hg help -e %s" to show help for '
3259 msg = _('use "hg help -e %s" to show help for '
3260 'the %s extension') % (name, name)
3260 'the %s extension') % (name, name)
3261 rst.append('\n%s\n' % msg)
3261 rst.append('\n%s\n' % msg)
3262 except KeyError:
3262 except KeyError:
3263 pass
3263 pass
3264
3264
3265 # options
3265 # options
3266 if not ui.quiet and entry[1]:
3266 if not ui.quiet and entry[1]:
3267 rst.append('\n%s\n\n' % _("options:"))
3267 rst.append('\n%s\n\n' % _("options:"))
3268 rst.append(help.optrst(entry[1], ui.verbose))
3268 rst.append(help.optrst(entry[1], ui.verbose))
3269
3269
3270 if ui.verbose:
3270 if ui.verbose:
3271 rst.append('\n%s\n\n' % _("global options:"))
3271 rst.append('\n%s\n\n' % _("global options:"))
3272 rst.append(help.optrst(globalopts, ui.verbose))
3272 rst.append(help.optrst(globalopts, ui.verbose))
3273
3273
3274 if not ui.verbose:
3274 if not ui.verbose:
3275 if not full:
3275 if not full:
3276 rst.append(_('\nuse "hg help %s" to show the full help text\n')
3276 rst.append(_('\nuse "hg help %s" to show the full help text\n')
3277 % name)
3277 % name)
3278 elif not ui.quiet:
3278 elif not ui.quiet:
3279 omitted = _('use "hg -v help %s" to show more complete'
3279 omitted = _('use "hg -v help %s" to show more complete'
3280 ' help and the global options') % name
3280 ' help and the global options') % name
3281 notomitted = _('use "hg -v help %s" to show'
3281 notomitted = _('use "hg -v help %s" to show'
3282 ' the global options') % name
3282 ' the global options') % name
3283 help.indicateomitted(rst, omitted, notomitted)
3283 help.indicateomitted(rst, omitted, notomitted)
3284
3284
3285 return rst
3285 return rst
3286
3286
3287
3287
3288 def helplist(select=None):
3288 def helplist(select=None):
3289 # list of commands
3289 # list of commands
3290 if name == "shortlist":
3290 if name == "shortlist":
3291 header = _('basic commands:\n\n')
3291 header = _('basic commands:\n\n')
3292 else:
3292 else:
3293 header = _('list of commands:\n\n')
3293 header = _('list of commands:\n\n')
3294
3294
3295 h = {}
3295 h = {}
3296 cmds = {}
3296 cmds = {}
3297 for c, e in table.iteritems():
3297 for c, e in table.iteritems():
3298 f = c.split("|", 1)[0]
3298 f = c.split("|", 1)[0]
3299 if select and not select(f):
3299 if select and not select(f):
3300 continue
3300 continue
3301 if (not select and name != 'shortlist' and
3301 if (not select and name != 'shortlist' and
3302 e[0].__module__ != __name__):
3302 e[0].__module__ != __name__):
3303 continue
3303 continue
3304 if name == "shortlist" and not f.startswith("^"):
3304 if name == "shortlist" and not f.startswith("^"):
3305 continue
3305 continue
3306 f = f.lstrip("^")
3306 f = f.lstrip("^")
3307 if not ui.debugflag and f.startswith("debug"):
3307 if not ui.debugflag and f.startswith("debug"):
3308 continue
3308 continue
3309 doc = e[0].__doc__
3309 doc = e[0].__doc__
3310 if doc and 'DEPRECATED' in doc and not ui.verbose:
3310 if doc and 'DEPRECATED' in doc and not ui.verbose:
3311 continue
3311 continue
3312 doc = gettext(doc)
3312 doc = gettext(doc)
3313 if not doc:
3313 if not doc:
3314 doc = _("(no help text available)")
3314 doc = _("(no help text available)")
3315 h[f] = doc.splitlines()[0].rstrip()
3315 h[f] = doc.splitlines()[0].rstrip()
3316 cmds[f] = c.lstrip("^")
3316 cmds[f] = c.lstrip("^")
3317
3317
3318 rst = []
3318 rst = []
3319 if not h:
3319 if not h:
3320 if not ui.quiet:
3320 if not ui.quiet:
3321 rst.append(_('no commands defined\n'))
3321 rst.append(_('no commands defined\n'))
3322 return rst
3322 return rst
3323
3323
3324 if not ui.quiet:
3324 if not ui.quiet:
3325 rst.append(header)
3325 rst.append(header)
3326 fns = sorted(h)
3326 fns = sorted(h)
3327 for f in fns:
3327 for f in fns:
3328 if ui.verbose:
3328 if ui.verbose:
3329 commands = cmds[f].replace("|",", ")
3329 commands = cmds[f].replace("|",", ")
3330 rst.append(" :%s: %s\n" % (commands, h[f]))
3330 rst.append(" :%s: %s\n" % (commands, h[f]))
3331 else:
3331 else:
3332 rst.append(' :%s: %s\n' % (f, h[f]))
3332 rst.append(' :%s: %s\n' % (f, h[f]))
3333
3333
3334 if not name:
3334 if not name:
3335 exts = help.listexts(_('enabled extensions:'), extensions.enabled())
3335 exts = help.listexts(_('enabled extensions:'), extensions.enabled())
3336 if exts:
3336 if exts:
3337 rst.append('\n')
3337 rst.append('\n')
3338 rst.extend(exts)
3338 rst.extend(exts)
3339
3339
3340 rst.append(_("\nadditional help topics:\n\n"))
3340 rst.append(_("\nadditional help topics:\n\n"))
3341 topics = []
3341 topics = []
3342 for names, header, doc in help.helptable:
3342 for names, header, doc in help.helptable:
3343 topics.append((names[0], header))
3343 topics.append((names[0], header))
3344 for t, desc in topics:
3344 for t, desc in topics:
3345 rst.append(" :%s: %s\n" % (t, desc))
3345 rst.append(" :%s: %s\n" % (t, desc))
3346
3346
3347 optlist = []
3347 optlist = []
3348 if not ui.quiet:
3348 if not ui.quiet:
3349 if ui.verbose:
3349 if ui.verbose:
3350 optlist.append((_("global options:"), globalopts))
3350 optlist.append((_("global options:"), globalopts))
3351 if name == 'shortlist':
3351 if name == 'shortlist':
3352 optlist.append((_('use "hg help" for the full list '
3352 optlist.append((_('use "hg help" for the full list '
3353 'of commands'), ()))
3353 'of commands'), ()))
3354 else:
3354 else:
3355 if name == 'shortlist':
3355 if name == 'shortlist':
3356 msg = _('use "hg help" for the full list of commands '
3356 msg = _('use "hg help" for the full list of commands '
3357 'or "hg -v" for details')
3357 'or "hg -v" for details')
3358 elif name and not full:
3358 elif name and not full:
3359 msg = _('use "hg help %s" to show the full help '
3359 msg = _('use "hg help %s" to show the full help '
3360 'text') % name
3360 'text') % name
3361 else:
3361 else:
3362 msg = _('use "hg -v help%s" to show builtin aliases and '
3362 msg = _('use "hg -v help%s" to show builtin aliases and '
3363 'global options') % (name and " " + name or "")
3363 'global options') % (name and " " + name or "")
3364 optlist.append((msg, ()))
3364 optlist.append((msg, ()))
3365
3365
3366 if optlist:
3366 if optlist:
3367 for title, options in optlist:
3367 for title, options in optlist:
3368 rst.append('\n%s\n' % title)
3368 rst.append('\n%s\n' % title)
3369 if options:
3369 if options:
3370 rst.append('\n%s\n' % help.optrst(options, ui.verbose))
3370 rst.append('\n%s\n' % help.optrst(options, ui.verbose))
3371 return rst
3371 return rst
3372
3372
3373 def helptopic(name):
3373 def helptopic(name):
3374 for names, header, doc in help.helptable:
3374 for names, header, doc in help.helptable:
3375 if name in names:
3375 if name in names:
3376 break
3376 break
3377 else:
3377 else:
3378 raise error.UnknownCommand(name)
3378 raise error.UnknownCommand(name)
3379
3379
3380 rst = ["%s\n\n" % header]
3380 rst = ["%s\n\n" % header]
3381 # description
3381 # description
3382 if not doc:
3382 if not doc:
3383 rst.append(" %s\n" % _("(no help text available)"))
3383 rst.append(" %s\n" % _("(no help text available)"))
3384 if util.safehasattr(doc, '__call__'):
3384 if util.safehasattr(doc, '__call__'):
3385 rst += [" %s\n" % l for l in doc().splitlines()]
3385 rst += [" %s\n" % l for l in doc().splitlines()]
3386
3386
3387 if not ui.verbose:
3387 if not ui.verbose:
3388 omitted = (_('use "hg help -v %s" to show more complete help') %
3388 omitted = (_('use "hg help -v %s" to show more complete help') %
3389 name)
3389 name)
3390 help.indicateomitted(rst, omitted)
3390 help.indicateomitted(rst, omitted)
3391
3391
3392 try:
3392 try:
3393 cmdutil.findcmd(name, table)
3393 cmdutil.findcmd(name, table)
3394 rst.append(_('\nuse "hg help -c %s" to see help for '
3394 rst.append(_('\nuse "hg help -c %s" to see help for '
3395 'the %s command\n') % (name, name))
3395 'the %s command\n') % (name, name))
3396 except error.UnknownCommand:
3396 except error.UnknownCommand:
3397 pass
3397 pass
3398 return rst
3398 return rst
3399
3399
3400 def helpext(name):
3400 def helpext(name):
3401 try:
3401 try:
3402 mod = extensions.find(name)
3402 mod = extensions.find(name)
3403 doc = gettext(mod.__doc__) or _('no help text available')
3403 doc = gettext(mod.__doc__) or _('no help text available')
3404 except KeyError:
3404 except KeyError:
3405 mod = None
3405 mod = None
3406 doc = extensions.disabledext(name)
3406 doc = extensions.disabledext(name)
3407 if not doc:
3407 if not doc:
3408 raise error.UnknownCommand(name)
3408 raise error.UnknownCommand(name)
3409
3409
3410 if '\n' not in doc:
3410 if '\n' not in doc:
3411 head, tail = doc, ""
3411 head, tail = doc, ""
3412 else:
3412 else:
3413 head, tail = doc.split('\n', 1)
3413 head, tail = doc.split('\n', 1)
3414 rst = [_('%s extension - %s\n\n') % (name.split('.')[-1], head)]
3414 rst = [_('%s extension - %s\n\n') % (name.split('.')[-1], head)]
3415 if tail:
3415 if tail:
3416 rst.extend(tail.splitlines(True))
3416 rst.extend(tail.splitlines(True))
3417 rst.append('\n')
3417 rst.append('\n')
3418
3418
3419 if not ui.verbose:
3419 if not ui.verbose:
3420 omitted = (_('use "hg help -v %s" to show more complete help') %
3420 omitted = (_('use "hg help -v %s" to show more complete help') %
3421 name)
3421 name)
3422 help.indicateomitted(rst, omitted)
3422 help.indicateomitted(rst, omitted)
3423
3423
3424 if mod:
3424 if mod:
3425 try:
3425 try:
3426 ct = mod.cmdtable
3426 ct = mod.cmdtable
3427 except AttributeError:
3427 except AttributeError:
3428 ct = {}
3428 ct = {}
3429 modcmds = set([c.split('|', 1)[0] for c in ct])
3429 modcmds = set([c.split('|', 1)[0] for c in ct])
3430 rst.extend(helplist(modcmds.__contains__))
3430 rst.extend(helplist(modcmds.__contains__))
3431 else:
3431 else:
3432 rst.append(_('use "hg help extensions" for information on enabling '
3432 rst.append(_('use "hg help extensions" for information on enabling '
3433 'extensions\n'))
3433 'extensions\n'))
3434 return rst
3434 return rst
3435
3435
3436 def helpextcmd(name):
3436 def helpextcmd(name):
3437 cmd, ext, mod = extensions.disabledcmd(ui, name,
3437 cmd, ext, mod = extensions.disabledcmd(ui, name,
3438 ui.configbool('ui', 'strict'))
3438 ui.configbool('ui', 'strict'))
3439 doc = gettext(mod.__doc__).splitlines()[0]
3439 doc = gettext(mod.__doc__).splitlines()[0]
3440
3440
3441 rst = help.listexts(_("'%s' is provided by the following "
3441 rst = help.listexts(_("'%s' is provided by the following "
3442 "extension:") % cmd, {ext: doc}, indent=4)
3442 "extension:") % cmd, {ext: doc}, indent=4)
3443 rst.append('\n')
3443 rst.append('\n')
3444 rst.append(_('use "hg help extensions" for information on enabling '
3444 rst.append(_('use "hg help extensions" for information on enabling '
3445 'extensions\n'))
3445 'extensions\n'))
3446 return rst
3446 return rst
3447
3447
3448
3448
3449 rst = []
3449 rst = []
3450 kw = opts.get('keyword')
3450 kw = opts.get('keyword')
3451 if kw:
3451 if kw:
3452 matches = help.topicmatch(kw)
3452 matches = help.topicmatch(kw)
3453 for t, title in (('topics', _('Topics')),
3453 for t, title in (('topics', _('Topics')),
3454 ('commands', _('Commands')),
3454 ('commands', _('Commands')),
3455 ('extensions', _('Extensions')),
3455 ('extensions', _('Extensions')),
3456 ('extensioncommands', _('Extension Commands'))):
3456 ('extensioncommands', _('Extension Commands'))):
3457 if matches[t]:
3457 if matches[t]:
3458 rst.append('%s:\n\n' % title)
3458 rst.append('%s:\n\n' % title)
3459 rst.extend(minirst.maketable(sorted(matches[t]), 1))
3459 rst.extend(minirst.maketable(sorted(matches[t]), 1))
3460 rst.append('\n')
3460 rst.append('\n')
3461 elif name and name != 'shortlist':
3461 elif name and name != 'shortlist':
3462 i = None
3462 i = None
3463 if unknowncmd:
3463 if unknowncmd:
3464 queries = (helpextcmd,)
3464 queries = (helpextcmd,)
3465 elif opts.get('extension'):
3465 elif opts.get('extension'):
3466 queries = (helpext,)
3466 queries = (helpext,)
3467 elif opts.get('command'):
3467 elif opts.get('command'):
3468 queries = (helpcmd,)
3468 queries = (helpcmd,)
3469 else:
3469 else:
3470 queries = (helptopic, helpcmd, helpext, helpextcmd)
3470 queries = (helptopic, helpcmd, helpext, helpextcmd)
3471 for f in queries:
3471 for f in queries:
3472 try:
3472 try:
3473 rst = f(name)
3473 rst = f(name)
3474 i = None
3474 i = None
3475 break
3475 break
3476 except error.UnknownCommand, inst:
3476 except error.UnknownCommand, inst:
3477 i = inst
3477 i = inst
3478 if i:
3478 if i:
3479 raise i
3479 raise i
3480 else:
3480 else:
3481 # program name
3481 # program name
3482 if not ui.quiet:
3482 if not ui.quiet:
3483 rst = [_("Mercurial Distributed SCM\n"), '\n']
3483 rst = [_("Mercurial Distributed SCM\n"), '\n']
3484 rst.extend(helplist())
3484 rst.extend(helplist())
3485
3485
3486 keep = ui.verbose and ['verbose'] or []
3486 keep = ui.verbose and ['verbose'] or []
3487 text = ''.join(rst)
3487 text = ''.join(rst)
3488 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3488 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3489 if 'verbose' in pruned:
3489 if 'verbose' in pruned:
3490 keep.append('omitted')
3490 keep.append('omitted')
3491 else:
3491 else:
3492 keep.append('notomitted')
3492 keep.append('notomitted')
3493 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3493 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3494 ui.write(formatted)
3494 ui.write(formatted)
3495
3495
3496
3496
3497 @command('identify|id',
3497 @command('identify|id',
3498 [('r', 'rev', '',
3498 [('r', 'rev', '',
3499 _('identify the specified revision'), _('REV')),
3499 _('identify the specified revision'), _('REV')),
3500 ('n', 'num', None, _('show local revision number')),
3500 ('n', 'num', None, _('show local revision number')),
3501 ('i', 'id', None, _('show global revision id')),
3501 ('i', 'id', None, _('show global revision id')),
3502 ('b', 'branch', None, _('show branch')),
3502 ('b', 'branch', None, _('show branch')),
3503 ('t', 'tags', None, _('show tags')),
3503 ('t', 'tags', None, _('show tags')),
3504 ('B', 'bookmarks', None, _('show bookmarks')),
3504 ('B', 'bookmarks', None, _('show bookmarks')),
3505 ] + remoteopts,
3505 ] + remoteopts,
3506 _('[-nibtB] [-r REV] [SOURCE]'))
3506 _('[-nibtB] [-r REV] [SOURCE]'))
3507 def identify(ui, repo, source=None, rev=None,
3507 def identify(ui, repo, source=None, rev=None,
3508 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3508 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3509 """identify the working copy or specified revision
3509 """identify the working copy or specified revision
3510
3510
3511 Print a summary identifying the repository state at REV using one or
3511 Print a summary identifying the repository state at REV using one or
3512 two parent hash identifiers, followed by a "+" if the working
3512 two parent hash identifiers, followed by a "+" if the working
3513 directory has uncommitted changes, the branch name (if not default),
3513 directory has uncommitted changes, the branch name (if not default),
3514 a list of tags, and a list of bookmarks.
3514 a list of tags, and a list of bookmarks.
3515
3515
3516 When REV is not given, print a summary of the current state of the
3516 When REV is not given, print a summary of the current state of the
3517 repository.
3517 repository.
3518
3518
3519 Specifying a path to a repository root or Mercurial bundle will
3519 Specifying a path to a repository root or Mercurial bundle will
3520 cause lookup to operate on that repository/bundle.
3520 cause lookup to operate on that repository/bundle.
3521
3521
3522 .. container:: verbose
3522 .. container:: verbose
3523
3523
3524 Examples:
3524 Examples:
3525
3525
3526 - generate a build identifier for the working directory::
3526 - generate a build identifier for the working directory::
3527
3527
3528 hg id --id > build-id.dat
3528 hg id --id > build-id.dat
3529
3529
3530 - find the revision corresponding to a tag::
3530 - find the revision corresponding to a tag::
3531
3531
3532 hg id -n -r 1.3
3532 hg id -n -r 1.3
3533
3533
3534 - check the most recent revision of a remote repository::
3534 - check the most recent revision of a remote repository::
3535
3535
3536 hg id -r tip http://selenic.com/hg/
3536 hg id -r tip http://selenic.com/hg/
3537
3537
3538 Returns 0 if successful.
3538 Returns 0 if successful.
3539 """
3539 """
3540
3540
3541 if not repo and not source:
3541 if not repo and not source:
3542 raise util.Abort(_("there is no Mercurial repository here "
3542 raise util.Abort(_("there is no Mercurial repository here "
3543 "(.hg not found)"))
3543 "(.hg not found)"))
3544
3544
3545 hexfunc = ui.debugflag and hex or short
3545 hexfunc = ui.debugflag and hex or short
3546 default = not (num or id or branch or tags or bookmarks)
3546 default = not (num or id or branch or tags or bookmarks)
3547 output = []
3547 output = []
3548 revs = []
3548 revs = []
3549
3549
3550 if source:
3550 if source:
3551 source, branches = hg.parseurl(ui.expandpath(source))
3551 source, branches = hg.parseurl(ui.expandpath(source))
3552 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3552 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3553 repo = peer.local()
3553 repo = peer.local()
3554 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3554 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3555
3555
3556 if not repo:
3556 if not repo:
3557 if num or branch or tags:
3557 if num or branch or tags:
3558 raise util.Abort(
3558 raise util.Abort(
3559 _("can't query remote revision number, branch, or tags"))
3559 _("can't query remote revision number, branch, or tags"))
3560 if not rev and revs:
3560 if not rev and revs:
3561 rev = revs[0]
3561 rev = revs[0]
3562 if not rev:
3562 if not rev:
3563 rev = "tip"
3563 rev = "tip"
3564
3564
3565 remoterev = peer.lookup(rev)
3565 remoterev = peer.lookup(rev)
3566 if default or id:
3566 if default or id:
3567 output = [hexfunc(remoterev)]
3567 output = [hexfunc(remoterev)]
3568
3568
3569 def getbms():
3569 def getbms():
3570 bms = []
3570 bms = []
3571
3571
3572 if 'bookmarks' in peer.listkeys('namespaces'):
3572 if 'bookmarks' in peer.listkeys('namespaces'):
3573 hexremoterev = hex(remoterev)
3573 hexremoterev = hex(remoterev)
3574 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3574 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3575 if bmr == hexremoterev]
3575 if bmr == hexremoterev]
3576
3576
3577 return bms
3577 return bms
3578
3578
3579 if bookmarks:
3579 if bookmarks:
3580 output.extend(getbms())
3580 output.extend(getbms())
3581 elif default and not ui.quiet:
3581 elif default and not ui.quiet:
3582 # multiple bookmarks for a single parent separated by '/'
3582 # multiple bookmarks for a single parent separated by '/'
3583 bm = '/'.join(getbms())
3583 bm = '/'.join(getbms())
3584 if bm:
3584 if bm:
3585 output.append(bm)
3585 output.append(bm)
3586 else:
3586 else:
3587 if not rev:
3587 if not rev:
3588 ctx = repo[None]
3588 ctx = repo[None]
3589 parents = ctx.parents()
3589 parents = ctx.parents()
3590 changed = ""
3590 changed = ""
3591 if default or id or num:
3591 if default or id or num:
3592 if (util.any(repo.status())
3592 if (util.any(repo.status())
3593 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3593 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3594 changed = '+'
3594 changed = '+'
3595 if default or id:
3595 if default or id:
3596 output = ["%s%s" %
3596 output = ["%s%s" %
3597 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3597 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3598 if num:
3598 if num:
3599 output.append("%s%s" %
3599 output.append("%s%s" %
3600 ('+'.join([str(p.rev()) for p in parents]), changed))
3600 ('+'.join([str(p.rev()) for p in parents]), changed))
3601 else:
3601 else:
3602 ctx = scmutil.revsingle(repo, rev)
3602 ctx = scmutil.revsingle(repo, rev)
3603 if default or id:
3603 if default or id:
3604 output = [hexfunc(ctx.node())]
3604 output = [hexfunc(ctx.node())]
3605 if num:
3605 if num:
3606 output.append(str(ctx.rev()))
3606 output.append(str(ctx.rev()))
3607
3607
3608 if default and not ui.quiet:
3608 if default and not ui.quiet:
3609 b = ctx.branch()
3609 b = ctx.branch()
3610 if b != 'default':
3610 if b != 'default':
3611 output.append("(%s)" % b)
3611 output.append("(%s)" % b)
3612
3612
3613 # multiple tags for a single parent separated by '/'
3613 # multiple tags for a single parent separated by '/'
3614 t = '/'.join(ctx.tags())
3614 t = '/'.join(ctx.tags())
3615 if t:
3615 if t:
3616 output.append(t)
3616 output.append(t)
3617
3617
3618 # multiple bookmarks for a single parent separated by '/'
3618 # multiple bookmarks for a single parent separated by '/'
3619 bm = '/'.join(ctx.bookmarks())
3619 bm = '/'.join(ctx.bookmarks())
3620 if bm:
3620 if bm:
3621 output.append(bm)
3621 output.append(bm)
3622 else:
3622 else:
3623 if branch:
3623 if branch:
3624 output.append(ctx.branch())
3624 output.append(ctx.branch())
3625
3625
3626 if tags:
3626 if tags:
3627 output.extend(ctx.tags())
3627 output.extend(ctx.tags())
3628
3628
3629 if bookmarks:
3629 if bookmarks:
3630 output.extend(ctx.bookmarks())
3630 output.extend(ctx.bookmarks())
3631
3631
3632 ui.write("%s\n" % ' '.join(output))
3632 ui.write("%s\n" % ' '.join(output))
3633
3633
3634 @command('import|patch',
3634 @command('import|patch',
3635 [('p', 'strip', 1,
3635 [('p', 'strip', 1,
3636 _('directory strip option for patch. This has the same '
3636 _('directory strip option for patch. This has the same '
3637 'meaning as the corresponding patch option'), _('NUM')),
3637 'meaning as the corresponding patch option'), _('NUM')),
3638 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3638 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3639 ('e', 'edit', False, _('invoke editor on commit messages')),
3639 ('e', 'edit', False, _('invoke editor on commit messages')),
3640 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3640 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3641 ('', 'no-commit', None,
3641 ('', 'no-commit', None,
3642 _("don't commit, just update the working directory")),
3642 _("don't commit, just update the working directory")),
3643 ('', 'bypass', None,
3643 ('', 'bypass', None,
3644 _("apply patch without touching the working directory")),
3644 _("apply patch without touching the working directory")),
3645 ('', 'exact', None,
3645 ('', 'exact', None,
3646 _('apply patch to the nodes from which it was generated')),
3646 _('apply patch to the nodes from which it was generated')),
3647 ('', 'import-branch', None,
3647 ('', 'import-branch', None,
3648 _('use any branch information in patch (implied by --exact)'))] +
3648 _('use any branch information in patch (implied by --exact)'))] +
3649 commitopts + commitopts2 + similarityopts,
3649 commitopts + commitopts2 + similarityopts,
3650 _('[OPTION]... PATCH...'))
3650 _('[OPTION]... PATCH...'))
3651 def import_(ui, repo, patch1=None, *patches, **opts):
3651 def import_(ui, repo, patch1=None, *patches, **opts):
3652 """import an ordered set of patches
3652 """import an ordered set of patches
3653
3653
3654 Import a list of patches and commit them individually (unless
3654 Import a list of patches and commit them individually (unless
3655 --no-commit is specified).
3655 --no-commit is specified).
3656
3656
3657 If there are outstanding changes in the working directory, import
3657 If there are outstanding changes in the working directory, import
3658 will abort unless given the -f/--force flag.
3658 will abort unless given the -f/--force flag.
3659
3659
3660 You can import a patch straight from a mail message. Even patches
3660 You can import a patch straight from a mail message. Even patches
3661 as attachments work (to use the body part, it must have type
3661 as attachments work (to use the body part, it must have type
3662 text/plain or text/x-patch). From and Subject headers of email
3662 text/plain or text/x-patch). From and Subject headers of email
3663 message are used as default committer and commit message. All
3663 message are used as default committer and commit message. All
3664 text/plain body parts before first diff are added to commit
3664 text/plain body parts before first diff are added to commit
3665 message.
3665 message.
3666
3666
3667 If the imported patch was generated by :hg:`export`, user and
3667 If the imported patch was generated by :hg:`export`, user and
3668 description from patch override values from message headers and
3668 description from patch override values from message headers and
3669 body. Values given on command line with -m/--message and -u/--user
3669 body. Values given on command line with -m/--message and -u/--user
3670 override these.
3670 override these.
3671
3671
3672 If --exact is specified, import will set the working directory to
3672 If --exact is specified, import will set the working directory to
3673 the parent of each patch before applying it, and will abort if the
3673 the parent of each patch before applying it, and will abort if the
3674 resulting changeset has a different ID than the one recorded in
3674 resulting changeset has a different ID than the one recorded in
3675 the patch. This may happen due to character set problems or other
3675 the patch. This may happen due to character set problems or other
3676 deficiencies in the text patch format.
3676 deficiencies in the text patch format.
3677
3677
3678 Use --bypass to apply and commit patches directly to the
3678 Use --bypass to apply and commit patches directly to the
3679 repository, not touching the working directory. Without --exact,
3679 repository, not touching the working directory. Without --exact,
3680 patches will be applied on top of the working directory parent
3680 patches will be applied on top of the working directory parent
3681 revision.
3681 revision.
3682
3682
3683 With -s/--similarity, hg will attempt to discover renames and
3683 With -s/--similarity, hg will attempt to discover renames and
3684 copies in the patch in the same way as :hg:`addremove`.
3684 copies in the patch in the same way as :hg:`addremove`.
3685
3685
3686 To read a patch from standard input, use "-" as the patch name. If
3686 To read a patch from standard input, use "-" as the patch name. If
3687 a URL is specified, the patch will be downloaded from it.
3687 a URL is specified, the patch will be downloaded from it.
3688 See :hg:`help dates` for a list of formats valid for -d/--date.
3688 See :hg:`help dates` for a list of formats valid for -d/--date.
3689
3689
3690 .. container:: verbose
3690 .. container:: verbose
3691
3691
3692 Examples:
3692 Examples:
3693
3693
3694 - import a traditional patch from a website and detect renames::
3694 - import a traditional patch from a website and detect renames::
3695
3695
3696 hg import -s 80 http://example.com/bugfix.patch
3696 hg import -s 80 http://example.com/bugfix.patch
3697
3697
3698 - import a changeset from an hgweb server::
3698 - import a changeset from an hgweb server::
3699
3699
3700 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3700 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3701
3701
3702 - import all the patches in an Unix-style mbox::
3702 - import all the patches in an Unix-style mbox::
3703
3703
3704 hg import incoming-patches.mbox
3704 hg import incoming-patches.mbox
3705
3705
3706 - attempt to exactly restore an exported changeset (not always
3706 - attempt to exactly restore an exported changeset (not always
3707 possible)::
3707 possible)::
3708
3708
3709 hg import --exact proposed-fix.patch
3709 hg import --exact proposed-fix.patch
3710
3710
3711 Returns 0 on success.
3711 Returns 0 on success.
3712 """
3712 """
3713
3713
3714 if not patch1:
3714 if not patch1:
3715 raise util.Abort(_('need at least one patch to import'))
3715 raise util.Abort(_('need at least one patch to import'))
3716
3716
3717 patches = (patch1,) + patches
3717 patches = (patch1,) + patches
3718
3718
3719 date = opts.get('date')
3719 date = opts.get('date')
3720 if date:
3720 if date:
3721 opts['date'] = util.parsedate(date)
3721 opts['date'] = util.parsedate(date)
3722
3722
3723 editor = cmdutil.commiteditor
3723 editor = cmdutil.commiteditor
3724 if opts.get('edit'):
3724 if opts.get('edit'):
3725 editor = cmdutil.commitforceeditor
3725 editor = cmdutil.commitforceeditor
3726
3726
3727 update = not opts.get('bypass')
3727 update = not opts.get('bypass')
3728 if not update and opts.get('no_commit'):
3728 if not update and opts.get('no_commit'):
3729 raise util.Abort(_('cannot use --no-commit with --bypass'))
3729 raise util.Abort(_('cannot use --no-commit with --bypass'))
3730 try:
3730 try:
3731 sim = float(opts.get('similarity') or 0)
3731 sim = float(opts.get('similarity') or 0)
3732 except ValueError:
3732 except ValueError:
3733 raise util.Abort(_('similarity must be a number'))
3733 raise util.Abort(_('similarity must be a number'))
3734 if sim < 0 or sim > 100:
3734 if sim < 0 or sim > 100:
3735 raise util.Abort(_('similarity must be between 0 and 100'))
3735 raise util.Abort(_('similarity must be between 0 and 100'))
3736 if sim and not update:
3736 if sim and not update:
3737 raise util.Abort(_('cannot use --similarity with --bypass'))
3737 raise util.Abort(_('cannot use --similarity with --bypass'))
3738
3738
3739 if (opts.get('exact') or not opts.get('force')) and update:
3739 if (opts.get('exact') or not opts.get('force')) and update:
3740 cmdutil.bailifchanged(repo)
3740 cmdutil.bailifchanged(repo)
3741
3741
3742 base = opts["base"]
3742 base = opts["base"]
3743 strip = opts["strip"]
3743 strip = opts["strip"]
3744 wlock = lock = tr = None
3744 wlock = lock = tr = None
3745 msgs = []
3745 msgs = []
3746
3746
3747 def checkexact(repo, n, nodeid):
3747 def checkexact(repo, n, nodeid):
3748 if opts.get('exact') and hex(n) != nodeid:
3748 if opts.get('exact') and hex(n) != nodeid:
3749 repo.rollback()
3749 repo.rollback()
3750 raise util.Abort(_('patch is damaged or loses information'))
3750 raise util.Abort(_('patch is damaged or loses information'))
3751
3751
3752 def tryone(ui, hunk, parents):
3752 def tryone(ui, hunk, parents):
3753 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3753 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3754 patch.extract(ui, hunk)
3754 patch.extract(ui, hunk)
3755
3755
3756 if not tmpname:
3756 if not tmpname:
3757 return (None, None)
3757 return (None, None)
3758 msg = _('applied to working directory')
3758 msg = _('applied to working directory')
3759
3759
3760 try:
3760 try:
3761 cmdline_message = cmdutil.logmessage(ui, opts)
3761 cmdline_message = cmdutil.logmessage(ui, opts)
3762 if cmdline_message:
3762 if cmdline_message:
3763 # pickup the cmdline msg
3763 # pickup the cmdline msg
3764 message = cmdline_message
3764 message = cmdline_message
3765 elif message:
3765 elif message:
3766 # pickup the patch msg
3766 # pickup the patch msg
3767 message = message.strip()
3767 message = message.strip()
3768 else:
3768 else:
3769 # launch the editor
3769 # launch the editor
3770 message = None
3770 message = None
3771 ui.debug('message:\n%s\n' % message)
3771 ui.debug('message:\n%s\n' % message)
3772
3772
3773 if len(parents) == 1:
3773 if len(parents) == 1:
3774 parents.append(repo[nullid])
3774 parents.append(repo[nullid])
3775 if opts.get('exact'):
3775 if opts.get('exact'):
3776 if not nodeid or not p1:
3776 if not nodeid or not p1:
3777 raise util.Abort(_('not a Mercurial patch'))
3777 raise util.Abort(_('not a Mercurial patch'))
3778 p1 = repo[p1]
3778 p1 = repo[p1]
3779 p2 = repo[p2 or nullid]
3779 p2 = repo[p2 or nullid]
3780 elif p2:
3780 elif p2:
3781 try:
3781 try:
3782 p1 = repo[p1]
3782 p1 = repo[p1]
3783 p2 = repo[p2]
3783 p2 = repo[p2]
3784 # Without any options, consider p2 only if the
3784 # Without any options, consider p2 only if the
3785 # patch is being applied on top of the recorded
3785 # patch is being applied on top of the recorded
3786 # first parent.
3786 # first parent.
3787 if p1 != parents[0]:
3787 if p1 != parents[0]:
3788 p1 = parents[0]
3788 p1 = parents[0]
3789 p2 = repo[nullid]
3789 p2 = repo[nullid]
3790 except error.RepoError:
3790 except error.RepoError:
3791 p1, p2 = parents
3791 p1, p2 = parents
3792 else:
3792 else:
3793 p1, p2 = parents
3793 p1, p2 = parents
3794
3794
3795 n = None
3795 n = None
3796 if update:
3796 if update:
3797 if p1 != parents[0]:
3797 if p1 != parents[0]:
3798 hg.clean(repo, p1.node())
3798 hg.clean(repo, p1.node())
3799 if p2 != parents[1]:
3799 if p2 != parents[1]:
3800 repo.setparents(p1.node(), p2.node())
3800 repo.setparents(p1.node(), p2.node())
3801
3801
3802 if opts.get('exact') or opts.get('import_branch'):
3802 if opts.get('exact') or opts.get('import_branch'):
3803 repo.dirstate.setbranch(branch or 'default')
3803 repo.dirstate.setbranch(branch or 'default')
3804
3804
3805 files = set()
3805 files = set()
3806 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3806 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3807 eolmode=None, similarity=sim / 100.0)
3807 eolmode=None, similarity=sim / 100.0)
3808 files = list(files)
3808 files = list(files)
3809 if opts.get('no_commit'):
3809 if opts.get('no_commit'):
3810 if message:
3810 if message:
3811 msgs.append(message)
3811 msgs.append(message)
3812 else:
3812 else:
3813 if opts.get('exact') or p2:
3813 if opts.get('exact') or p2:
3814 # If you got here, you either use --force and know what
3814 # If you got here, you either use --force and know what
3815 # you are doing or used --exact or a merge patch while
3815 # you are doing or used --exact or a merge patch while
3816 # being updated to its first parent.
3816 # being updated to its first parent.
3817 m = None
3817 m = None
3818 else:
3818 else:
3819 m = scmutil.matchfiles(repo, files or [])
3819 m = scmutil.matchfiles(repo, files or [])
3820 n = repo.commit(message, opts.get('user') or user,
3820 n = repo.commit(message, opts.get('user') or user,
3821 opts.get('date') or date, match=m,
3821 opts.get('date') or date, match=m,
3822 editor=editor)
3822 editor=editor)
3823 checkexact(repo, n, nodeid)
3823 checkexact(repo, n, nodeid)
3824 else:
3824 else:
3825 if opts.get('exact') or opts.get('import_branch'):
3825 if opts.get('exact') or opts.get('import_branch'):
3826 branch = branch or 'default'
3826 branch = branch or 'default'
3827 else:
3827 else:
3828 branch = p1.branch()
3828 branch = p1.branch()
3829 store = patch.filestore()
3829 store = patch.filestore()
3830 try:
3830 try:
3831 files = set()
3831 files = set()
3832 try:
3832 try:
3833 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3833 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3834 files, eolmode=None)
3834 files, eolmode=None)
3835 except patch.PatchError, e:
3835 except patch.PatchError, e:
3836 raise util.Abort(str(e))
3836 raise util.Abort(str(e))
3837 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3837 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3838 message,
3838 message,
3839 opts.get('user') or user,
3839 opts.get('user') or user,
3840 opts.get('date') or date,
3840 opts.get('date') or date,
3841 branch, files, store,
3841 branch, files, store,
3842 editor=cmdutil.commiteditor)
3842 editor=cmdutil.commiteditor)
3843 repo.savecommitmessage(memctx.description())
3843 repo.savecommitmessage(memctx.description())
3844 n = memctx.commit()
3844 n = memctx.commit()
3845 checkexact(repo, n, nodeid)
3845 checkexact(repo, n, nodeid)
3846 finally:
3846 finally:
3847 store.close()
3847 store.close()
3848 if n:
3848 if n:
3849 # i18n: refers to a short changeset id
3849 # i18n: refers to a short changeset id
3850 msg = _('created %s') % short(n)
3850 msg = _('created %s') % short(n)
3851 return (msg, n)
3851 return (msg, n)
3852 finally:
3852 finally:
3853 os.unlink(tmpname)
3853 os.unlink(tmpname)
3854
3854
3855 try:
3855 try:
3856 try:
3856 try:
3857 wlock = repo.wlock()
3857 wlock = repo.wlock()
3858 if not opts.get('no_commit'):
3858 if not opts.get('no_commit'):
3859 lock = repo.lock()
3859 lock = repo.lock()
3860 tr = repo.transaction('import')
3860 tr = repo.transaction('import')
3861 parents = repo.parents()
3861 parents = repo.parents()
3862 for patchurl in patches:
3862 for patchurl in patches:
3863 if patchurl == '-':
3863 if patchurl == '-':
3864 ui.status(_('applying patch from stdin\n'))
3864 ui.status(_('applying patch from stdin\n'))
3865 patchfile = ui.fin
3865 patchfile = ui.fin
3866 patchurl = 'stdin' # for error message
3866 patchurl = 'stdin' # for error message
3867 else:
3867 else:
3868 patchurl = os.path.join(base, patchurl)
3868 patchurl = os.path.join(base, patchurl)
3869 ui.status(_('applying %s\n') % patchurl)
3869 ui.status(_('applying %s\n') % patchurl)
3870 patchfile = hg.openpath(ui, patchurl)
3870 patchfile = hg.openpath(ui, patchurl)
3871
3871
3872 haspatch = False
3872 haspatch = False
3873 for hunk in patch.split(patchfile):
3873 for hunk in patch.split(patchfile):
3874 (msg, node) = tryone(ui, hunk, parents)
3874 (msg, node) = tryone(ui, hunk, parents)
3875 if msg:
3875 if msg:
3876 haspatch = True
3876 haspatch = True
3877 ui.note(msg + '\n')
3877 ui.note(msg + '\n')
3878 if update or opts.get('exact'):
3878 if update or opts.get('exact'):
3879 parents = repo.parents()
3879 parents = repo.parents()
3880 else:
3880 else:
3881 parents = [repo[node]]
3881 parents = [repo[node]]
3882
3882
3883 if not haspatch:
3883 if not haspatch:
3884 raise util.Abort(_('%s: no diffs found') % patchurl)
3884 raise util.Abort(_('%s: no diffs found') % patchurl)
3885
3885
3886 if tr:
3886 if tr:
3887 tr.close()
3887 tr.close()
3888 if msgs:
3888 if msgs:
3889 repo.savecommitmessage('\n* * *\n'.join(msgs))
3889 repo.savecommitmessage('\n* * *\n'.join(msgs))
3890 except: # re-raises
3890 except: # re-raises
3891 # wlock.release() indirectly calls dirstate.write(): since
3891 # wlock.release() indirectly calls dirstate.write(): since
3892 # we're crashing, we do not want to change the working dir
3892 # we're crashing, we do not want to change the working dir
3893 # parent after all, so make sure it writes nothing
3893 # parent after all, so make sure it writes nothing
3894 repo.dirstate.invalidate()
3894 repo.dirstate.invalidate()
3895 raise
3895 raise
3896 finally:
3896 finally:
3897 if tr:
3897 if tr:
3898 tr.release()
3898 tr.release()
3899 release(lock, wlock)
3899 release(lock, wlock)
3900
3900
3901 @command('incoming|in',
3901 @command('incoming|in',
3902 [('f', 'force', None,
3902 [('f', 'force', None,
3903 _('run even if remote repository is unrelated')),
3903 _('run even if remote repository is unrelated')),
3904 ('n', 'newest-first', None, _('show newest record first')),
3904 ('n', 'newest-first', None, _('show newest record first')),
3905 ('', 'bundle', '',
3905 ('', 'bundle', '',
3906 _('file to store the bundles into'), _('FILE')),
3906 _('file to store the bundles into'), _('FILE')),
3907 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3907 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3908 ('B', 'bookmarks', False, _("compare bookmarks")),
3908 ('B', 'bookmarks', False, _("compare bookmarks")),
3909 ('b', 'branch', [],
3909 ('b', 'branch', [],
3910 _('a specific branch you would like to pull'), _('BRANCH')),
3910 _('a specific branch you would like to pull'), _('BRANCH')),
3911 ] + logopts + remoteopts + subrepoopts,
3911 ] + logopts + remoteopts + subrepoopts,
3912 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3912 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3913 def incoming(ui, repo, source="default", **opts):
3913 def incoming(ui, repo, source="default", **opts):
3914 """show new changesets found in source
3914 """show new changesets found in source
3915
3915
3916 Show new changesets found in the specified path/URL or the default
3916 Show new changesets found in the specified path/URL or the default
3917 pull location. These are the changesets that would have been pulled
3917 pull location. These are the changesets that would have been pulled
3918 if a pull at the time you issued this command.
3918 if a pull at the time you issued this command.
3919
3919
3920 For remote repository, using --bundle avoids downloading the
3920 For remote repository, using --bundle avoids downloading the
3921 changesets twice if the incoming is followed by a pull.
3921 changesets twice if the incoming is followed by a pull.
3922
3922
3923 See pull for valid source format details.
3923 See pull for valid source format details.
3924
3924
3925 Returns 0 if there are incoming changes, 1 otherwise.
3925 Returns 0 if there are incoming changes, 1 otherwise.
3926 """
3926 """
3927 if opts.get('graph'):
3927 if opts.get('graph'):
3928 cmdutil.checkunsupportedgraphflags([], opts)
3928 cmdutil.checkunsupportedgraphflags([], opts)
3929 def display(other, chlist, displayer):
3929 def display(other, chlist, displayer):
3930 revdag = cmdutil.graphrevs(other, chlist, opts)
3930 revdag = cmdutil.graphrevs(other, chlist, opts)
3931 showparents = [ctx.node() for ctx in repo[None].parents()]
3931 showparents = [ctx.node() for ctx in repo[None].parents()]
3932 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3932 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3933 graphmod.asciiedges)
3933 graphmod.asciiedges)
3934
3934
3935 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3935 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3936 return 0
3936 return 0
3937
3937
3938 if opts.get('bundle') and opts.get('subrepos'):
3938 if opts.get('bundle') and opts.get('subrepos'):
3939 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3939 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3940
3940
3941 if opts.get('bookmarks'):
3941 if opts.get('bookmarks'):
3942 source, branches = hg.parseurl(ui.expandpath(source),
3942 source, branches = hg.parseurl(ui.expandpath(source),
3943 opts.get('branch'))
3943 opts.get('branch'))
3944 other = hg.peer(repo, opts, source)
3944 other = hg.peer(repo, opts, source)
3945 if 'bookmarks' not in other.listkeys('namespaces'):
3945 if 'bookmarks' not in other.listkeys('namespaces'):
3946 ui.warn(_("remote doesn't support bookmarks\n"))
3946 ui.warn(_("remote doesn't support bookmarks\n"))
3947 return 0
3947 return 0
3948 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3948 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3949 return bookmarks.diff(ui, repo, other)
3949 return bookmarks.diff(ui, repo, other)
3950
3950
3951 repo._subtoppath = ui.expandpath(source)
3951 repo._subtoppath = ui.expandpath(source)
3952 try:
3952 try:
3953 return hg.incoming(ui, repo, source, opts)
3953 return hg.incoming(ui, repo, source, opts)
3954 finally:
3954 finally:
3955 del repo._subtoppath
3955 del repo._subtoppath
3956
3956
3957
3957
3958 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3958 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3959 def init(ui, dest=".", **opts):
3959 def init(ui, dest=".", **opts):
3960 """create a new repository in the given directory
3960 """create a new repository in the given directory
3961
3961
3962 Initialize a new repository in the given directory. If the given
3962 Initialize a new repository in the given directory. If the given
3963 directory does not exist, it will be created.
3963 directory does not exist, it will be created.
3964
3964
3965 If no directory is given, the current directory is used.
3965 If no directory is given, the current directory is used.
3966
3966
3967 It is possible to specify an ``ssh://`` URL as the destination.
3967 It is possible to specify an ``ssh://`` URL as the destination.
3968 See :hg:`help urls` for more information.
3968 See :hg:`help urls` for more information.
3969
3969
3970 Returns 0 on success.
3970 Returns 0 on success.
3971 """
3971 """
3972 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3972 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3973
3973
3974 @command('locate',
3974 @command('locate',
3975 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3975 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3976 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3976 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3977 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3977 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3978 ] + walkopts,
3978 ] + walkopts,
3979 _('[OPTION]... [PATTERN]...'))
3979 _('[OPTION]... [PATTERN]...'))
3980 def locate(ui, repo, *pats, **opts):
3980 def locate(ui, repo, *pats, **opts):
3981 """locate files matching specific patterns
3981 """locate files matching specific patterns
3982
3982
3983 Print files under Mercurial control in the working directory whose
3983 Print files under Mercurial control in the working directory whose
3984 names match the given patterns.
3984 names match the given patterns.
3985
3985
3986 By default, this command searches all directories in the working
3986 By default, this command searches all directories in the working
3987 directory. To search just the current directory and its
3987 directory. To search just the current directory and its
3988 subdirectories, use "--include .".
3988 subdirectories, use "--include .".
3989
3989
3990 If no patterns are given to match, this command prints the names
3990 If no patterns are given to match, this command prints the names
3991 of all files under Mercurial control in the working directory.
3991 of all files under Mercurial control in the working directory.
3992
3992
3993 If you want to feed the output of this command into the "xargs"
3993 If you want to feed the output of this command into the "xargs"
3994 command, use the -0 option to both this command and "xargs". This
3994 command, use the -0 option to both this command and "xargs". This
3995 will avoid the problem of "xargs" treating single filenames that
3995 will avoid the problem of "xargs" treating single filenames that
3996 contain whitespace as multiple filenames.
3996 contain whitespace as multiple filenames.
3997
3997
3998 Returns 0 if a match is found, 1 otherwise.
3998 Returns 0 if a match is found, 1 otherwise.
3999 """
3999 """
4000 end = opts.get('print0') and '\0' or '\n'
4000 end = opts.get('print0') and '\0' or '\n'
4001 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4001 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
4002
4002
4003 ret = 1
4003 ret = 1
4004 m = scmutil.match(repo[rev], pats, opts, default='relglob')
4004 m = scmutil.match(repo[rev], pats, opts, default='relglob')
4005 m.bad = lambda x, y: False
4005 m.bad = lambda x, y: False
4006 for abs in repo[rev].walk(m):
4006 for abs in repo[rev].walk(m):
4007 if not rev and abs not in repo.dirstate:
4007 if not rev and abs not in repo.dirstate:
4008 continue
4008 continue
4009 if opts.get('fullpath'):
4009 if opts.get('fullpath'):
4010 ui.write(repo.wjoin(abs), end)
4010 ui.write(repo.wjoin(abs), end)
4011 else:
4011 else:
4012 ui.write(((pats and m.rel(abs)) or abs), end)
4012 ui.write(((pats and m.rel(abs)) or abs), end)
4013 ret = 0
4013 ret = 0
4014
4014
4015 return ret
4015 return ret
4016
4016
4017 @command('^log|history',
4017 @command('^log|history',
4018 [('f', 'follow', None,
4018 [('f', 'follow', None,
4019 _('follow changeset history, or file history across copies and renames')),
4019 _('follow changeset history, or file history across copies and renames')),
4020 ('', 'follow-first', None,
4020 ('', 'follow-first', None,
4021 _('only follow the first parent of merge changesets (DEPRECATED)')),
4021 _('only follow the first parent of merge changesets (DEPRECATED)')),
4022 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4022 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
4023 ('C', 'copies', None, _('show copied files')),
4023 ('C', 'copies', None, _('show copied files')),
4024 ('k', 'keyword', [],
4024 ('k', 'keyword', [],
4025 _('do case-insensitive search for a given text'), _('TEXT')),
4025 _('do case-insensitive search for a given text'), _('TEXT')),
4026 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4026 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
4027 ('', 'removed', None, _('include revisions where files were removed')),
4027 ('', 'removed', None, _('include revisions where files were removed')),
4028 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4028 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4029 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4029 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4030 ('', 'only-branch', [],
4030 ('', 'only-branch', [],
4031 _('show only changesets within the given named branch (DEPRECATED)'),
4031 _('show only changesets within the given named branch (DEPRECATED)'),
4032 _('BRANCH')),
4032 _('BRANCH')),
4033 ('b', 'branch', [],
4033 ('b', 'branch', [],
4034 _('show changesets within the given named branch'), _('BRANCH')),
4034 _('show changesets within the given named branch'), _('BRANCH')),
4035 ('P', 'prune', [],
4035 ('P', 'prune', [],
4036 _('do not display revision or any of its ancestors'), _('REV')),
4036 _('do not display revision or any of its ancestors'), _('REV')),
4037 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
4037 ('', 'hidden', False, _('show hidden changesets (DEPRECATED)')),
4038 ] + logopts + walkopts,
4038 ] + logopts + walkopts,
4039 _('[OPTION]... [FILE]'))
4039 _('[OPTION]... [FILE]'))
4040 def log(ui, repo, *pats, **opts):
4040 def log(ui, repo, *pats, **opts):
4041 """show revision history of entire repository or files
4041 """show revision history of entire repository or files
4042
4042
4043 Print the revision history of the specified files or the entire
4043 Print the revision history of the specified files or the entire
4044 project.
4044 project.
4045
4045
4046 If no revision range is specified, the default is ``tip:0`` unless
4046 If no revision range is specified, the default is ``tip:0`` unless
4047 --follow is set, in which case the working directory parent is
4047 --follow is set, in which case the working directory parent is
4048 used as the starting revision.
4048 used as the starting revision.
4049
4049
4050 File history is shown without following rename or copy history of
4050 File history is shown without following rename or copy history of
4051 files. Use -f/--follow with a filename to follow history across
4051 files. Use -f/--follow with a filename to follow history across
4052 renames and copies. --follow without a filename will only show
4052 renames and copies. --follow without a filename will only show
4053 ancestors or descendants of the starting revision.
4053 ancestors or descendants of the starting revision.
4054
4054
4055 By default this command prints revision number and changeset id,
4055 By default this command prints revision number and changeset id,
4056 tags, non-trivial parents, user, date and time, and a summary for
4056 tags, non-trivial parents, user, date and time, and a summary for
4057 each commit. When the -v/--verbose switch is used, the list of
4057 each commit. When the -v/--verbose switch is used, the list of
4058 changed files and full commit message are shown.
4058 changed files and full commit message are shown.
4059
4059
4060 .. note::
4060 .. note::
4061 log -p/--patch may generate unexpected diff output for merge
4061 log -p/--patch may generate unexpected diff output for merge
4062 changesets, as it will only compare the merge changeset against
4062 changesets, as it will only compare the merge changeset against
4063 its first parent. Also, only files different from BOTH parents
4063 its first parent. Also, only files different from BOTH parents
4064 will appear in files:.
4064 will appear in files:.
4065
4065
4066 .. note::
4066 .. note::
4067 for performance reasons, log FILE may omit duplicate changes
4067 for performance reasons, log FILE may omit duplicate changes
4068 made on branches and will not show deletions. To see all
4068 made on branches and will not show deletions. To see all
4069 changes including duplicates and deletions, use the --removed
4069 changes including duplicates and deletions, use the --removed
4070 switch.
4070 switch.
4071
4071
4072 .. container:: verbose
4072 .. container:: verbose
4073
4073
4074 Some examples:
4074 Some examples:
4075
4075
4076 - changesets with full descriptions and file lists::
4076 - changesets with full descriptions and file lists::
4077
4077
4078 hg log -v
4078 hg log -v
4079
4079
4080 - changesets ancestral to the working directory::
4080 - changesets ancestral to the working directory::
4081
4081
4082 hg log -f
4082 hg log -f
4083
4083
4084 - last 10 commits on the current branch::
4084 - last 10 commits on the current branch::
4085
4085
4086 hg log -l 10 -b .
4086 hg log -l 10 -b .
4087
4087
4088 - changesets showing all modifications of a file, including removals::
4088 - changesets showing all modifications of a file, including removals::
4089
4089
4090 hg log --removed file.c
4090 hg log --removed file.c
4091
4091
4092 - all changesets that touch a directory, with diffs, excluding merges::
4092 - all changesets that touch a directory, with diffs, excluding merges::
4093
4093
4094 hg log -Mp lib/
4094 hg log -Mp lib/
4095
4095
4096 - all revision numbers that match a keyword::
4096 - all revision numbers that match a keyword::
4097
4097
4098 hg log -k bug --template "{rev}\\n"
4098 hg log -k bug --template "{rev}\\n"
4099
4099
4100 - check if a given changeset is included is a tagged release::
4100 - check if a given changeset is included is a tagged release::
4101
4101
4102 hg log -r "a21ccf and ancestor(1.9)"
4102 hg log -r "a21ccf and ancestor(1.9)"
4103
4103
4104 - find all changesets by some user in a date range::
4104 - find all changesets by some user in a date range::
4105
4105
4106 hg log -k alice -d "may 2008 to jul 2008"
4106 hg log -k alice -d "may 2008 to jul 2008"
4107
4107
4108 - summary of all changesets after the last tag::
4108 - summary of all changesets after the last tag::
4109
4109
4110 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4110 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4111
4111
4112 See :hg:`help dates` for a list of formats valid for -d/--date.
4112 See :hg:`help dates` for a list of formats valid for -d/--date.
4113
4113
4114 See :hg:`help revisions` and :hg:`help revsets` for more about
4114 See :hg:`help revisions` and :hg:`help revsets` for more about
4115 specifying revisions.
4115 specifying revisions.
4116
4116
4117 See :hg:`help templates` for more about pre-packaged styles and
4117 See :hg:`help templates` for more about pre-packaged styles and
4118 specifying custom templates.
4118 specifying custom templates.
4119
4119
4120 Returns 0 on success.
4120 Returns 0 on success.
4121 """
4121 """
4122 if opts.get('graph'):
4122 if opts.get('graph'):
4123 return cmdutil.graphlog(ui, repo, *pats, **opts)
4123 return cmdutil.graphlog(ui, repo, *pats, **opts)
4124
4124
4125 matchfn = scmutil.match(repo[None], pats, opts)
4125 matchfn = scmutil.match(repo[None], pats, opts)
4126 limit = cmdutil.loglimit(opts)
4126 limit = cmdutil.loglimit(opts)
4127 count = 0
4127 count = 0
4128
4128
4129 getrenamed, endrev = None, None
4129 getrenamed, endrev = None, None
4130 if opts.get('copies'):
4130 if opts.get('copies'):
4131 if opts.get('rev'):
4131 if opts.get('rev'):
4132 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4132 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4133 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4133 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4134
4134
4135 df = False
4135 df = False
4136 if opts.get("date"):
4136 if opts.get("date"):
4137 df = util.matchdate(opts["date"])
4137 df = util.matchdate(opts["date"])
4138
4138
4139 branches = opts.get('branch', []) + opts.get('only_branch', [])
4139 branches = opts.get('branch', []) + opts.get('only_branch', [])
4140 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4140 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4141
4141
4142 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4142 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4143 def prep(ctx, fns):
4143 def prep(ctx, fns):
4144 rev = ctx.rev()
4144 rev = ctx.rev()
4145 parents = [p for p in repo.changelog.parentrevs(rev)
4145 parents = [p for p in repo.changelog.parentrevs(rev)
4146 if p != nullrev]
4146 if p != nullrev]
4147 if opts.get('no_merges') and len(parents) == 2:
4147 if opts.get('no_merges') and len(parents) == 2:
4148 return
4148 return
4149 if opts.get('only_merges') and len(parents) != 2:
4149 if opts.get('only_merges') and len(parents) != 2:
4150 return
4150 return
4151 if opts.get('branch') and ctx.branch() not in opts['branch']:
4151 if opts.get('branch') and ctx.branch() not in opts['branch']:
4152 return
4152 return
4153 if not opts.get('hidden') and ctx.hidden():
4153 if not opts.get('hidden') and ctx.hidden():
4154 return
4154 return
4155 if df and not df(ctx.date()[0]):
4155 if df and not df(ctx.date()[0]):
4156 return
4156 return
4157
4157
4158 lower = encoding.lower
4158 lower = encoding.lower
4159 if opts.get('user'):
4159 if opts.get('user'):
4160 luser = lower(ctx.user())
4160 luser = lower(ctx.user())
4161 for k in [lower(x) for x in opts['user']]:
4161 for k in [lower(x) for x in opts['user']]:
4162 if (k in luser):
4162 if (k in luser):
4163 break
4163 break
4164 else:
4164 else:
4165 return
4165 return
4166 if opts.get('keyword'):
4166 if opts.get('keyword'):
4167 luser = lower(ctx.user())
4167 luser = lower(ctx.user())
4168 ldesc = lower(ctx.description())
4168 ldesc = lower(ctx.description())
4169 lfiles = lower(" ".join(ctx.files()))
4169 lfiles = lower(" ".join(ctx.files()))
4170 for k in [lower(x) for x in opts['keyword']]:
4170 for k in [lower(x) for x in opts['keyword']]:
4171 if (k in luser or k in ldesc or k in lfiles):
4171 if (k in luser or k in ldesc or k in lfiles):
4172 break
4172 break
4173 else:
4173 else:
4174 return
4174 return
4175
4175
4176 copies = None
4176 copies = None
4177 if getrenamed is not None and rev:
4177 if getrenamed is not None and rev:
4178 copies = []
4178 copies = []
4179 for fn in ctx.files():
4179 for fn in ctx.files():
4180 rename = getrenamed(fn, rev)
4180 rename = getrenamed(fn, rev)
4181 if rename:
4181 if rename:
4182 copies.append((fn, rename[0]))
4182 copies.append((fn, rename[0]))
4183
4183
4184 revmatchfn = None
4184 revmatchfn = None
4185 if opts.get('patch') or opts.get('stat'):
4185 if opts.get('patch') or opts.get('stat'):
4186 if opts.get('follow') or opts.get('follow_first'):
4186 if opts.get('follow') or opts.get('follow_first'):
4187 # note: this might be wrong when following through merges
4187 # note: this might be wrong when following through merges
4188 revmatchfn = scmutil.match(repo[None], fns, default='path')
4188 revmatchfn = scmutil.match(repo[None], fns, default='path')
4189 else:
4189 else:
4190 revmatchfn = matchfn
4190 revmatchfn = matchfn
4191
4191
4192 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4192 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4193
4193
4194 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4194 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4195 if count == limit:
4195 if count == limit:
4196 break
4196 break
4197 if displayer.flush(ctx.rev()):
4197 if displayer.flush(ctx.rev()):
4198 count += 1
4198 count += 1
4199 displayer.close()
4199 displayer.close()
4200
4200
4201 @command('manifest',
4201 @command('manifest',
4202 [('r', 'rev', '', _('revision to display'), _('REV')),
4202 [('r', 'rev', '', _('revision to display'), _('REV')),
4203 ('', 'all', False, _("list files from all revisions"))],
4203 ('', 'all', False, _("list files from all revisions"))],
4204 _('[-r REV]'))
4204 _('[-r REV]'))
4205 def manifest(ui, repo, node=None, rev=None, **opts):
4205 def manifest(ui, repo, node=None, rev=None, **opts):
4206 """output the current or given revision of the project manifest
4206 """output the current or given revision of the project manifest
4207
4207
4208 Print a list of version controlled files for the given revision.
4208 Print a list of version controlled files for the given revision.
4209 If no revision is given, the first parent of the working directory
4209 If no revision is given, the first parent of the working directory
4210 is used, or the null revision if no revision is checked out.
4210 is used, or the null revision if no revision is checked out.
4211
4211
4212 With -v, print file permissions, symlink and executable bits.
4212 With -v, print file permissions, symlink and executable bits.
4213 With --debug, print file revision hashes.
4213 With --debug, print file revision hashes.
4214
4214
4215 If option --all is specified, the list of all files from all revisions
4215 If option --all is specified, the list of all files from all revisions
4216 is printed. This includes deleted and renamed files.
4216 is printed. This includes deleted and renamed files.
4217
4217
4218 Returns 0 on success.
4218 Returns 0 on success.
4219 """
4219 """
4220
4220
4221 fm = ui.formatter('manifest', opts)
4221 fm = ui.formatter('manifest', opts)
4222
4222
4223 if opts.get('all'):
4223 if opts.get('all'):
4224 if rev or node:
4224 if rev or node:
4225 raise util.Abort(_("can't specify a revision with --all"))
4225 raise util.Abort(_("can't specify a revision with --all"))
4226
4226
4227 res = []
4227 res = []
4228 prefix = "data/"
4228 prefix = "data/"
4229 suffix = ".i"
4229 suffix = ".i"
4230 plen = len(prefix)
4230 plen = len(prefix)
4231 slen = len(suffix)
4231 slen = len(suffix)
4232 lock = repo.lock()
4232 lock = repo.lock()
4233 try:
4233 try:
4234 for fn, b, size in repo.store.datafiles():
4234 for fn, b, size in repo.store.datafiles():
4235 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4235 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4236 res.append(fn[plen:-slen])
4236 res.append(fn[plen:-slen])
4237 finally:
4237 finally:
4238 lock.release()
4238 lock.release()
4239 for f in res:
4239 for f in res:
4240 fm.startitem()
4240 fm.startitem()
4241 fm.write("path", '%s\n', f)
4241 fm.write("path", '%s\n', f)
4242 fm.end()
4242 fm.end()
4243 return
4243 return
4244
4244
4245 if rev and node:
4245 if rev and node:
4246 raise util.Abort(_("please specify just one revision"))
4246 raise util.Abort(_("please specify just one revision"))
4247
4247
4248 if not node:
4248 if not node:
4249 node = rev
4249 node = rev
4250
4250
4251 char = {'l': '@', 'x': '*', '': ''}
4251 char = {'l': '@', 'x': '*', '': ''}
4252 mode = {'l': '644', 'x': '755', '': '644'}
4252 mode = {'l': '644', 'x': '755', '': '644'}
4253 ctx = scmutil.revsingle(repo, node)
4253 ctx = scmutil.revsingle(repo, node)
4254 mf = ctx.manifest()
4254 mf = ctx.manifest()
4255 for f in ctx:
4255 for f in ctx:
4256 fm.startitem()
4256 fm.startitem()
4257 fl = ctx[f].flags()
4257 fl = ctx[f].flags()
4258 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4258 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4259 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4259 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4260 fm.write('path', '%s\n', f)
4260 fm.write('path', '%s\n', f)
4261 fm.end()
4261 fm.end()
4262
4262
4263 @command('^merge',
4263 @command('^merge',
4264 [('f', 'force', None, _('force a merge with outstanding changes')),
4264 [('f', 'force', None, _('force a merge with outstanding changes')),
4265 ('r', 'rev', '', _('revision to merge'), _('REV')),
4265 ('r', 'rev', '', _('revision to merge'), _('REV')),
4266 ('P', 'preview', None,
4266 ('P', 'preview', None,
4267 _('review revisions to merge (no merge is performed)'))
4267 _('review revisions to merge (no merge is performed)'))
4268 ] + mergetoolopts,
4268 ] + mergetoolopts,
4269 _('[-P] [-f] [[-r] REV]'))
4269 _('[-P] [-f] [[-r] REV]'))
4270 def merge(ui, repo, node=None, **opts):
4270 def merge(ui, repo, node=None, **opts):
4271 """merge working directory with another revision
4271 """merge working directory with another revision
4272
4272
4273 The current working directory is updated with all changes made in
4273 The current working directory is updated with all changes made in
4274 the requested revision since the last common predecessor revision.
4274 the requested revision since the last common predecessor revision.
4275
4275
4276 Files that changed between either parent are marked as changed for
4276 Files that changed between either parent are marked as changed for
4277 the next commit and a commit must be performed before any further
4277 the next commit and a commit must be performed before any further
4278 updates to the repository are allowed. The next commit will have
4278 updates to the repository are allowed. The next commit will have
4279 two parents.
4279 two parents.
4280
4280
4281 ``--tool`` can be used to specify the merge tool used for file
4281 ``--tool`` can be used to specify the merge tool used for file
4282 merges. It overrides the HGMERGE environment variable and your
4282 merges. It overrides the HGMERGE environment variable and your
4283 configuration files. See :hg:`help merge-tools` for options.
4283 configuration files. See :hg:`help merge-tools` for options.
4284
4284
4285 If no revision is specified, the working directory's parent is a
4285 If no revision is specified, the working directory's parent is a
4286 head revision, and the current branch contains exactly one other
4286 head revision, and the current branch contains exactly one other
4287 head, the other head is merged with by default. Otherwise, an
4287 head, the other head is merged with by default. Otherwise, an
4288 explicit revision with which to merge with must be provided.
4288 explicit revision with which to merge with must be provided.
4289
4289
4290 :hg:`resolve` must be used to resolve unresolved files.
4290 :hg:`resolve` must be used to resolve unresolved files.
4291
4291
4292 To undo an uncommitted merge, use :hg:`update --clean .` which
4292 To undo an uncommitted merge, use :hg:`update --clean .` which
4293 will check out a clean copy of the original merge parent, losing
4293 will check out a clean copy of the original merge parent, losing
4294 all changes.
4294 all changes.
4295
4295
4296 Returns 0 on success, 1 if there are unresolved files.
4296 Returns 0 on success, 1 if there are unresolved files.
4297 """
4297 """
4298
4298
4299 if opts.get('rev') and node:
4299 if opts.get('rev') and node:
4300 raise util.Abort(_("please specify just one revision"))
4300 raise util.Abort(_("please specify just one revision"))
4301 if not node:
4301 if not node:
4302 node = opts.get('rev')
4302 node = opts.get('rev')
4303
4303
4304 if node:
4304 if node:
4305 node = scmutil.revsingle(repo, node).node()
4305 node = scmutil.revsingle(repo, node).node()
4306
4306
4307 if not node and repo._bookmarkcurrent:
4307 if not node and repo._bookmarkcurrent:
4308 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4308 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4309 curhead = repo[repo._bookmarkcurrent]
4309 curhead = repo[repo._bookmarkcurrent]
4310 if len(bmheads) == 2:
4310 if len(bmheads) == 2:
4311 if curhead == bmheads[0]:
4311 if curhead == bmheads[0]:
4312 node = bmheads[1]
4312 node = bmheads[1]
4313 else:
4313 else:
4314 node = bmheads[0]
4314 node = bmheads[0]
4315 elif len(bmheads) > 2:
4315 elif len(bmheads) > 2:
4316 raise util.Abort(_("multiple matching bookmarks to merge - "
4316 raise util.Abort(_("multiple matching bookmarks to merge - "
4317 "please merge with an explicit rev or bookmark"),
4317 "please merge with an explicit rev or bookmark"),
4318 hint=_("run 'hg heads' to see all heads"))
4318 hint=_("run 'hg heads' to see all heads"))
4319 elif len(bmheads) <= 1:
4319 elif len(bmheads) <= 1:
4320 raise util.Abort(_("no matching bookmark to merge - "
4320 raise util.Abort(_("no matching bookmark to merge - "
4321 "please merge with an explicit rev or bookmark"),
4321 "please merge with an explicit rev or bookmark"),
4322 hint=_("run 'hg heads' to see all heads"))
4322 hint=_("run 'hg heads' to see all heads"))
4323
4323
4324 if not node and not repo._bookmarkcurrent:
4324 if not node and not repo._bookmarkcurrent:
4325 branch = repo[None].branch()
4325 branch = repo[None].branch()
4326 bheads = repo.branchheads(branch)
4326 bheads = repo.branchheads(branch)
4327 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4327 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4328
4328
4329 if len(nbhs) > 2:
4329 if len(nbhs) > 2:
4330 raise util.Abort(_("branch '%s' has %d heads - "
4330 raise util.Abort(_("branch '%s' has %d heads - "
4331 "please merge with an explicit rev")
4331 "please merge with an explicit rev")
4332 % (branch, len(bheads)),
4332 % (branch, len(bheads)),
4333 hint=_("run 'hg heads .' to see heads"))
4333 hint=_("run 'hg heads .' to see heads"))
4334
4334
4335 parent = repo.dirstate.p1()
4335 parent = repo.dirstate.p1()
4336 if len(nbhs) <= 1:
4336 if len(nbhs) <= 1:
4337 if len(bheads) > 1:
4337 if len(bheads) > 1:
4338 raise util.Abort(_("heads are bookmarked - "
4338 raise util.Abort(_("heads are bookmarked - "
4339 "please merge with an explicit rev"),
4339 "please merge with an explicit rev"),
4340 hint=_("run 'hg heads' to see all heads"))
4340 hint=_("run 'hg heads' to see all heads"))
4341 if len(repo.heads()) > 1:
4341 if len(repo.heads()) > 1:
4342 raise util.Abort(_("branch '%s' has one head - "
4342 raise util.Abort(_("branch '%s' has one head - "
4343 "please merge with an explicit rev")
4343 "please merge with an explicit rev")
4344 % branch,
4344 % branch,
4345 hint=_("run 'hg heads' to see all heads"))
4345 hint=_("run 'hg heads' to see all heads"))
4346 msg, hint = _('nothing to merge'), None
4346 msg, hint = _('nothing to merge'), None
4347 if parent != repo.lookup(branch):
4347 if parent != repo.lookup(branch):
4348 hint = _("use 'hg update' instead")
4348 hint = _("use 'hg update' instead")
4349 raise util.Abort(msg, hint=hint)
4349 raise util.Abort(msg, hint=hint)
4350
4350
4351 if parent not in bheads:
4351 if parent not in bheads:
4352 raise util.Abort(_('working directory not at a head revision'),
4352 raise util.Abort(_('working directory not at a head revision'),
4353 hint=_("use 'hg update' or merge with an "
4353 hint=_("use 'hg update' or merge with an "
4354 "explicit revision"))
4354 "explicit revision"))
4355 if parent == nbhs[0]:
4355 if parent == nbhs[0]:
4356 node = nbhs[-1]
4356 node = nbhs[-1]
4357 else:
4357 else:
4358 node = nbhs[0]
4358 node = nbhs[0]
4359
4359
4360 if opts.get('preview'):
4360 if opts.get('preview'):
4361 # find nodes that are ancestors of p2 but not of p1
4361 # find nodes that are ancestors of p2 but not of p1
4362 p1 = repo.lookup('.')
4362 p1 = repo.lookup('.')
4363 p2 = repo.lookup(node)
4363 p2 = repo.lookup(node)
4364 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4364 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4365
4365
4366 displayer = cmdutil.show_changeset(ui, repo, opts)
4366 displayer = cmdutil.show_changeset(ui, repo, opts)
4367 for node in nodes:
4367 for node in nodes:
4368 displayer.show(repo[node])
4368 displayer.show(repo[node])
4369 displayer.close()
4369 displayer.close()
4370 return 0
4370 return 0
4371
4371
4372 try:
4372 try:
4373 # ui.forcemerge is an internal variable, do not document
4373 # ui.forcemerge is an internal variable, do not document
4374 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4374 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4375 return hg.merge(repo, node, force=opts.get('force'))
4375 return hg.merge(repo, node, force=opts.get('force'))
4376 finally:
4376 finally:
4377 ui.setconfig('ui', 'forcemerge', '')
4377 ui.setconfig('ui', 'forcemerge', '')
4378
4378
4379 @command('outgoing|out',
4379 @command('outgoing|out',
4380 [('f', 'force', None, _('run even when the destination is unrelated')),
4380 [('f', 'force', None, _('run even when the destination is unrelated')),
4381 ('r', 'rev', [],
4381 ('r', 'rev', [],
4382 _('a changeset intended to be included in the destination'), _('REV')),
4382 _('a changeset intended to be included in the destination'), _('REV')),
4383 ('n', 'newest-first', None, _('show newest record first')),
4383 ('n', 'newest-first', None, _('show newest record first')),
4384 ('B', 'bookmarks', False, _('compare bookmarks')),
4384 ('B', 'bookmarks', False, _('compare bookmarks')),
4385 ('b', 'branch', [], _('a specific branch you would like to push'),
4385 ('b', 'branch', [], _('a specific branch you would like to push'),
4386 _('BRANCH')),
4386 _('BRANCH')),
4387 ] + logopts + remoteopts + subrepoopts,
4387 ] + logopts + remoteopts + subrepoopts,
4388 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4388 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4389 def outgoing(ui, repo, dest=None, **opts):
4389 def outgoing(ui, repo, dest=None, **opts):
4390 """show changesets not found in the destination
4390 """show changesets not found in the destination
4391
4391
4392 Show changesets not found in the specified destination repository
4392 Show changesets not found in the specified destination repository
4393 or the default push location. These are the changesets that would
4393 or the default push location. These are the changesets that would
4394 be pushed if a push was requested.
4394 be pushed if a push was requested.
4395
4395
4396 See pull for details of valid destination formats.
4396 See pull for details of valid destination formats.
4397
4397
4398 Returns 0 if there are outgoing changes, 1 otherwise.
4398 Returns 0 if there are outgoing changes, 1 otherwise.
4399 """
4399 """
4400 if opts.get('graph'):
4400 if opts.get('graph'):
4401 cmdutil.checkunsupportedgraphflags([], opts)
4401 cmdutil.checkunsupportedgraphflags([], opts)
4402 o = hg._outgoing(ui, repo, dest, opts)
4402 o = hg._outgoing(ui, repo, dest, opts)
4403 if o is None:
4403 if o is None:
4404 return
4404 return
4405
4405
4406 revdag = cmdutil.graphrevs(repo, o, opts)
4406 revdag = cmdutil.graphrevs(repo, o, opts)
4407 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4407 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4408 showparents = [ctx.node() for ctx in repo[None].parents()]
4408 showparents = [ctx.node() for ctx in repo[None].parents()]
4409 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4409 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4410 graphmod.asciiedges)
4410 graphmod.asciiedges)
4411 return 0
4411 return 0
4412
4412
4413 if opts.get('bookmarks'):
4413 if opts.get('bookmarks'):
4414 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4414 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4415 dest, branches = hg.parseurl(dest, opts.get('branch'))
4415 dest, branches = hg.parseurl(dest, opts.get('branch'))
4416 other = hg.peer(repo, opts, dest)
4416 other = hg.peer(repo, opts, dest)
4417 if 'bookmarks' not in other.listkeys('namespaces'):
4417 if 'bookmarks' not in other.listkeys('namespaces'):
4418 ui.warn(_("remote doesn't support bookmarks\n"))
4418 ui.warn(_("remote doesn't support bookmarks\n"))
4419 return 0
4419 return 0
4420 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4420 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4421 return bookmarks.diff(ui, other, repo)
4421 return bookmarks.diff(ui, other, repo)
4422
4422
4423 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4423 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4424 try:
4424 try:
4425 return hg.outgoing(ui, repo, dest, opts)
4425 return hg.outgoing(ui, repo, dest, opts)
4426 finally:
4426 finally:
4427 del repo._subtoppath
4427 del repo._subtoppath
4428
4428
4429 @command('parents',
4429 @command('parents',
4430 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4430 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4431 ] + templateopts,
4431 ] + templateopts,
4432 _('[-r REV] [FILE]'))
4432 _('[-r REV] [FILE]'))
4433 def parents(ui, repo, file_=None, **opts):
4433 def parents(ui, repo, file_=None, **opts):
4434 """show the parents of the working directory or revision
4434 """show the parents of the working directory or revision
4435
4435
4436 Print the working directory's parent revisions. If a revision is
4436 Print the working directory's parent revisions. If a revision is
4437 given via -r/--rev, the parent of that revision will be printed.
4437 given via -r/--rev, the parent of that revision will be printed.
4438 If a file argument is given, the revision in which the file was
4438 If a file argument is given, the revision in which the file was
4439 last changed (before the working directory revision or the
4439 last changed (before the working directory revision or the
4440 argument to --rev if given) is printed.
4440 argument to --rev if given) is printed.
4441
4441
4442 Returns 0 on success.
4442 Returns 0 on success.
4443 """
4443 """
4444
4444
4445 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4445 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4446
4446
4447 if file_:
4447 if file_:
4448 m = scmutil.match(ctx, (file_,), opts)
4448 m = scmutil.match(ctx, (file_,), opts)
4449 if m.anypats() or len(m.files()) != 1:
4449 if m.anypats() or len(m.files()) != 1:
4450 raise util.Abort(_('can only specify an explicit filename'))
4450 raise util.Abort(_('can only specify an explicit filename'))
4451 file_ = m.files()[0]
4451 file_ = m.files()[0]
4452 filenodes = []
4452 filenodes = []
4453 for cp in ctx.parents():
4453 for cp in ctx.parents():
4454 if not cp:
4454 if not cp:
4455 continue
4455 continue
4456 try:
4456 try:
4457 filenodes.append(cp.filenode(file_))
4457 filenodes.append(cp.filenode(file_))
4458 except error.LookupError:
4458 except error.LookupError:
4459 pass
4459 pass
4460 if not filenodes:
4460 if not filenodes:
4461 raise util.Abort(_("'%s' not found in manifest!") % file_)
4461 raise util.Abort(_("'%s' not found in manifest!") % file_)
4462 fl = repo.file(file_)
4462 fl = repo.file(file_)
4463 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4463 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
4464 else:
4464 else:
4465 p = [cp.node() for cp in ctx.parents()]
4465 p = [cp.node() for cp in ctx.parents()]
4466
4466
4467 displayer = cmdutil.show_changeset(ui, repo, opts)
4467 displayer = cmdutil.show_changeset(ui, repo, opts)
4468 for n in p:
4468 for n in p:
4469 if n != nullid:
4469 if n != nullid:
4470 displayer.show(repo[n])
4470 displayer.show(repo[n])
4471 displayer.close()
4471 displayer.close()
4472
4472
4473 @command('paths', [], _('[NAME]'))
4473 @command('paths', [], _('[NAME]'))
4474 def paths(ui, repo, search=None):
4474 def paths(ui, repo, search=None):
4475 """show aliases for remote repositories
4475 """show aliases for remote repositories
4476
4476
4477 Show definition of symbolic path name NAME. If no name is given,
4477 Show definition of symbolic path name NAME. If no name is given,
4478 show definition of all available names.
4478 show definition of all available names.
4479
4479
4480 Option -q/--quiet suppresses all output when searching for NAME
4480 Option -q/--quiet suppresses all output when searching for NAME
4481 and shows only the path names when listing all definitions.
4481 and shows only the path names when listing all definitions.
4482
4482
4483 Path names are defined in the [paths] section of your
4483 Path names are defined in the [paths] section of your
4484 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4484 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4485 repository, ``.hg/hgrc`` is used, too.
4485 repository, ``.hg/hgrc`` is used, too.
4486
4486
4487 The path names ``default`` and ``default-push`` have a special
4487 The path names ``default`` and ``default-push`` have a special
4488 meaning. When performing a push or pull operation, they are used
4488 meaning. When performing a push or pull operation, they are used
4489 as fallbacks if no location is specified on the command-line.
4489 as fallbacks if no location is specified on the command-line.
4490 When ``default-push`` is set, it will be used for push and
4490 When ``default-push`` is set, it will be used for push and
4491 ``default`` will be used for pull; otherwise ``default`` is used
4491 ``default`` will be used for pull; otherwise ``default`` is used
4492 as the fallback for both. When cloning a repository, the clone
4492 as the fallback for both. When cloning a repository, the clone
4493 source is written as ``default`` in ``.hg/hgrc``. Note that
4493 source is written as ``default`` in ``.hg/hgrc``. Note that
4494 ``default`` and ``default-push`` apply to all inbound (e.g.
4494 ``default`` and ``default-push`` apply to all inbound (e.g.
4495 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4495 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4496 :hg:`bundle`) operations.
4496 :hg:`bundle`) operations.
4497
4497
4498 See :hg:`help urls` for more information.
4498 See :hg:`help urls` for more information.
4499
4499
4500 Returns 0 on success.
4500 Returns 0 on success.
4501 """
4501 """
4502 if search:
4502 if search:
4503 for name, path in ui.configitems("paths"):
4503 for name, path in ui.configitems("paths"):
4504 if name == search:
4504 if name == search:
4505 ui.status("%s\n" % util.hidepassword(path))
4505 ui.status("%s\n" % util.hidepassword(path))
4506 return
4506 return
4507 if not ui.quiet:
4507 if not ui.quiet:
4508 ui.warn(_("not found!\n"))
4508 ui.warn(_("not found!\n"))
4509 return 1
4509 return 1
4510 else:
4510 else:
4511 for name, path in ui.configitems("paths"):
4511 for name, path in ui.configitems("paths"):
4512 if ui.quiet:
4512 if ui.quiet:
4513 ui.write("%s\n" % name)
4513 ui.write("%s\n" % name)
4514 else:
4514 else:
4515 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4515 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4516
4516
4517 @command('phase',
4517 @command('phase',
4518 [('p', 'public', False, _('set changeset phase to public')),
4518 [('p', 'public', False, _('set changeset phase to public')),
4519 ('d', 'draft', False, _('set changeset phase to draft')),
4519 ('d', 'draft', False, _('set changeset phase to draft')),
4520 ('s', 'secret', False, _('set changeset phase to secret')),
4520 ('s', 'secret', False, _('set changeset phase to secret')),
4521 ('f', 'force', False, _('allow to move boundary backward')),
4521 ('f', 'force', False, _('allow to move boundary backward')),
4522 ('r', 'rev', [], _('target revision'), _('REV')),
4522 ('r', 'rev', [], _('target revision'), _('REV')),
4523 ],
4523 ],
4524 _('[-p|-d|-s] [-f] [-r] REV...'))
4524 _('[-p|-d|-s] [-f] [-r] REV...'))
4525 def phase(ui, repo, *revs, **opts):
4525 def phase(ui, repo, *revs, **opts):
4526 """set or show the current phase name
4526 """set or show the current phase name
4527
4527
4528 With no argument, show the phase name of specified revisions.
4528 With no argument, show the phase name of specified revisions.
4529
4529
4530 With one of -p/--public, -d/--draft or -s/--secret, change the
4530 With one of -p/--public, -d/--draft or -s/--secret, change the
4531 phase value of the specified revisions.
4531 phase value of the specified revisions.
4532
4532
4533 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4533 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4534 lower phase to an higher phase. Phases are ordered as follows::
4534 lower phase to an higher phase. Phases are ordered as follows::
4535
4535
4536 public < draft < secret
4536 public < draft < secret
4537
4537
4538 Return 0 on success, 1 if no phases were changed or some could not
4538 Return 0 on success, 1 if no phases were changed or some could not
4539 be changed.
4539 be changed.
4540 """
4540 """
4541 # search for a unique phase argument
4541 # search for a unique phase argument
4542 targetphase = None
4542 targetphase = None
4543 for idx, name in enumerate(phases.phasenames):
4543 for idx, name in enumerate(phases.phasenames):
4544 if opts[name]:
4544 if opts[name]:
4545 if targetphase is not None:
4545 if targetphase is not None:
4546 raise util.Abort(_('only one phase can be specified'))
4546 raise util.Abort(_('only one phase can be specified'))
4547 targetphase = idx
4547 targetphase = idx
4548
4548
4549 # look for specified revision
4549 # look for specified revision
4550 revs = list(revs)
4550 revs = list(revs)
4551 revs.extend(opts['rev'])
4551 revs.extend(opts['rev'])
4552 if not revs:
4552 if not revs:
4553 raise util.Abort(_('no revisions specified'))
4553 raise util.Abort(_('no revisions specified'))
4554
4554
4555 revs = scmutil.revrange(repo, revs)
4555 revs = scmutil.revrange(repo, revs)
4556
4556
4557 lock = None
4557 lock = None
4558 ret = 0
4558 ret = 0
4559 if targetphase is None:
4559 if targetphase is None:
4560 # display
4560 # display
4561 for r in revs:
4561 for r in revs:
4562 ctx = repo[r]
4562 ctx = repo[r]
4563 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4563 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4564 else:
4564 else:
4565 lock = repo.lock()
4565 lock = repo.lock()
4566 try:
4566 try:
4567 # set phase
4567 # set phase
4568 if not revs:
4568 if not revs:
4569 raise util.Abort(_('empty revision set'))
4569 raise util.Abort(_('empty revision set'))
4570 nodes = [repo[r].node() for r in revs]
4570 nodes = [repo[r].node() for r in revs]
4571 olddata = repo._phasecache.getphaserevs(repo)[:]
4571 olddata = repo._phasecache.getphaserevs(repo)[:]
4572 phases.advanceboundary(repo, targetphase, nodes)
4572 phases.advanceboundary(repo, targetphase, nodes)
4573 if opts['force']:
4573 if opts['force']:
4574 phases.retractboundary(repo, targetphase, nodes)
4574 phases.retractboundary(repo, targetphase, nodes)
4575 finally:
4575 finally:
4576 lock.release()
4576 lock.release()
4577 newdata = repo._phasecache.getphaserevs(repo)
4577 newdata = repo._phasecache.getphaserevs(repo)
4578 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4578 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4579 rejected = [n for n in nodes
4579 rejected = [n for n in nodes
4580 if newdata[repo[n].rev()] < targetphase]
4580 if newdata[repo[n].rev()] < targetphase]
4581 if rejected:
4581 if rejected:
4582 ui.warn(_('cannot move %i changesets to a more permissive '
4582 ui.warn(_('cannot move %i changesets to a more permissive '
4583 'phase, use --force\n') % len(rejected))
4583 'phase, use --force\n') % len(rejected))
4584 ret = 1
4584 ret = 1
4585 if changes:
4585 if changes:
4586 msg = _('phase changed for %i changesets\n') % changes
4586 msg = _('phase changed for %i changesets\n') % changes
4587 if ret:
4587 if ret:
4588 ui.status(msg)
4588 ui.status(msg)
4589 else:
4589 else:
4590 ui.note(msg)
4590 ui.note(msg)
4591 else:
4591 else:
4592 ui.warn(_('no phases changed\n'))
4592 ui.warn(_('no phases changed\n'))
4593 ret = 1
4593 ret = 1
4594 return ret
4594 return ret
4595
4595
4596 def postincoming(ui, repo, modheads, optupdate, checkout):
4596 def postincoming(ui, repo, modheads, optupdate, checkout):
4597 if modheads == 0:
4597 if modheads == 0:
4598 return
4598 return
4599 if optupdate:
4599 if optupdate:
4600 movemarkfrom = repo['.'].node()
4600 movemarkfrom = repo['.'].node()
4601 try:
4601 try:
4602 ret = hg.update(repo, checkout)
4602 ret = hg.update(repo, checkout)
4603 except util.Abort, inst:
4603 except util.Abort, inst:
4604 ui.warn(_("not updating: %s\n") % str(inst))
4604 ui.warn(_("not updating: %s\n") % str(inst))
4605 return 0
4605 return 0
4606 if not ret and not checkout:
4606 if not ret and not checkout:
4607 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4607 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4608 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4608 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4609 return ret
4609 return ret
4610 if modheads > 1:
4610 if modheads > 1:
4611 currentbranchheads = len(repo.branchheads())
4611 currentbranchheads = len(repo.branchheads())
4612 if currentbranchheads == modheads:
4612 if currentbranchheads == modheads:
4613 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4613 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4614 elif currentbranchheads > 1:
4614 elif currentbranchheads > 1:
4615 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4615 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4616 "merge)\n"))
4616 "merge)\n"))
4617 else:
4617 else:
4618 ui.status(_("(run 'hg heads' to see heads)\n"))
4618 ui.status(_("(run 'hg heads' to see heads)\n"))
4619 else:
4619 else:
4620 ui.status(_("(run 'hg update' to get a working copy)\n"))
4620 ui.status(_("(run 'hg update' to get a working copy)\n"))
4621
4621
4622 @command('^pull',
4622 @command('^pull',
4623 [('u', 'update', None,
4623 [('u', 'update', None,
4624 _('update to new branch head if changesets were pulled')),
4624 _('update to new branch head if changesets were pulled')),
4625 ('f', 'force', None, _('run even when remote repository is unrelated')),
4625 ('f', 'force', None, _('run even when remote repository is unrelated')),
4626 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4626 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4627 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4627 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4628 ('b', 'branch', [], _('a specific branch you would like to pull'),
4628 ('b', 'branch', [], _('a specific branch you would like to pull'),
4629 _('BRANCH')),
4629 _('BRANCH')),
4630 ] + remoteopts,
4630 ] + remoteopts,
4631 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4631 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4632 def pull(ui, repo, source="default", **opts):
4632 def pull(ui, repo, source="default", **opts):
4633 """pull changes from the specified source
4633 """pull changes from the specified source
4634
4634
4635 Pull changes from a remote repository to a local one.
4635 Pull changes from a remote repository to a local one.
4636
4636
4637 This finds all changes from the repository at the specified path
4637 This finds all changes from the repository at the specified path
4638 or URL and adds them to a local repository (the current one unless
4638 or URL and adds them to a local repository (the current one unless
4639 -R is specified). By default, this does not update the copy of the
4639 -R is specified). By default, this does not update the copy of the
4640 project in the working directory.
4640 project in the working directory.
4641
4641
4642 Use :hg:`incoming` if you want to see what would have been added
4642 Use :hg:`incoming` if you want to see what would have been added
4643 by a pull at the time you issued this command. If you then decide
4643 by a pull at the time you issued this command. If you then decide
4644 to add those changes to the repository, you should use :hg:`pull
4644 to add those changes to the repository, you should use :hg:`pull
4645 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4645 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4646
4646
4647 If SOURCE is omitted, the 'default' path will be used.
4647 If SOURCE is omitted, the 'default' path will be used.
4648 See :hg:`help urls` for more information.
4648 See :hg:`help urls` for more information.
4649
4649
4650 Returns 0 on success, 1 if an update had unresolved files.
4650 Returns 0 on success, 1 if an update had unresolved files.
4651 """
4651 """
4652 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4652 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4653 other = hg.peer(repo, opts, source)
4653 other = hg.peer(repo, opts, source)
4654 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4654 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4655 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4655 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4656
4656
4657 if opts.get('bookmark'):
4657 if opts.get('bookmark'):
4658 if not revs:
4658 if not revs:
4659 revs = []
4659 revs = []
4660 rb = other.listkeys('bookmarks')
4660 rb = other.listkeys('bookmarks')
4661 for b in opts['bookmark']:
4661 for b in opts['bookmark']:
4662 if b not in rb:
4662 if b not in rb:
4663 raise util.Abort(_('remote bookmark %s not found!') % b)
4663 raise util.Abort(_('remote bookmark %s not found!') % b)
4664 revs.append(rb[b])
4664 revs.append(rb[b])
4665
4665
4666 if revs:
4666 if revs:
4667 try:
4667 try:
4668 revs = [other.lookup(rev) for rev in revs]
4668 revs = [other.lookup(rev) for rev in revs]
4669 except error.CapabilityError:
4669 except error.CapabilityError:
4670 err = _("other repository doesn't support revision lookup, "
4670 err = _("other repository doesn't support revision lookup, "
4671 "so a rev cannot be specified.")
4671 "so a rev cannot be specified.")
4672 raise util.Abort(err)
4672 raise util.Abort(err)
4673
4673
4674 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4674 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4675 bookmarks.updatefromremote(ui, repo, other, source)
4675 bookmarks.updatefromremote(ui, repo, other, source)
4676 if checkout:
4676 if checkout:
4677 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4677 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4678 repo._subtoppath = source
4678 repo._subtoppath = source
4679 try:
4679 try:
4680 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4680 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4681
4681
4682 finally:
4682 finally:
4683 del repo._subtoppath
4683 del repo._subtoppath
4684
4684
4685 # update specified bookmarks
4685 # update specified bookmarks
4686 if opts.get('bookmark'):
4686 if opts.get('bookmark'):
4687 marks = repo._bookmarks
4687 marks = repo._bookmarks
4688 for b in opts['bookmark']:
4688 for b in opts['bookmark']:
4689 # explicit pull overrides local bookmark if any
4689 # explicit pull overrides local bookmark if any
4690 ui.status(_("importing bookmark %s\n") % b)
4690 ui.status(_("importing bookmark %s\n") % b)
4691 marks[b] = repo[rb[b]].node()
4691 marks[b] = repo[rb[b]].node()
4692 marks.write()
4692 marks.write()
4693
4693
4694 return ret
4694 return ret
4695
4695
4696 @command('^push',
4696 @command('^push',
4697 [('f', 'force', None, _('force push')),
4697 [('f', 'force', None, _('force push')),
4698 ('r', 'rev', [],
4698 ('r', 'rev', [],
4699 _('a changeset intended to be included in the destination'),
4699 _('a changeset intended to be included in the destination'),
4700 _('REV')),
4700 _('REV')),
4701 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4701 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4702 ('b', 'branch', [],
4702 ('b', 'branch', [],
4703 _('a specific branch you would like to push'), _('BRANCH')),
4703 _('a specific branch you would like to push'), _('BRANCH')),
4704 ('', 'new-branch', False, _('allow pushing a new branch')),
4704 ('', 'new-branch', False, _('allow pushing a new branch')),
4705 ] + remoteopts,
4705 ] + remoteopts,
4706 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4706 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4707 def push(ui, repo, dest=None, **opts):
4707 def push(ui, repo, dest=None, **opts):
4708 """push changes to the specified destination
4708 """push changes to the specified destination
4709
4709
4710 Push changesets from the local repository to the specified
4710 Push changesets from the local repository to the specified
4711 destination.
4711 destination.
4712
4712
4713 This operation is symmetrical to pull: it is identical to a pull
4713 This operation is symmetrical to pull: it is identical to a pull
4714 in the destination repository from the current one.
4714 in the destination repository from the current one.
4715
4715
4716 By default, push will not allow creation of new heads at the
4716 By default, push will not allow creation of new heads at the
4717 destination, since multiple heads would make it unclear which head
4717 destination, since multiple heads would make it unclear which head
4718 to use. In this situation, it is recommended to pull and merge
4718 to use. In this situation, it is recommended to pull and merge
4719 before pushing.
4719 before pushing.
4720
4720
4721 Use --new-branch if you want to allow push to create a new named
4721 Use --new-branch if you want to allow push to create a new named
4722 branch that is not present at the destination. This allows you to
4722 branch that is not present at the destination. This allows you to
4723 only create a new branch without forcing other changes.
4723 only create a new branch without forcing other changes.
4724
4724
4725 Use -f/--force to override the default behavior and push all
4725 Use -f/--force to override the default behavior and push all
4726 changesets on all branches.
4726 changesets on all branches.
4727
4727
4728 If -r/--rev is used, the specified revision and all its ancestors
4728 If -r/--rev is used, the specified revision and all its ancestors
4729 will be pushed to the remote repository.
4729 will be pushed to the remote repository.
4730
4730
4731 If -B/--bookmark is used, the specified bookmarked revision, its
4731 If -B/--bookmark is used, the specified bookmarked revision, its
4732 ancestors, and the bookmark will be pushed to the remote
4732 ancestors, and the bookmark will be pushed to the remote
4733 repository.
4733 repository.
4734
4734
4735 Please see :hg:`help urls` for important details about ``ssh://``
4735 Please see :hg:`help urls` for important details about ``ssh://``
4736 URLs. If DESTINATION is omitted, a default path will be used.
4736 URLs. If DESTINATION is omitted, a default path will be used.
4737
4737
4738 Returns 0 if push was successful, 1 if nothing to push.
4738 Returns 0 if push was successful, 1 if nothing to push.
4739 """
4739 """
4740
4740
4741 if opts.get('bookmark'):
4741 if opts.get('bookmark'):
4742 for b in opts['bookmark']:
4742 for b in opts['bookmark']:
4743 # translate -B options to -r so changesets get pushed
4743 # translate -B options to -r so changesets get pushed
4744 if b in repo._bookmarks:
4744 if b in repo._bookmarks:
4745 opts.setdefault('rev', []).append(b)
4745 opts.setdefault('rev', []).append(b)
4746 else:
4746 else:
4747 # if we try to push a deleted bookmark, translate it to null
4747 # if we try to push a deleted bookmark, translate it to null
4748 # this lets simultaneous -r, -b options continue working
4748 # this lets simultaneous -r, -b options continue working
4749 opts.setdefault('rev', []).append("null")
4749 opts.setdefault('rev', []).append("null")
4750
4750
4751 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4751 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4752 dest, branches = hg.parseurl(dest, opts.get('branch'))
4752 dest, branches = hg.parseurl(dest, opts.get('branch'))
4753 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4753 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4754 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4754 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4755 other = hg.peer(repo, opts, dest)
4755 other = hg.peer(repo, opts, dest)
4756 if revs:
4756 if revs:
4757 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4757 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4758
4758
4759 repo._subtoppath = dest
4759 repo._subtoppath = dest
4760 try:
4760 try:
4761 # push subrepos depth-first for coherent ordering
4761 # push subrepos depth-first for coherent ordering
4762 c = repo['']
4762 c = repo['']
4763 subs = c.substate # only repos that are committed
4763 subs = c.substate # only repos that are committed
4764 for s in sorted(subs):
4764 for s in sorted(subs):
4765 if c.sub(s).push(opts) == 0:
4765 if c.sub(s).push(opts) == 0:
4766 return False
4766 return False
4767 finally:
4767 finally:
4768 del repo._subtoppath
4768 del repo._subtoppath
4769 result = repo.push(other, opts.get('force'), revs=revs,
4769 result = repo.push(other, opts.get('force'), revs=revs,
4770 newbranch=opts.get('new_branch'))
4770 newbranch=opts.get('new_branch'))
4771
4771
4772 result = not result
4772 result = not result
4773
4773
4774 if opts.get('bookmark'):
4774 if opts.get('bookmark'):
4775 rb = other.listkeys('bookmarks')
4775 rb = other.listkeys('bookmarks')
4776 for b in opts['bookmark']:
4776 for b in opts['bookmark']:
4777 # explicit push overrides remote bookmark if any
4777 # explicit push overrides remote bookmark if any
4778 if b in repo._bookmarks:
4778 if b in repo._bookmarks:
4779 ui.status(_("exporting bookmark %s\n") % b)
4779 ui.status(_("exporting bookmark %s\n") % b)
4780 new = repo[b].hex()
4780 new = repo[b].hex()
4781 elif b in rb:
4781 elif b in rb:
4782 ui.status(_("deleting remote bookmark %s\n") % b)
4782 ui.status(_("deleting remote bookmark %s\n") % b)
4783 new = '' # delete
4783 new = '' # delete
4784 else:
4784 else:
4785 ui.warn(_('bookmark %s does not exist on the local '
4785 ui.warn(_('bookmark %s does not exist on the local '
4786 'or remote repository!\n') % b)
4786 'or remote repository!\n') % b)
4787 return 2
4787 return 2
4788 old = rb.get(b, '')
4788 old = rb.get(b, '')
4789 r = other.pushkey('bookmarks', b, old, new)
4789 r = other.pushkey('bookmarks', b, old, new)
4790 if not r:
4790 if not r:
4791 ui.warn(_('updating bookmark %s failed!\n') % b)
4791 ui.warn(_('updating bookmark %s failed!\n') % b)
4792 if not result:
4792 if not result:
4793 result = 2
4793 result = 2
4794
4794
4795 return result
4795 return result
4796
4796
4797 @command('recover', [])
4797 @command('recover', [])
4798 def recover(ui, repo):
4798 def recover(ui, repo):
4799 """roll back an interrupted transaction
4799 """roll back an interrupted transaction
4800
4800
4801 Recover from an interrupted commit or pull.
4801 Recover from an interrupted commit or pull.
4802
4802
4803 This command tries to fix the repository status after an
4803 This command tries to fix the repository status after an
4804 interrupted operation. It should only be necessary when Mercurial
4804 interrupted operation. It should only be necessary when Mercurial
4805 suggests it.
4805 suggests it.
4806
4806
4807 Returns 0 if successful, 1 if nothing to recover or verify fails.
4807 Returns 0 if successful, 1 if nothing to recover or verify fails.
4808 """
4808 """
4809 if repo.recover():
4809 if repo.recover():
4810 return hg.verify(repo)
4810 return hg.verify(repo)
4811 return 1
4811 return 1
4812
4812
4813 @command('^remove|rm',
4813 @command('^remove|rm',
4814 [('A', 'after', None, _('record delete for missing files')),
4814 [('A', 'after', None, _('record delete for missing files')),
4815 ('f', 'force', None,
4815 ('f', 'force', None,
4816 _('remove (and delete) file even if added or modified')),
4816 _('remove (and delete) file even if added or modified')),
4817 ] + walkopts,
4817 ] + walkopts,
4818 _('[OPTION]... FILE...'))
4818 _('[OPTION]... FILE...'))
4819 def remove(ui, repo, *pats, **opts):
4819 def remove(ui, repo, *pats, **opts):
4820 """remove the specified files on the next commit
4820 """remove the specified files on the next commit
4821
4821
4822 Schedule the indicated files for removal from the current branch.
4822 Schedule the indicated files for removal from the current branch.
4823
4823
4824 This command schedules the files to be removed at the next commit.
4824 This command schedules the files to be removed at the next commit.
4825 To undo a remove before that, see :hg:`revert`. To undo added
4825 To undo a remove before that, see :hg:`revert`. To undo added
4826 files, see :hg:`forget`.
4826 files, see :hg:`forget`.
4827
4827
4828 .. container:: verbose
4828 .. container:: verbose
4829
4829
4830 -A/--after can be used to remove only files that have already
4830 -A/--after can be used to remove only files that have already
4831 been deleted, -f/--force can be used to force deletion, and -Af
4831 been deleted, -f/--force can be used to force deletion, and -Af
4832 can be used to remove files from the next revision without
4832 can be used to remove files from the next revision without
4833 deleting them from the working directory.
4833 deleting them from the working directory.
4834
4834
4835 The following table details the behavior of remove for different
4835 The following table details the behavior of remove for different
4836 file states (columns) and option combinations (rows). The file
4836 file states (columns) and option combinations (rows). The file
4837 states are Added [A], Clean [C], Modified [M] and Missing [!]
4837 states are Added [A], Clean [C], Modified [M] and Missing [!]
4838 (as reported by :hg:`status`). The actions are Warn, Remove
4838 (as reported by :hg:`status`). The actions are Warn, Remove
4839 (from branch) and Delete (from disk):
4839 (from branch) and Delete (from disk):
4840
4840
4841 ======= == == == ==
4841 ======= == == == ==
4842 A C M !
4842 A C M !
4843 ======= == == == ==
4843 ======= == == == ==
4844 none W RD W R
4844 none W RD W R
4845 -f R RD RD R
4845 -f R RD RD R
4846 -A W W W R
4846 -A W W W R
4847 -Af R R R R
4847 -Af R R R R
4848 ======= == == == ==
4848 ======= == == == ==
4849
4849
4850 Note that remove never deletes files in Added [A] state from the
4850 Note that remove never deletes files in Added [A] state from the
4851 working directory, not even if option --force is specified.
4851 working directory, not even if option --force is specified.
4852
4852
4853 Returns 0 on success, 1 if any warnings encountered.
4853 Returns 0 on success, 1 if any warnings encountered.
4854 """
4854 """
4855
4855
4856 ret = 0
4856 ret = 0
4857 after, force = opts.get('after'), opts.get('force')
4857 after, force = opts.get('after'), opts.get('force')
4858 if not pats and not after:
4858 if not pats and not after:
4859 raise util.Abort(_('no files specified'))
4859 raise util.Abort(_('no files specified'))
4860
4860
4861 m = scmutil.match(repo[None], pats, opts)
4861 m = scmutil.match(repo[None], pats, opts)
4862 s = repo.status(match=m, clean=True)
4862 s = repo.status(match=m, clean=True)
4863 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4863 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4864
4864
4865 # warn about failure to delete explicit files/dirs
4865 # warn about failure to delete explicit files/dirs
4866 wctx = repo[None]
4866 wctx = repo[None]
4867 for f in m.files():
4867 for f in m.files():
4868 if f in repo.dirstate or f in wctx.dirs():
4868 if f in repo.dirstate or f in wctx.dirs():
4869 continue
4869 continue
4870 if os.path.exists(m.rel(f)):
4870 if os.path.exists(m.rel(f)):
4871 if os.path.isdir(m.rel(f)):
4871 if os.path.isdir(m.rel(f)):
4872 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4872 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4873 else:
4873 else:
4874 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4874 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4875 # missing files will generate a warning elsewhere
4875 # missing files will generate a warning elsewhere
4876 ret = 1
4876 ret = 1
4877
4877
4878 if force:
4878 if force:
4879 list = modified + deleted + clean + added
4879 list = modified + deleted + clean + added
4880 elif after:
4880 elif after:
4881 list = deleted
4881 list = deleted
4882 for f in modified + added + clean:
4882 for f in modified + added + clean:
4883 ui.warn(_('not removing %s: file still exists (use -f'
4883 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4884 ' to force removal)\n') % m.rel(f))
4885 ret = 1
4884 ret = 1
4886 else:
4885 else:
4887 list = deleted + clean
4886 list = deleted + clean
4888 for f in modified:
4887 for f in modified:
4889 ui.warn(_('not removing %s: file is modified (use -f'
4888 ui.warn(_('not removing %s: file is modified (use -f'
4890 ' to force removal)\n') % m.rel(f))
4889 ' to force removal)\n') % m.rel(f))
4891 ret = 1
4890 ret = 1
4892 for f in added:
4891 for f in added:
4893 ui.warn(_('not removing %s: file has been marked for add'
4892 ui.warn(_('not removing %s: file has been marked for add'
4894 ' (use forget to undo)\n') % m.rel(f))
4893 ' (use forget to undo)\n') % m.rel(f))
4895 ret = 1
4894 ret = 1
4896
4895
4897 for f in sorted(list):
4896 for f in sorted(list):
4898 if ui.verbose or not m.exact(f):
4897 if ui.verbose or not m.exact(f):
4899 ui.status(_('removing %s\n') % m.rel(f))
4898 ui.status(_('removing %s\n') % m.rel(f))
4900
4899
4901 wlock = repo.wlock()
4900 wlock = repo.wlock()
4902 try:
4901 try:
4903 if not after:
4902 if not after:
4904 for f in list:
4903 for f in list:
4905 if f in added:
4904 if f in added:
4906 continue # we never unlink added files on remove
4905 continue # we never unlink added files on remove
4907 try:
4906 try:
4908 util.unlinkpath(repo.wjoin(f))
4907 util.unlinkpath(repo.wjoin(f))
4909 except OSError, inst:
4908 except OSError, inst:
4910 if inst.errno != errno.ENOENT:
4909 if inst.errno != errno.ENOENT:
4911 raise
4910 raise
4912 repo[None].forget(list)
4911 repo[None].forget(list)
4913 finally:
4912 finally:
4914 wlock.release()
4913 wlock.release()
4915
4914
4916 return ret
4915 return ret
4917
4916
4918 @command('rename|move|mv',
4917 @command('rename|move|mv',
4919 [('A', 'after', None, _('record a rename that has already occurred')),
4918 [('A', 'after', None, _('record a rename that has already occurred')),
4920 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4919 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4921 ] + walkopts + dryrunopts,
4920 ] + walkopts + dryrunopts,
4922 _('[OPTION]... SOURCE... DEST'))
4921 _('[OPTION]... SOURCE... DEST'))
4923 def rename(ui, repo, *pats, **opts):
4922 def rename(ui, repo, *pats, **opts):
4924 """rename files; equivalent of copy + remove
4923 """rename files; equivalent of copy + remove
4925
4924
4926 Mark dest as copies of sources; mark sources for deletion. If dest
4925 Mark dest as copies of sources; mark sources for deletion. If dest
4927 is a directory, copies are put in that directory. If dest is a
4926 is a directory, copies are put in that directory. If dest is a
4928 file, there can only be one source.
4927 file, there can only be one source.
4929
4928
4930 By default, this command copies the contents of files as they
4929 By default, this command copies the contents of files as they
4931 exist in the working directory. If invoked with -A/--after, the
4930 exist in the working directory. If invoked with -A/--after, the
4932 operation is recorded, but no copying is performed.
4931 operation is recorded, but no copying is performed.
4933
4932
4934 This command takes effect at the next commit. To undo a rename
4933 This command takes effect at the next commit. To undo a rename
4935 before that, see :hg:`revert`.
4934 before that, see :hg:`revert`.
4936
4935
4937 Returns 0 on success, 1 if errors are encountered.
4936 Returns 0 on success, 1 if errors are encountered.
4938 """
4937 """
4939 wlock = repo.wlock(False)
4938 wlock = repo.wlock(False)
4940 try:
4939 try:
4941 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4940 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4942 finally:
4941 finally:
4943 wlock.release()
4942 wlock.release()
4944
4943
4945 @command('resolve',
4944 @command('resolve',
4946 [('a', 'all', None, _('select all unresolved files')),
4945 [('a', 'all', None, _('select all unresolved files')),
4947 ('l', 'list', None, _('list state of files needing merge')),
4946 ('l', 'list', None, _('list state of files needing merge')),
4948 ('m', 'mark', None, _('mark files as resolved')),
4947 ('m', 'mark', None, _('mark files as resolved')),
4949 ('u', 'unmark', None, _('mark files as unresolved')),
4948 ('u', 'unmark', None, _('mark files as unresolved')),
4950 ('n', 'no-status', None, _('hide status prefix'))]
4949 ('n', 'no-status', None, _('hide status prefix'))]
4951 + mergetoolopts + walkopts,
4950 + mergetoolopts + walkopts,
4952 _('[OPTION]... [FILE]...'))
4951 _('[OPTION]... [FILE]...'))
4953 def resolve(ui, repo, *pats, **opts):
4952 def resolve(ui, repo, *pats, **opts):
4954 """redo merges or set/view the merge status of files
4953 """redo merges or set/view the merge status of files
4955
4954
4956 Merges with unresolved conflicts are often the result of
4955 Merges with unresolved conflicts are often the result of
4957 non-interactive merging using the ``internal:merge`` configuration
4956 non-interactive merging using the ``internal:merge`` configuration
4958 setting, or a command-line merge tool like ``diff3``. The resolve
4957 setting, or a command-line merge tool like ``diff3``. The resolve
4959 command is used to manage the files involved in a merge, after
4958 command is used to manage the files involved in a merge, after
4960 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4959 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4961 working directory must have two parents). See :hg:`help
4960 working directory must have two parents). See :hg:`help
4962 merge-tools` for information on configuring merge tools.
4961 merge-tools` for information on configuring merge tools.
4963
4962
4964 The resolve command can be used in the following ways:
4963 The resolve command can be used in the following ways:
4965
4964
4966 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4965 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4967 files, discarding any previous merge attempts. Re-merging is not
4966 files, discarding any previous merge attempts. Re-merging is not
4968 performed for files already marked as resolved. Use ``--all/-a``
4967 performed for files already marked as resolved. Use ``--all/-a``
4969 to select all unresolved files. ``--tool`` can be used to specify
4968 to select all unresolved files. ``--tool`` can be used to specify
4970 the merge tool used for the given files. It overrides the HGMERGE
4969 the merge tool used for the given files. It overrides the HGMERGE
4971 environment variable and your configuration files. Previous file
4970 environment variable and your configuration files. Previous file
4972 contents are saved with a ``.orig`` suffix.
4971 contents are saved with a ``.orig`` suffix.
4973
4972
4974 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4973 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4975 (e.g. after having manually fixed-up the files). The default is
4974 (e.g. after having manually fixed-up the files). The default is
4976 to mark all unresolved files.
4975 to mark all unresolved files.
4977
4976
4978 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4977 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4979 default is to mark all resolved files.
4978 default is to mark all resolved files.
4980
4979
4981 - :hg:`resolve -l`: list files which had or still have conflicts.
4980 - :hg:`resolve -l`: list files which had or still have conflicts.
4982 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4981 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4983
4982
4984 Note that Mercurial will not let you commit files with unresolved
4983 Note that Mercurial will not let you commit files with unresolved
4985 merge conflicts. You must use :hg:`resolve -m ...` before you can
4984 merge conflicts. You must use :hg:`resolve -m ...` before you can
4986 commit after a conflicting merge.
4985 commit after a conflicting merge.
4987
4986
4988 Returns 0 on success, 1 if any files fail a resolve attempt.
4987 Returns 0 on success, 1 if any files fail a resolve attempt.
4989 """
4988 """
4990
4989
4991 all, mark, unmark, show, nostatus = \
4990 all, mark, unmark, show, nostatus = \
4992 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4991 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4993
4992
4994 if (show and (mark or unmark)) or (mark and unmark):
4993 if (show and (mark or unmark)) or (mark and unmark):
4995 raise util.Abort(_("too many options specified"))
4994 raise util.Abort(_("too many options specified"))
4996 if pats and all:
4995 if pats and all:
4997 raise util.Abort(_("can't specify --all and patterns"))
4996 raise util.Abort(_("can't specify --all and patterns"))
4998 if not (all or pats or show or mark or unmark):
4997 if not (all or pats or show or mark or unmark):
4999 raise util.Abort(_('no files or directories specified; '
4998 raise util.Abort(_('no files or directories specified; '
5000 'use --all to remerge all files'))
4999 'use --all to remerge all files'))
5001
5000
5002 ms = mergemod.mergestate(repo)
5001 ms = mergemod.mergestate(repo)
5003 m = scmutil.match(repo[None], pats, opts)
5002 m = scmutil.match(repo[None], pats, opts)
5004 ret = 0
5003 ret = 0
5005
5004
5006 for f in ms:
5005 for f in ms:
5007 if m(f):
5006 if m(f):
5008 if show:
5007 if show:
5009 if nostatus:
5008 if nostatus:
5010 ui.write("%s\n" % f)
5009 ui.write("%s\n" % f)
5011 else:
5010 else:
5012 ui.write("%s %s\n" % (ms[f].upper(), f),
5011 ui.write("%s %s\n" % (ms[f].upper(), f),
5013 label='resolve.' +
5012 label='resolve.' +
5014 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5013 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
5015 elif mark:
5014 elif mark:
5016 ms.mark(f, "r")
5015 ms.mark(f, "r")
5017 elif unmark:
5016 elif unmark:
5018 ms.mark(f, "u")
5017 ms.mark(f, "u")
5019 else:
5018 else:
5020 wctx = repo[None]
5019 wctx = repo[None]
5021 mctx = wctx.parents()[-1]
5020 mctx = wctx.parents()[-1]
5022
5021
5023 # backup pre-resolve (merge uses .orig for its own purposes)
5022 # backup pre-resolve (merge uses .orig for its own purposes)
5024 a = repo.wjoin(f)
5023 a = repo.wjoin(f)
5025 util.copyfile(a, a + ".resolve")
5024 util.copyfile(a, a + ".resolve")
5026
5025
5027 try:
5026 try:
5028 # resolve file
5027 # resolve file
5029 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
5028 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
5030 if ms.resolve(f, wctx, mctx):
5029 if ms.resolve(f, wctx, mctx):
5031 ret = 1
5030 ret = 1
5032 finally:
5031 finally:
5033 ui.setconfig('ui', 'forcemerge', '')
5032 ui.setconfig('ui', 'forcemerge', '')
5034 ms.commit()
5033 ms.commit()
5035
5034
5036 # replace filemerge's .orig file with our resolve file
5035 # replace filemerge's .orig file with our resolve file
5037 util.rename(a + ".resolve", a + ".orig")
5036 util.rename(a + ".resolve", a + ".orig")
5038
5037
5039 ms.commit()
5038 ms.commit()
5040 return ret
5039 return ret
5041
5040
5042 @command('revert',
5041 @command('revert',
5043 [('a', 'all', None, _('revert all changes when no arguments given')),
5042 [('a', 'all', None, _('revert all changes when no arguments given')),
5044 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5043 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5045 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5044 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5046 ('C', 'no-backup', None, _('do not save backup copies of files')),
5045 ('C', 'no-backup', None, _('do not save backup copies of files')),
5047 ] + walkopts + dryrunopts,
5046 ] + walkopts + dryrunopts,
5048 _('[OPTION]... [-r REV] [NAME]...'))
5047 _('[OPTION]... [-r REV] [NAME]...'))
5049 def revert(ui, repo, *pats, **opts):
5048 def revert(ui, repo, *pats, **opts):
5050 """restore files to their checkout state
5049 """restore files to their checkout state
5051
5050
5052 .. note::
5051 .. note::
5053
5052
5054 To check out earlier revisions, you should use :hg:`update REV`.
5053 To check out earlier revisions, you should use :hg:`update REV`.
5055 To cancel an uncommitted merge (and lose your changes), use
5054 To cancel an uncommitted merge (and lose your changes), use
5056 :hg:`update --clean .`.
5055 :hg:`update --clean .`.
5057
5056
5058 With no revision specified, revert the specified files or directories
5057 With no revision specified, revert the specified files or directories
5059 to the contents they had in the parent of the working directory.
5058 to the contents they had in the parent of the working directory.
5060 This restores the contents of files to an unmodified
5059 This restores the contents of files to an unmodified
5061 state and unschedules adds, removes, copies, and renames. If the
5060 state and unschedules adds, removes, copies, and renames. If the
5062 working directory has two parents, you must explicitly specify a
5061 working directory has two parents, you must explicitly specify a
5063 revision.
5062 revision.
5064
5063
5065 Using the -r/--rev or -d/--date options, revert the given files or
5064 Using the -r/--rev or -d/--date options, revert the given files or
5066 directories to their states as of a specific revision. Because
5065 directories to their states as of a specific revision. Because
5067 revert does not change the working directory parents, this will
5066 revert does not change the working directory parents, this will
5068 cause these files to appear modified. This can be helpful to "back
5067 cause these files to appear modified. This can be helpful to "back
5069 out" some or all of an earlier change. See :hg:`backout` for a
5068 out" some or all of an earlier change. See :hg:`backout` for a
5070 related method.
5069 related method.
5071
5070
5072 Modified files are saved with a .orig suffix before reverting.
5071 Modified files are saved with a .orig suffix before reverting.
5073 To disable these backups, use --no-backup.
5072 To disable these backups, use --no-backup.
5074
5073
5075 See :hg:`help dates` for a list of formats valid for -d/--date.
5074 See :hg:`help dates` for a list of formats valid for -d/--date.
5076
5075
5077 Returns 0 on success.
5076 Returns 0 on success.
5078 """
5077 """
5079
5078
5080 if opts.get("date"):
5079 if opts.get("date"):
5081 if opts.get("rev"):
5080 if opts.get("rev"):
5082 raise util.Abort(_("you can't specify a revision and a date"))
5081 raise util.Abort(_("you can't specify a revision and a date"))
5083 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5082 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5084
5083
5085 parent, p2 = repo.dirstate.parents()
5084 parent, p2 = repo.dirstate.parents()
5086 if not opts.get('rev') and p2 != nullid:
5085 if not opts.get('rev') and p2 != nullid:
5087 # revert after merge is a trap for new users (issue2915)
5086 # revert after merge is a trap for new users (issue2915)
5088 raise util.Abort(_('uncommitted merge with no revision specified'),
5087 raise util.Abort(_('uncommitted merge with no revision specified'),
5089 hint=_('use "hg update" or see "hg help revert"'))
5088 hint=_('use "hg update" or see "hg help revert"'))
5090
5089
5091 ctx = scmutil.revsingle(repo, opts.get('rev'))
5090 ctx = scmutil.revsingle(repo, opts.get('rev'))
5092
5091
5093 if not pats and not opts.get('all'):
5092 if not pats and not opts.get('all'):
5094 msg = _("no files or directories specified")
5093 msg = _("no files or directories specified")
5095 if p2 != nullid:
5094 if p2 != nullid:
5096 hint = _("uncommitted merge, use --all to discard all changes,"
5095 hint = _("uncommitted merge, use --all to discard all changes,"
5097 " or 'hg update -C .' to abort the merge")
5096 " or 'hg update -C .' to abort the merge")
5098 raise util.Abort(msg, hint=hint)
5097 raise util.Abort(msg, hint=hint)
5099 dirty = util.any(repo.status())
5098 dirty = util.any(repo.status())
5100 node = ctx.node()
5099 node = ctx.node()
5101 if node != parent:
5100 if node != parent:
5102 if dirty:
5101 if dirty:
5103 hint = _("uncommitted changes, use --all to discard all"
5102 hint = _("uncommitted changes, use --all to discard all"
5104 " changes, or 'hg update %s' to update") % ctx.rev()
5103 " changes, or 'hg update %s' to update") % ctx.rev()
5105 else:
5104 else:
5106 hint = _("use --all to revert all files,"
5105 hint = _("use --all to revert all files,"
5107 " or 'hg update %s' to update") % ctx.rev()
5106 " or 'hg update %s' to update") % ctx.rev()
5108 elif dirty:
5107 elif dirty:
5109 hint = _("uncommitted changes, use --all to discard all changes")
5108 hint = _("uncommitted changes, use --all to discard all changes")
5110 else:
5109 else:
5111 hint = _("use --all to revert all files")
5110 hint = _("use --all to revert all files")
5112 raise util.Abort(msg, hint=hint)
5111 raise util.Abort(msg, hint=hint)
5113
5112
5114 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5113 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5115
5114
5116 @command('rollback', dryrunopts +
5115 @command('rollback', dryrunopts +
5117 [('f', 'force', False, _('ignore safety measures'))])
5116 [('f', 'force', False, _('ignore safety measures'))])
5118 def rollback(ui, repo, **opts):
5117 def rollback(ui, repo, **opts):
5119 """roll back the last transaction (dangerous)
5118 """roll back the last transaction (dangerous)
5120
5119
5121 This command should be used with care. There is only one level of
5120 This command should be used with care. There is only one level of
5122 rollback, and there is no way to undo a rollback. It will also
5121 rollback, and there is no way to undo a rollback. It will also
5123 restore the dirstate at the time of the last transaction, losing
5122 restore the dirstate at the time of the last transaction, losing
5124 any dirstate changes since that time. This command does not alter
5123 any dirstate changes since that time. This command does not alter
5125 the working directory.
5124 the working directory.
5126
5125
5127 Transactions are used to encapsulate the effects of all commands
5126 Transactions are used to encapsulate the effects of all commands
5128 that create new changesets or propagate existing changesets into a
5127 that create new changesets or propagate existing changesets into a
5129 repository.
5128 repository.
5130
5129
5131 .. container:: verbose
5130 .. container:: verbose
5132
5131
5133 For example, the following commands are transactional, and their
5132 For example, the following commands are transactional, and their
5134 effects can be rolled back:
5133 effects can be rolled back:
5135
5134
5136 - commit
5135 - commit
5137 - import
5136 - import
5138 - pull
5137 - pull
5139 - push (with this repository as the destination)
5138 - push (with this repository as the destination)
5140 - unbundle
5139 - unbundle
5141
5140
5142 To avoid permanent data loss, rollback will refuse to rollback a
5141 To avoid permanent data loss, rollback will refuse to rollback a
5143 commit transaction if it isn't checked out. Use --force to
5142 commit transaction if it isn't checked out. Use --force to
5144 override this protection.
5143 override this protection.
5145
5144
5146 This command is not intended for use on public repositories. Once
5145 This command is not intended for use on public repositories. Once
5147 changes are visible for pull by other users, rolling a transaction
5146 changes are visible for pull by other users, rolling a transaction
5148 back locally is ineffective (someone else may already have pulled
5147 back locally is ineffective (someone else may already have pulled
5149 the changes). Furthermore, a race is possible with readers of the
5148 the changes). Furthermore, a race is possible with readers of the
5150 repository; for example an in-progress pull from the repository
5149 repository; for example an in-progress pull from the repository
5151 may fail if a rollback is performed.
5150 may fail if a rollback is performed.
5152
5151
5153 Returns 0 on success, 1 if no rollback data is available.
5152 Returns 0 on success, 1 if no rollback data is available.
5154 """
5153 """
5155 return repo.rollback(dryrun=opts.get('dry_run'),
5154 return repo.rollback(dryrun=opts.get('dry_run'),
5156 force=opts.get('force'))
5155 force=opts.get('force'))
5157
5156
5158 @command('root', [])
5157 @command('root', [])
5159 def root(ui, repo):
5158 def root(ui, repo):
5160 """print the root (top) of the current working directory
5159 """print the root (top) of the current working directory
5161
5160
5162 Print the root directory of the current repository.
5161 Print the root directory of the current repository.
5163
5162
5164 Returns 0 on success.
5163 Returns 0 on success.
5165 """
5164 """
5166 ui.write(repo.root + "\n")
5165 ui.write(repo.root + "\n")
5167
5166
5168 @command('^serve',
5167 @command('^serve',
5169 [('A', 'accesslog', '', _('name of access log file to write to'),
5168 [('A', 'accesslog', '', _('name of access log file to write to'),
5170 _('FILE')),
5169 _('FILE')),
5171 ('d', 'daemon', None, _('run server in background')),
5170 ('d', 'daemon', None, _('run server in background')),
5172 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5171 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5173 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5172 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5174 # use string type, then we can check if something was passed
5173 # use string type, then we can check if something was passed
5175 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5174 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5176 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5175 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5177 _('ADDR')),
5176 _('ADDR')),
5178 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5177 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5179 _('PREFIX')),
5178 _('PREFIX')),
5180 ('n', 'name', '',
5179 ('n', 'name', '',
5181 _('name to show in web pages (default: working directory)'), _('NAME')),
5180 _('name to show in web pages (default: working directory)'), _('NAME')),
5182 ('', 'web-conf', '',
5181 ('', 'web-conf', '',
5183 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5182 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5184 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5183 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5185 _('FILE')),
5184 _('FILE')),
5186 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5185 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5187 ('', 'stdio', None, _('for remote clients')),
5186 ('', 'stdio', None, _('for remote clients')),
5188 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5187 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5189 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5188 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5190 ('', 'style', '', _('template style to use'), _('STYLE')),
5189 ('', 'style', '', _('template style to use'), _('STYLE')),
5191 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5190 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5192 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5191 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5193 _('[OPTION]...'))
5192 _('[OPTION]...'))
5194 def serve(ui, repo, **opts):
5193 def serve(ui, repo, **opts):
5195 """start stand-alone webserver
5194 """start stand-alone webserver
5196
5195
5197 Start a local HTTP repository browser and pull server. You can use
5196 Start a local HTTP repository browser and pull server. You can use
5198 this for ad-hoc sharing and browsing of repositories. It is
5197 this for ad-hoc sharing and browsing of repositories. It is
5199 recommended to use a real web server to serve a repository for
5198 recommended to use a real web server to serve a repository for
5200 longer periods of time.
5199 longer periods of time.
5201
5200
5202 Please note that the server does not implement access control.
5201 Please note that the server does not implement access control.
5203 This means that, by default, anybody can read from the server and
5202 This means that, by default, anybody can read from the server and
5204 nobody can write to it by default. Set the ``web.allow_push``
5203 nobody can write to it by default. Set the ``web.allow_push``
5205 option to ``*`` to allow everybody to push to the server. You
5204 option to ``*`` to allow everybody to push to the server. You
5206 should use a real web server if you need to authenticate users.
5205 should use a real web server if you need to authenticate users.
5207
5206
5208 By default, the server logs accesses to stdout and errors to
5207 By default, the server logs accesses to stdout and errors to
5209 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5208 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5210 files.
5209 files.
5211
5210
5212 To have the server choose a free port number to listen on, specify
5211 To have the server choose a free port number to listen on, specify
5213 a port number of 0; in this case, the server will print the port
5212 a port number of 0; in this case, the server will print the port
5214 number it uses.
5213 number it uses.
5215
5214
5216 Returns 0 on success.
5215 Returns 0 on success.
5217 """
5216 """
5218
5217
5219 if opts["stdio"] and opts["cmdserver"]:
5218 if opts["stdio"] and opts["cmdserver"]:
5220 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5219 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5221
5220
5222 def checkrepo():
5221 def checkrepo():
5223 if repo is None:
5222 if repo is None:
5224 raise error.RepoError(_("there is no Mercurial repository here"
5223 raise error.RepoError(_("there is no Mercurial repository here"
5225 " (.hg not found)"))
5224 " (.hg not found)"))
5226
5225
5227 if opts["stdio"]:
5226 if opts["stdio"]:
5228 checkrepo()
5227 checkrepo()
5229 s = sshserver.sshserver(ui, repo)
5228 s = sshserver.sshserver(ui, repo)
5230 s.serve_forever()
5229 s.serve_forever()
5231
5230
5232 if opts["cmdserver"]:
5231 if opts["cmdserver"]:
5233 checkrepo()
5232 checkrepo()
5234 s = commandserver.server(ui, repo, opts["cmdserver"])
5233 s = commandserver.server(ui, repo, opts["cmdserver"])
5235 return s.serve()
5234 return s.serve()
5236
5235
5237 # this way we can check if something was given in the command-line
5236 # this way we can check if something was given in the command-line
5238 if opts.get('port'):
5237 if opts.get('port'):
5239 opts['port'] = util.getport(opts.get('port'))
5238 opts['port'] = util.getport(opts.get('port'))
5240
5239
5241 baseui = repo and repo.baseui or ui
5240 baseui = repo and repo.baseui or ui
5242 optlist = ("name templates style address port prefix ipv6"
5241 optlist = ("name templates style address port prefix ipv6"
5243 " accesslog errorlog certificate encoding")
5242 " accesslog errorlog certificate encoding")
5244 for o in optlist.split():
5243 for o in optlist.split():
5245 val = opts.get(o, '')
5244 val = opts.get(o, '')
5246 if val in (None, ''): # should check against default options instead
5245 if val in (None, ''): # should check against default options instead
5247 continue
5246 continue
5248 baseui.setconfig("web", o, val)
5247 baseui.setconfig("web", o, val)
5249 if repo and repo.ui != baseui:
5248 if repo and repo.ui != baseui:
5250 repo.ui.setconfig("web", o, val)
5249 repo.ui.setconfig("web", o, val)
5251
5250
5252 o = opts.get('web_conf') or opts.get('webdir_conf')
5251 o = opts.get('web_conf') or opts.get('webdir_conf')
5253 if not o:
5252 if not o:
5254 if not repo:
5253 if not repo:
5255 raise error.RepoError(_("there is no Mercurial repository"
5254 raise error.RepoError(_("there is no Mercurial repository"
5256 " here (.hg not found)"))
5255 " here (.hg not found)"))
5257 o = repo.root
5256 o = repo.root
5258
5257
5259 app = hgweb.hgweb(o, baseui=ui)
5258 app = hgweb.hgweb(o, baseui=ui)
5260
5259
5261 class service(object):
5260 class service(object):
5262 def init(self):
5261 def init(self):
5263 util.setsignalhandler()
5262 util.setsignalhandler()
5264 self.httpd = hgweb.server.create_server(ui, app)
5263 self.httpd = hgweb.server.create_server(ui, app)
5265
5264
5266 if opts['port'] and not ui.verbose:
5265 if opts['port'] and not ui.verbose:
5267 return
5266 return
5268
5267
5269 if self.httpd.prefix:
5268 if self.httpd.prefix:
5270 prefix = self.httpd.prefix.strip('/') + '/'
5269 prefix = self.httpd.prefix.strip('/') + '/'
5271 else:
5270 else:
5272 prefix = ''
5271 prefix = ''
5273
5272
5274 port = ':%d' % self.httpd.port
5273 port = ':%d' % self.httpd.port
5275 if port == ':80':
5274 if port == ':80':
5276 port = ''
5275 port = ''
5277
5276
5278 bindaddr = self.httpd.addr
5277 bindaddr = self.httpd.addr
5279 if bindaddr == '0.0.0.0':
5278 if bindaddr == '0.0.0.0':
5280 bindaddr = '*'
5279 bindaddr = '*'
5281 elif ':' in bindaddr: # IPv6
5280 elif ':' in bindaddr: # IPv6
5282 bindaddr = '[%s]' % bindaddr
5281 bindaddr = '[%s]' % bindaddr
5283
5282
5284 fqaddr = self.httpd.fqaddr
5283 fqaddr = self.httpd.fqaddr
5285 if ':' in fqaddr:
5284 if ':' in fqaddr:
5286 fqaddr = '[%s]' % fqaddr
5285 fqaddr = '[%s]' % fqaddr
5287 if opts['port']:
5286 if opts['port']:
5288 write = ui.status
5287 write = ui.status
5289 else:
5288 else:
5290 write = ui.write
5289 write = ui.write
5291 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5290 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5292 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5291 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5293
5292
5294 def run(self):
5293 def run(self):
5295 self.httpd.serve_forever()
5294 self.httpd.serve_forever()
5296
5295
5297 service = service()
5296 service = service()
5298
5297
5299 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5298 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5300
5299
5301 @command('showconfig|debugconfig',
5300 @command('showconfig|debugconfig',
5302 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5301 [('u', 'untrusted', None, _('show untrusted configuration options'))],
5303 _('[-u] [NAME]...'))
5302 _('[-u] [NAME]...'))
5304 def showconfig(ui, repo, *values, **opts):
5303 def showconfig(ui, repo, *values, **opts):
5305 """show combined config settings from all hgrc files
5304 """show combined config settings from all hgrc files
5306
5305
5307 With no arguments, print names and values of all config items.
5306 With no arguments, print names and values of all config items.
5308
5307
5309 With one argument of the form section.name, print just the value
5308 With one argument of the form section.name, print just the value
5310 of that config item.
5309 of that config item.
5311
5310
5312 With multiple arguments, print names and values of all config
5311 With multiple arguments, print names and values of all config
5313 items with matching section names.
5312 items with matching section names.
5314
5313
5315 With --debug, the source (filename and line number) is printed
5314 With --debug, the source (filename and line number) is printed
5316 for each config item.
5315 for each config item.
5317
5316
5318 Returns 0 on success.
5317 Returns 0 on success.
5319 """
5318 """
5320
5319
5321 for f in scmutil.rcpath():
5320 for f in scmutil.rcpath():
5322 ui.debug('read config from: %s\n' % f)
5321 ui.debug('read config from: %s\n' % f)
5323 untrusted = bool(opts.get('untrusted'))
5322 untrusted = bool(opts.get('untrusted'))
5324 if values:
5323 if values:
5325 sections = [v for v in values if '.' not in v]
5324 sections = [v for v in values if '.' not in v]
5326 items = [v for v in values if '.' in v]
5325 items = [v for v in values if '.' in v]
5327 if len(items) > 1 or items and sections:
5326 if len(items) > 1 or items and sections:
5328 raise util.Abort(_('only one config item permitted'))
5327 raise util.Abort(_('only one config item permitted'))
5329 for section, name, value in ui.walkconfig(untrusted=untrusted):
5328 for section, name, value in ui.walkconfig(untrusted=untrusted):
5330 value = str(value).replace('\n', '\\n')
5329 value = str(value).replace('\n', '\\n')
5331 sectname = section + '.' + name
5330 sectname = section + '.' + name
5332 if values:
5331 if values:
5333 for v in values:
5332 for v in values:
5334 if v == section:
5333 if v == section:
5335 ui.debug('%s: ' %
5334 ui.debug('%s: ' %
5336 ui.configsource(section, name, untrusted))
5335 ui.configsource(section, name, untrusted))
5337 ui.write('%s=%s\n' % (sectname, value))
5336 ui.write('%s=%s\n' % (sectname, value))
5338 elif v == sectname:
5337 elif v == sectname:
5339 ui.debug('%s: ' %
5338 ui.debug('%s: ' %
5340 ui.configsource(section, name, untrusted))
5339 ui.configsource(section, name, untrusted))
5341 ui.write(value, '\n')
5340 ui.write(value, '\n')
5342 else:
5341 else:
5343 ui.debug('%s: ' %
5342 ui.debug('%s: ' %
5344 ui.configsource(section, name, untrusted))
5343 ui.configsource(section, name, untrusted))
5345 ui.write('%s=%s\n' % (sectname, value))
5344 ui.write('%s=%s\n' % (sectname, value))
5346
5345
5347 @command('^status|st',
5346 @command('^status|st',
5348 [('A', 'all', None, _('show status of all files')),
5347 [('A', 'all', None, _('show status of all files')),
5349 ('m', 'modified', None, _('show only modified files')),
5348 ('m', 'modified', None, _('show only modified files')),
5350 ('a', 'added', None, _('show only added files')),
5349 ('a', 'added', None, _('show only added files')),
5351 ('r', 'removed', None, _('show only removed files')),
5350 ('r', 'removed', None, _('show only removed files')),
5352 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5351 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5353 ('c', 'clean', None, _('show only files without changes')),
5352 ('c', 'clean', None, _('show only files without changes')),
5354 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5353 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5355 ('i', 'ignored', None, _('show only ignored files')),
5354 ('i', 'ignored', None, _('show only ignored files')),
5356 ('n', 'no-status', None, _('hide status prefix')),
5355 ('n', 'no-status', None, _('hide status prefix')),
5357 ('C', 'copies', None, _('show source of copied files')),
5356 ('C', 'copies', None, _('show source of copied files')),
5358 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5357 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5359 ('', 'rev', [], _('show difference from revision'), _('REV')),
5358 ('', 'rev', [], _('show difference from revision'), _('REV')),
5360 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5359 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5361 ] + walkopts + subrepoopts,
5360 ] + walkopts + subrepoopts,
5362 _('[OPTION]... [FILE]...'))
5361 _('[OPTION]... [FILE]...'))
5363 def status(ui, repo, *pats, **opts):
5362 def status(ui, repo, *pats, **opts):
5364 """show changed files in the working directory
5363 """show changed files in the working directory
5365
5364
5366 Show status of files in the repository. If names are given, only
5365 Show status of files in the repository. If names are given, only
5367 files that match are shown. Files that are clean or ignored or
5366 files that match are shown. Files that are clean or ignored or
5368 the source of a copy/move operation, are not listed unless
5367 the source of a copy/move operation, are not listed unless
5369 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5368 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5370 Unless options described with "show only ..." are given, the
5369 Unless options described with "show only ..." are given, the
5371 options -mardu are used.
5370 options -mardu are used.
5372
5371
5373 Option -q/--quiet hides untracked (unknown and ignored) files
5372 Option -q/--quiet hides untracked (unknown and ignored) files
5374 unless explicitly requested with -u/--unknown or -i/--ignored.
5373 unless explicitly requested with -u/--unknown or -i/--ignored.
5375
5374
5376 .. note::
5375 .. note::
5377 status may appear to disagree with diff if permissions have
5376 status may appear to disagree with diff if permissions have
5378 changed or a merge has occurred. The standard diff format does
5377 changed or a merge has occurred. The standard diff format does
5379 not report permission changes and diff only reports changes
5378 not report permission changes and diff only reports changes
5380 relative to one merge parent.
5379 relative to one merge parent.
5381
5380
5382 If one revision is given, it is used as the base revision.
5381 If one revision is given, it is used as the base revision.
5383 If two revisions are given, the differences between them are
5382 If two revisions are given, the differences between them are
5384 shown. The --change option can also be used as a shortcut to list
5383 shown. The --change option can also be used as a shortcut to list
5385 the changed files of a revision from its first parent.
5384 the changed files of a revision from its first parent.
5386
5385
5387 The codes used to show the status of files are::
5386 The codes used to show the status of files are::
5388
5387
5389 M = modified
5388 M = modified
5390 A = added
5389 A = added
5391 R = removed
5390 R = removed
5392 C = clean
5391 C = clean
5393 ! = missing (deleted by non-hg command, but still tracked)
5392 ! = missing (deleted by non-hg command, but still tracked)
5394 ? = not tracked
5393 ? = not tracked
5395 I = ignored
5394 I = ignored
5396 = origin of the previous file listed as A (added)
5395 = origin of the previous file listed as A (added)
5397
5396
5398 .. container:: verbose
5397 .. container:: verbose
5399
5398
5400 Examples:
5399 Examples:
5401
5400
5402 - show changes in the working directory relative to a
5401 - show changes in the working directory relative to a
5403 changeset::
5402 changeset::
5404
5403
5405 hg status --rev 9353
5404 hg status --rev 9353
5406
5405
5407 - show all changes including copies in an existing changeset::
5406 - show all changes including copies in an existing changeset::
5408
5407
5409 hg status --copies --change 9353
5408 hg status --copies --change 9353
5410
5409
5411 - get a NUL separated list of added files, suitable for xargs::
5410 - get a NUL separated list of added files, suitable for xargs::
5412
5411
5413 hg status -an0
5412 hg status -an0
5414
5413
5415 Returns 0 on success.
5414 Returns 0 on success.
5416 """
5415 """
5417
5416
5418 revs = opts.get('rev')
5417 revs = opts.get('rev')
5419 change = opts.get('change')
5418 change = opts.get('change')
5420
5419
5421 if revs and change:
5420 if revs and change:
5422 msg = _('cannot specify --rev and --change at the same time')
5421 msg = _('cannot specify --rev and --change at the same time')
5423 raise util.Abort(msg)
5422 raise util.Abort(msg)
5424 elif change:
5423 elif change:
5425 node2 = scmutil.revsingle(repo, change, None).node()
5424 node2 = scmutil.revsingle(repo, change, None).node()
5426 node1 = repo[node2].p1().node()
5425 node1 = repo[node2].p1().node()
5427 else:
5426 else:
5428 node1, node2 = scmutil.revpair(repo, revs)
5427 node1, node2 = scmutil.revpair(repo, revs)
5429
5428
5430 cwd = (pats and repo.getcwd()) or ''
5429 cwd = (pats and repo.getcwd()) or ''
5431 end = opts.get('print0') and '\0' or '\n'
5430 end = opts.get('print0') and '\0' or '\n'
5432 copy = {}
5431 copy = {}
5433 states = 'modified added removed deleted unknown ignored clean'.split()
5432 states = 'modified added removed deleted unknown ignored clean'.split()
5434 show = [k for k in states if opts.get(k)]
5433 show = [k for k in states if opts.get(k)]
5435 if opts.get('all'):
5434 if opts.get('all'):
5436 show += ui.quiet and (states[:4] + ['clean']) or states
5435 show += ui.quiet and (states[:4] + ['clean']) or states
5437 if not show:
5436 if not show:
5438 show = ui.quiet and states[:4] or states[:5]
5437 show = ui.quiet and states[:4] or states[:5]
5439
5438
5440 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5439 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5441 'ignored' in show, 'clean' in show, 'unknown' in show,
5440 'ignored' in show, 'clean' in show, 'unknown' in show,
5442 opts.get('subrepos'))
5441 opts.get('subrepos'))
5443 changestates = zip(states, 'MAR!?IC', stat)
5442 changestates = zip(states, 'MAR!?IC', stat)
5444
5443
5445 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5444 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5446 copy = copies.pathcopies(repo[node1], repo[node2])
5445 copy = copies.pathcopies(repo[node1], repo[node2])
5447
5446
5448 fm = ui.formatter('status', opts)
5447 fm = ui.formatter('status', opts)
5449 fmt = '%s' + end
5448 fmt = '%s' + end
5450 showchar = not opts.get('no_status')
5449 showchar = not opts.get('no_status')
5451
5450
5452 for state, char, files in changestates:
5451 for state, char, files in changestates:
5453 if state in show:
5452 if state in show:
5454 label = 'status.' + state
5453 label = 'status.' + state
5455 for f in files:
5454 for f in files:
5456 fm.startitem()
5455 fm.startitem()
5457 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5456 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5458 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5457 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5459 if f in copy:
5458 if f in copy:
5460 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5459 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5461 label='status.copied')
5460 label='status.copied')
5462 fm.end()
5461 fm.end()
5463
5462
5464 @command('^summary|sum',
5463 @command('^summary|sum',
5465 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5464 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5466 def summary(ui, repo, **opts):
5465 def summary(ui, repo, **opts):
5467 """summarize working directory state
5466 """summarize working directory state
5468
5467
5469 This generates a brief summary of the working directory state,
5468 This generates a brief summary of the working directory state,
5470 including parents, branch, commit status, and available updates.
5469 including parents, branch, commit status, and available updates.
5471
5470
5472 With the --remote option, this will check the default paths for
5471 With the --remote option, this will check the default paths for
5473 incoming and outgoing changes. This can be time-consuming.
5472 incoming and outgoing changes. This can be time-consuming.
5474
5473
5475 Returns 0 on success.
5474 Returns 0 on success.
5476 """
5475 """
5477
5476
5478 ctx = repo[None]
5477 ctx = repo[None]
5479 parents = ctx.parents()
5478 parents = ctx.parents()
5480 pnode = parents[0].node()
5479 pnode = parents[0].node()
5481 marks = []
5480 marks = []
5482
5481
5483 for p in parents:
5482 for p in parents:
5484 # label with log.changeset (instead of log.parent) since this
5483 # label with log.changeset (instead of log.parent) since this
5485 # shows a working directory parent *changeset*:
5484 # shows a working directory parent *changeset*:
5486 # i18n: column positioning for "hg summary"
5485 # i18n: column positioning for "hg summary"
5487 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5486 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5488 label='log.changeset changeset.%s' % p.phasestr())
5487 label='log.changeset changeset.%s' % p.phasestr())
5489 ui.write(' '.join(p.tags()), label='log.tag')
5488 ui.write(' '.join(p.tags()), label='log.tag')
5490 if p.bookmarks():
5489 if p.bookmarks():
5491 marks.extend(p.bookmarks())
5490 marks.extend(p.bookmarks())
5492 if p.rev() == -1:
5491 if p.rev() == -1:
5493 if not len(repo):
5492 if not len(repo):
5494 ui.write(_(' (empty repository)'))
5493 ui.write(_(' (empty repository)'))
5495 else:
5494 else:
5496 ui.write(_(' (no revision checked out)'))
5495 ui.write(_(' (no revision checked out)'))
5497 ui.write('\n')
5496 ui.write('\n')
5498 if p.description():
5497 if p.description():
5499 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5498 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5500 label='log.summary')
5499 label='log.summary')
5501
5500
5502 branch = ctx.branch()
5501 branch = ctx.branch()
5503 bheads = repo.branchheads(branch)
5502 bheads = repo.branchheads(branch)
5504 # i18n: column positioning for "hg summary"
5503 # i18n: column positioning for "hg summary"
5505 m = _('branch: %s\n') % branch
5504 m = _('branch: %s\n') % branch
5506 if branch != 'default':
5505 if branch != 'default':
5507 ui.write(m, label='log.branch')
5506 ui.write(m, label='log.branch')
5508 else:
5507 else:
5509 ui.status(m, label='log.branch')
5508 ui.status(m, label='log.branch')
5510
5509
5511 if marks:
5510 if marks:
5512 current = repo._bookmarkcurrent
5511 current = repo._bookmarkcurrent
5513 # i18n: column positioning for "hg summary"
5512 # i18n: column positioning for "hg summary"
5514 ui.write(_('bookmarks:'), label='log.bookmark')
5513 ui.write(_('bookmarks:'), label='log.bookmark')
5515 if current is not None:
5514 if current is not None:
5516 try:
5515 try:
5517 marks.remove(current)
5516 marks.remove(current)
5518 ui.write(' *' + current, label='bookmarks.current')
5517 ui.write(' *' + current, label='bookmarks.current')
5519 except ValueError:
5518 except ValueError:
5520 # current bookmark not in parent ctx marks
5519 # current bookmark not in parent ctx marks
5521 pass
5520 pass
5522 for m in marks:
5521 for m in marks:
5523 ui.write(' ' + m, label='log.bookmark')
5522 ui.write(' ' + m, label='log.bookmark')
5524 ui.write('\n', label='log.bookmark')
5523 ui.write('\n', label='log.bookmark')
5525
5524
5526 st = list(repo.status(unknown=True))[:6]
5525 st = list(repo.status(unknown=True))[:6]
5527
5526
5528 c = repo.dirstate.copies()
5527 c = repo.dirstate.copies()
5529 copied, renamed = [], []
5528 copied, renamed = [], []
5530 for d, s in c.iteritems():
5529 for d, s in c.iteritems():
5531 if s in st[2]:
5530 if s in st[2]:
5532 st[2].remove(s)
5531 st[2].remove(s)
5533 renamed.append(d)
5532 renamed.append(d)
5534 else:
5533 else:
5535 copied.append(d)
5534 copied.append(d)
5536 if d in st[1]:
5535 if d in st[1]:
5537 st[1].remove(d)
5536 st[1].remove(d)
5538 st.insert(3, renamed)
5537 st.insert(3, renamed)
5539 st.insert(4, copied)
5538 st.insert(4, copied)
5540
5539
5541 ms = mergemod.mergestate(repo)
5540 ms = mergemod.mergestate(repo)
5542 st.append([f for f in ms if ms[f] == 'u'])
5541 st.append([f for f in ms if ms[f] == 'u'])
5543
5542
5544 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5543 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5545 st.append(subs)
5544 st.append(subs)
5546
5545
5547 labels = [ui.label(_('%d modified'), 'status.modified'),
5546 labels = [ui.label(_('%d modified'), 'status.modified'),
5548 ui.label(_('%d added'), 'status.added'),
5547 ui.label(_('%d added'), 'status.added'),
5549 ui.label(_('%d removed'), 'status.removed'),
5548 ui.label(_('%d removed'), 'status.removed'),
5550 ui.label(_('%d renamed'), 'status.copied'),
5549 ui.label(_('%d renamed'), 'status.copied'),
5551 ui.label(_('%d copied'), 'status.copied'),
5550 ui.label(_('%d copied'), 'status.copied'),
5552 ui.label(_('%d deleted'), 'status.deleted'),
5551 ui.label(_('%d deleted'), 'status.deleted'),
5553 ui.label(_('%d unknown'), 'status.unknown'),
5552 ui.label(_('%d unknown'), 'status.unknown'),
5554 ui.label(_('%d ignored'), 'status.ignored'),
5553 ui.label(_('%d ignored'), 'status.ignored'),
5555 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5554 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5556 ui.label(_('%d subrepos'), 'status.modified')]
5555 ui.label(_('%d subrepos'), 'status.modified')]
5557 t = []
5556 t = []
5558 for s, l in zip(st, labels):
5557 for s, l in zip(st, labels):
5559 if s:
5558 if s:
5560 t.append(l % len(s))
5559 t.append(l % len(s))
5561
5560
5562 t = ', '.join(t)
5561 t = ', '.join(t)
5563 cleanworkdir = False
5562 cleanworkdir = False
5564
5563
5565 if len(parents) > 1:
5564 if len(parents) > 1:
5566 t += _(' (merge)')
5565 t += _(' (merge)')
5567 elif branch != parents[0].branch():
5566 elif branch != parents[0].branch():
5568 t += _(' (new branch)')
5567 t += _(' (new branch)')
5569 elif (parents[0].closesbranch() and
5568 elif (parents[0].closesbranch() and
5570 pnode in repo.branchheads(branch, closed=True)):
5569 pnode in repo.branchheads(branch, closed=True)):
5571 t += _(' (head closed)')
5570 t += _(' (head closed)')
5572 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5571 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5573 t += _(' (clean)')
5572 t += _(' (clean)')
5574 cleanworkdir = True
5573 cleanworkdir = True
5575 elif pnode not in bheads:
5574 elif pnode not in bheads:
5576 t += _(' (new branch head)')
5575 t += _(' (new branch head)')
5577
5576
5578 if cleanworkdir:
5577 if cleanworkdir:
5579 # i18n: column positioning for "hg summary"
5578 # i18n: column positioning for "hg summary"
5580 ui.status(_('commit: %s\n') % t.strip())
5579 ui.status(_('commit: %s\n') % t.strip())
5581 else:
5580 else:
5582 # i18n: column positioning for "hg summary"
5581 # i18n: column positioning for "hg summary"
5583 ui.write(_('commit: %s\n') % t.strip())
5582 ui.write(_('commit: %s\n') % t.strip())
5584
5583
5585 # all ancestors of branch heads - all ancestors of parent = new csets
5584 # all ancestors of branch heads - all ancestors of parent = new csets
5586 new = [0] * len(repo)
5585 new = [0] * len(repo)
5587 cl = repo.changelog
5586 cl = repo.changelog
5588 for a in [cl.rev(n) for n in bheads]:
5587 for a in [cl.rev(n) for n in bheads]:
5589 new[a] = 1
5588 new[a] = 1
5590 for a in cl.ancestors([cl.rev(n) for n in bheads]):
5589 for a in cl.ancestors([cl.rev(n) for n in bheads]):
5591 new[a] = 1
5590 new[a] = 1
5592 for a in [p.rev() for p in parents]:
5591 for a in [p.rev() for p in parents]:
5593 if a >= 0:
5592 if a >= 0:
5594 new[a] = 0
5593 new[a] = 0
5595 for a in cl.ancestors([p.rev() for p in parents]):
5594 for a in cl.ancestors([p.rev() for p in parents]):
5596 new[a] = 0
5595 new[a] = 0
5597 new = sum(new)
5596 new = sum(new)
5598
5597
5599 if new == 0:
5598 if new == 0:
5600 # i18n: column positioning for "hg summary"
5599 # i18n: column positioning for "hg summary"
5601 ui.status(_('update: (current)\n'))
5600 ui.status(_('update: (current)\n'))
5602 elif pnode not in bheads:
5601 elif pnode not in bheads:
5603 # i18n: column positioning for "hg summary"
5602 # i18n: column positioning for "hg summary"
5604 ui.write(_('update: %d new changesets (update)\n') % new)
5603 ui.write(_('update: %d new changesets (update)\n') % new)
5605 else:
5604 else:
5606 # i18n: column positioning for "hg summary"
5605 # i18n: column positioning for "hg summary"
5607 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5606 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5608 (new, len(bheads)))
5607 (new, len(bheads)))
5609
5608
5610 if opts.get('remote'):
5609 if opts.get('remote'):
5611 t = []
5610 t = []
5612 source, branches = hg.parseurl(ui.expandpath('default'))
5611 source, branches = hg.parseurl(ui.expandpath('default'))
5613 other = hg.peer(repo, {}, source)
5612 other = hg.peer(repo, {}, source)
5614 revs, checkout = hg.addbranchrevs(repo, other, branches,
5613 revs, checkout = hg.addbranchrevs(repo, other, branches,
5615 opts.get('rev'))
5614 opts.get('rev'))
5616 ui.debug('comparing with %s\n' % util.hidepassword(source))
5615 ui.debug('comparing with %s\n' % util.hidepassword(source))
5617 repo.ui.pushbuffer()
5616 repo.ui.pushbuffer()
5618 commoninc = discovery.findcommonincoming(repo, other)
5617 commoninc = discovery.findcommonincoming(repo, other)
5619 _common, incoming, _rheads = commoninc
5618 _common, incoming, _rheads = commoninc
5620 repo.ui.popbuffer()
5619 repo.ui.popbuffer()
5621 if incoming:
5620 if incoming:
5622 t.append(_('1 or more incoming'))
5621 t.append(_('1 or more incoming'))
5623
5622
5624 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5623 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5625 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5624 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5626 if source != dest:
5625 if source != dest:
5627 other = hg.peer(repo, {}, dest)
5626 other = hg.peer(repo, {}, dest)
5628 commoninc = None
5627 commoninc = None
5629 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5628 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5630 repo.ui.pushbuffer()
5629 repo.ui.pushbuffer()
5631 outgoing = discovery.findcommonoutgoing(repo, other,
5630 outgoing = discovery.findcommonoutgoing(repo, other,
5632 commoninc=commoninc)
5631 commoninc=commoninc)
5633 repo.ui.popbuffer()
5632 repo.ui.popbuffer()
5634 o = outgoing.missing
5633 o = outgoing.missing
5635 if o:
5634 if o:
5636 t.append(_('%d outgoing') % len(o))
5635 t.append(_('%d outgoing') % len(o))
5637 if 'bookmarks' in other.listkeys('namespaces'):
5636 if 'bookmarks' in other.listkeys('namespaces'):
5638 lmarks = repo.listkeys('bookmarks')
5637 lmarks = repo.listkeys('bookmarks')
5639 rmarks = other.listkeys('bookmarks')
5638 rmarks = other.listkeys('bookmarks')
5640 diff = set(rmarks) - set(lmarks)
5639 diff = set(rmarks) - set(lmarks)
5641 if len(diff) > 0:
5640 if len(diff) > 0:
5642 t.append(_('%d incoming bookmarks') % len(diff))
5641 t.append(_('%d incoming bookmarks') % len(diff))
5643 diff = set(lmarks) - set(rmarks)
5642 diff = set(lmarks) - set(rmarks)
5644 if len(diff) > 0:
5643 if len(diff) > 0:
5645 t.append(_('%d outgoing bookmarks') % len(diff))
5644 t.append(_('%d outgoing bookmarks') % len(diff))
5646
5645
5647 if t:
5646 if t:
5648 # i18n: column positioning for "hg summary"
5647 # i18n: column positioning for "hg summary"
5649 ui.write(_('remote: %s\n') % (', '.join(t)))
5648 ui.write(_('remote: %s\n') % (', '.join(t)))
5650 else:
5649 else:
5651 # i18n: column positioning for "hg summary"
5650 # i18n: column positioning for "hg summary"
5652 ui.status(_('remote: (synced)\n'))
5651 ui.status(_('remote: (synced)\n'))
5653
5652
5654 @command('tag',
5653 @command('tag',
5655 [('f', 'force', None, _('force tag')),
5654 [('f', 'force', None, _('force tag')),
5656 ('l', 'local', None, _('make the tag local')),
5655 ('l', 'local', None, _('make the tag local')),
5657 ('r', 'rev', '', _('revision to tag'), _('REV')),
5656 ('r', 'rev', '', _('revision to tag'), _('REV')),
5658 ('', 'remove', None, _('remove a tag')),
5657 ('', 'remove', None, _('remove a tag')),
5659 # -l/--local is already there, commitopts cannot be used
5658 # -l/--local is already there, commitopts cannot be used
5660 ('e', 'edit', None, _('edit commit message')),
5659 ('e', 'edit', None, _('edit commit message')),
5661 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5660 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5662 ] + commitopts2,
5661 ] + commitopts2,
5663 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5662 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5664 def tag(ui, repo, name1, *names, **opts):
5663 def tag(ui, repo, name1, *names, **opts):
5665 """add one or more tags for the current or given revision
5664 """add one or more tags for the current or given revision
5666
5665
5667 Name a particular revision using <name>.
5666 Name a particular revision using <name>.
5668
5667
5669 Tags are used to name particular revisions of the repository and are
5668 Tags are used to name particular revisions of the repository and are
5670 very useful to compare different revisions, to go back to significant
5669 very useful to compare different revisions, to go back to significant
5671 earlier versions or to mark branch points as releases, etc. Changing
5670 earlier versions or to mark branch points as releases, etc. Changing
5672 an existing tag is normally disallowed; use -f/--force to override.
5671 an existing tag is normally disallowed; use -f/--force to override.
5673
5672
5674 If no revision is given, the parent of the working directory is
5673 If no revision is given, the parent of the working directory is
5675 used, or tip if no revision is checked out.
5674 used, or tip if no revision is checked out.
5676
5675
5677 To facilitate version control, distribution, and merging of tags,
5676 To facilitate version control, distribution, and merging of tags,
5678 they are stored as a file named ".hgtags" which is managed similarly
5677 they are stored as a file named ".hgtags" which is managed similarly
5679 to other project files and can be hand-edited if necessary. This
5678 to other project files and can be hand-edited if necessary. This
5680 also means that tagging creates a new commit. The file
5679 also means that tagging creates a new commit. The file
5681 ".hg/localtags" is used for local tags (not shared among
5680 ".hg/localtags" is used for local tags (not shared among
5682 repositories).
5681 repositories).
5683
5682
5684 Tag commits are usually made at the head of a branch. If the parent
5683 Tag commits are usually made at the head of a branch. If the parent
5685 of the working directory is not a branch head, :hg:`tag` aborts; use
5684 of the working directory is not a branch head, :hg:`tag` aborts; use
5686 -f/--force to force the tag commit to be based on a non-head
5685 -f/--force to force the tag commit to be based on a non-head
5687 changeset.
5686 changeset.
5688
5687
5689 See :hg:`help dates` for a list of formats valid for -d/--date.
5688 See :hg:`help dates` for a list of formats valid for -d/--date.
5690
5689
5691 Since tag names have priority over branch names during revision
5690 Since tag names have priority over branch names during revision
5692 lookup, using an existing branch name as a tag name is discouraged.
5691 lookup, using an existing branch name as a tag name is discouraged.
5693
5692
5694 Returns 0 on success.
5693 Returns 0 on success.
5695 """
5694 """
5696 wlock = lock = None
5695 wlock = lock = None
5697 try:
5696 try:
5698 wlock = repo.wlock()
5697 wlock = repo.wlock()
5699 lock = repo.lock()
5698 lock = repo.lock()
5700 rev_ = "."
5699 rev_ = "."
5701 names = [t.strip() for t in (name1,) + names]
5700 names = [t.strip() for t in (name1,) + names]
5702 if len(names) != len(set(names)):
5701 if len(names) != len(set(names)):
5703 raise util.Abort(_('tag names must be unique'))
5702 raise util.Abort(_('tag names must be unique'))
5704 for n in names:
5703 for n in names:
5705 scmutil.checknewlabel(repo, n, 'tag')
5704 scmutil.checknewlabel(repo, n, 'tag')
5706 if not n:
5705 if not n:
5707 raise util.Abort(_('tag names cannot consist entirely of '
5706 raise util.Abort(_('tag names cannot consist entirely of '
5708 'whitespace'))
5707 'whitespace'))
5709 if opts.get('rev') and opts.get('remove'):
5708 if opts.get('rev') and opts.get('remove'):
5710 raise util.Abort(_("--rev and --remove are incompatible"))
5709 raise util.Abort(_("--rev and --remove are incompatible"))
5711 if opts.get('rev'):
5710 if opts.get('rev'):
5712 rev_ = opts['rev']
5711 rev_ = opts['rev']
5713 message = opts.get('message')
5712 message = opts.get('message')
5714 if opts.get('remove'):
5713 if opts.get('remove'):
5715 expectedtype = opts.get('local') and 'local' or 'global'
5714 expectedtype = opts.get('local') and 'local' or 'global'
5716 for n in names:
5715 for n in names:
5717 if not repo.tagtype(n):
5716 if not repo.tagtype(n):
5718 raise util.Abort(_("tag '%s' does not exist") % n)
5717 raise util.Abort(_("tag '%s' does not exist") % n)
5719 if repo.tagtype(n) != expectedtype:
5718 if repo.tagtype(n) != expectedtype:
5720 if expectedtype == 'global':
5719 if expectedtype == 'global':
5721 raise util.Abort(_("tag '%s' is not a global tag") % n)
5720 raise util.Abort(_("tag '%s' is not a global tag") % n)
5722 else:
5721 else:
5723 raise util.Abort(_("tag '%s' is not a local tag") % n)
5722 raise util.Abort(_("tag '%s' is not a local tag") % n)
5724 rev_ = nullid
5723 rev_ = nullid
5725 if not message:
5724 if not message:
5726 # we don't translate commit messages
5725 # we don't translate commit messages
5727 message = 'Removed tag %s' % ', '.join(names)
5726 message = 'Removed tag %s' % ', '.join(names)
5728 elif not opts.get('force'):
5727 elif not opts.get('force'):
5729 for n in names:
5728 for n in names:
5730 if n in repo.tags():
5729 if n in repo.tags():
5731 raise util.Abort(_("tag '%s' already exists "
5730 raise util.Abort(_("tag '%s' already exists "
5732 "(use -f to force)") % n)
5731 "(use -f to force)") % n)
5733 if not opts.get('local'):
5732 if not opts.get('local'):
5734 p1, p2 = repo.dirstate.parents()
5733 p1, p2 = repo.dirstate.parents()
5735 if p2 != nullid:
5734 if p2 != nullid:
5736 raise util.Abort(_('uncommitted merge'))
5735 raise util.Abort(_('uncommitted merge'))
5737 bheads = repo.branchheads()
5736 bheads = repo.branchheads()
5738 if not opts.get('force') and bheads and p1 not in bheads:
5737 if not opts.get('force') and bheads and p1 not in bheads:
5739 raise util.Abort(_('not at a branch head (use -f to force)'))
5738 raise util.Abort(_('not at a branch head (use -f to force)'))
5740 r = scmutil.revsingle(repo, rev_).node()
5739 r = scmutil.revsingle(repo, rev_).node()
5741
5740
5742 if not message:
5741 if not message:
5743 # we don't translate commit messages
5742 # we don't translate commit messages
5744 message = ('Added tag %s for changeset %s' %
5743 message = ('Added tag %s for changeset %s' %
5745 (', '.join(names), short(r)))
5744 (', '.join(names), short(r)))
5746
5745
5747 date = opts.get('date')
5746 date = opts.get('date')
5748 if date:
5747 if date:
5749 date = util.parsedate(date)
5748 date = util.parsedate(date)
5750
5749
5751 if opts.get('edit'):
5750 if opts.get('edit'):
5752 message = ui.edit(message, ui.username())
5751 message = ui.edit(message, ui.username())
5753
5752
5754 # don't allow tagging the null rev
5753 # don't allow tagging the null rev
5755 if (not opts.get('remove') and
5754 if (not opts.get('remove') and
5756 scmutil.revsingle(repo, rev_).rev() == nullrev):
5755 scmutil.revsingle(repo, rev_).rev() == nullrev):
5757 raise util.Abort(_("null revision specified"))
5756 raise util.Abort(_("null revision specified"))
5758
5757
5759 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5758 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5760 finally:
5759 finally:
5761 release(lock, wlock)
5760 release(lock, wlock)
5762
5761
5763 @command('tags', [], '')
5762 @command('tags', [], '')
5764 def tags(ui, repo, **opts):
5763 def tags(ui, repo, **opts):
5765 """list repository tags
5764 """list repository tags
5766
5765
5767 This lists both regular and local tags. When the -v/--verbose
5766 This lists both regular and local tags. When the -v/--verbose
5768 switch is used, a third column "local" is printed for local tags.
5767 switch is used, a third column "local" is printed for local tags.
5769
5768
5770 Returns 0 on success.
5769 Returns 0 on success.
5771 """
5770 """
5772
5771
5773 fm = ui.formatter('tags', opts)
5772 fm = ui.formatter('tags', opts)
5774 hexfunc = ui.debugflag and hex or short
5773 hexfunc = ui.debugflag and hex or short
5775 tagtype = ""
5774 tagtype = ""
5776
5775
5777 for t, n in reversed(repo.tagslist()):
5776 for t, n in reversed(repo.tagslist()):
5778 hn = hexfunc(n)
5777 hn = hexfunc(n)
5779 label = 'tags.normal'
5778 label = 'tags.normal'
5780 tagtype = ''
5779 tagtype = ''
5781 if repo.tagtype(t) == 'local':
5780 if repo.tagtype(t) == 'local':
5782 label = 'tags.local'
5781 label = 'tags.local'
5783 tagtype = 'local'
5782 tagtype = 'local'
5784
5783
5785 fm.startitem()
5784 fm.startitem()
5786 fm.write('tag', '%s', t, label=label)
5785 fm.write('tag', '%s', t, label=label)
5787 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5786 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5788 fm.condwrite(not ui.quiet, 'rev id', fmt,
5787 fm.condwrite(not ui.quiet, 'rev id', fmt,
5789 repo.changelog.rev(n), hn, label=label)
5788 repo.changelog.rev(n), hn, label=label)
5790 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5789 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5791 tagtype, label=label)
5790 tagtype, label=label)
5792 fm.plain('\n')
5791 fm.plain('\n')
5793 fm.end()
5792 fm.end()
5794
5793
5795 @command('tip',
5794 @command('tip',
5796 [('p', 'patch', None, _('show patch')),
5795 [('p', 'patch', None, _('show patch')),
5797 ('g', 'git', None, _('use git extended diff format')),
5796 ('g', 'git', None, _('use git extended diff format')),
5798 ] + templateopts,
5797 ] + templateopts,
5799 _('[-p] [-g]'))
5798 _('[-p] [-g]'))
5800 def tip(ui, repo, **opts):
5799 def tip(ui, repo, **opts):
5801 """show the tip revision
5800 """show the tip revision
5802
5801
5803 The tip revision (usually just called the tip) is the changeset
5802 The tip revision (usually just called the tip) is the changeset
5804 most recently added to the repository (and therefore the most
5803 most recently added to the repository (and therefore the most
5805 recently changed head).
5804 recently changed head).
5806
5805
5807 If you have just made a commit, that commit will be the tip. If
5806 If you have just made a commit, that commit will be the tip. If
5808 you have just pulled changes from another repository, the tip of
5807 you have just pulled changes from another repository, the tip of
5809 that repository becomes the current tip. The "tip" tag is special
5808 that repository becomes the current tip. The "tip" tag is special
5810 and cannot be renamed or assigned to a different changeset.
5809 and cannot be renamed or assigned to a different changeset.
5811
5810
5812 Returns 0 on success.
5811 Returns 0 on success.
5813 """
5812 """
5814 displayer = cmdutil.show_changeset(ui, repo, opts)
5813 displayer = cmdutil.show_changeset(ui, repo, opts)
5815 displayer.show(repo[len(repo) - 1])
5814 displayer.show(repo[len(repo) - 1])
5816 displayer.close()
5815 displayer.close()
5817
5816
5818 @command('unbundle',
5817 @command('unbundle',
5819 [('u', 'update', None,
5818 [('u', 'update', None,
5820 _('update to new branch head if changesets were unbundled'))],
5819 _('update to new branch head if changesets were unbundled'))],
5821 _('[-u] FILE...'))
5820 _('[-u] FILE...'))
5822 def unbundle(ui, repo, fname1, *fnames, **opts):
5821 def unbundle(ui, repo, fname1, *fnames, **opts):
5823 """apply one or more changegroup files
5822 """apply one or more changegroup files
5824
5823
5825 Apply one or more compressed changegroup files generated by the
5824 Apply one or more compressed changegroup files generated by the
5826 bundle command.
5825 bundle command.
5827
5826
5828 Returns 0 on success, 1 if an update has unresolved files.
5827 Returns 0 on success, 1 if an update has unresolved files.
5829 """
5828 """
5830 fnames = (fname1,) + fnames
5829 fnames = (fname1,) + fnames
5831
5830
5832 lock = repo.lock()
5831 lock = repo.lock()
5833 wc = repo['.']
5832 wc = repo['.']
5834 try:
5833 try:
5835 for fname in fnames:
5834 for fname in fnames:
5836 f = hg.openpath(ui, fname)
5835 f = hg.openpath(ui, fname)
5837 gen = changegroup.readbundle(f, fname)
5836 gen = changegroup.readbundle(f, fname)
5838 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5837 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5839 finally:
5838 finally:
5840 lock.release()
5839 lock.release()
5841 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5840 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5842 return postincoming(ui, repo, modheads, opts.get('update'), None)
5841 return postincoming(ui, repo, modheads, opts.get('update'), None)
5843
5842
5844 @command('^update|up|checkout|co',
5843 @command('^update|up|checkout|co',
5845 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5844 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5846 ('c', 'check', None,
5845 ('c', 'check', None,
5847 _('update across branches if no uncommitted changes')),
5846 _('update across branches if no uncommitted changes')),
5848 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5847 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5849 ('r', 'rev', '', _('revision'), _('REV'))],
5848 ('r', 'rev', '', _('revision'), _('REV'))],
5850 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5849 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5851 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5850 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5852 """update working directory (or switch revisions)
5851 """update working directory (or switch revisions)
5853
5852
5854 Update the repository's working directory to the specified
5853 Update the repository's working directory to the specified
5855 changeset. If no changeset is specified, update to the tip of the
5854 changeset. If no changeset is specified, update to the tip of the
5856 current named branch and move the current bookmark (see :hg:`help
5855 current named branch and move the current bookmark (see :hg:`help
5857 bookmarks`).
5856 bookmarks`).
5858
5857
5859 Update sets the working directory's parent revision to the specified
5858 Update sets the working directory's parent revision to the specified
5860 changeset (see :hg:`help parents`).
5859 changeset (see :hg:`help parents`).
5861
5860
5862 If the changeset is not a descendant or ancestor of the working
5861 If the changeset is not a descendant or ancestor of the working
5863 directory's parent, the update is aborted. With the -c/--check
5862 directory's parent, the update is aborted. With the -c/--check
5864 option, the working directory is checked for uncommitted changes; if
5863 option, the working directory is checked for uncommitted changes; if
5865 none are found, the working directory is updated to the specified
5864 none are found, the working directory is updated to the specified
5866 changeset.
5865 changeset.
5867
5866
5868 .. container:: verbose
5867 .. container:: verbose
5869
5868
5870 The following rules apply when the working directory contains
5869 The following rules apply when the working directory contains
5871 uncommitted changes:
5870 uncommitted changes:
5872
5871
5873 1. If neither -c/--check nor -C/--clean is specified, and if
5872 1. If neither -c/--check nor -C/--clean is specified, and if
5874 the requested changeset is an ancestor or descendant of
5873 the requested changeset is an ancestor or descendant of
5875 the working directory's parent, the uncommitted changes
5874 the working directory's parent, the uncommitted changes
5876 are merged into the requested changeset and the merged
5875 are merged into the requested changeset and the merged
5877 result is left uncommitted. If the requested changeset is
5876 result is left uncommitted. If the requested changeset is
5878 not an ancestor or descendant (that is, it is on another
5877 not an ancestor or descendant (that is, it is on another
5879 branch), the update is aborted and the uncommitted changes
5878 branch), the update is aborted and the uncommitted changes
5880 are preserved.
5879 are preserved.
5881
5880
5882 2. With the -c/--check option, the update is aborted and the
5881 2. With the -c/--check option, the update is aborted and the
5883 uncommitted changes are preserved.
5882 uncommitted changes are preserved.
5884
5883
5885 3. With the -C/--clean option, uncommitted changes are discarded and
5884 3. With the -C/--clean option, uncommitted changes are discarded and
5886 the working directory is updated to the requested changeset.
5885 the working directory is updated to the requested changeset.
5887
5886
5888 To cancel an uncommitted merge (and lose your changes), use
5887 To cancel an uncommitted merge (and lose your changes), use
5889 :hg:`update --clean .`.
5888 :hg:`update --clean .`.
5890
5889
5891 Use null as the changeset to remove the working directory (like
5890 Use null as the changeset to remove the working directory (like
5892 :hg:`clone -U`).
5891 :hg:`clone -U`).
5893
5892
5894 If you want to revert just one file to an older revision, use
5893 If you want to revert just one file to an older revision, use
5895 :hg:`revert [-r REV] NAME`.
5894 :hg:`revert [-r REV] NAME`.
5896
5895
5897 See :hg:`help dates` for a list of formats valid for -d/--date.
5896 See :hg:`help dates` for a list of formats valid for -d/--date.
5898
5897
5899 Returns 0 on success, 1 if there are unresolved files.
5898 Returns 0 on success, 1 if there are unresolved files.
5900 """
5899 """
5901 if rev and node:
5900 if rev and node:
5902 raise util.Abort(_("please specify just one revision"))
5901 raise util.Abort(_("please specify just one revision"))
5903
5902
5904 if rev is None or rev == '':
5903 if rev is None or rev == '':
5905 rev = node
5904 rev = node
5906
5905
5907 # with no argument, we also move the current bookmark, if any
5906 # with no argument, we also move the current bookmark, if any
5908 movemarkfrom = None
5907 movemarkfrom = None
5909 if rev is None:
5908 if rev is None:
5910 movemarkfrom = repo['.'].node()
5909 movemarkfrom = repo['.'].node()
5911
5910
5912 # if we defined a bookmark, we have to remember the original bookmark name
5911 # if we defined a bookmark, we have to remember the original bookmark name
5913 brev = rev
5912 brev = rev
5914 rev = scmutil.revsingle(repo, rev, rev).rev()
5913 rev = scmutil.revsingle(repo, rev, rev).rev()
5915
5914
5916 if check and clean:
5915 if check and clean:
5917 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5916 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5918
5917
5919 if date:
5918 if date:
5920 if rev is not None:
5919 if rev is not None:
5921 raise util.Abort(_("you can't specify a revision and a date"))
5920 raise util.Abort(_("you can't specify a revision and a date"))
5922 rev = cmdutil.finddate(ui, repo, date)
5921 rev = cmdutil.finddate(ui, repo, date)
5923
5922
5924 if check:
5923 if check:
5925 c = repo[None]
5924 c = repo[None]
5926 if c.dirty(merge=False, branch=False, missing=True):
5925 if c.dirty(merge=False, branch=False, missing=True):
5927 raise util.Abort(_("uncommitted local changes"))
5926 raise util.Abort(_("uncommitted local changes"))
5928 if rev is None:
5927 if rev is None:
5929 rev = repo[repo[None].branch()].rev()
5928 rev = repo[repo[None].branch()].rev()
5930 mergemod._checkunknown(repo, repo[None], repo[rev])
5929 mergemod._checkunknown(repo, repo[None], repo[rev])
5931
5930
5932 if clean:
5931 if clean:
5933 ret = hg.clean(repo, rev)
5932 ret = hg.clean(repo, rev)
5934 else:
5933 else:
5935 ret = hg.update(repo, rev)
5934 ret = hg.update(repo, rev)
5936
5935
5937 if not ret and movemarkfrom:
5936 if not ret and movemarkfrom:
5938 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5937 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5939 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5938 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5940 elif brev in repo._bookmarks:
5939 elif brev in repo._bookmarks:
5941 bookmarks.setcurrent(repo, brev)
5940 bookmarks.setcurrent(repo, brev)
5942 elif brev:
5941 elif brev:
5943 bookmarks.unsetcurrent(repo)
5942 bookmarks.unsetcurrent(repo)
5944
5943
5945 return ret
5944 return ret
5946
5945
5947 @command('verify', [])
5946 @command('verify', [])
5948 def verify(ui, repo):
5947 def verify(ui, repo):
5949 """verify the integrity of the repository
5948 """verify the integrity of the repository
5950
5949
5951 Verify the integrity of the current repository.
5950 Verify the integrity of the current repository.
5952
5951
5953 This will perform an extensive check of the repository's
5952 This will perform an extensive check of the repository's
5954 integrity, validating the hashes and checksums of each entry in
5953 integrity, validating the hashes and checksums of each entry in
5955 the changelog, manifest, and tracked files, as well as the
5954 the changelog, manifest, and tracked files, as well as the
5956 integrity of their crosslinks and indices.
5955 integrity of their crosslinks and indices.
5957
5956
5958 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5957 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5959 for more information about recovery from corruption of the
5958 for more information about recovery from corruption of the
5960 repository.
5959 repository.
5961
5960
5962 Returns 0 on success, 1 if errors are encountered.
5961 Returns 0 on success, 1 if errors are encountered.
5963 """
5962 """
5964 return hg.verify(repo)
5963 return hg.verify(repo)
5965
5964
5966 @command('version', [])
5965 @command('version', [])
5967 def version_(ui):
5966 def version_(ui):
5968 """output version and copyright information"""
5967 """output version and copyright information"""
5969 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5968 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5970 % util.version())
5969 % util.version())
5971 ui.status(_(
5970 ui.status(_(
5972 "(see http://mercurial.selenic.com for more information)\n"
5971 "(see http://mercurial.selenic.com for more information)\n"
5973 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5972 "\nCopyright (C) 2005-2012 Matt Mackall and others\n"
5974 "This is free software; see the source for copying conditions. "
5973 "This is free software; see the source for copying conditions. "
5975 "There is NO\nwarranty; "
5974 "There is NO\nwarranty; "
5976 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5975 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5977 ))
5976 ))
5978
5977
5979 norepo = ("clone init version help debugcommands debugcomplete"
5978 norepo = ("clone init version help debugcommands debugcomplete"
5980 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5979 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5981 " debugknown debuggetbundle debugbundle")
5980 " debugknown debuggetbundle debugbundle")
5982 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5981 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5983 " debugdata debugindex debugindexdot debugrevlog")
5982 " debugdata debugindex debugindexdot debugrevlog")
5984 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5983 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5985 " remove resolve status debugwalk")
5984 " remove resolve status debugwalk")
@@ -1,287 +1,287 b''
1 $ remove() {
1 $ remove() {
2 > hg rm $@
2 > hg rm $@
3 > echo "exit code: $?" # no-check-code
3 > echo "exit code: $?" # no-check-code
4 > hg st
4 > hg st
5 > # do not use ls -R, which recurses in .hg subdirs on Mac OS X 10.5
5 > # do not use ls -R, which recurses in .hg subdirs on Mac OS X 10.5
6 > find . -name .hg -prune -o -type f -print | sort
6 > find . -name .hg -prune -o -type f -print | sort
7 > hg up -C
7 > hg up -C
8 > }
8 > }
9
9
10 $ hg init a
10 $ hg init a
11 $ cd a
11 $ cd a
12 $ echo a > foo
12 $ echo a > foo
13
13
14 file not managed
14 file not managed
15
15
16 $ remove foo
16 $ remove foo
17 not removing foo: file is untracked
17 not removing foo: file is untracked
18 exit code: 1
18 exit code: 1
19 ? foo
19 ? foo
20 ./foo
20 ./foo
21 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
21 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
22
22
23 $ hg add foo
23 $ hg add foo
24 $ hg commit -m1
24 $ hg commit -m1
25
25
26 the table cases
26 the table cases
27 00 state added, options none
27 00 state added, options none
28
28
29 $ echo b > bar
29 $ echo b > bar
30 $ hg add bar
30 $ hg add bar
31 $ remove bar
31 $ remove bar
32 not removing bar: file has been marked for add (use forget to undo)
32 not removing bar: file has been marked for add (use forget to undo)
33 exit code: 1
33 exit code: 1
34 A bar
34 A bar
35 ./bar
35 ./bar
36 ./foo
36 ./foo
37 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
37 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
38
38
39 01 state clean, options none
39 01 state clean, options none
40
40
41 $ remove foo
41 $ remove foo
42 exit code: 0
42 exit code: 0
43 R foo
43 R foo
44 ? bar
44 ? bar
45 ./bar
45 ./bar
46 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
46 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
47
47
48 02 state modified, options none
48 02 state modified, options none
49
49
50 $ echo b >> foo
50 $ echo b >> foo
51 $ remove foo
51 $ remove foo
52 not removing foo: file is modified (use -f to force removal)
52 not removing foo: file is modified (use -f to force removal)
53 exit code: 1
53 exit code: 1
54 M foo
54 M foo
55 ? bar
55 ? bar
56 ./bar
56 ./bar
57 ./foo
57 ./foo
58 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
58 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
59
59
60 03 state missing, options none
60 03 state missing, options none
61
61
62 $ rm foo
62 $ rm foo
63 $ remove foo
63 $ remove foo
64 exit code: 0
64 exit code: 0
65 R foo
65 R foo
66 ? bar
66 ? bar
67 ./bar
67 ./bar
68 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
68 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
69
69
70 10 state added, options -f
70 10 state added, options -f
71
71
72 $ echo b > bar
72 $ echo b > bar
73 $ hg add bar
73 $ hg add bar
74 $ remove -f bar
74 $ remove -f bar
75 exit code: 0
75 exit code: 0
76 ? bar
76 ? bar
77 ./bar
77 ./bar
78 ./foo
78 ./foo
79 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
79 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
80 $ rm bar
80 $ rm bar
81
81
82 11 state clean, options -f
82 11 state clean, options -f
83
83
84 $ remove -f foo
84 $ remove -f foo
85 exit code: 0
85 exit code: 0
86 R foo
86 R foo
87 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
87 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
88
88
89 12 state modified, options -f
89 12 state modified, options -f
90
90
91 $ echo b >> foo
91 $ echo b >> foo
92 $ remove -f foo
92 $ remove -f foo
93 exit code: 0
93 exit code: 0
94 R foo
94 R foo
95 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
95 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
96
96
97 13 state missing, options -f
97 13 state missing, options -f
98
98
99 $ rm foo
99 $ rm foo
100 $ remove -f foo
100 $ remove -f foo
101 exit code: 0
101 exit code: 0
102 R foo
102 R foo
103 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
103 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
104
104
105 20 state added, options -A
105 20 state added, options -A
106
106
107 $ echo b > bar
107 $ echo b > bar
108 $ hg add bar
108 $ hg add bar
109 $ remove -A bar
109 $ remove -A bar
110 not removing bar: file still exists (use -f to force removal)
110 not removing bar: file still exists
111 exit code: 1
111 exit code: 1
112 A bar
112 A bar
113 ./bar
113 ./bar
114 ./foo
114 ./foo
115 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
115 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
116
116
117 21 state clean, options -A
117 21 state clean, options -A
118
118
119 $ remove -A foo
119 $ remove -A foo
120 not removing foo: file still exists (use -f to force removal)
120 not removing foo: file still exists
121 exit code: 1
121 exit code: 1
122 ? bar
122 ? bar
123 ./bar
123 ./bar
124 ./foo
124 ./foo
125 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
125 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
126
126
127 22 state modified, options -A
127 22 state modified, options -A
128
128
129 $ echo b >> foo
129 $ echo b >> foo
130 $ remove -A foo
130 $ remove -A foo
131 not removing foo: file still exists (use -f to force removal)
131 not removing foo: file still exists
132 exit code: 1
132 exit code: 1
133 M foo
133 M foo
134 ? bar
134 ? bar
135 ./bar
135 ./bar
136 ./foo
136 ./foo
137 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
137 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
138
138
139 23 state missing, options -A
139 23 state missing, options -A
140
140
141 $ rm foo
141 $ rm foo
142 $ remove -A foo
142 $ remove -A foo
143 exit code: 0
143 exit code: 0
144 R foo
144 R foo
145 ? bar
145 ? bar
146 ./bar
146 ./bar
147 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
147 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
148
148
149 30 state added, options -Af
149 30 state added, options -Af
150
150
151 $ echo b > bar
151 $ echo b > bar
152 $ hg add bar
152 $ hg add bar
153 $ remove -Af bar
153 $ remove -Af bar
154 exit code: 0
154 exit code: 0
155 ? bar
155 ? bar
156 ./bar
156 ./bar
157 ./foo
157 ./foo
158 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
158 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
159 $ rm bar
159 $ rm bar
160
160
161 31 state clean, options -Af
161 31 state clean, options -Af
162
162
163 $ remove -Af foo
163 $ remove -Af foo
164 exit code: 0
164 exit code: 0
165 R foo
165 R foo
166 ./foo
166 ./foo
167 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
167 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
168
168
169 32 state modified, options -Af
169 32 state modified, options -Af
170
170
171 $ echo b >> foo
171 $ echo b >> foo
172 $ remove -Af foo
172 $ remove -Af foo
173 exit code: 0
173 exit code: 0
174 R foo
174 R foo
175 ./foo
175 ./foo
176 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
176 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
177
177
178 33 state missing, options -Af
178 33 state missing, options -Af
179
179
180 $ rm foo
180 $ rm foo
181 $ remove -Af foo
181 $ remove -Af foo
182 exit code: 0
182 exit code: 0
183 R foo
183 R foo
184 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
184 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
185
185
186 test some directory stuff
186 test some directory stuff
187
187
188 $ mkdir test
188 $ mkdir test
189 $ echo a > test/foo
189 $ echo a > test/foo
190 $ echo b > test/bar
190 $ echo b > test/bar
191 $ hg ci -Am2
191 $ hg ci -Am2
192 adding test/bar
192 adding test/bar
193 adding test/foo
193 adding test/foo
194
194
195 dir, options none
195 dir, options none
196
196
197 $ rm test/bar
197 $ rm test/bar
198 $ remove test
198 $ remove test
199 removing test/bar (glob)
199 removing test/bar (glob)
200 removing test/foo (glob)
200 removing test/foo (glob)
201 exit code: 0
201 exit code: 0
202 R test/bar
202 R test/bar
203 R test/foo
203 R test/foo
204 ./foo
204 ./foo
205 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
205 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
206
206
207 dir, options -f
207 dir, options -f
208
208
209 $ rm test/bar
209 $ rm test/bar
210 $ remove -f test
210 $ remove -f test
211 removing test/bar (glob)
211 removing test/bar (glob)
212 removing test/foo (glob)
212 removing test/foo (glob)
213 exit code: 0
213 exit code: 0
214 R test/bar
214 R test/bar
215 R test/foo
215 R test/foo
216 ./foo
216 ./foo
217 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
217 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
218
218
219 dir, options -A
219 dir, options -A
220
220
221 $ rm test/bar
221 $ rm test/bar
222 $ remove -A test
222 $ remove -A test
223 not removing test/foo: file still exists (use -f to force removal) (glob)
223 not removing test/foo: file still exists (glob)
224 removing test/bar (glob)
224 removing test/bar (glob)
225 exit code: 1
225 exit code: 1
226 R test/bar
226 R test/bar
227 ./foo
227 ./foo
228 ./test/foo
228 ./test/foo
229 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
229 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
230
230
231 dir, options -Af
231 dir, options -Af
232
232
233 $ rm test/bar
233 $ rm test/bar
234 $ remove -Af test
234 $ remove -Af test
235 removing test/bar (glob)
235 removing test/bar (glob)
236 removing test/foo (glob)
236 removing test/foo (glob)
237 exit code: 0
237 exit code: 0
238 R test/bar
238 R test/bar
239 R test/foo
239 R test/foo
240 ./foo
240 ./foo
241 ./test/foo
241 ./test/foo
242 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
242 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
243
243
244 test remove dropping empty trees (issue1861)
244 test remove dropping empty trees (issue1861)
245
245
246 $ mkdir -p issue1861/b/c
246 $ mkdir -p issue1861/b/c
247 $ echo x > issue1861/x
247 $ echo x > issue1861/x
248 $ echo y > issue1861/b/c/y
248 $ echo y > issue1861/b/c/y
249 $ hg ci -Am add
249 $ hg ci -Am add
250 adding issue1861/b/c/y
250 adding issue1861/b/c/y
251 adding issue1861/x
251 adding issue1861/x
252 $ hg rm issue1861/b
252 $ hg rm issue1861/b
253 removing issue1861/b/c/y (glob)
253 removing issue1861/b/c/y (glob)
254 $ hg ci -m remove
254 $ hg ci -m remove
255 $ ls issue1861
255 $ ls issue1861
256 x
256 x
257
257
258 test that commit does not crash if the user removes a newly added file
258 test that commit does not crash if the user removes a newly added file
259
259
260 $ touch f1
260 $ touch f1
261 $ hg add f1
261 $ hg add f1
262 $ rm f1
262 $ rm f1
263 $ hg ci -A -mx
263 $ hg ci -A -mx
264 removing f1
264 removing f1
265 nothing changed
265 nothing changed
266 [1]
266 [1]
267
267
268 handling of untracked directories and missing files
268 handling of untracked directories and missing files
269
269
270 $ mkdir d1
270 $ mkdir d1
271 $ echo a > d1/a
271 $ echo a > d1/a
272 $ hg rm --after d1
272 $ hg rm --after d1
273 not removing d1: no tracked files
273 not removing d1: no tracked files
274 [1]
274 [1]
275 $ hg add d1/a
275 $ hg add d1/a
276 $ rm d1/a
276 $ rm d1/a
277 $ hg rm --after d1
277 $ hg rm --after d1
278 removing d1/a (glob)
278 removing d1/a (glob)
279 #if windows
279 #if windows
280 $ hg rm --after nosuch
280 $ hg rm --after nosuch
281 nosuch: * (glob)
281 nosuch: * (glob)
282 [1]
282 [1]
283 #else
283 #else
284 $ hg rm --after nosuch
284 $ hg rm --after nosuch
285 nosuch: No such file or directory
285 nosuch: No such file or directory
286 [1]
286 [1]
287 #endif
287 #endif
General Comments 0
You need to be logged in to leave comments. Login now