##// END OF EJS Templates
grep: reuse the first "util.binary()" result for efficiency...
FUJIWARA Katsunori -
r20836:a8b4541b default
parent child Browse files
Show More
@@ -1,5929 +1,5930 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 _
10 from i18n import _
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import sys
12 import sys
13 import hg, scmutil, util, revlog, copies, error, bookmarks
13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 import patch, help, encoding, templatekw, discovery
14 import patch, help, encoding, templatekw, discovery
15 import archival, changegroup, cmdutil, hbisect
15 import archival, changegroup, cmdutil, hbisect
16 import sshserver, hgweb, commandserver
16 import sshserver, hgweb, commandserver
17 from hgweb import server as hgweb_server
17 from hgweb import server as hgweb_server
18 import merge as mergemod
18 import merge as mergemod
19 import minirst, revset, fileset
19 import minirst, revset, fileset
20 import dagparser, context, simplemerge, graphmod
20 import dagparser, context, simplemerge, graphmod
21 import random
21 import random
22 import setdiscovery, treediscovery, dagutil, pvec, localrepo
22 import setdiscovery, treediscovery, dagutil, pvec, localrepo
23 import phases, obsolete
23 import phases, obsolete
24
24
25 table = {}
25 table = {}
26
26
27 command = cmdutil.command(table)
27 command = cmdutil.command(table)
28
28
29 # common command options
29 # common command options
30
30
31 globalopts = [
31 globalopts = [
32 ('R', 'repository', '',
32 ('R', 'repository', '',
33 _('repository root directory or name of overlay bundle file'),
33 _('repository root directory or name of overlay bundle file'),
34 _('REPO')),
34 _('REPO')),
35 ('', 'cwd', '',
35 ('', 'cwd', '',
36 _('change working directory'), _('DIR')),
36 _('change working directory'), _('DIR')),
37 ('y', 'noninteractive', None,
37 ('y', 'noninteractive', None,
38 _('do not prompt, automatically pick the first choice for all prompts')),
38 _('do not prompt, automatically pick the first choice for all prompts')),
39 ('q', 'quiet', None, _('suppress output')),
39 ('q', 'quiet', None, _('suppress output')),
40 ('v', 'verbose', None, _('enable additional output')),
40 ('v', 'verbose', None, _('enable additional output')),
41 ('', 'config', [],
41 ('', 'config', [],
42 _('set/override config option (use \'section.name=value\')'),
42 _('set/override config option (use \'section.name=value\')'),
43 _('CONFIG')),
43 _('CONFIG')),
44 ('', 'debug', None, _('enable debugging output')),
44 ('', 'debug', None, _('enable debugging output')),
45 ('', 'debugger', None, _('start debugger')),
45 ('', 'debugger', None, _('start debugger')),
46 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
46 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
47 _('ENCODE')),
47 _('ENCODE')),
48 ('', 'encodingmode', encoding.encodingmode,
48 ('', 'encodingmode', encoding.encodingmode,
49 _('set the charset encoding mode'), _('MODE')),
49 _('set the charset encoding mode'), _('MODE')),
50 ('', 'traceback', None, _('always print a traceback on exception')),
50 ('', 'traceback', None, _('always print a traceback on exception')),
51 ('', 'time', None, _('time how long the command takes')),
51 ('', 'time', None, _('time how long the command takes')),
52 ('', 'profile', None, _('print command execution profile')),
52 ('', 'profile', None, _('print command execution profile')),
53 ('', 'version', None, _('output version information and exit')),
53 ('', 'version', None, _('output version information and exit')),
54 ('h', 'help', None, _('display help and exit')),
54 ('h', 'help', None, _('display help and exit')),
55 ('', 'hidden', False, _('consider hidden changesets')),
55 ('', 'hidden', False, _('consider hidden changesets')),
56 ]
56 ]
57
57
58 dryrunopts = [('n', 'dry-run', None,
58 dryrunopts = [('n', 'dry-run', None,
59 _('do not perform actions, just print output'))]
59 _('do not perform actions, just print output'))]
60
60
61 remoteopts = [
61 remoteopts = [
62 ('e', 'ssh', '',
62 ('e', 'ssh', '',
63 _('specify ssh command to use'), _('CMD')),
63 _('specify ssh command to use'), _('CMD')),
64 ('', 'remotecmd', '',
64 ('', 'remotecmd', '',
65 _('specify hg command to run on the remote side'), _('CMD')),
65 _('specify hg command to run on the remote side'), _('CMD')),
66 ('', 'insecure', None,
66 ('', 'insecure', None,
67 _('do not verify server certificate (ignoring web.cacerts config)')),
67 _('do not verify server certificate (ignoring web.cacerts config)')),
68 ]
68 ]
69
69
70 walkopts = [
70 walkopts = [
71 ('I', 'include', [],
71 ('I', 'include', [],
72 _('include names matching the given patterns'), _('PATTERN')),
72 _('include names matching the given patterns'), _('PATTERN')),
73 ('X', 'exclude', [],
73 ('X', 'exclude', [],
74 _('exclude names matching the given patterns'), _('PATTERN')),
74 _('exclude names matching the given patterns'), _('PATTERN')),
75 ]
75 ]
76
76
77 commitopts = [
77 commitopts = [
78 ('m', 'message', '',
78 ('m', 'message', '',
79 _('use text as commit message'), _('TEXT')),
79 _('use text as commit message'), _('TEXT')),
80 ('l', 'logfile', '',
80 ('l', 'logfile', '',
81 _('read commit message from file'), _('FILE')),
81 _('read commit message from file'), _('FILE')),
82 ]
82 ]
83
83
84 commitopts2 = [
84 commitopts2 = [
85 ('d', 'date', '',
85 ('d', 'date', '',
86 _('record the specified date as commit date'), _('DATE')),
86 _('record the specified date as commit date'), _('DATE')),
87 ('u', 'user', '',
87 ('u', 'user', '',
88 _('record the specified user as committer'), _('USER')),
88 _('record the specified user as committer'), _('USER')),
89 ]
89 ]
90
90
91 templateopts = [
91 templateopts = [
92 ('', 'style', '',
92 ('', 'style', '',
93 _('display using template map file (DEPRECATED)'), _('STYLE')),
93 _('display using template map file (DEPRECATED)'), _('STYLE')),
94 ('T', 'template', '',
94 ('T', 'template', '',
95 _('display with template'), _('TEMPLATE')),
95 _('display with template'), _('TEMPLATE')),
96 ]
96 ]
97
97
98 logopts = [
98 logopts = [
99 ('p', 'patch', None, _('show patch')),
99 ('p', 'patch', None, _('show patch')),
100 ('g', 'git', None, _('use git extended diff format')),
100 ('g', 'git', None, _('use git extended diff format')),
101 ('l', 'limit', '',
101 ('l', 'limit', '',
102 _('limit number of changes displayed'), _('NUM')),
102 _('limit number of changes displayed'), _('NUM')),
103 ('M', 'no-merges', None, _('do not show merges')),
103 ('M', 'no-merges', None, _('do not show merges')),
104 ('', 'stat', None, _('output diffstat-style summary of changes')),
104 ('', 'stat', None, _('output diffstat-style summary of changes')),
105 ('G', 'graph', None, _("show the revision DAG")),
105 ('G', 'graph', None, _("show the revision DAG")),
106 ] + templateopts
106 ] + templateopts
107
107
108 diffopts = [
108 diffopts = [
109 ('a', 'text', None, _('treat all files as text')),
109 ('a', 'text', None, _('treat all files as text')),
110 ('g', 'git', None, _('use git extended diff format')),
110 ('g', 'git', None, _('use git extended diff format')),
111 ('', 'nodates', None, _('omit dates from diff headers'))
111 ('', 'nodates', None, _('omit dates from diff headers'))
112 ]
112 ]
113
113
114 diffwsopts = [
114 diffwsopts = [
115 ('w', 'ignore-all-space', None,
115 ('w', 'ignore-all-space', None,
116 _('ignore white space when comparing lines')),
116 _('ignore white space when comparing lines')),
117 ('b', 'ignore-space-change', None,
117 ('b', 'ignore-space-change', None,
118 _('ignore changes in the amount of white space')),
118 _('ignore changes in the amount of white space')),
119 ('B', 'ignore-blank-lines', None,
119 ('B', 'ignore-blank-lines', None,
120 _('ignore changes whose lines are all blank')),
120 _('ignore changes whose lines are all blank')),
121 ]
121 ]
122
122
123 diffopts2 = [
123 diffopts2 = [
124 ('p', 'show-function', None, _('show which function each change is in')),
124 ('p', 'show-function', None, _('show which function each change is in')),
125 ('', 'reverse', None, _('produce a diff that undoes the changes')),
125 ('', 'reverse', None, _('produce a diff that undoes the changes')),
126 ] + diffwsopts + [
126 ] + diffwsopts + [
127 ('U', 'unified', '',
127 ('U', 'unified', '',
128 _('number of lines of context to show'), _('NUM')),
128 _('number of lines of context to show'), _('NUM')),
129 ('', 'stat', None, _('output diffstat-style summary of changes')),
129 ('', 'stat', None, _('output diffstat-style summary of changes')),
130 ]
130 ]
131
131
132 mergetoolopts = [
132 mergetoolopts = [
133 ('t', 'tool', '', _('specify merge tool')),
133 ('t', 'tool', '', _('specify merge tool')),
134 ]
134 ]
135
135
136 similarityopts = [
136 similarityopts = [
137 ('s', 'similarity', '',
137 ('s', 'similarity', '',
138 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
138 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
139 ]
139 ]
140
140
141 subrepoopts = [
141 subrepoopts = [
142 ('S', 'subrepos', None,
142 ('S', 'subrepos', None,
143 _('recurse into subrepositories'))
143 _('recurse into subrepositories'))
144 ]
144 ]
145
145
146 # Commands start here, listed alphabetically
146 # Commands start here, listed alphabetically
147
147
148 @command('^add',
148 @command('^add',
149 walkopts + subrepoopts + dryrunopts,
149 walkopts + subrepoopts + dryrunopts,
150 _('[OPTION]... [FILE]...'))
150 _('[OPTION]... [FILE]...'))
151 def add(ui, repo, *pats, **opts):
151 def add(ui, repo, *pats, **opts):
152 """add the specified files on the next commit
152 """add the specified files on the next commit
153
153
154 Schedule files to be version controlled and added to the
154 Schedule files to be version controlled and added to the
155 repository.
155 repository.
156
156
157 The files will be added to the repository at the next commit. To
157 The files will be added to the repository at the next commit. To
158 undo an add before that, see :hg:`forget`.
158 undo an add before that, see :hg:`forget`.
159
159
160 If no names are given, add all files to the repository.
160 If no names are given, add all files to the repository.
161
161
162 .. container:: verbose
162 .. container:: verbose
163
163
164 An example showing how new (unknown) files are added
164 An example showing how new (unknown) files are added
165 automatically by :hg:`add`::
165 automatically by :hg:`add`::
166
166
167 $ ls
167 $ ls
168 foo.c
168 foo.c
169 $ hg status
169 $ hg status
170 ? foo.c
170 ? foo.c
171 $ hg add
171 $ hg add
172 adding foo.c
172 adding foo.c
173 $ hg status
173 $ hg status
174 A foo.c
174 A foo.c
175
175
176 Returns 0 if all files are successfully added.
176 Returns 0 if all files are successfully added.
177 """
177 """
178
178
179 m = scmutil.match(repo[None], pats, opts)
179 m = scmutil.match(repo[None], pats, opts)
180 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
180 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
181 opts.get('subrepos'), prefix="", explicitonly=False)
181 opts.get('subrepos'), prefix="", explicitonly=False)
182 return rejected and 1 or 0
182 return rejected and 1 or 0
183
183
184 @command('addremove',
184 @command('addremove',
185 similarityopts + walkopts + dryrunopts,
185 similarityopts + walkopts + dryrunopts,
186 _('[OPTION]... [FILE]...'))
186 _('[OPTION]... [FILE]...'))
187 def addremove(ui, repo, *pats, **opts):
187 def addremove(ui, repo, *pats, **opts):
188 """add all new files, delete all missing files
188 """add all new files, delete all missing files
189
189
190 Add all new files and remove all missing files from the
190 Add all new files and remove all missing files from the
191 repository.
191 repository.
192
192
193 New files are ignored if they match any of the patterns in
193 New files are ignored if they match any of the patterns in
194 ``.hgignore``. As with add, these changes take effect at the next
194 ``.hgignore``. As with add, these changes take effect at the next
195 commit.
195 commit.
196
196
197 Use the -s/--similarity option to detect renamed files. This
197 Use the -s/--similarity option to detect renamed files. This
198 option takes a percentage between 0 (disabled) and 100 (files must
198 option takes a percentage between 0 (disabled) and 100 (files must
199 be identical) as its parameter. With a parameter greater than 0,
199 be identical) as its parameter. With a parameter greater than 0,
200 this compares every removed file with every added file and records
200 this compares every removed file with every added file and records
201 those similar enough as renames. Detecting renamed files this way
201 those similar enough as renames. Detecting renamed files this way
202 can be expensive. After using this option, :hg:`status -C` can be
202 can be expensive. After using this option, :hg:`status -C` can be
203 used to check which files were identified as moved or renamed. If
203 used to check which files were identified as moved or renamed. If
204 not specified, -s/--similarity defaults to 100 and only renames of
204 not specified, -s/--similarity defaults to 100 and only renames of
205 identical files are detected.
205 identical files are detected.
206
206
207 Returns 0 if all files are successfully added.
207 Returns 0 if all files are successfully added.
208 """
208 """
209 try:
209 try:
210 sim = float(opts.get('similarity') or 100)
210 sim = float(opts.get('similarity') or 100)
211 except ValueError:
211 except ValueError:
212 raise util.Abort(_('similarity must be a number'))
212 raise util.Abort(_('similarity must be a number'))
213 if sim < 0 or sim > 100:
213 if sim < 0 or sim > 100:
214 raise util.Abort(_('similarity must be between 0 and 100'))
214 raise util.Abort(_('similarity must be between 0 and 100'))
215 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
215 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
216
216
217 @command('^annotate|blame',
217 @command('^annotate|blame',
218 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
218 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
219 ('', 'follow', None,
219 ('', 'follow', None,
220 _('follow copies/renames and list the filename (DEPRECATED)')),
220 _('follow copies/renames and list the filename (DEPRECATED)')),
221 ('', 'no-follow', None, _("don't follow copies and renames")),
221 ('', 'no-follow', None, _("don't follow copies and renames")),
222 ('a', 'text', None, _('treat all files as text')),
222 ('a', 'text', None, _('treat all files as text')),
223 ('u', 'user', None, _('list the author (long with -v)')),
223 ('u', 'user', None, _('list the author (long with -v)')),
224 ('f', 'file', None, _('list the filename')),
224 ('f', 'file', None, _('list the filename')),
225 ('d', 'date', None, _('list the date (short with -q)')),
225 ('d', 'date', None, _('list the date (short with -q)')),
226 ('n', 'number', None, _('list the revision number (default)')),
226 ('n', 'number', None, _('list the revision number (default)')),
227 ('c', 'changeset', None, _('list the changeset')),
227 ('c', 'changeset', None, _('list the changeset')),
228 ('l', 'line-number', None, _('show line number at the first appearance'))
228 ('l', 'line-number', None, _('show line number at the first appearance'))
229 ] + diffwsopts + walkopts,
229 ] + diffwsopts + walkopts,
230 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
230 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
231 def annotate(ui, repo, *pats, **opts):
231 def annotate(ui, repo, *pats, **opts):
232 """show changeset information by line for each file
232 """show changeset information by line for each file
233
233
234 List changes in files, showing the revision id responsible for
234 List changes in files, showing the revision id responsible for
235 each line
235 each line
236
236
237 This command is useful for discovering when a change was made and
237 This command is useful for discovering when a change was made and
238 by whom.
238 by whom.
239
239
240 Without the -a/--text option, annotate will avoid processing files
240 Without the -a/--text option, annotate will avoid processing files
241 it detects as binary. With -a, annotate will annotate the file
241 it detects as binary. With -a, annotate will annotate the file
242 anyway, although the results will probably be neither useful
242 anyway, although the results will probably be neither useful
243 nor desirable.
243 nor desirable.
244
244
245 Returns 0 on success.
245 Returns 0 on success.
246 """
246 """
247 if opts.get('follow'):
247 if opts.get('follow'):
248 # --follow is deprecated and now just an alias for -f/--file
248 # --follow is deprecated and now just an alias for -f/--file
249 # to mimic the behavior of Mercurial before version 1.5
249 # to mimic the behavior of Mercurial before version 1.5
250 opts['file'] = True
250 opts['file'] = True
251
251
252 datefunc = ui.quiet and util.shortdate or util.datestr
252 datefunc = ui.quiet and util.shortdate or util.datestr
253 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
253 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
254
254
255 if not pats:
255 if not pats:
256 raise util.Abort(_('at least one filename or pattern is required'))
256 raise util.Abort(_('at least one filename or pattern is required'))
257
257
258 hexfn = ui.debugflag and hex or short
258 hexfn = ui.debugflag and hex or short
259
259
260 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
260 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
261 ('number', ' ', lambda x: str(x[0].rev())),
261 ('number', ' ', lambda x: str(x[0].rev())),
262 ('changeset', ' ', lambda x: hexfn(x[0].node())),
262 ('changeset', ' ', lambda x: hexfn(x[0].node())),
263 ('date', ' ', getdate),
263 ('date', ' ', getdate),
264 ('file', ' ', lambda x: x[0].path()),
264 ('file', ' ', lambda x: x[0].path()),
265 ('line_number', ':', lambda x: str(x[1])),
265 ('line_number', ':', lambda x: str(x[1])),
266 ]
266 ]
267
267
268 if (not opts.get('user') and not opts.get('changeset')
268 if (not opts.get('user') and not opts.get('changeset')
269 and not opts.get('date') and not opts.get('file')):
269 and not opts.get('date') and not opts.get('file')):
270 opts['number'] = True
270 opts['number'] = True
271
271
272 linenumber = opts.get('line_number') is not None
272 linenumber = opts.get('line_number') is not None
273 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
273 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
274 raise util.Abort(_('at least one of -n/-c is required for -l'))
274 raise util.Abort(_('at least one of -n/-c is required for -l'))
275
275
276 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
276 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
277 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
277 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
278
278
279 def bad(x, y):
279 def bad(x, y):
280 raise util.Abort("%s: %s" % (x, y))
280 raise util.Abort("%s: %s" % (x, y))
281
281
282 ctx = scmutil.revsingle(repo, opts.get('rev'))
282 ctx = scmutil.revsingle(repo, opts.get('rev'))
283 m = scmutil.match(ctx, pats, opts)
283 m = scmutil.match(ctx, pats, opts)
284 m.bad = bad
284 m.bad = bad
285 follow = not opts.get('no_follow')
285 follow = not opts.get('no_follow')
286 diffopts = patch.diffopts(ui, opts, section='annotate')
286 diffopts = patch.diffopts(ui, opts, section='annotate')
287 for abs in ctx.walk(m):
287 for abs in ctx.walk(m):
288 fctx = ctx[abs]
288 fctx = ctx[abs]
289 if not opts.get('text') and util.binary(fctx.data()):
289 if not opts.get('text') and util.binary(fctx.data()):
290 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
290 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
291 continue
291 continue
292
292
293 lines = fctx.annotate(follow=follow, linenumber=linenumber,
293 lines = fctx.annotate(follow=follow, linenumber=linenumber,
294 diffopts=diffopts)
294 diffopts=diffopts)
295 pieces = []
295 pieces = []
296
296
297 for f, sep in funcmap:
297 for f, sep in funcmap:
298 l = [f(n) for n, dummy in lines]
298 l = [f(n) for n, dummy in lines]
299 if l:
299 if l:
300 sized = [(x, encoding.colwidth(x)) for x in l]
300 sized = [(x, encoding.colwidth(x)) for x in l]
301 ml = max([w for x, w in sized])
301 ml = max([w for x, w in sized])
302 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
302 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
303 for x, w in sized])
303 for x, w in sized])
304
304
305 if pieces:
305 if pieces:
306 for p, l in zip(zip(*pieces), lines):
306 for p, l in zip(zip(*pieces), lines):
307 ui.write("%s: %s" % ("".join(p), l[1]))
307 ui.write("%s: %s" % ("".join(p), l[1]))
308
308
309 if lines and not lines[-1][1].endswith('\n'):
309 if lines and not lines[-1][1].endswith('\n'):
310 ui.write('\n')
310 ui.write('\n')
311
311
312 @command('archive',
312 @command('archive',
313 [('', 'no-decode', None, _('do not pass files through decoders')),
313 [('', 'no-decode', None, _('do not pass files through decoders')),
314 ('p', 'prefix', '', _('directory prefix for files in archive'),
314 ('p', 'prefix', '', _('directory prefix for files in archive'),
315 _('PREFIX')),
315 _('PREFIX')),
316 ('r', 'rev', '', _('revision to distribute'), _('REV')),
316 ('r', 'rev', '', _('revision to distribute'), _('REV')),
317 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
317 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
318 ] + subrepoopts + walkopts,
318 ] + subrepoopts + walkopts,
319 _('[OPTION]... DEST'))
319 _('[OPTION]... DEST'))
320 def archive(ui, repo, dest, **opts):
320 def archive(ui, repo, dest, **opts):
321 '''create an unversioned archive of a repository revision
321 '''create an unversioned archive of a repository revision
322
322
323 By default, the revision used is the parent of the working
323 By default, the revision used is the parent of the working
324 directory; use -r/--rev to specify a different revision.
324 directory; use -r/--rev to specify a different revision.
325
325
326 The archive type is automatically detected based on file
326 The archive type is automatically detected based on file
327 extension (or override using -t/--type).
327 extension (or override using -t/--type).
328
328
329 .. container:: verbose
329 .. container:: verbose
330
330
331 Examples:
331 Examples:
332
332
333 - create a zip file containing the 1.0 release::
333 - create a zip file containing the 1.0 release::
334
334
335 hg archive -r 1.0 project-1.0.zip
335 hg archive -r 1.0 project-1.0.zip
336
336
337 - create a tarball excluding .hg files::
337 - create a tarball excluding .hg files::
338
338
339 hg archive project.tar.gz -X ".hg*"
339 hg archive project.tar.gz -X ".hg*"
340
340
341 Valid types are:
341 Valid types are:
342
342
343 :``files``: a directory full of files (default)
343 :``files``: a directory full of files (default)
344 :``tar``: tar archive, uncompressed
344 :``tar``: tar archive, uncompressed
345 :``tbz2``: tar archive, compressed using bzip2
345 :``tbz2``: tar archive, compressed using bzip2
346 :``tgz``: tar archive, compressed using gzip
346 :``tgz``: tar archive, compressed using gzip
347 :``uzip``: zip archive, uncompressed
347 :``uzip``: zip archive, uncompressed
348 :``zip``: zip archive, compressed using deflate
348 :``zip``: zip archive, compressed using deflate
349
349
350 The exact name of the destination archive or directory is given
350 The exact name of the destination archive or directory is given
351 using a format string; see :hg:`help export` for details.
351 using a format string; see :hg:`help export` for details.
352
352
353 Each member added to an archive file has a directory prefix
353 Each member added to an archive file has a directory prefix
354 prepended. Use -p/--prefix to specify a format string for the
354 prepended. Use -p/--prefix to specify a format string for the
355 prefix. The default is the basename of the archive, with suffixes
355 prefix. The default is the basename of the archive, with suffixes
356 removed.
356 removed.
357
357
358 Returns 0 on success.
358 Returns 0 on success.
359 '''
359 '''
360
360
361 ctx = scmutil.revsingle(repo, opts.get('rev'))
361 ctx = scmutil.revsingle(repo, opts.get('rev'))
362 if not ctx:
362 if not ctx:
363 raise util.Abort(_('no working directory: please specify a revision'))
363 raise util.Abort(_('no working directory: please specify a revision'))
364 node = ctx.node()
364 node = ctx.node()
365 dest = cmdutil.makefilename(repo, dest, node)
365 dest = cmdutil.makefilename(repo, dest, node)
366 if os.path.realpath(dest) == repo.root:
366 if os.path.realpath(dest) == repo.root:
367 raise util.Abort(_('repository root cannot be destination'))
367 raise util.Abort(_('repository root cannot be destination'))
368
368
369 kind = opts.get('type') or archival.guesskind(dest) or 'files'
369 kind = opts.get('type') or archival.guesskind(dest) or 'files'
370 prefix = opts.get('prefix')
370 prefix = opts.get('prefix')
371
371
372 if dest == '-':
372 if dest == '-':
373 if kind == 'files':
373 if kind == 'files':
374 raise util.Abort(_('cannot archive plain files to stdout'))
374 raise util.Abort(_('cannot archive plain files to stdout'))
375 dest = cmdutil.makefileobj(repo, dest)
375 dest = cmdutil.makefileobj(repo, dest)
376 if not prefix:
376 if not prefix:
377 prefix = os.path.basename(repo.root) + '-%h'
377 prefix = os.path.basename(repo.root) + '-%h'
378
378
379 prefix = cmdutil.makefilename(repo, prefix, node)
379 prefix = cmdutil.makefilename(repo, prefix, node)
380 matchfn = scmutil.match(ctx, [], opts)
380 matchfn = scmutil.match(ctx, [], opts)
381 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
381 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
382 matchfn, prefix, subrepos=opts.get('subrepos'))
382 matchfn, prefix, subrepos=opts.get('subrepos'))
383
383
384 @command('backout',
384 @command('backout',
385 [('', 'merge', None, _('merge with old dirstate parent after backout')),
385 [('', 'merge', None, _('merge with old dirstate parent after backout')),
386 ('', 'parent', '',
386 ('', 'parent', '',
387 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
387 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
388 ('r', 'rev', '', _('revision to backout'), _('REV')),
388 ('r', 'rev', '', _('revision to backout'), _('REV')),
389 ] + mergetoolopts + walkopts + commitopts + commitopts2,
389 ] + mergetoolopts + walkopts + commitopts + commitopts2,
390 _('[OPTION]... [-r] REV'))
390 _('[OPTION]... [-r] REV'))
391 def backout(ui, repo, node=None, rev=None, **opts):
391 def backout(ui, repo, node=None, rev=None, **opts):
392 '''reverse effect of earlier changeset
392 '''reverse effect of earlier changeset
393
393
394 Prepare a new changeset with the effect of REV undone in the
394 Prepare a new changeset with the effect of REV undone in the
395 current working directory.
395 current working directory.
396
396
397 If REV is the parent of the working directory, then this new changeset
397 If REV is the parent of the working directory, then this new changeset
398 is committed automatically. Otherwise, hg needs to merge the
398 is committed automatically. Otherwise, hg needs to merge the
399 changes and the merged result is left uncommitted.
399 changes and the merged result is left uncommitted.
400
400
401 .. note::
401 .. note::
402
402
403 backout cannot be used to fix either an unwanted or
403 backout cannot be used to fix either an unwanted or
404 incorrect merge.
404 incorrect merge.
405
405
406 .. container:: verbose
406 .. container:: verbose
407
407
408 By default, the pending changeset will have one parent,
408 By default, the pending changeset will have one parent,
409 maintaining a linear history. With --merge, the pending
409 maintaining a linear history. With --merge, the pending
410 changeset will instead have two parents: the old parent of the
410 changeset will instead have two parents: the old parent of the
411 working directory and a new child of REV that simply undoes REV.
411 working directory and a new child of REV that simply undoes REV.
412
412
413 Before version 1.7, the behavior without --merge was equivalent
413 Before version 1.7, the behavior without --merge was equivalent
414 to specifying --merge followed by :hg:`update --clean .` to
414 to specifying --merge followed by :hg:`update --clean .` to
415 cancel the merge and leave the child of REV as a head to be
415 cancel the merge and leave the child of REV as a head to be
416 merged separately.
416 merged separately.
417
417
418 See :hg:`help dates` for a list of formats valid for -d/--date.
418 See :hg:`help dates` for a list of formats valid for -d/--date.
419
419
420 Returns 0 on success.
420 Returns 0 on success.
421 '''
421 '''
422 if rev and node:
422 if rev and node:
423 raise util.Abort(_("please specify just one revision"))
423 raise util.Abort(_("please specify just one revision"))
424
424
425 if not rev:
425 if not rev:
426 rev = node
426 rev = node
427
427
428 if not rev:
428 if not rev:
429 raise util.Abort(_("please specify a revision to backout"))
429 raise util.Abort(_("please specify a revision to backout"))
430
430
431 date = opts.get('date')
431 date = opts.get('date')
432 if date:
432 if date:
433 opts['date'] = util.parsedate(date)
433 opts['date'] = util.parsedate(date)
434
434
435 cmdutil.checkunfinished(repo)
435 cmdutil.checkunfinished(repo)
436 cmdutil.bailifchanged(repo)
436 cmdutil.bailifchanged(repo)
437 node = scmutil.revsingle(repo, rev).node()
437 node = scmutil.revsingle(repo, rev).node()
438
438
439 op1, op2 = repo.dirstate.parents()
439 op1, op2 = repo.dirstate.parents()
440 a = repo.changelog.ancestor(op1, node)
440 a = repo.changelog.ancestor(op1, node)
441 if a != node:
441 if a != node:
442 raise util.Abort(_('cannot backout change that is not an ancestor'))
442 raise util.Abort(_('cannot backout change that is not an ancestor'))
443
443
444 p1, p2 = repo.changelog.parents(node)
444 p1, p2 = repo.changelog.parents(node)
445 if p1 == nullid:
445 if p1 == nullid:
446 raise util.Abort(_('cannot backout a change with no parents'))
446 raise util.Abort(_('cannot backout a change with no parents'))
447 if p2 != nullid:
447 if p2 != nullid:
448 if not opts.get('parent'):
448 if not opts.get('parent'):
449 raise util.Abort(_('cannot backout a merge changeset'))
449 raise util.Abort(_('cannot backout a merge changeset'))
450 p = repo.lookup(opts['parent'])
450 p = repo.lookup(opts['parent'])
451 if p not in (p1, p2):
451 if p not in (p1, p2):
452 raise util.Abort(_('%s is not a parent of %s') %
452 raise util.Abort(_('%s is not a parent of %s') %
453 (short(p), short(node)))
453 (short(p), short(node)))
454 parent = p
454 parent = p
455 else:
455 else:
456 if opts.get('parent'):
456 if opts.get('parent'):
457 raise util.Abort(_('cannot use --parent on non-merge changeset'))
457 raise util.Abort(_('cannot use --parent on non-merge changeset'))
458 parent = p1
458 parent = p1
459
459
460 # the backout should appear on the same branch
460 # the backout should appear on the same branch
461 wlock = repo.wlock()
461 wlock = repo.wlock()
462 try:
462 try:
463 branch = repo.dirstate.branch()
463 branch = repo.dirstate.branch()
464 bheads = repo.branchheads(branch)
464 bheads = repo.branchheads(branch)
465 rctx = scmutil.revsingle(repo, hex(parent))
465 rctx = scmutil.revsingle(repo, hex(parent))
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 'backout')
469 'backout')
470 stats = mergemod.update(repo, parent, True, True, False,
470 stats = mergemod.update(repo, parent, True, True, False,
471 node, False)
471 node, False)
472 repo.setparents(op1, op2)
472 repo.setparents(op1, op2)
473 hg._showstats(repo, stats)
473 hg._showstats(repo, stats)
474 if stats[3]:
474 if stats[3]:
475 repo.ui.status(_("use 'hg resolve' to retry unresolved "
475 repo.ui.status(_("use 'hg resolve' to retry unresolved "
476 "file merges\n"))
476 "file merges\n"))
477 else:
477 else:
478 msg = _("changeset %s backed out, "
478 msg = _("changeset %s backed out, "
479 "don't forget to commit.\n")
479 "don't forget to commit.\n")
480 ui.status(msg % short(node))
480 ui.status(msg % short(node))
481 return stats[3] > 0
481 return stats[3] > 0
482 finally:
482 finally:
483 ui.setconfig('ui', 'forcemerge', '', '')
483 ui.setconfig('ui', 'forcemerge', '', '')
484 else:
484 else:
485 hg.clean(repo, node, show_stats=False)
485 hg.clean(repo, node, show_stats=False)
486 repo.dirstate.setbranch(branch)
486 repo.dirstate.setbranch(branch)
487 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
487 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
488
488
489
489
490 e = cmdutil.commiteditor
490 e = cmdutil.commiteditor
491 if not opts['message'] and not opts['logfile']:
491 if not opts['message'] and not opts['logfile']:
492 # we don't translate commit messages
492 # we don't translate commit messages
493 opts['message'] = "Backed out changeset %s" % short(node)
493 opts['message'] = "Backed out changeset %s" % short(node)
494 e = cmdutil.commitforceeditor
494 e = cmdutil.commitforceeditor
495
495
496 def commitfunc(ui, repo, message, match, opts):
496 def commitfunc(ui, repo, message, match, opts):
497 return repo.commit(message, opts.get('user'), opts.get('date'),
497 return repo.commit(message, opts.get('user'), opts.get('date'),
498 match, editor=e)
498 match, editor=e)
499 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
499 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
500 cmdutil.commitstatus(repo, newnode, branch, bheads)
500 cmdutil.commitstatus(repo, newnode, branch, bheads)
501
501
502 def nice(node):
502 def nice(node):
503 return '%d:%s' % (repo.changelog.rev(node), short(node))
503 return '%d:%s' % (repo.changelog.rev(node), short(node))
504 ui.status(_('changeset %s backs out changeset %s\n') %
504 ui.status(_('changeset %s backs out changeset %s\n') %
505 (nice(repo.changelog.tip()), nice(node)))
505 (nice(repo.changelog.tip()), nice(node)))
506 if opts.get('merge') and op1 != node:
506 if opts.get('merge') and op1 != node:
507 hg.clean(repo, op1, show_stats=False)
507 hg.clean(repo, op1, show_stats=False)
508 ui.status(_('merging with changeset %s\n')
508 ui.status(_('merging with changeset %s\n')
509 % nice(repo.changelog.tip()))
509 % nice(repo.changelog.tip()))
510 try:
510 try:
511 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
511 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
512 'backout')
512 'backout')
513 return hg.merge(repo, hex(repo.changelog.tip()))
513 return hg.merge(repo, hex(repo.changelog.tip()))
514 finally:
514 finally:
515 ui.setconfig('ui', 'forcemerge', '', '')
515 ui.setconfig('ui', 'forcemerge', '', '')
516 finally:
516 finally:
517 wlock.release()
517 wlock.release()
518 return 0
518 return 0
519
519
520 @command('bisect',
520 @command('bisect',
521 [('r', 'reset', False, _('reset bisect state')),
521 [('r', 'reset', False, _('reset bisect state')),
522 ('g', 'good', False, _('mark changeset good')),
522 ('g', 'good', False, _('mark changeset good')),
523 ('b', 'bad', False, _('mark changeset bad')),
523 ('b', 'bad', False, _('mark changeset bad')),
524 ('s', 'skip', False, _('skip testing changeset')),
524 ('s', 'skip', False, _('skip testing changeset')),
525 ('e', 'extend', False, _('extend the bisect range')),
525 ('e', 'extend', False, _('extend the bisect range')),
526 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
526 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
527 ('U', 'noupdate', False, _('do not update to target'))],
527 ('U', 'noupdate', False, _('do not update to target'))],
528 _("[-gbsr] [-U] [-c CMD] [REV]"))
528 _("[-gbsr] [-U] [-c CMD] [REV]"))
529 def bisect(ui, repo, rev=None, extra=None, command=None,
529 def bisect(ui, repo, rev=None, extra=None, command=None,
530 reset=None, good=None, bad=None, skip=None, extend=None,
530 reset=None, good=None, bad=None, skip=None, extend=None,
531 noupdate=None):
531 noupdate=None):
532 """subdivision search of changesets
532 """subdivision search of changesets
533
533
534 This command helps to find changesets which introduce problems. To
534 This command helps to find changesets which introduce problems. To
535 use, mark the earliest changeset you know exhibits the problem as
535 use, mark the earliest changeset you know exhibits the problem as
536 bad, then mark the latest changeset which is free from the problem
536 bad, then mark the latest changeset which is free from the problem
537 as good. Bisect will update your working directory to a revision
537 as good. Bisect will update your working directory to a revision
538 for testing (unless the -U/--noupdate option is specified). Once
538 for testing (unless the -U/--noupdate option is specified). Once
539 you have performed tests, mark the working directory as good or
539 you have performed tests, mark the working directory as good or
540 bad, and bisect will either update to another candidate changeset
540 bad, and bisect will either update to another candidate changeset
541 or announce that it has found the bad revision.
541 or announce that it has found the bad revision.
542
542
543 As a shortcut, you can also use the revision argument to mark a
543 As a shortcut, you can also use the revision argument to mark a
544 revision as good or bad without checking it out first.
544 revision as good or bad without checking it out first.
545
545
546 If you supply a command, it will be used for automatic bisection.
546 If you supply a command, it will be used for automatic bisection.
547 The environment variable HG_NODE will contain the ID of the
547 The environment variable HG_NODE will contain the ID of the
548 changeset being tested. The exit status of the command will be
548 changeset being tested. The exit status of the command will be
549 used to mark revisions as good or bad: status 0 means good, 125
549 used to mark revisions as good or bad: status 0 means good, 125
550 means to skip the revision, 127 (command not found) will abort the
550 means to skip the revision, 127 (command not found) will abort the
551 bisection, and any other non-zero exit status means the revision
551 bisection, and any other non-zero exit status means the revision
552 is bad.
552 is bad.
553
553
554 .. container:: verbose
554 .. container:: verbose
555
555
556 Some examples:
556 Some examples:
557
557
558 - start a bisection with known bad revision 34, and good revision 12::
558 - start a bisection with known bad revision 34, and good revision 12::
559
559
560 hg bisect --bad 34
560 hg bisect --bad 34
561 hg bisect --good 12
561 hg bisect --good 12
562
562
563 - advance the current bisection by marking current revision as good or
563 - advance the current bisection by marking current revision as good or
564 bad::
564 bad::
565
565
566 hg bisect --good
566 hg bisect --good
567 hg bisect --bad
567 hg bisect --bad
568
568
569 - mark the current revision, or a known revision, to be skipped (e.g. if
569 - mark the current revision, or a known revision, to be skipped (e.g. if
570 that revision is not usable because of another issue)::
570 that revision is not usable because of another issue)::
571
571
572 hg bisect --skip
572 hg bisect --skip
573 hg bisect --skip 23
573 hg bisect --skip 23
574
574
575 - skip all revisions that do not touch directories ``foo`` or ``bar``::
575 - skip all revisions that do not touch directories ``foo`` or ``bar``::
576
576
577 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
577 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
578
578
579 - forget the current bisection::
579 - forget the current bisection::
580
580
581 hg bisect --reset
581 hg bisect --reset
582
582
583 - use 'make && make tests' to automatically find the first broken
583 - use 'make && make tests' to automatically find the first broken
584 revision::
584 revision::
585
585
586 hg bisect --reset
586 hg bisect --reset
587 hg bisect --bad 34
587 hg bisect --bad 34
588 hg bisect --good 12
588 hg bisect --good 12
589 hg bisect --command "make && make tests"
589 hg bisect --command "make && make tests"
590
590
591 - see all changesets whose states are already known in the current
591 - see all changesets whose states are already known in the current
592 bisection::
592 bisection::
593
593
594 hg log -r "bisect(pruned)"
594 hg log -r "bisect(pruned)"
595
595
596 - see the changeset currently being bisected (especially useful
596 - see the changeset currently being bisected (especially useful
597 if running with -U/--noupdate)::
597 if running with -U/--noupdate)::
598
598
599 hg log -r "bisect(current)"
599 hg log -r "bisect(current)"
600
600
601 - see all changesets that took part in the current bisection::
601 - see all changesets that took part in the current bisection::
602
602
603 hg log -r "bisect(range)"
603 hg log -r "bisect(range)"
604
604
605 - you can even get a nice graph::
605 - you can even get a nice graph::
606
606
607 hg log --graph -r "bisect(range)"
607 hg log --graph -r "bisect(range)"
608
608
609 See :hg:`help revsets` for more about the `bisect()` keyword.
609 See :hg:`help revsets` for more about the `bisect()` keyword.
610
610
611 Returns 0 on success.
611 Returns 0 on success.
612 """
612 """
613 def extendbisectrange(nodes, good):
613 def extendbisectrange(nodes, good):
614 # bisect is incomplete when it ends on a merge node and
614 # bisect is incomplete when it ends on a merge node and
615 # one of the parent was not checked.
615 # one of the parent was not checked.
616 parents = repo[nodes[0]].parents()
616 parents = repo[nodes[0]].parents()
617 if len(parents) > 1:
617 if len(parents) > 1:
618 side = good and state['bad'] or state['good']
618 side = good and state['bad'] or state['good']
619 num = len(set(i.node() for i in parents) & set(side))
619 num = len(set(i.node() for i in parents) & set(side))
620 if num == 1:
620 if num == 1:
621 return parents[0].ancestor(parents[1])
621 return parents[0].ancestor(parents[1])
622 return None
622 return None
623
623
624 def print_result(nodes, good):
624 def print_result(nodes, good):
625 displayer = cmdutil.show_changeset(ui, repo, {})
625 displayer = cmdutil.show_changeset(ui, repo, {})
626 if len(nodes) == 1:
626 if len(nodes) == 1:
627 # narrowed it down to a single revision
627 # narrowed it down to a single revision
628 if good:
628 if good:
629 ui.write(_("The first good revision is:\n"))
629 ui.write(_("The first good revision is:\n"))
630 else:
630 else:
631 ui.write(_("The first bad revision is:\n"))
631 ui.write(_("The first bad revision is:\n"))
632 displayer.show(repo[nodes[0]])
632 displayer.show(repo[nodes[0]])
633 extendnode = extendbisectrange(nodes, good)
633 extendnode = extendbisectrange(nodes, good)
634 if extendnode is not None:
634 if extendnode is not None:
635 ui.write(_('Not all ancestors of this changeset have been'
635 ui.write(_('Not all ancestors of this changeset have been'
636 ' checked.\nUse bisect --extend to continue the '
636 ' checked.\nUse bisect --extend to continue the '
637 'bisection from\nthe common ancestor, %s.\n')
637 'bisection from\nthe common ancestor, %s.\n')
638 % extendnode)
638 % extendnode)
639 else:
639 else:
640 # multiple possible revisions
640 # multiple possible revisions
641 if good:
641 if good:
642 ui.write(_("Due to skipped revisions, the first "
642 ui.write(_("Due to skipped revisions, the first "
643 "good revision could be any of:\n"))
643 "good revision could be any of:\n"))
644 else:
644 else:
645 ui.write(_("Due to skipped revisions, the first "
645 ui.write(_("Due to skipped revisions, the first "
646 "bad revision could be any of:\n"))
646 "bad revision could be any of:\n"))
647 for n in nodes:
647 for n in nodes:
648 displayer.show(repo[n])
648 displayer.show(repo[n])
649 displayer.close()
649 displayer.close()
650
650
651 def check_state(state, interactive=True):
651 def check_state(state, interactive=True):
652 if not state['good'] or not state['bad']:
652 if not state['good'] or not state['bad']:
653 if (good or bad or skip or reset) and interactive:
653 if (good or bad or skip or reset) and interactive:
654 return
654 return
655 if not state['good']:
655 if not state['good']:
656 raise util.Abort(_('cannot bisect (no known good revisions)'))
656 raise util.Abort(_('cannot bisect (no known good revisions)'))
657 else:
657 else:
658 raise util.Abort(_('cannot bisect (no known bad revisions)'))
658 raise util.Abort(_('cannot bisect (no known bad revisions)'))
659 return True
659 return True
660
660
661 # backward compatibility
661 # backward compatibility
662 if rev in "good bad reset init".split():
662 if rev in "good bad reset init".split():
663 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
663 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
664 cmd, rev, extra = rev, extra, None
664 cmd, rev, extra = rev, extra, None
665 if cmd == "good":
665 if cmd == "good":
666 good = True
666 good = True
667 elif cmd == "bad":
667 elif cmd == "bad":
668 bad = True
668 bad = True
669 else:
669 else:
670 reset = True
670 reset = True
671 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
671 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
672 raise util.Abort(_('incompatible arguments'))
672 raise util.Abort(_('incompatible arguments'))
673
673
674 cmdutil.checkunfinished(repo)
674 cmdutil.checkunfinished(repo)
675
675
676 if reset:
676 if reset:
677 p = repo.join("bisect.state")
677 p = repo.join("bisect.state")
678 if os.path.exists(p):
678 if os.path.exists(p):
679 os.unlink(p)
679 os.unlink(p)
680 return
680 return
681
681
682 state = hbisect.load_state(repo)
682 state = hbisect.load_state(repo)
683
683
684 if command:
684 if command:
685 changesets = 1
685 changesets = 1
686 if noupdate:
686 if noupdate:
687 try:
687 try:
688 node = state['current'][0]
688 node = state['current'][0]
689 except LookupError:
689 except LookupError:
690 raise util.Abort(_('current bisect revision is unknown - '
690 raise util.Abort(_('current bisect revision is unknown - '
691 'start a new bisect to fix'))
691 'start a new bisect to fix'))
692 else:
692 else:
693 node, p2 = repo.dirstate.parents()
693 node, p2 = repo.dirstate.parents()
694 if p2 != nullid:
694 if p2 != nullid:
695 raise util.Abort(_('current bisect revision is a merge'))
695 raise util.Abort(_('current bisect revision is a merge'))
696 try:
696 try:
697 while changesets:
697 while changesets:
698 # update state
698 # update state
699 state['current'] = [node]
699 state['current'] = [node]
700 hbisect.save_state(repo, state)
700 hbisect.save_state(repo, state)
701 status = util.system(command,
701 status = util.system(command,
702 environ={'HG_NODE': hex(node)},
702 environ={'HG_NODE': hex(node)},
703 out=ui.fout)
703 out=ui.fout)
704 if status == 125:
704 if status == 125:
705 transition = "skip"
705 transition = "skip"
706 elif status == 0:
706 elif status == 0:
707 transition = "good"
707 transition = "good"
708 # status < 0 means process was killed
708 # status < 0 means process was killed
709 elif status == 127:
709 elif status == 127:
710 raise util.Abort(_("failed to execute %s") % command)
710 raise util.Abort(_("failed to execute %s") % command)
711 elif status < 0:
711 elif status < 0:
712 raise util.Abort(_("%s killed") % command)
712 raise util.Abort(_("%s killed") % command)
713 else:
713 else:
714 transition = "bad"
714 transition = "bad"
715 ctx = scmutil.revsingle(repo, rev, node)
715 ctx = scmutil.revsingle(repo, rev, node)
716 rev = None # clear for future iterations
716 rev = None # clear for future iterations
717 state[transition].append(ctx.node())
717 state[transition].append(ctx.node())
718 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
718 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
719 check_state(state, interactive=False)
719 check_state(state, interactive=False)
720 # bisect
720 # bisect
721 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
721 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
722 # update to next check
722 # update to next check
723 node = nodes[0]
723 node = nodes[0]
724 if not noupdate:
724 if not noupdate:
725 cmdutil.bailifchanged(repo)
725 cmdutil.bailifchanged(repo)
726 hg.clean(repo, node, show_stats=False)
726 hg.clean(repo, node, show_stats=False)
727 finally:
727 finally:
728 state['current'] = [node]
728 state['current'] = [node]
729 hbisect.save_state(repo, state)
729 hbisect.save_state(repo, state)
730 print_result(nodes, bgood)
730 print_result(nodes, bgood)
731 return
731 return
732
732
733 # update state
733 # update state
734
734
735 if rev:
735 if rev:
736 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
736 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
737 else:
737 else:
738 nodes = [repo.lookup('.')]
738 nodes = [repo.lookup('.')]
739
739
740 if good or bad or skip:
740 if good or bad or skip:
741 if good:
741 if good:
742 state['good'] += nodes
742 state['good'] += nodes
743 elif bad:
743 elif bad:
744 state['bad'] += nodes
744 state['bad'] += nodes
745 elif skip:
745 elif skip:
746 state['skip'] += nodes
746 state['skip'] += nodes
747 hbisect.save_state(repo, state)
747 hbisect.save_state(repo, state)
748
748
749 if not check_state(state):
749 if not check_state(state):
750 return
750 return
751
751
752 # actually bisect
752 # actually bisect
753 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
753 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
754 if extend:
754 if extend:
755 if not changesets:
755 if not changesets:
756 extendnode = extendbisectrange(nodes, good)
756 extendnode = extendbisectrange(nodes, good)
757 if extendnode is not None:
757 if extendnode is not None:
758 ui.write(_("Extending search to changeset %d:%s\n"
758 ui.write(_("Extending search to changeset %d:%s\n"
759 % (extendnode.rev(), extendnode)))
759 % (extendnode.rev(), extendnode)))
760 state['current'] = [extendnode.node()]
760 state['current'] = [extendnode.node()]
761 hbisect.save_state(repo, state)
761 hbisect.save_state(repo, state)
762 if noupdate:
762 if noupdate:
763 return
763 return
764 cmdutil.bailifchanged(repo)
764 cmdutil.bailifchanged(repo)
765 return hg.clean(repo, extendnode.node())
765 return hg.clean(repo, extendnode.node())
766 raise util.Abort(_("nothing to extend"))
766 raise util.Abort(_("nothing to extend"))
767
767
768 if changesets == 0:
768 if changesets == 0:
769 print_result(nodes, good)
769 print_result(nodes, good)
770 else:
770 else:
771 assert len(nodes) == 1 # only a single node can be tested next
771 assert len(nodes) == 1 # only a single node can be tested next
772 node = nodes[0]
772 node = nodes[0]
773 # compute the approximate number of remaining tests
773 # compute the approximate number of remaining tests
774 tests, size = 0, 2
774 tests, size = 0, 2
775 while size <= changesets:
775 while size <= changesets:
776 tests, size = tests + 1, size * 2
776 tests, size = tests + 1, size * 2
777 rev = repo.changelog.rev(node)
777 rev = repo.changelog.rev(node)
778 ui.write(_("Testing changeset %d:%s "
778 ui.write(_("Testing changeset %d:%s "
779 "(%d changesets remaining, ~%d tests)\n")
779 "(%d changesets remaining, ~%d tests)\n")
780 % (rev, short(node), changesets, tests))
780 % (rev, short(node), changesets, tests))
781 state['current'] = [node]
781 state['current'] = [node]
782 hbisect.save_state(repo, state)
782 hbisect.save_state(repo, state)
783 if not noupdate:
783 if not noupdate:
784 cmdutil.bailifchanged(repo)
784 cmdutil.bailifchanged(repo)
785 return hg.clean(repo, node)
785 return hg.clean(repo, node)
786
786
787 @command('bookmarks|bookmark',
787 @command('bookmarks|bookmark',
788 [('f', 'force', False, _('force')),
788 [('f', 'force', False, _('force')),
789 ('r', 'rev', '', _('revision'), _('REV')),
789 ('r', 'rev', '', _('revision'), _('REV')),
790 ('d', 'delete', False, _('delete a given bookmark')),
790 ('d', 'delete', False, _('delete a given bookmark')),
791 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
791 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
792 ('i', 'inactive', False, _('mark a bookmark inactive'))],
792 ('i', 'inactive', False, _('mark a bookmark inactive'))],
793 _('hg bookmarks [OPTIONS]... [NAME]...'))
793 _('hg bookmarks [OPTIONS]... [NAME]...'))
794 def bookmark(ui, repo, *names, **opts):
794 def bookmark(ui, repo, *names, **opts):
795 '''track a line of development with movable markers
795 '''track a line of development with movable markers
796
796
797 Bookmarks are pointers to certain commits that move when committing.
797 Bookmarks are pointers to certain commits that move when committing.
798 Bookmarks are local. They can be renamed, copied and deleted. It is
798 Bookmarks are local. They can be renamed, copied and deleted. It is
799 possible to use :hg:`merge NAME` to merge from a given bookmark, and
799 possible to use :hg:`merge NAME` to merge from a given bookmark, and
800 :hg:`update NAME` to update to a given bookmark.
800 :hg:`update NAME` to update to a given bookmark.
801
801
802 You can use :hg:`bookmark NAME` to set a bookmark on the working
802 You can use :hg:`bookmark NAME` to set a bookmark on the working
803 directory's parent revision with the given name. If you specify
803 directory's parent revision with the given name. If you specify
804 a revision using -r REV (where REV may be an existing bookmark),
804 a revision using -r REV (where REV may be an existing bookmark),
805 the bookmark is assigned to that revision.
805 the bookmark is assigned to that revision.
806
806
807 Bookmarks can be pushed and pulled between repositories (see :hg:`help
807 Bookmarks can be pushed and pulled between repositories (see :hg:`help
808 push` and :hg:`help pull`). This requires both the local and remote
808 push` and :hg:`help pull`). This requires both the local and remote
809 repositories to support bookmarks. For versions prior to 1.8, this means
809 repositories to support bookmarks. For versions prior to 1.8, this means
810 the bookmarks extension must be enabled.
810 the bookmarks extension must be enabled.
811
811
812 If you set a bookmark called '@', new clones of the repository will
812 If you set a bookmark called '@', new clones of the repository will
813 have that revision checked out (and the bookmark made active) by
813 have that revision checked out (and the bookmark made active) by
814 default.
814 default.
815
815
816 With -i/--inactive, the new bookmark will not be made the active
816 With -i/--inactive, the new bookmark will not be made the active
817 bookmark. If -r/--rev is given, the new bookmark will not be made
817 bookmark. If -r/--rev is given, the new bookmark will not be made
818 active even if -i/--inactive is not given. If no NAME is given, the
818 active even if -i/--inactive is not given. If no NAME is given, the
819 current active bookmark will be marked inactive.
819 current active bookmark will be marked inactive.
820 '''
820 '''
821 force = opts.get('force')
821 force = opts.get('force')
822 rev = opts.get('rev')
822 rev = opts.get('rev')
823 delete = opts.get('delete')
823 delete = opts.get('delete')
824 rename = opts.get('rename')
824 rename = opts.get('rename')
825 inactive = opts.get('inactive')
825 inactive = opts.get('inactive')
826
826
827 def checkformat(mark):
827 def checkformat(mark):
828 mark = mark.strip()
828 mark = mark.strip()
829 if not mark:
829 if not mark:
830 raise util.Abort(_("bookmark names cannot consist entirely of "
830 raise util.Abort(_("bookmark names cannot consist entirely of "
831 "whitespace"))
831 "whitespace"))
832 scmutil.checknewlabel(repo, mark, 'bookmark')
832 scmutil.checknewlabel(repo, mark, 'bookmark')
833 return mark
833 return mark
834
834
835 def checkconflict(repo, mark, cur, force=False, target=None):
835 def checkconflict(repo, mark, cur, force=False, target=None):
836 if mark in marks and not force:
836 if mark in marks and not force:
837 if target:
837 if target:
838 if marks[mark] == target and target == cur:
838 if marks[mark] == target and target == cur:
839 # re-activating a bookmark
839 # re-activating a bookmark
840 return
840 return
841 anc = repo.changelog.ancestors([repo[target].rev()])
841 anc = repo.changelog.ancestors([repo[target].rev()])
842 bmctx = repo[marks[mark]]
842 bmctx = repo[marks[mark]]
843 divs = [repo[b].node() for b in marks
843 divs = [repo[b].node() for b in marks
844 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
844 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
845
845
846 # allow resolving a single divergent bookmark even if moving
846 # allow resolving a single divergent bookmark even if moving
847 # the bookmark across branches when a revision is specified
847 # the bookmark across branches when a revision is specified
848 # that contains a divergent bookmark
848 # that contains a divergent bookmark
849 if bmctx.rev() not in anc and target in divs:
849 if bmctx.rev() not in anc and target in divs:
850 bookmarks.deletedivergent(repo, [target], mark)
850 bookmarks.deletedivergent(repo, [target], mark)
851 return
851 return
852
852
853 deletefrom = [b for b in divs
853 deletefrom = [b for b in divs
854 if repo[b].rev() in anc or b == target]
854 if repo[b].rev() in anc or b == target]
855 bookmarks.deletedivergent(repo, deletefrom, mark)
855 bookmarks.deletedivergent(repo, deletefrom, mark)
856 if bookmarks.validdest(repo, bmctx, repo[target]):
856 if bookmarks.validdest(repo, bmctx, repo[target]):
857 ui.status(_("moving bookmark '%s' forward from %s\n") %
857 ui.status(_("moving bookmark '%s' forward from %s\n") %
858 (mark, short(bmctx.node())))
858 (mark, short(bmctx.node())))
859 return
859 return
860 raise util.Abort(_("bookmark '%s' already exists "
860 raise util.Abort(_("bookmark '%s' already exists "
861 "(use -f to force)") % mark)
861 "(use -f to force)") % mark)
862 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
862 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
863 and not force):
863 and not force):
864 raise util.Abort(
864 raise util.Abort(
865 _("a bookmark cannot have the name of an existing branch"))
865 _("a bookmark cannot have the name of an existing branch"))
866
866
867 if delete and rename:
867 if delete and rename:
868 raise util.Abort(_("--delete and --rename are incompatible"))
868 raise util.Abort(_("--delete and --rename are incompatible"))
869 if delete and rev:
869 if delete and rev:
870 raise util.Abort(_("--rev is incompatible with --delete"))
870 raise util.Abort(_("--rev is incompatible with --delete"))
871 if rename and rev:
871 if rename and rev:
872 raise util.Abort(_("--rev is incompatible with --rename"))
872 raise util.Abort(_("--rev is incompatible with --rename"))
873 if not names and (delete or rev):
873 if not names and (delete or rev):
874 raise util.Abort(_("bookmark name required"))
874 raise util.Abort(_("bookmark name required"))
875
875
876 if delete or rename or names or inactive:
876 if delete or rename or names or inactive:
877 wlock = repo.wlock()
877 wlock = repo.wlock()
878 try:
878 try:
879 cur = repo.changectx('.').node()
879 cur = repo.changectx('.').node()
880 marks = repo._bookmarks
880 marks = repo._bookmarks
881 if delete:
881 if delete:
882 for mark in names:
882 for mark in names:
883 if mark not in marks:
883 if mark not in marks:
884 raise util.Abort(_("bookmark '%s' does not exist") %
884 raise util.Abort(_("bookmark '%s' does not exist") %
885 mark)
885 mark)
886 if mark == repo._bookmarkcurrent:
886 if mark == repo._bookmarkcurrent:
887 bookmarks.unsetcurrent(repo)
887 bookmarks.unsetcurrent(repo)
888 del marks[mark]
888 del marks[mark]
889 marks.write()
889 marks.write()
890
890
891 elif rename:
891 elif rename:
892 if not names:
892 if not names:
893 raise util.Abort(_("new bookmark name required"))
893 raise util.Abort(_("new bookmark name required"))
894 elif len(names) > 1:
894 elif len(names) > 1:
895 raise util.Abort(_("only one new bookmark name allowed"))
895 raise util.Abort(_("only one new bookmark name allowed"))
896 mark = checkformat(names[0])
896 mark = checkformat(names[0])
897 if rename not in marks:
897 if rename not in marks:
898 raise util.Abort(_("bookmark '%s' does not exist") % rename)
898 raise util.Abort(_("bookmark '%s' does not exist") % rename)
899 checkconflict(repo, mark, cur, force)
899 checkconflict(repo, mark, cur, force)
900 marks[mark] = marks[rename]
900 marks[mark] = marks[rename]
901 if repo._bookmarkcurrent == rename and not inactive:
901 if repo._bookmarkcurrent == rename and not inactive:
902 bookmarks.setcurrent(repo, mark)
902 bookmarks.setcurrent(repo, mark)
903 del marks[rename]
903 del marks[rename]
904 marks.write()
904 marks.write()
905
905
906 elif names:
906 elif names:
907 newact = None
907 newact = None
908 for mark in names:
908 for mark in names:
909 mark = checkformat(mark)
909 mark = checkformat(mark)
910 if newact is None:
910 if newact is None:
911 newact = mark
911 newact = mark
912 if inactive and mark == repo._bookmarkcurrent:
912 if inactive and mark == repo._bookmarkcurrent:
913 bookmarks.unsetcurrent(repo)
913 bookmarks.unsetcurrent(repo)
914 return
914 return
915 tgt = cur
915 tgt = cur
916 if rev:
916 if rev:
917 tgt = scmutil.revsingle(repo, rev).node()
917 tgt = scmutil.revsingle(repo, rev).node()
918 checkconflict(repo, mark, cur, force, tgt)
918 checkconflict(repo, mark, cur, force, tgt)
919 marks[mark] = tgt
919 marks[mark] = tgt
920 if not inactive and cur == marks[newact] and not rev:
920 if not inactive and cur == marks[newact] and not rev:
921 bookmarks.setcurrent(repo, newact)
921 bookmarks.setcurrent(repo, newact)
922 elif cur != tgt and newact == repo._bookmarkcurrent:
922 elif cur != tgt and newact == repo._bookmarkcurrent:
923 bookmarks.unsetcurrent(repo)
923 bookmarks.unsetcurrent(repo)
924 marks.write()
924 marks.write()
925
925
926 elif inactive:
926 elif inactive:
927 if len(marks) == 0:
927 if len(marks) == 0:
928 ui.status(_("no bookmarks set\n"))
928 ui.status(_("no bookmarks set\n"))
929 elif not repo._bookmarkcurrent:
929 elif not repo._bookmarkcurrent:
930 ui.status(_("no active bookmark\n"))
930 ui.status(_("no active bookmark\n"))
931 else:
931 else:
932 bookmarks.unsetcurrent(repo)
932 bookmarks.unsetcurrent(repo)
933 finally:
933 finally:
934 wlock.release()
934 wlock.release()
935 else: # show bookmarks
935 else: # show bookmarks
936 hexfn = ui.debugflag and hex or short
936 hexfn = ui.debugflag and hex or short
937 marks = repo._bookmarks
937 marks = repo._bookmarks
938 if len(marks) == 0:
938 if len(marks) == 0:
939 ui.status(_("no bookmarks set\n"))
939 ui.status(_("no bookmarks set\n"))
940 else:
940 else:
941 for bmark, n in sorted(marks.iteritems()):
941 for bmark, n in sorted(marks.iteritems()):
942 current = repo._bookmarkcurrent
942 current = repo._bookmarkcurrent
943 if bmark == current:
943 if bmark == current:
944 prefix, label = '*', 'bookmarks.current'
944 prefix, label = '*', 'bookmarks.current'
945 else:
945 else:
946 prefix, label = ' ', ''
946 prefix, label = ' ', ''
947
947
948 if ui.quiet:
948 if ui.quiet:
949 ui.write("%s\n" % bmark, label=label)
949 ui.write("%s\n" % bmark, label=label)
950 else:
950 else:
951 ui.write(" %s %-25s %d:%s\n" % (
951 ui.write(" %s %-25s %d:%s\n" % (
952 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
952 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
953 label=label)
953 label=label)
954
954
955 @command('branch',
955 @command('branch',
956 [('f', 'force', None,
956 [('f', 'force', None,
957 _('set branch name even if it shadows an existing branch')),
957 _('set branch name even if it shadows an existing branch')),
958 ('C', 'clean', None, _('reset branch name to parent branch name'))],
958 ('C', 'clean', None, _('reset branch name to parent branch name'))],
959 _('[-fC] [NAME]'))
959 _('[-fC] [NAME]'))
960 def branch(ui, repo, label=None, **opts):
960 def branch(ui, repo, label=None, **opts):
961 """set or show the current branch name
961 """set or show the current branch name
962
962
963 .. note::
963 .. note::
964
964
965 Branch names are permanent and global. Use :hg:`bookmark` to create a
965 Branch names are permanent and global. Use :hg:`bookmark` to create a
966 light-weight bookmark instead. See :hg:`help glossary` for more
966 light-weight bookmark instead. See :hg:`help glossary` for more
967 information about named branches and bookmarks.
967 information about named branches and bookmarks.
968
968
969 With no argument, show the current branch name. With one argument,
969 With no argument, show the current branch name. With one argument,
970 set the working directory branch name (the branch will not exist
970 set the working directory branch name (the branch will not exist
971 in the repository until the next commit). Standard practice
971 in the repository until the next commit). Standard practice
972 recommends that primary development take place on the 'default'
972 recommends that primary development take place on the 'default'
973 branch.
973 branch.
974
974
975 Unless -f/--force is specified, branch will not let you set a
975 Unless -f/--force is specified, branch will not let you set a
976 branch name that already exists, even if it's inactive.
976 branch name that already exists, even if it's inactive.
977
977
978 Use -C/--clean to reset the working directory branch to that of
978 Use -C/--clean to reset the working directory branch to that of
979 the parent of the working directory, negating a previous branch
979 the parent of the working directory, negating a previous branch
980 change.
980 change.
981
981
982 Use the command :hg:`update` to switch to an existing branch. Use
982 Use the command :hg:`update` to switch to an existing branch. Use
983 :hg:`commit --close-branch` to mark this branch as closed.
983 :hg:`commit --close-branch` to mark this branch as closed.
984
984
985 Returns 0 on success.
985 Returns 0 on success.
986 """
986 """
987 if label:
987 if label:
988 label = label.strip()
988 label = label.strip()
989
989
990 if not opts.get('clean') and not label:
990 if not opts.get('clean') and not label:
991 ui.write("%s\n" % repo.dirstate.branch())
991 ui.write("%s\n" % repo.dirstate.branch())
992 return
992 return
993
993
994 wlock = repo.wlock()
994 wlock = repo.wlock()
995 try:
995 try:
996 if opts.get('clean'):
996 if opts.get('clean'):
997 label = repo[None].p1().branch()
997 label = repo[None].p1().branch()
998 repo.dirstate.setbranch(label)
998 repo.dirstate.setbranch(label)
999 ui.status(_('reset working directory to branch %s\n') % label)
999 ui.status(_('reset working directory to branch %s\n') % label)
1000 elif label:
1000 elif label:
1001 if not opts.get('force') and label in repo.branchmap():
1001 if not opts.get('force') and label in repo.branchmap():
1002 if label not in [p.branch() for p in repo.parents()]:
1002 if label not in [p.branch() for p in repo.parents()]:
1003 raise util.Abort(_('a branch of the same name already'
1003 raise util.Abort(_('a branch of the same name already'
1004 ' exists'),
1004 ' exists'),
1005 # i18n: "it" refers to an existing branch
1005 # i18n: "it" refers to an existing branch
1006 hint=_("use 'hg update' to switch to it"))
1006 hint=_("use 'hg update' to switch to it"))
1007 scmutil.checknewlabel(repo, label, 'branch')
1007 scmutil.checknewlabel(repo, label, 'branch')
1008 repo.dirstate.setbranch(label)
1008 repo.dirstate.setbranch(label)
1009 ui.status(_('marked working directory as branch %s\n') % label)
1009 ui.status(_('marked working directory as branch %s\n') % label)
1010 ui.status(_('(branches are permanent and global, '
1010 ui.status(_('(branches are permanent and global, '
1011 'did you want a bookmark?)\n'))
1011 'did you want a bookmark?)\n'))
1012 finally:
1012 finally:
1013 wlock.release()
1013 wlock.release()
1014
1014
1015 @command('branches',
1015 @command('branches',
1016 [('a', 'active', False, _('show only branches that have unmerged heads')),
1016 [('a', 'active', False, _('show only branches that have unmerged heads')),
1017 ('c', 'closed', False, _('show normal and closed branches'))],
1017 ('c', 'closed', False, _('show normal and closed branches'))],
1018 _('[-ac]'))
1018 _('[-ac]'))
1019 def branches(ui, repo, active=False, closed=False):
1019 def branches(ui, repo, active=False, closed=False):
1020 """list repository named branches
1020 """list repository named branches
1021
1021
1022 List the repository's named branches, indicating which ones are
1022 List the repository's named branches, indicating which ones are
1023 inactive. If -c/--closed is specified, also list branches which have
1023 inactive. If -c/--closed is specified, also list branches which have
1024 been marked closed (see :hg:`commit --close-branch`).
1024 been marked closed (see :hg:`commit --close-branch`).
1025
1025
1026 If -a/--active is specified, only show active branches. A branch
1026 If -a/--active is specified, only show active branches. A branch
1027 is considered active if it contains repository heads.
1027 is considered active if it contains repository heads.
1028
1028
1029 Use the command :hg:`update` to switch to an existing branch.
1029 Use the command :hg:`update` to switch to an existing branch.
1030
1030
1031 Returns 0.
1031 Returns 0.
1032 """
1032 """
1033
1033
1034 hexfunc = ui.debugflag and hex or short
1034 hexfunc = ui.debugflag and hex or short
1035
1035
1036 allheads = set(repo.heads())
1036 allheads = set(repo.heads())
1037 branches = []
1037 branches = []
1038 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1038 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1039 isactive = not isclosed and bool(set(heads) & allheads)
1039 isactive = not isclosed and bool(set(heads) & allheads)
1040 branches.append((tag, repo[tip], isactive, not isclosed))
1040 branches.append((tag, repo[tip], isactive, not isclosed))
1041 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1041 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1042 reverse=True)
1042 reverse=True)
1043
1043
1044 for tag, ctx, isactive, isopen in branches:
1044 for tag, ctx, isactive, isopen in branches:
1045 if (not active) or isactive:
1045 if (not active) or isactive:
1046 if isactive:
1046 if isactive:
1047 label = 'branches.active'
1047 label = 'branches.active'
1048 notice = ''
1048 notice = ''
1049 elif not isopen:
1049 elif not isopen:
1050 if not closed:
1050 if not closed:
1051 continue
1051 continue
1052 label = 'branches.closed'
1052 label = 'branches.closed'
1053 notice = _(' (closed)')
1053 notice = _(' (closed)')
1054 else:
1054 else:
1055 label = 'branches.inactive'
1055 label = 'branches.inactive'
1056 notice = _(' (inactive)')
1056 notice = _(' (inactive)')
1057 if tag == repo.dirstate.branch():
1057 if tag == repo.dirstate.branch():
1058 label = 'branches.current'
1058 label = 'branches.current'
1059 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1059 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1060 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1060 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1061 'log.changeset changeset.%s' % ctx.phasestr())
1061 'log.changeset changeset.%s' % ctx.phasestr())
1062 labeledtag = ui.label(tag, label)
1062 labeledtag = ui.label(tag, label)
1063 if ui.quiet:
1063 if ui.quiet:
1064 ui.write("%s\n" % labeledtag)
1064 ui.write("%s\n" % labeledtag)
1065 else:
1065 else:
1066 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1066 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1067
1067
1068 @command('bundle',
1068 @command('bundle',
1069 [('f', 'force', None, _('run even when the destination is unrelated')),
1069 [('f', 'force', None, _('run even when the destination is unrelated')),
1070 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1070 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1071 _('REV')),
1071 _('REV')),
1072 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1072 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1073 _('BRANCH')),
1073 _('BRANCH')),
1074 ('', 'base', [],
1074 ('', 'base', [],
1075 _('a base changeset assumed to be available at the destination'),
1075 _('a base changeset assumed to be available at the destination'),
1076 _('REV')),
1076 _('REV')),
1077 ('a', 'all', None, _('bundle all changesets in the repository')),
1077 ('a', 'all', None, _('bundle all changesets in the repository')),
1078 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1078 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1079 ] + remoteopts,
1079 ] + remoteopts,
1080 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1080 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1081 def bundle(ui, repo, fname, dest=None, **opts):
1081 def bundle(ui, repo, fname, dest=None, **opts):
1082 """create a changegroup file
1082 """create a changegroup file
1083
1083
1084 Generate a compressed changegroup file collecting changesets not
1084 Generate a compressed changegroup file collecting changesets not
1085 known to be in another repository.
1085 known to be in another repository.
1086
1086
1087 If you omit the destination repository, then hg assumes the
1087 If you omit the destination repository, then hg assumes the
1088 destination will have all the nodes you specify with --base
1088 destination will have all the nodes you specify with --base
1089 parameters. To create a bundle containing all changesets, use
1089 parameters. To create a bundle containing all changesets, use
1090 -a/--all (or --base null).
1090 -a/--all (or --base null).
1091
1091
1092 You can change compression method with the -t/--type option.
1092 You can change compression method with the -t/--type option.
1093 The available compression methods are: none, bzip2, and
1093 The available compression methods are: none, bzip2, and
1094 gzip (by default, bundles are compressed using bzip2).
1094 gzip (by default, bundles are compressed using bzip2).
1095
1095
1096 The bundle file can then be transferred using conventional means
1096 The bundle file can then be transferred using conventional means
1097 and applied to another repository with the unbundle or pull
1097 and applied to another repository with the unbundle or pull
1098 command. This is useful when direct push and pull are not
1098 command. This is useful when direct push and pull are not
1099 available or when exporting an entire repository is undesirable.
1099 available or when exporting an entire repository is undesirable.
1100
1100
1101 Applying bundles preserves all changeset contents including
1101 Applying bundles preserves all changeset contents including
1102 permissions, copy/rename information, and revision history.
1102 permissions, copy/rename information, and revision history.
1103
1103
1104 Returns 0 on success, 1 if no changes found.
1104 Returns 0 on success, 1 if no changes found.
1105 """
1105 """
1106 revs = None
1106 revs = None
1107 if 'rev' in opts:
1107 if 'rev' in opts:
1108 revs = scmutil.revrange(repo, opts['rev'])
1108 revs = scmutil.revrange(repo, opts['rev'])
1109
1109
1110 bundletype = opts.get('type', 'bzip2').lower()
1110 bundletype = opts.get('type', 'bzip2').lower()
1111 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1111 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1112 bundletype = btypes.get(bundletype)
1112 bundletype = btypes.get(bundletype)
1113 if bundletype not in changegroup.bundletypes:
1113 if bundletype not in changegroup.bundletypes:
1114 raise util.Abort(_('unknown bundle type specified with --type'))
1114 raise util.Abort(_('unknown bundle type specified with --type'))
1115
1115
1116 if opts.get('all'):
1116 if opts.get('all'):
1117 base = ['null']
1117 base = ['null']
1118 else:
1118 else:
1119 base = scmutil.revrange(repo, opts.get('base'))
1119 base = scmutil.revrange(repo, opts.get('base'))
1120 # TODO: get desired bundlecaps from command line.
1120 # TODO: get desired bundlecaps from command line.
1121 bundlecaps = None
1121 bundlecaps = None
1122 if base:
1122 if base:
1123 if dest:
1123 if dest:
1124 raise util.Abort(_("--base is incompatible with specifying "
1124 raise util.Abort(_("--base is incompatible with specifying "
1125 "a destination"))
1125 "a destination"))
1126 common = [repo.lookup(rev) for rev in base]
1126 common = [repo.lookup(rev) for rev in base]
1127 heads = revs and map(repo.lookup, revs) or revs
1127 heads = revs and map(repo.lookup, revs) or revs
1128 cg = repo.getbundle('bundle', heads=heads, common=common,
1128 cg = repo.getbundle('bundle', heads=heads, common=common,
1129 bundlecaps=bundlecaps)
1129 bundlecaps=bundlecaps)
1130 outgoing = None
1130 outgoing = None
1131 else:
1131 else:
1132 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1132 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1133 dest, branches = hg.parseurl(dest, opts.get('branch'))
1133 dest, branches = hg.parseurl(dest, opts.get('branch'))
1134 other = hg.peer(repo, opts, dest)
1134 other = hg.peer(repo, opts, dest)
1135 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1135 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1136 heads = revs and map(repo.lookup, revs) or revs
1136 heads = revs and map(repo.lookup, revs) or revs
1137 outgoing = discovery.findcommonoutgoing(repo, other,
1137 outgoing = discovery.findcommonoutgoing(repo, other,
1138 onlyheads=heads,
1138 onlyheads=heads,
1139 force=opts.get('force'),
1139 force=opts.get('force'),
1140 portable=True)
1140 portable=True)
1141 cg = repo.getlocalbundle('bundle', outgoing, bundlecaps)
1141 cg = repo.getlocalbundle('bundle', outgoing, bundlecaps)
1142 if not cg:
1142 if not cg:
1143 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1143 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1144 return 1
1144 return 1
1145
1145
1146 changegroup.writebundle(cg, fname, bundletype)
1146 changegroup.writebundle(cg, fname, bundletype)
1147
1147
1148 @command('cat',
1148 @command('cat',
1149 [('o', 'output', '',
1149 [('o', 'output', '',
1150 _('print output to file with formatted name'), _('FORMAT')),
1150 _('print output to file with formatted name'), _('FORMAT')),
1151 ('r', 'rev', '', _('print the given revision'), _('REV')),
1151 ('r', 'rev', '', _('print the given revision'), _('REV')),
1152 ('', 'decode', None, _('apply any matching decode filter')),
1152 ('', 'decode', None, _('apply any matching decode filter')),
1153 ] + walkopts,
1153 ] + walkopts,
1154 _('[OPTION]... FILE...'))
1154 _('[OPTION]... FILE...'))
1155 def cat(ui, repo, file1, *pats, **opts):
1155 def cat(ui, repo, file1, *pats, **opts):
1156 """output the current or given revision of files
1156 """output the current or given revision of files
1157
1157
1158 Print the specified files as they were at the given revision. If
1158 Print the specified files as they were at the given revision. If
1159 no revision is given, the parent of the working directory is used.
1159 no revision is given, the parent of the working directory is used.
1160
1160
1161 Output may be to a file, in which case the name of the file is
1161 Output may be to a file, in which case the name of the file is
1162 given using a format string. The formatting rules are the same as
1162 given using a format string. The formatting rules are the same as
1163 for the export command, with the following additions:
1163 for the export command, with the following additions:
1164
1164
1165 :``%s``: basename of file being printed
1165 :``%s``: basename of file being printed
1166 :``%d``: dirname of file being printed, or '.' if in repository root
1166 :``%d``: dirname of file being printed, or '.' if in repository root
1167 :``%p``: root-relative path name of file being printed
1167 :``%p``: root-relative path name of file being printed
1168
1168
1169 Returns 0 on success.
1169 Returns 0 on success.
1170 """
1170 """
1171 ctx = scmutil.revsingle(repo, opts.get('rev'))
1171 ctx = scmutil.revsingle(repo, opts.get('rev'))
1172 err = 1
1172 err = 1
1173 m = scmutil.match(ctx, (file1,) + pats, opts)
1173 m = scmutil.match(ctx, (file1,) + pats, opts)
1174
1174
1175 def write(path):
1175 def write(path):
1176 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1176 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
1177 pathname=path)
1177 pathname=path)
1178 data = ctx[path].data()
1178 data = ctx[path].data()
1179 if opts.get('decode'):
1179 if opts.get('decode'):
1180 data = repo.wwritedata(path, data)
1180 data = repo.wwritedata(path, data)
1181 fp.write(data)
1181 fp.write(data)
1182 fp.close()
1182 fp.close()
1183
1183
1184 # Automation often uses hg cat on single files, so special case it
1184 # Automation often uses hg cat on single files, so special case it
1185 # for performance to avoid the cost of parsing the manifest.
1185 # for performance to avoid the cost of parsing the manifest.
1186 if len(m.files()) == 1 and not m.anypats():
1186 if len(m.files()) == 1 and not m.anypats():
1187 file = m.files()[0]
1187 file = m.files()[0]
1188 mf = repo.manifest
1188 mf = repo.manifest
1189 mfnode = ctx._changeset[0]
1189 mfnode = ctx._changeset[0]
1190 if mf.find(mfnode, file)[0]:
1190 if mf.find(mfnode, file)[0]:
1191 write(file)
1191 write(file)
1192 return 0
1192 return 0
1193
1193
1194 for abs in ctx.walk(m):
1194 for abs in ctx.walk(m):
1195 write(abs)
1195 write(abs)
1196 err = 0
1196 err = 0
1197 return err
1197 return err
1198
1198
1199 @command('^clone',
1199 @command('^clone',
1200 [('U', 'noupdate', None,
1200 [('U', 'noupdate', None,
1201 _('the clone will include an empty working copy (only a repository)')),
1201 _('the clone will include an empty working copy (only a repository)')),
1202 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1202 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1203 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1203 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1204 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1204 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1205 ('', 'pull', None, _('use pull protocol to copy metadata')),
1205 ('', 'pull', None, _('use pull protocol to copy metadata')),
1206 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1206 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1207 ] + remoteopts,
1207 ] + remoteopts,
1208 _('[OPTION]... SOURCE [DEST]'))
1208 _('[OPTION]... SOURCE [DEST]'))
1209 def clone(ui, source, dest=None, **opts):
1209 def clone(ui, source, dest=None, **opts):
1210 """make a copy of an existing repository
1210 """make a copy of an existing repository
1211
1211
1212 Create a copy of an existing repository in a new directory.
1212 Create a copy of an existing repository in a new directory.
1213
1213
1214 If no destination directory name is specified, it defaults to the
1214 If no destination directory name is specified, it defaults to the
1215 basename of the source.
1215 basename of the source.
1216
1216
1217 The location of the source is added to the new repository's
1217 The location of the source is added to the new repository's
1218 ``.hg/hgrc`` file, as the default to be used for future pulls.
1218 ``.hg/hgrc`` file, as the default to be used for future pulls.
1219
1219
1220 Only local paths and ``ssh://`` URLs are supported as
1220 Only local paths and ``ssh://`` URLs are supported as
1221 destinations. For ``ssh://`` destinations, no working directory or
1221 destinations. For ``ssh://`` destinations, no working directory or
1222 ``.hg/hgrc`` will be created on the remote side.
1222 ``.hg/hgrc`` will be created on the remote side.
1223
1223
1224 To pull only a subset of changesets, specify one or more revisions
1224 To pull only a subset of changesets, specify one or more revisions
1225 identifiers with -r/--rev or branches with -b/--branch. The
1225 identifiers with -r/--rev or branches with -b/--branch. The
1226 resulting clone will contain only the specified changesets and
1226 resulting clone will contain only the specified changesets and
1227 their ancestors. These options (or 'clone src#rev dest') imply
1227 their ancestors. These options (or 'clone src#rev dest') imply
1228 --pull, even for local source repositories. Note that specifying a
1228 --pull, even for local source repositories. Note that specifying a
1229 tag will include the tagged changeset but not the changeset
1229 tag will include the tagged changeset but not the changeset
1230 containing the tag.
1230 containing the tag.
1231
1231
1232 If the source repository has a bookmark called '@' set, that
1232 If the source repository has a bookmark called '@' set, that
1233 revision will be checked out in the new repository by default.
1233 revision will be checked out in the new repository by default.
1234
1234
1235 To check out a particular version, use -u/--update, or
1235 To check out a particular version, use -u/--update, or
1236 -U/--noupdate to create a clone with no working directory.
1236 -U/--noupdate to create a clone with no working directory.
1237
1237
1238 .. container:: verbose
1238 .. container:: verbose
1239
1239
1240 For efficiency, hardlinks are used for cloning whenever the
1240 For efficiency, hardlinks are used for cloning whenever the
1241 source and destination are on the same filesystem (note this
1241 source and destination are on the same filesystem (note this
1242 applies only to the repository data, not to the working
1242 applies only to the repository data, not to the working
1243 directory). Some filesystems, such as AFS, implement hardlinking
1243 directory). Some filesystems, such as AFS, implement hardlinking
1244 incorrectly, but do not report errors. In these cases, use the
1244 incorrectly, but do not report errors. In these cases, use the
1245 --pull option to avoid hardlinking.
1245 --pull option to avoid hardlinking.
1246
1246
1247 In some cases, you can clone repositories and the working
1247 In some cases, you can clone repositories and the working
1248 directory using full hardlinks with ::
1248 directory using full hardlinks with ::
1249
1249
1250 $ cp -al REPO REPOCLONE
1250 $ cp -al REPO REPOCLONE
1251
1251
1252 This is the fastest way to clone, but it is not always safe. The
1252 This is the fastest way to clone, but it is not always safe. The
1253 operation is not atomic (making sure REPO is not modified during
1253 operation is not atomic (making sure REPO is not modified during
1254 the operation is up to you) and you have to make sure your
1254 the operation is up to you) and you have to make sure your
1255 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1255 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1256 so). Also, this is not compatible with certain extensions that
1256 so). Also, this is not compatible with certain extensions that
1257 place their metadata under the .hg directory, such as mq.
1257 place their metadata under the .hg directory, such as mq.
1258
1258
1259 Mercurial will update the working directory to the first applicable
1259 Mercurial will update the working directory to the first applicable
1260 revision from this list:
1260 revision from this list:
1261
1261
1262 a) null if -U or the source repository has no changesets
1262 a) null if -U or the source repository has no changesets
1263 b) if -u . and the source repository is local, the first parent of
1263 b) if -u . and the source repository is local, the first parent of
1264 the source repository's working directory
1264 the source repository's working directory
1265 c) the changeset specified with -u (if a branch name, this means the
1265 c) the changeset specified with -u (if a branch name, this means the
1266 latest head of that branch)
1266 latest head of that branch)
1267 d) the changeset specified with -r
1267 d) the changeset specified with -r
1268 e) the tipmost head specified with -b
1268 e) the tipmost head specified with -b
1269 f) the tipmost head specified with the url#branch source syntax
1269 f) the tipmost head specified with the url#branch source syntax
1270 g) the revision marked with the '@' bookmark, if present
1270 g) the revision marked with the '@' bookmark, if present
1271 h) the tipmost head of the default branch
1271 h) the tipmost head of the default branch
1272 i) tip
1272 i) tip
1273
1273
1274 Examples:
1274 Examples:
1275
1275
1276 - clone a remote repository to a new directory named hg/::
1276 - clone a remote repository to a new directory named hg/::
1277
1277
1278 hg clone http://selenic.com/hg
1278 hg clone http://selenic.com/hg
1279
1279
1280 - create a lightweight local clone::
1280 - create a lightweight local clone::
1281
1281
1282 hg clone project/ project-feature/
1282 hg clone project/ project-feature/
1283
1283
1284 - clone from an absolute path on an ssh server (note double-slash)::
1284 - clone from an absolute path on an ssh server (note double-slash)::
1285
1285
1286 hg clone ssh://user@server//home/projects/alpha/
1286 hg clone ssh://user@server//home/projects/alpha/
1287
1287
1288 - do a high-speed clone over a LAN while checking out a
1288 - do a high-speed clone over a LAN while checking out a
1289 specified version::
1289 specified version::
1290
1290
1291 hg clone --uncompressed http://server/repo -u 1.5
1291 hg clone --uncompressed http://server/repo -u 1.5
1292
1292
1293 - create a repository without changesets after a particular revision::
1293 - create a repository without changesets after a particular revision::
1294
1294
1295 hg clone -r 04e544 experimental/ good/
1295 hg clone -r 04e544 experimental/ good/
1296
1296
1297 - clone (and track) a particular named branch::
1297 - clone (and track) a particular named branch::
1298
1298
1299 hg clone http://selenic.com/hg#stable
1299 hg clone http://selenic.com/hg#stable
1300
1300
1301 See :hg:`help urls` for details on specifying URLs.
1301 See :hg:`help urls` for details on specifying URLs.
1302
1302
1303 Returns 0 on success.
1303 Returns 0 on success.
1304 """
1304 """
1305 if opts.get('noupdate') and opts.get('updaterev'):
1305 if opts.get('noupdate') and opts.get('updaterev'):
1306 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1306 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1307
1307
1308 r = hg.clone(ui, opts, source, dest,
1308 r = hg.clone(ui, opts, source, dest,
1309 pull=opts.get('pull'),
1309 pull=opts.get('pull'),
1310 stream=opts.get('uncompressed'),
1310 stream=opts.get('uncompressed'),
1311 rev=opts.get('rev'),
1311 rev=opts.get('rev'),
1312 update=opts.get('updaterev') or not opts.get('noupdate'),
1312 update=opts.get('updaterev') or not opts.get('noupdate'),
1313 branch=opts.get('branch'))
1313 branch=opts.get('branch'))
1314
1314
1315 return r is None
1315 return r is None
1316
1316
1317 @command('^commit|ci',
1317 @command('^commit|ci',
1318 [('A', 'addremove', None,
1318 [('A', 'addremove', None,
1319 _('mark new/missing files as added/removed before committing')),
1319 _('mark new/missing files as added/removed before committing')),
1320 ('', 'close-branch', None,
1320 ('', 'close-branch', None,
1321 _('mark a branch as closed, hiding it from the branch list')),
1321 _('mark a branch as closed, hiding it from the branch list')),
1322 ('', 'amend', None, _('amend the parent of the working dir')),
1322 ('', 'amend', None, _('amend the parent of the working dir')),
1323 ('s', 'secret', None, _('use the secret phase for committing')),
1323 ('s', 'secret', None, _('use the secret phase for committing')),
1324 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1324 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1325 _('[OPTION]... [FILE]...'))
1325 _('[OPTION]... [FILE]...'))
1326 def commit(ui, repo, *pats, **opts):
1326 def commit(ui, repo, *pats, **opts):
1327 """commit the specified files or all outstanding changes
1327 """commit the specified files or all outstanding changes
1328
1328
1329 Commit changes to the given files into the repository. Unlike a
1329 Commit changes to the given files into the repository. Unlike a
1330 centralized SCM, this operation is a local operation. See
1330 centralized SCM, this operation is a local operation. See
1331 :hg:`push` for a way to actively distribute your changes.
1331 :hg:`push` for a way to actively distribute your changes.
1332
1332
1333 If a list of files is omitted, all changes reported by :hg:`status`
1333 If a list of files is omitted, all changes reported by :hg:`status`
1334 will be committed.
1334 will be committed.
1335
1335
1336 If you are committing the result of a merge, do not provide any
1336 If you are committing the result of a merge, do not provide any
1337 filenames or -I/-X filters.
1337 filenames or -I/-X filters.
1338
1338
1339 If no commit message is specified, Mercurial starts your
1339 If no commit message is specified, Mercurial starts your
1340 configured editor where you can enter a message. In case your
1340 configured editor where you can enter a message. In case your
1341 commit fails, you will find a backup of your message in
1341 commit fails, you will find a backup of your message in
1342 ``.hg/last-message.txt``.
1342 ``.hg/last-message.txt``.
1343
1343
1344 The --amend flag can be used to amend the parent of the
1344 The --amend flag can be used to amend the parent of the
1345 working directory with a new commit that contains the changes
1345 working directory with a new commit that contains the changes
1346 in the parent in addition to those currently reported by :hg:`status`,
1346 in the parent in addition to those currently reported by :hg:`status`,
1347 if there are any. The old commit is stored in a backup bundle in
1347 if there are any. The old commit is stored in a backup bundle in
1348 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1348 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1349 on how to restore it).
1349 on how to restore it).
1350
1350
1351 Message, user and date are taken from the amended commit unless
1351 Message, user and date are taken from the amended commit unless
1352 specified. When a message isn't specified on the command line,
1352 specified. When a message isn't specified on the command line,
1353 the editor will open with the message of the amended commit.
1353 the editor will open with the message of the amended commit.
1354
1354
1355 It is not possible to amend public changesets (see :hg:`help phases`)
1355 It is not possible to amend public changesets (see :hg:`help phases`)
1356 or changesets that have children.
1356 or changesets that have children.
1357
1357
1358 See :hg:`help dates` for a list of formats valid for -d/--date.
1358 See :hg:`help dates` for a list of formats valid for -d/--date.
1359
1359
1360 Returns 0 on success, 1 if nothing changed.
1360 Returns 0 on success, 1 if nothing changed.
1361 """
1361 """
1362 if opts.get('subrepos'):
1362 if opts.get('subrepos'):
1363 if opts.get('amend'):
1363 if opts.get('amend'):
1364 raise util.Abort(_('cannot amend with --subrepos'))
1364 raise util.Abort(_('cannot amend with --subrepos'))
1365 # Let --subrepos on the command line override config setting.
1365 # Let --subrepos on the command line override config setting.
1366 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1366 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1367
1367
1368 # Save this for restoring it later
1368 # Save this for restoring it later
1369 oldcommitphase = ui.config('phases', 'new-commit')
1369 oldcommitphase = ui.config('phases', 'new-commit')
1370
1370
1371 cmdutil.checkunfinished(repo, commit=True)
1371 cmdutil.checkunfinished(repo, commit=True)
1372
1372
1373 branch = repo[None].branch()
1373 branch = repo[None].branch()
1374 bheads = repo.branchheads(branch)
1374 bheads = repo.branchheads(branch)
1375
1375
1376 extra = {}
1376 extra = {}
1377 if opts.get('close_branch'):
1377 if opts.get('close_branch'):
1378 extra['close'] = 1
1378 extra['close'] = 1
1379
1379
1380 if not bheads:
1380 if not bheads:
1381 raise util.Abort(_('can only close branch heads'))
1381 raise util.Abort(_('can only close branch heads'))
1382 elif opts.get('amend'):
1382 elif opts.get('amend'):
1383 if repo.parents()[0].p1().branch() != branch and \
1383 if repo.parents()[0].p1().branch() != branch and \
1384 repo.parents()[0].p2().branch() != branch:
1384 repo.parents()[0].p2().branch() != branch:
1385 raise util.Abort(_('can only close branch heads'))
1385 raise util.Abort(_('can only close branch heads'))
1386
1386
1387 if opts.get('amend'):
1387 if opts.get('amend'):
1388 if ui.configbool('ui', 'commitsubrepos'):
1388 if ui.configbool('ui', 'commitsubrepos'):
1389 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1389 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1390
1390
1391 old = repo['.']
1391 old = repo['.']
1392 if old.phase() == phases.public:
1392 if old.phase() == phases.public:
1393 raise util.Abort(_('cannot amend public changesets'))
1393 raise util.Abort(_('cannot amend public changesets'))
1394 if len(repo[None].parents()) > 1:
1394 if len(repo[None].parents()) > 1:
1395 raise util.Abort(_('cannot amend while merging'))
1395 raise util.Abort(_('cannot amend while merging'))
1396 if (not obsolete._enabled) and old.children():
1396 if (not obsolete._enabled) and old.children():
1397 raise util.Abort(_('cannot amend changeset with children'))
1397 raise util.Abort(_('cannot amend changeset with children'))
1398
1398
1399 e = cmdutil.commiteditor
1399 e = cmdutil.commiteditor
1400 if opts.get('force_editor'):
1400 if opts.get('force_editor'):
1401 e = cmdutil.commitforceeditor
1401 e = cmdutil.commitforceeditor
1402
1402
1403 # commitfunc is used only for temporary amend commit by cmdutil.amend
1403 # commitfunc is used only for temporary amend commit by cmdutil.amend
1404 def commitfunc(ui, repo, message, match, opts):
1404 def commitfunc(ui, repo, message, match, opts):
1405 editor = e
1405 editor = e
1406 # message contains text from -m or -l, if it's empty,
1406 # message contains text from -m or -l, if it's empty,
1407 # open the editor with the old message
1407 # open the editor with the old message
1408 if not message:
1408 if not message:
1409 message = old.description()
1409 message = old.description()
1410 editor = cmdutil.commitforceeditor
1410 editor = cmdutil.commitforceeditor
1411 return repo.commit(message,
1411 return repo.commit(message,
1412 opts.get('user') or old.user(),
1412 opts.get('user') or old.user(),
1413 opts.get('date') or old.date(),
1413 opts.get('date') or old.date(),
1414 match,
1414 match,
1415 editor=editor,
1415 editor=editor,
1416 extra=extra)
1416 extra=extra)
1417
1417
1418 current = repo._bookmarkcurrent
1418 current = repo._bookmarkcurrent
1419 marks = old.bookmarks()
1419 marks = old.bookmarks()
1420 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1420 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1421 if node == old.node():
1421 if node == old.node():
1422 ui.status(_("nothing changed\n"))
1422 ui.status(_("nothing changed\n"))
1423 return 1
1423 return 1
1424 elif marks:
1424 elif marks:
1425 ui.debug('moving bookmarks %r from %s to %s\n' %
1425 ui.debug('moving bookmarks %r from %s to %s\n' %
1426 (marks, old.hex(), hex(node)))
1426 (marks, old.hex(), hex(node)))
1427 newmarks = repo._bookmarks
1427 newmarks = repo._bookmarks
1428 for bm in marks:
1428 for bm in marks:
1429 newmarks[bm] = node
1429 newmarks[bm] = node
1430 if bm == current:
1430 if bm == current:
1431 bookmarks.setcurrent(repo, bm)
1431 bookmarks.setcurrent(repo, bm)
1432 newmarks.write()
1432 newmarks.write()
1433 else:
1433 else:
1434 e = cmdutil.commiteditor
1434 e = cmdutil.commiteditor
1435 if opts.get('force_editor'):
1435 if opts.get('force_editor'):
1436 e = cmdutil.commitforceeditor
1436 e = cmdutil.commitforceeditor
1437
1437
1438 def commitfunc(ui, repo, message, match, opts):
1438 def commitfunc(ui, repo, message, match, opts):
1439 try:
1439 try:
1440 if opts.get('secret'):
1440 if opts.get('secret'):
1441 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1441 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1442 # Propagate to subrepos
1442 # Propagate to subrepos
1443 repo.baseui.setconfig('phases', 'new-commit', 'secret',
1443 repo.baseui.setconfig('phases', 'new-commit', 'secret',
1444 'commit')
1444 'commit')
1445
1445
1446 return repo.commit(message, opts.get('user'), opts.get('date'),
1446 return repo.commit(message, opts.get('user'), opts.get('date'),
1447 match, editor=e, extra=extra)
1447 match, editor=e, extra=extra)
1448 finally:
1448 finally:
1449 ui.setconfig('phases', 'new-commit', oldcommitphase, 'commit')
1449 ui.setconfig('phases', 'new-commit', oldcommitphase, 'commit')
1450 repo.baseui.setconfig('phases', 'new-commit', oldcommitphase,
1450 repo.baseui.setconfig('phases', 'new-commit', oldcommitphase,
1451 'commit')
1451 'commit')
1452
1452
1453
1453
1454 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1454 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1455
1455
1456 if not node:
1456 if not node:
1457 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1457 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1458 if stat[3]:
1458 if stat[3]:
1459 ui.status(_("nothing changed (%d missing files, see "
1459 ui.status(_("nothing changed (%d missing files, see "
1460 "'hg status')\n") % len(stat[3]))
1460 "'hg status')\n") % len(stat[3]))
1461 else:
1461 else:
1462 ui.status(_("nothing changed\n"))
1462 ui.status(_("nothing changed\n"))
1463 return 1
1463 return 1
1464
1464
1465 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1465 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1466
1466
1467 @command('config|showconfig|debugconfig',
1467 @command('config|showconfig|debugconfig',
1468 [('u', 'untrusted', None, _('show untrusted configuration options')),
1468 [('u', 'untrusted', None, _('show untrusted configuration options')),
1469 ('e', 'edit', None, _('edit user config')),
1469 ('e', 'edit', None, _('edit user config')),
1470 ('l', 'local', None, _('edit repository config')),
1470 ('l', 'local', None, _('edit repository config')),
1471 ('g', 'global', None, _('edit global config'))],
1471 ('g', 'global', None, _('edit global config'))],
1472 _('[-u] [NAME]...'))
1472 _('[-u] [NAME]...'))
1473 def config(ui, repo, *values, **opts):
1473 def config(ui, repo, *values, **opts):
1474 """show combined config settings from all hgrc files
1474 """show combined config settings from all hgrc files
1475
1475
1476 With no arguments, print names and values of all config items.
1476 With no arguments, print names and values of all config items.
1477
1477
1478 With one argument of the form section.name, print just the value
1478 With one argument of the form section.name, print just the value
1479 of that config item.
1479 of that config item.
1480
1480
1481 With multiple arguments, print names and values of all config
1481 With multiple arguments, print names and values of all config
1482 items with matching section names.
1482 items with matching section names.
1483
1483
1484 With --edit, start an editor on the user-level config file. With
1484 With --edit, start an editor on the user-level config file. With
1485 --global, edit the system-wide config file. With --local, edit the
1485 --global, edit the system-wide config file. With --local, edit the
1486 repository-level config file.
1486 repository-level config file.
1487
1487
1488 With --debug, the source (filename and line number) is printed
1488 With --debug, the source (filename and line number) is printed
1489 for each config item.
1489 for each config item.
1490
1490
1491 See :hg:`help config` for more information about config files.
1491 See :hg:`help config` for more information about config files.
1492
1492
1493 Returns 0 on success.
1493 Returns 0 on success.
1494
1494
1495 """
1495 """
1496
1496
1497 if opts.get('edit') or opts.get('local') or opts.get('global'):
1497 if opts.get('edit') or opts.get('local') or opts.get('global'):
1498 if opts.get('local') and opts.get('global'):
1498 if opts.get('local') and opts.get('global'):
1499 raise util.Abort(_("can't use --local and --global together"))
1499 raise util.Abort(_("can't use --local and --global together"))
1500
1500
1501 if opts.get('local'):
1501 if opts.get('local'):
1502 if not repo:
1502 if not repo:
1503 raise util.Abort(_("can't use --local outside a repository"))
1503 raise util.Abort(_("can't use --local outside a repository"))
1504 paths = [repo.join('hgrc')]
1504 paths = [repo.join('hgrc')]
1505 elif opts.get('global'):
1505 elif opts.get('global'):
1506 paths = scmutil.systemrcpath()
1506 paths = scmutil.systemrcpath()
1507 else:
1507 else:
1508 paths = scmutil.userrcpath()
1508 paths = scmutil.userrcpath()
1509
1509
1510 for f in paths:
1510 for f in paths:
1511 if os.path.exists(f):
1511 if os.path.exists(f):
1512 break
1512 break
1513 else:
1513 else:
1514 f = paths[0]
1514 f = paths[0]
1515 fp = open(f, "w")
1515 fp = open(f, "w")
1516 fp.write(
1516 fp.write(
1517 '# example config (see "hg help config" for more info)\n'
1517 '# example config (see "hg help config" for more info)\n'
1518 '\n'
1518 '\n'
1519 '[ui]\n'
1519 '[ui]\n'
1520 '# name and email, e.g.\n'
1520 '# name and email, e.g.\n'
1521 '# username = Jane Doe <jdoe@example.com>\n'
1521 '# username = Jane Doe <jdoe@example.com>\n'
1522 'username =\n'
1522 'username =\n'
1523 '\n'
1523 '\n'
1524 '[extensions]\n'
1524 '[extensions]\n'
1525 '# uncomment these lines to enable some popular extensions\n'
1525 '# uncomment these lines to enable some popular extensions\n'
1526 '# (see "hg help extensions" for more info)\n'
1526 '# (see "hg help extensions" for more info)\n'
1527 '# pager =\n'
1527 '# pager =\n'
1528 '# progress =\n'
1528 '# progress =\n'
1529 '# color =\n')
1529 '# color =\n')
1530 fp.close()
1530 fp.close()
1531
1531
1532 editor = ui.geteditor()
1532 editor = ui.geteditor()
1533 util.system("%s \"%s\"" % (editor, f),
1533 util.system("%s \"%s\"" % (editor, f),
1534 onerr=util.Abort, errprefix=_("edit failed"),
1534 onerr=util.Abort, errprefix=_("edit failed"),
1535 out=ui.fout)
1535 out=ui.fout)
1536 return
1536 return
1537
1537
1538 for f in scmutil.rcpath():
1538 for f in scmutil.rcpath():
1539 ui.debug('read config from: %s\n' % f)
1539 ui.debug('read config from: %s\n' % f)
1540 untrusted = bool(opts.get('untrusted'))
1540 untrusted = bool(opts.get('untrusted'))
1541 if values:
1541 if values:
1542 sections = [v for v in values if '.' not in v]
1542 sections = [v for v in values if '.' not in v]
1543 items = [v for v in values if '.' in v]
1543 items = [v for v in values if '.' in v]
1544 if len(items) > 1 or items and sections:
1544 if len(items) > 1 or items and sections:
1545 raise util.Abort(_('only one config item permitted'))
1545 raise util.Abort(_('only one config item permitted'))
1546 for section, name, value in ui.walkconfig(untrusted=untrusted):
1546 for section, name, value in ui.walkconfig(untrusted=untrusted):
1547 value = str(value).replace('\n', '\\n')
1547 value = str(value).replace('\n', '\\n')
1548 sectname = section + '.' + name
1548 sectname = section + '.' + name
1549 if values:
1549 if values:
1550 for v in values:
1550 for v in values:
1551 if v == section:
1551 if v == section:
1552 ui.debug('%s: ' %
1552 ui.debug('%s: ' %
1553 ui.configsource(section, name, untrusted))
1553 ui.configsource(section, name, untrusted))
1554 ui.write('%s=%s\n' % (sectname, value))
1554 ui.write('%s=%s\n' % (sectname, value))
1555 elif v == sectname:
1555 elif v == sectname:
1556 ui.debug('%s: ' %
1556 ui.debug('%s: ' %
1557 ui.configsource(section, name, untrusted))
1557 ui.configsource(section, name, untrusted))
1558 ui.write(value, '\n')
1558 ui.write(value, '\n')
1559 else:
1559 else:
1560 ui.debug('%s: ' %
1560 ui.debug('%s: ' %
1561 ui.configsource(section, name, untrusted))
1561 ui.configsource(section, name, untrusted))
1562 ui.write('%s=%s\n' % (sectname, value))
1562 ui.write('%s=%s\n' % (sectname, value))
1563
1563
1564 @command('copy|cp',
1564 @command('copy|cp',
1565 [('A', 'after', None, _('record a copy that has already occurred')),
1565 [('A', 'after', None, _('record a copy that has already occurred')),
1566 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1566 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1567 ] + walkopts + dryrunopts,
1567 ] + walkopts + dryrunopts,
1568 _('[OPTION]... [SOURCE]... DEST'))
1568 _('[OPTION]... [SOURCE]... DEST'))
1569 def copy(ui, repo, *pats, **opts):
1569 def copy(ui, repo, *pats, **opts):
1570 """mark files as copied for the next commit
1570 """mark files as copied for the next commit
1571
1571
1572 Mark dest as having copies of source files. If dest is a
1572 Mark dest as having copies of source files. If dest is a
1573 directory, copies are put in that directory. If dest is a file,
1573 directory, copies are put in that directory. If dest is a file,
1574 the source must be a single file.
1574 the source must be a single file.
1575
1575
1576 By default, this command copies the contents of files as they
1576 By default, this command copies the contents of files as they
1577 exist in the working directory. If invoked with -A/--after, the
1577 exist in the working directory. If invoked with -A/--after, the
1578 operation is recorded, but no copying is performed.
1578 operation is recorded, but no copying is performed.
1579
1579
1580 This command takes effect with the next commit. To undo a copy
1580 This command takes effect with the next commit. To undo a copy
1581 before that, see :hg:`revert`.
1581 before that, see :hg:`revert`.
1582
1582
1583 Returns 0 on success, 1 if errors are encountered.
1583 Returns 0 on success, 1 if errors are encountered.
1584 """
1584 """
1585 wlock = repo.wlock(False)
1585 wlock = repo.wlock(False)
1586 try:
1586 try:
1587 return cmdutil.copy(ui, repo, pats, opts)
1587 return cmdutil.copy(ui, repo, pats, opts)
1588 finally:
1588 finally:
1589 wlock.release()
1589 wlock.release()
1590
1590
1591 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1591 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1592 def debugancestor(ui, repo, *args):
1592 def debugancestor(ui, repo, *args):
1593 """find the ancestor revision of two revisions in a given index"""
1593 """find the ancestor revision of two revisions in a given index"""
1594 if len(args) == 3:
1594 if len(args) == 3:
1595 index, rev1, rev2 = args
1595 index, rev1, rev2 = args
1596 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1596 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1597 lookup = r.lookup
1597 lookup = r.lookup
1598 elif len(args) == 2:
1598 elif len(args) == 2:
1599 if not repo:
1599 if not repo:
1600 raise util.Abort(_("there is no Mercurial repository here "
1600 raise util.Abort(_("there is no Mercurial repository here "
1601 "(.hg not found)"))
1601 "(.hg not found)"))
1602 rev1, rev2 = args
1602 rev1, rev2 = args
1603 r = repo.changelog
1603 r = repo.changelog
1604 lookup = repo.lookup
1604 lookup = repo.lookup
1605 else:
1605 else:
1606 raise util.Abort(_('either two or three arguments required'))
1606 raise util.Abort(_('either two or three arguments required'))
1607 a = r.ancestor(lookup(rev1), lookup(rev2))
1607 a = r.ancestor(lookup(rev1), lookup(rev2))
1608 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1608 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1609
1609
1610 @command('debugbuilddag',
1610 @command('debugbuilddag',
1611 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1611 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1612 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1612 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1613 ('n', 'new-file', None, _('add new file at each rev'))],
1613 ('n', 'new-file', None, _('add new file at each rev'))],
1614 _('[OPTION]... [TEXT]'))
1614 _('[OPTION]... [TEXT]'))
1615 def debugbuilddag(ui, repo, text=None,
1615 def debugbuilddag(ui, repo, text=None,
1616 mergeable_file=False,
1616 mergeable_file=False,
1617 overwritten_file=False,
1617 overwritten_file=False,
1618 new_file=False):
1618 new_file=False):
1619 """builds a repo with a given DAG from scratch in the current empty repo
1619 """builds a repo with a given DAG from scratch in the current empty repo
1620
1620
1621 The description of the DAG is read from stdin if not given on the
1621 The description of the DAG is read from stdin if not given on the
1622 command line.
1622 command line.
1623
1623
1624 Elements:
1624 Elements:
1625
1625
1626 - "+n" is a linear run of n nodes based on the current default parent
1626 - "+n" is a linear run of n nodes based on the current default parent
1627 - "." is a single node based on the current default parent
1627 - "." is a single node based on the current default parent
1628 - "$" resets the default parent to null (implied at the start);
1628 - "$" resets the default parent to null (implied at the start);
1629 otherwise the default parent is always the last node created
1629 otherwise the default parent is always the last node created
1630 - "<p" sets the default parent to the backref p
1630 - "<p" sets the default parent to the backref p
1631 - "*p" is a fork at parent p, which is a backref
1631 - "*p" is a fork at parent p, which is a backref
1632 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1632 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1633 - "/p2" is a merge of the preceding node and p2
1633 - "/p2" is a merge of the preceding node and p2
1634 - ":tag" defines a local tag for the preceding node
1634 - ":tag" defines a local tag for the preceding node
1635 - "@branch" sets the named branch for subsequent nodes
1635 - "@branch" sets the named branch for subsequent nodes
1636 - "#...\\n" is a comment up to the end of the line
1636 - "#...\\n" is a comment up to the end of the line
1637
1637
1638 Whitespace between the above elements is ignored.
1638 Whitespace between the above elements is ignored.
1639
1639
1640 A backref is either
1640 A backref is either
1641
1641
1642 - a number n, which references the node curr-n, where curr is the current
1642 - a number n, which references the node curr-n, where curr is the current
1643 node, or
1643 node, or
1644 - the name of a local tag you placed earlier using ":tag", or
1644 - the name of a local tag you placed earlier using ":tag", or
1645 - empty to denote the default parent.
1645 - empty to denote the default parent.
1646
1646
1647 All string valued-elements are either strictly alphanumeric, or must
1647 All string valued-elements are either strictly alphanumeric, or must
1648 be enclosed in double quotes ("..."), with "\\" as escape character.
1648 be enclosed in double quotes ("..."), with "\\" as escape character.
1649 """
1649 """
1650
1650
1651 if text is None:
1651 if text is None:
1652 ui.status(_("reading DAG from stdin\n"))
1652 ui.status(_("reading DAG from stdin\n"))
1653 text = ui.fin.read()
1653 text = ui.fin.read()
1654
1654
1655 cl = repo.changelog
1655 cl = repo.changelog
1656 if len(cl) > 0:
1656 if len(cl) > 0:
1657 raise util.Abort(_('repository is not empty'))
1657 raise util.Abort(_('repository is not empty'))
1658
1658
1659 # determine number of revs in DAG
1659 # determine number of revs in DAG
1660 total = 0
1660 total = 0
1661 for type, data in dagparser.parsedag(text):
1661 for type, data in dagparser.parsedag(text):
1662 if type == 'n':
1662 if type == 'n':
1663 total += 1
1663 total += 1
1664
1664
1665 if mergeable_file:
1665 if mergeable_file:
1666 linesperrev = 2
1666 linesperrev = 2
1667 # make a file with k lines per rev
1667 # make a file with k lines per rev
1668 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1668 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1669 initialmergedlines.append("")
1669 initialmergedlines.append("")
1670
1670
1671 tags = []
1671 tags = []
1672
1672
1673 lock = tr = None
1673 lock = tr = None
1674 try:
1674 try:
1675 lock = repo.lock()
1675 lock = repo.lock()
1676 tr = repo.transaction("builddag")
1676 tr = repo.transaction("builddag")
1677
1677
1678 at = -1
1678 at = -1
1679 atbranch = 'default'
1679 atbranch = 'default'
1680 nodeids = []
1680 nodeids = []
1681 id = 0
1681 id = 0
1682 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1682 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1683 for type, data in dagparser.parsedag(text):
1683 for type, data in dagparser.parsedag(text):
1684 if type == 'n':
1684 if type == 'n':
1685 ui.note(('node %s\n' % str(data)))
1685 ui.note(('node %s\n' % str(data)))
1686 id, ps = data
1686 id, ps = data
1687
1687
1688 files = []
1688 files = []
1689 fctxs = {}
1689 fctxs = {}
1690
1690
1691 p2 = None
1691 p2 = None
1692 if mergeable_file:
1692 if mergeable_file:
1693 fn = "mf"
1693 fn = "mf"
1694 p1 = repo[ps[0]]
1694 p1 = repo[ps[0]]
1695 if len(ps) > 1:
1695 if len(ps) > 1:
1696 p2 = repo[ps[1]]
1696 p2 = repo[ps[1]]
1697 pa = p1.ancestor(p2)
1697 pa = p1.ancestor(p2)
1698 base, local, other = [x[fn].data() for x in (pa, p1,
1698 base, local, other = [x[fn].data() for x in (pa, p1,
1699 p2)]
1699 p2)]
1700 m3 = simplemerge.Merge3Text(base, local, other)
1700 m3 = simplemerge.Merge3Text(base, local, other)
1701 ml = [l.strip() for l in m3.merge_lines()]
1701 ml = [l.strip() for l in m3.merge_lines()]
1702 ml.append("")
1702 ml.append("")
1703 elif at > 0:
1703 elif at > 0:
1704 ml = p1[fn].data().split("\n")
1704 ml = p1[fn].data().split("\n")
1705 else:
1705 else:
1706 ml = initialmergedlines
1706 ml = initialmergedlines
1707 ml[id * linesperrev] += " r%i" % id
1707 ml[id * linesperrev] += " r%i" % id
1708 mergedtext = "\n".join(ml)
1708 mergedtext = "\n".join(ml)
1709 files.append(fn)
1709 files.append(fn)
1710 fctxs[fn] = context.memfilectx(fn, mergedtext)
1710 fctxs[fn] = context.memfilectx(fn, mergedtext)
1711
1711
1712 if overwritten_file:
1712 if overwritten_file:
1713 fn = "of"
1713 fn = "of"
1714 files.append(fn)
1714 files.append(fn)
1715 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1715 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1716
1716
1717 if new_file:
1717 if new_file:
1718 fn = "nf%i" % id
1718 fn = "nf%i" % id
1719 files.append(fn)
1719 files.append(fn)
1720 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1720 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1721 if len(ps) > 1:
1721 if len(ps) > 1:
1722 if not p2:
1722 if not p2:
1723 p2 = repo[ps[1]]
1723 p2 = repo[ps[1]]
1724 for fn in p2:
1724 for fn in p2:
1725 if fn.startswith("nf"):
1725 if fn.startswith("nf"):
1726 files.append(fn)
1726 files.append(fn)
1727 fctxs[fn] = p2[fn]
1727 fctxs[fn] = p2[fn]
1728
1728
1729 def fctxfn(repo, cx, path):
1729 def fctxfn(repo, cx, path):
1730 return fctxs.get(path)
1730 return fctxs.get(path)
1731
1731
1732 if len(ps) == 0 or ps[0] < 0:
1732 if len(ps) == 0 or ps[0] < 0:
1733 pars = [None, None]
1733 pars = [None, None]
1734 elif len(ps) == 1:
1734 elif len(ps) == 1:
1735 pars = [nodeids[ps[0]], None]
1735 pars = [nodeids[ps[0]], None]
1736 else:
1736 else:
1737 pars = [nodeids[p] for p in ps]
1737 pars = [nodeids[p] for p in ps]
1738 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1738 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1739 date=(id, 0),
1739 date=(id, 0),
1740 user="debugbuilddag",
1740 user="debugbuilddag",
1741 extra={'branch': atbranch})
1741 extra={'branch': atbranch})
1742 nodeid = repo.commitctx(cx)
1742 nodeid = repo.commitctx(cx)
1743 nodeids.append(nodeid)
1743 nodeids.append(nodeid)
1744 at = id
1744 at = id
1745 elif type == 'l':
1745 elif type == 'l':
1746 id, name = data
1746 id, name = data
1747 ui.note(('tag %s\n' % name))
1747 ui.note(('tag %s\n' % name))
1748 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1748 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1749 elif type == 'a':
1749 elif type == 'a':
1750 ui.note(('branch %s\n' % data))
1750 ui.note(('branch %s\n' % data))
1751 atbranch = data
1751 atbranch = data
1752 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1752 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1753 tr.close()
1753 tr.close()
1754
1754
1755 if tags:
1755 if tags:
1756 repo.opener.write("localtags", "".join(tags))
1756 repo.opener.write("localtags", "".join(tags))
1757 finally:
1757 finally:
1758 ui.progress(_('building'), None)
1758 ui.progress(_('building'), None)
1759 release(tr, lock)
1759 release(tr, lock)
1760
1760
1761 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1761 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1762 def debugbundle(ui, bundlepath, all=None, **opts):
1762 def debugbundle(ui, bundlepath, all=None, **opts):
1763 """lists the contents of a bundle"""
1763 """lists the contents of a bundle"""
1764 f = hg.openpath(ui, bundlepath)
1764 f = hg.openpath(ui, bundlepath)
1765 try:
1765 try:
1766 gen = changegroup.readbundle(f, bundlepath)
1766 gen = changegroup.readbundle(f, bundlepath)
1767 if all:
1767 if all:
1768 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1768 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1769
1769
1770 def showchunks(named):
1770 def showchunks(named):
1771 ui.write("\n%s\n" % named)
1771 ui.write("\n%s\n" % named)
1772 chain = None
1772 chain = None
1773 while True:
1773 while True:
1774 chunkdata = gen.deltachunk(chain)
1774 chunkdata = gen.deltachunk(chain)
1775 if not chunkdata:
1775 if not chunkdata:
1776 break
1776 break
1777 node = chunkdata['node']
1777 node = chunkdata['node']
1778 p1 = chunkdata['p1']
1778 p1 = chunkdata['p1']
1779 p2 = chunkdata['p2']
1779 p2 = chunkdata['p2']
1780 cs = chunkdata['cs']
1780 cs = chunkdata['cs']
1781 deltabase = chunkdata['deltabase']
1781 deltabase = chunkdata['deltabase']
1782 delta = chunkdata['delta']
1782 delta = chunkdata['delta']
1783 ui.write("%s %s %s %s %s %s\n" %
1783 ui.write("%s %s %s %s %s %s\n" %
1784 (hex(node), hex(p1), hex(p2),
1784 (hex(node), hex(p1), hex(p2),
1785 hex(cs), hex(deltabase), len(delta)))
1785 hex(cs), hex(deltabase), len(delta)))
1786 chain = node
1786 chain = node
1787
1787
1788 chunkdata = gen.changelogheader()
1788 chunkdata = gen.changelogheader()
1789 showchunks("changelog")
1789 showchunks("changelog")
1790 chunkdata = gen.manifestheader()
1790 chunkdata = gen.manifestheader()
1791 showchunks("manifest")
1791 showchunks("manifest")
1792 while True:
1792 while True:
1793 chunkdata = gen.filelogheader()
1793 chunkdata = gen.filelogheader()
1794 if not chunkdata:
1794 if not chunkdata:
1795 break
1795 break
1796 fname = chunkdata['filename']
1796 fname = chunkdata['filename']
1797 showchunks(fname)
1797 showchunks(fname)
1798 else:
1798 else:
1799 chunkdata = gen.changelogheader()
1799 chunkdata = gen.changelogheader()
1800 chain = None
1800 chain = None
1801 while True:
1801 while True:
1802 chunkdata = gen.deltachunk(chain)
1802 chunkdata = gen.deltachunk(chain)
1803 if not chunkdata:
1803 if not chunkdata:
1804 break
1804 break
1805 node = chunkdata['node']
1805 node = chunkdata['node']
1806 ui.write("%s\n" % hex(node))
1806 ui.write("%s\n" % hex(node))
1807 chain = node
1807 chain = node
1808 finally:
1808 finally:
1809 f.close()
1809 f.close()
1810
1810
1811 @command('debugcheckstate', [], '')
1811 @command('debugcheckstate', [], '')
1812 def debugcheckstate(ui, repo):
1812 def debugcheckstate(ui, repo):
1813 """validate the correctness of the current dirstate"""
1813 """validate the correctness of the current dirstate"""
1814 parent1, parent2 = repo.dirstate.parents()
1814 parent1, parent2 = repo.dirstate.parents()
1815 m1 = repo[parent1].manifest()
1815 m1 = repo[parent1].manifest()
1816 m2 = repo[parent2].manifest()
1816 m2 = repo[parent2].manifest()
1817 errors = 0
1817 errors = 0
1818 for f in repo.dirstate:
1818 for f in repo.dirstate:
1819 state = repo.dirstate[f]
1819 state = repo.dirstate[f]
1820 if state in "nr" and f not in m1:
1820 if state in "nr" and f not in m1:
1821 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1821 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1822 errors += 1
1822 errors += 1
1823 if state in "a" and f in m1:
1823 if state in "a" and f in m1:
1824 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1824 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1825 errors += 1
1825 errors += 1
1826 if state in "m" and f not in m1 and f not in m2:
1826 if state in "m" and f not in m1 and f not in m2:
1827 ui.warn(_("%s in state %s, but not in either manifest\n") %
1827 ui.warn(_("%s in state %s, but not in either manifest\n") %
1828 (f, state))
1828 (f, state))
1829 errors += 1
1829 errors += 1
1830 for f in m1:
1830 for f in m1:
1831 state = repo.dirstate[f]
1831 state = repo.dirstate[f]
1832 if state not in "nrm":
1832 if state not in "nrm":
1833 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1833 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1834 errors += 1
1834 errors += 1
1835 if errors:
1835 if errors:
1836 error = _(".hg/dirstate inconsistent with current parent's manifest")
1836 error = _(".hg/dirstate inconsistent with current parent's manifest")
1837 raise util.Abort(error)
1837 raise util.Abort(error)
1838
1838
1839 @command('debugcommands', [], _('[COMMAND]'))
1839 @command('debugcommands', [], _('[COMMAND]'))
1840 def debugcommands(ui, cmd='', *args):
1840 def debugcommands(ui, cmd='', *args):
1841 """list all available commands and options"""
1841 """list all available commands and options"""
1842 for cmd, vals in sorted(table.iteritems()):
1842 for cmd, vals in sorted(table.iteritems()):
1843 cmd = cmd.split('|')[0].strip('^')
1843 cmd = cmd.split('|')[0].strip('^')
1844 opts = ', '.join([i[1] for i in vals[1]])
1844 opts = ', '.join([i[1] for i in vals[1]])
1845 ui.write('%s: %s\n' % (cmd, opts))
1845 ui.write('%s: %s\n' % (cmd, opts))
1846
1846
1847 @command('debugcomplete',
1847 @command('debugcomplete',
1848 [('o', 'options', None, _('show the command options'))],
1848 [('o', 'options', None, _('show the command options'))],
1849 _('[-o] CMD'))
1849 _('[-o] CMD'))
1850 def debugcomplete(ui, cmd='', **opts):
1850 def debugcomplete(ui, cmd='', **opts):
1851 """returns the completion list associated with the given command"""
1851 """returns the completion list associated with the given command"""
1852
1852
1853 if opts.get('options'):
1853 if opts.get('options'):
1854 options = []
1854 options = []
1855 otables = [globalopts]
1855 otables = [globalopts]
1856 if cmd:
1856 if cmd:
1857 aliases, entry = cmdutil.findcmd(cmd, table, False)
1857 aliases, entry = cmdutil.findcmd(cmd, table, False)
1858 otables.append(entry[1])
1858 otables.append(entry[1])
1859 for t in otables:
1859 for t in otables:
1860 for o in t:
1860 for o in t:
1861 if "(DEPRECATED)" in o[3]:
1861 if "(DEPRECATED)" in o[3]:
1862 continue
1862 continue
1863 if o[0]:
1863 if o[0]:
1864 options.append('-%s' % o[0])
1864 options.append('-%s' % o[0])
1865 options.append('--%s' % o[1])
1865 options.append('--%s' % o[1])
1866 ui.write("%s\n" % "\n".join(options))
1866 ui.write("%s\n" % "\n".join(options))
1867 return
1867 return
1868
1868
1869 cmdlist = cmdutil.findpossible(cmd, table)
1869 cmdlist = cmdutil.findpossible(cmd, table)
1870 if ui.verbose:
1870 if ui.verbose:
1871 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1871 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1872 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1872 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1873
1873
1874 @command('debugdag',
1874 @command('debugdag',
1875 [('t', 'tags', None, _('use tags as labels')),
1875 [('t', 'tags', None, _('use tags as labels')),
1876 ('b', 'branches', None, _('annotate with branch names')),
1876 ('b', 'branches', None, _('annotate with branch names')),
1877 ('', 'dots', None, _('use dots for runs')),
1877 ('', 'dots', None, _('use dots for runs')),
1878 ('s', 'spaces', None, _('separate elements by spaces'))],
1878 ('s', 'spaces', None, _('separate elements by spaces'))],
1879 _('[OPTION]... [FILE [REV]...]'))
1879 _('[OPTION]... [FILE [REV]...]'))
1880 def debugdag(ui, repo, file_=None, *revs, **opts):
1880 def debugdag(ui, repo, file_=None, *revs, **opts):
1881 """format the changelog or an index DAG as a concise textual description
1881 """format the changelog or an index DAG as a concise textual description
1882
1882
1883 If you pass a revlog index, the revlog's DAG is emitted. If you list
1883 If you pass a revlog index, the revlog's DAG is emitted. If you list
1884 revision numbers, they get labeled in the output as rN.
1884 revision numbers, they get labeled in the output as rN.
1885
1885
1886 Otherwise, the changelog DAG of the current repo is emitted.
1886 Otherwise, the changelog DAG of the current repo is emitted.
1887 """
1887 """
1888 spaces = opts.get('spaces')
1888 spaces = opts.get('spaces')
1889 dots = opts.get('dots')
1889 dots = opts.get('dots')
1890 if file_:
1890 if file_:
1891 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1891 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1892 revs = set((int(r) for r in revs))
1892 revs = set((int(r) for r in revs))
1893 def events():
1893 def events():
1894 for r in rlog:
1894 for r in rlog:
1895 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1895 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1896 if p != -1)))
1896 if p != -1)))
1897 if r in revs:
1897 if r in revs:
1898 yield 'l', (r, "r%i" % r)
1898 yield 'l', (r, "r%i" % r)
1899 elif repo:
1899 elif repo:
1900 cl = repo.changelog
1900 cl = repo.changelog
1901 tags = opts.get('tags')
1901 tags = opts.get('tags')
1902 branches = opts.get('branches')
1902 branches = opts.get('branches')
1903 if tags:
1903 if tags:
1904 labels = {}
1904 labels = {}
1905 for l, n in repo.tags().items():
1905 for l, n in repo.tags().items():
1906 labels.setdefault(cl.rev(n), []).append(l)
1906 labels.setdefault(cl.rev(n), []).append(l)
1907 def events():
1907 def events():
1908 b = "default"
1908 b = "default"
1909 for r in cl:
1909 for r in cl:
1910 if branches:
1910 if branches:
1911 newb = cl.read(cl.node(r))[5]['branch']
1911 newb = cl.read(cl.node(r))[5]['branch']
1912 if newb != b:
1912 if newb != b:
1913 yield 'a', newb
1913 yield 'a', newb
1914 b = newb
1914 b = newb
1915 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1915 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1916 if p != -1)))
1916 if p != -1)))
1917 if tags:
1917 if tags:
1918 ls = labels.get(r)
1918 ls = labels.get(r)
1919 if ls:
1919 if ls:
1920 for l in ls:
1920 for l in ls:
1921 yield 'l', (r, l)
1921 yield 'l', (r, l)
1922 else:
1922 else:
1923 raise util.Abort(_('need repo for changelog dag'))
1923 raise util.Abort(_('need repo for changelog dag'))
1924
1924
1925 for line in dagparser.dagtextlines(events(),
1925 for line in dagparser.dagtextlines(events(),
1926 addspaces=spaces,
1926 addspaces=spaces,
1927 wraplabels=True,
1927 wraplabels=True,
1928 wrapannotations=True,
1928 wrapannotations=True,
1929 wrapnonlinear=dots,
1929 wrapnonlinear=dots,
1930 usedots=dots,
1930 usedots=dots,
1931 maxlinewidth=70):
1931 maxlinewidth=70):
1932 ui.write(line)
1932 ui.write(line)
1933 ui.write("\n")
1933 ui.write("\n")
1934
1934
1935 @command('debugdata',
1935 @command('debugdata',
1936 [('c', 'changelog', False, _('open changelog')),
1936 [('c', 'changelog', False, _('open changelog')),
1937 ('m', 'manifest', False, _('open manifest'))],
1937 ('m', 'manifest', False, _('open manifest'))],
1938 _('-c|-m|FILE REV'))
1938 _('-c|-m|FILE REV'))
1939 def debugdata(ui, repo, file_, rev=None, **opts):
1939 def debugdata(ui, repo, file_, rev=None, **opts):
1940 """dump the contents of a data file revision"""
1940 """dump the contents of a data file revision"""
1941 if opts.get('changelog') or opts.get('manifest'):
1941 if opts.get('changelog') or opts.get('manifest'):
1942 file_, rev = None, file_
1942 file_, rev = None, file_
1943 elif rev is None:
1943 elif rev is None:
1944 raise error.CommandError('debugdata', _('invalid arguments'))
1944 raise error.CommandError('debugdata', _('invalid arguments'))
1945 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1945 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1946 try:
1946 try:
1947 ui.write(r.revision(r.lookup(rev)))
1947 ui.write(r.revision(r.lookup(rev)))
1948 except KeyError:
1948 except KeyError:
1949 raise util.Abort(_('invalid revision identifier %s') % rev)
1949 raise util.Abort(_('invalid revision identifier %s') % rev)
1950
1950
1951 @command('debugdate',
1951 @command('debugdate',
1952 [('e', 'extended', None, _('try extended date formats'))],
1952 [('e', 'extended', None, _('try extended date formats'))],
1953 _('[-e] DATE [RANGE]'))
1953 _('[-e] DATE [RANGE]'))
1954 def debugdate(ui, date, range=None, **opts):
1954 def debugdate(ui, date, range=None, **opts):
1955 """parse and display a date"""
1955 """parse and display a date"""
1956 if opts["extended"]:
1956 if opts["extended"]:
1957 d = util.parsedate(date, util.extendeddateformats)
1957 d = util.parsedate(date, util.extendeddateformats)
1958 else:
1958 else:
1959 d = util.parsedate(date)
1959 d = util.parsedate(date)
1960 ui.write(("internal: %s %s\n") % d)
1960 ui.write(("internal: %s %s\n") % d)
1961 ui.write(("standard: %s\n") % util.datestr(d))
1961 ui.write(("standard: %s\n") % util.datestr(d))
1962 if range:
1962 if range:
1963 m = util.matchdate(range)
1963 m = util.matchdate(range)
1964 ui.write(("match: %s\n") % m(d[0]))
1964 ui.write(("match: %s\n") % m(d[0]))
1965
1965
1966 @command('debugdiscovery',
1966 @command('debugdiscovery',
1967 [('', 'old', None, _('use old-style discovery')),
1967 [('', 'old', None, _('use old-style discovery')),
1968 ('', 'nonheads', None,
1968 ('', 'nonheads', None,
1969 _('use old-style discovery with non-heads included')),
1969 _('use old-style discovery with non-heads included')),
1970 ] + remoteopts,
1970 ] + remoteopts,
1971 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1971 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1972 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1972 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1973 """runs the changeset discovery protocol in isolation"""
1973 """runs the changeset discovery protocol in isolation"""
1974 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1974 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1975 opts.get('branch'))
1975 opts.get('branch'))
1976 remote = hg.peer(repo, opts, remoteurl)
1976 remote = hg.peer(repo, opts, remoteurl)
1977 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1977 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1978
1978
1979 # make sure tests are repeatable
1979 # make sure tests are repeatable
1980 random.seed(12323)
1980 random.seed(12323)
1981
1981
1982 def doit(localheads, remoteheads, remote=remote):
1982 def doit(localheads, remoteheads, remote=remote):
1983 if opts.get('old'):
1983 if opts.get('old'):
1984 if localheads:
1984 if localheads:
1985 raise util.Abort('cannot use localheads with old style '
1985 raise util.Abort('cannot use localheads with old style '
1986 'discovery')
1986 'discovery')
1987 if not util.safehasattr(remote, 'branches'):
1987 if not util.safehasattr(remote, 'branches'):
1988 # enable in-client legacy support
1988 # enable in-client legacy support
1989 remote = localrepo.locallegacypeer(remote.local())
1989 remote = localrepo.locallegacypeer(remote.local())
1990 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1990 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1991 force=True)
1991 force=True)
1992 common = set(common)
1992 common = set(common)
1993 if not opts.get('nonheads'):
1993 if not opts.get('nonheads'):
1994 ui.write(("unpruned common: %s\n") %
1994 ui.write(("unpruned common: %s\n") %
1995 " ".join(sorted(short(n) for n in common)))
1995 " ".join(sorted(short(n) for n in common)))
1996 dag = dagutil.revlogdag(repo.changelog)
1996 dag = dagutil.revlogdag(repo.changelog)
1997 all = dag.ancestorset(dag.internalizeall(common))
1997 all = dag.ancestorset(dag.internalizeall(common))
1998 common = dag.externalizeall(dag.headsetofconnecteds(all))
1998 common = dag.externalizeall(dag.headsetofconnecteds(all))
1999 else:
1999 else:
2000 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2000 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
2001 common = set(common)
2001 common = set(common)
2002 rheads = set(hds)
2002 rheads = set(hds)
2003 lheads = set(repo.heads())
2003 lheads = set(repo.heads())
2004 ui.write(("common heads: %s\n") %
2004 ui.write(("common heads: %s\n") %
2005 " ".join(sorted(short(n) for n in common)))
2005 " ".join(sorted(short(n) for n in common)))
2006 if lheads <= common:
2006 if lheads <= common:
2007 ui.write(("local is subset\n"))
2007 ui.write(("local is subset\n"))
2008 elif rheads <= common:
2008 elif rheads <= common:
2009 ui.write(("remote is subset\n"))
2009 ui.write(("remote is subset\n"))
2010
2010
2011 serverlogs = opts.get('serverlog')
2011 serverlogs = opts.get('serverlog')
2012 if serverlogs:
2012 if serverlogs:
2013 for filename in serverlogs:
2013 for filename in serverlogs:
2014 logfile = open(filename, 'r')
2014 logfile = open(filename, 'r')
2015 try:
2015 try:
2016 line = logfile.readline()
2016 line = logfile.readline()
2017 while line:
2017 while line:
2018 parts = line.strip().split(';')
2018 parts = line.strip().split(';')
2019 op = parts[1]
2019 op = parts[1]
2020 if op == 'cg':
2020 if op == 'cg':
2021 pass
2021 pass
2022 elif op == 'cgss':
2022 elif op == 'cgss':
2023 doit(parts[2].split(' '), parts[3].split(' '))
2023 doit(parts[2].split(' '), parts[3].split(' '))
2024 elif op == 'unb':
2024 elif op == 'unb':
2025 doit(parts[3].split(' '), parts[2].split(' '))
2025 doit(parts[3].split(' '), parts[2].split(' '))
2026 line = logfile.readline()
2026 line = logfile.readline()
2027 finally:
2027 finally:
2028 logfile.close()
2028 logfile.close()
2029
2029
2030 else:
2030 else:
2031 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2031 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2032 opts.get('remote_head'))
2032 opts.get('remote_head'))
2033 localrevs = opts.get('local_head')
2033 localrevs = opts.get('local_head')
2034 doit(localrevs, remoterevs)
2034 doit(localrevs, remoterevs)
2035
2035
2036 @command('debugfileset',
2036 @command('debugfileset',
2037 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2037 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2038 _('[-r REV] FILESPEC'))
2038 _('[-r REV] FILESPEC'))
2039 def debugfileset(ui, repo, expr, **opts):
2039 def debugfileset(ui, repo, expr, **opts):
2040 '''parse and apply a fileset specification'''
2040 '''parse and apply a fileset specification'''
2041 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2041 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2042 if ui.verbose:
2042 if ui.verbose:
2043 tree = fileset.parse(expr)[0]
2043 tree = fileset.parse(expr)[0]
2044 ui.note(tree, "\n")
2044 ui.note(tree, "\n")
2045
2045
2046 for f in ctx.getfileset(expr):
2046 for f in ctx.getfileset(expr):
2047 ui.write("%s\n" % f)
2047 ui.write("%s\n" % f)
2048
2048
2049 @command('debugfsinfo', [], _('[PATH]'))
2049 @command('debugfsinfo', [], _('[PATH]'))
2050 def debugfsinfo(ui, path="."):
2050 def debugfsinfo(ui, path="."):
2051 """show information detected about current filesystem"""
2051 """show information detected about current filesystem"""
2052 util.writefile('.debugfsinfo', '')
2052 util.writefile('.debugfsinfo', '')
2053 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2053 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2054 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2054 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2055 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2055 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2056 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2056 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2057 and 'yes' or 'no'))
2057 and 'yes' or 'no'))
2058 os.unlink('.debugfsinfo')
2058 os.unlink('.debugfsinfo')
2059
2059
2060 @command('debuggetbundle',
2060 @command('debuggetbundle',
2061 [('H', 'head', [], _('id of head node'), _('ID')),
2061 [('H', 'head', [], _('id of head node'), _('ID')),
2062 ('C', 'common', [], _('id of common node'), _('ID')),
2062 ('C', 'common', [], _('id of common node'), _('ID')),
2063 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2063 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2064 _('REPO FILE [-H|-C ID]...'))
2064 _('REPO FILE [-H|-C ID]...'))
2065 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2065 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2066 """retrieves a bundle from a repo
2066 """retrieves a bundle from a repo
2067
2067
2068 Every ID must be a full-length hex node id string. Saves the bundle to the
2068 Every ID must be a full-length hex node id string. Saves the bundle to the
2069 given file.
2069 given file.
2070 """
2070 """
2071 repo = hg.peer(ui, opts, repopath)
2071 repo = hg.peer(ui, opts, repopath)
2072 if not repo.capable('getbundle'):
2072 if not repo.capable('getbundle'):
2073 raise util.Abort("getbundle() not supported by target repository")
2073 raise util.Abort("getbundle() not supported by target repository")
2074 args = {}
2074 args = {}
2075 if common:
2075 if common:
2076 args['common'] = [bin(s) for s in common]
2076 args['common'] = [bin(s) for s in common]
2077 if head:
2077 if head:
2078 args['heads'] = [bin(s) for s in head]
2078 args['heads'] = [bin(s) for s in head]
2079 # TODO: get desired bundlecaps from command line.
2079 # TODO: get desired bundlecaps from command line.
2080 args['bundlecaps'] = None
2080 args['bundlecaps'] = None
2081 bundle = repo.getbundle('debug', **args)
2081 bundle = repo.getbundle('debug', **args)
2082
2082
2083 bundletype = opts.get('type', 'bzip2').lower()
2083 bundletype = opts.get('type', 'bzip2').lower()
2084 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2084 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2085 bundletype = btypes.get(bundletype)
2085 bundletype = btypes.get(bundletype)
2086 if bundletype not in changegroup.bundletypes:
2086 if bundletype not in changegroup.bundletypes:
2087 raise util.Abort(_('unknown bundle type specified with --type'))
2087 raise util.Abort(_('unknown bundle type specified with --type'))
2088 changegroup.writebundle(bundle, bundlepath, bundletype)
2088 changegroup.writebundle(bundle, bundlepath, bundletype)
2089
2089
2090 @command('debugignore', [], '')
2090 @command('debugignore', [], '')
2091 def debugignore(ui, repo, *values, **opts):
2091 def debugignore(ui, repo, *values, **opts):
2092 """display the combined ignore pattern"""
2092 """display the combined ignore pattern"""
2093 ignore = repo.dirstate._ignore
2093 ignore = repo.dirstate._ignore
2094 includepat = getattr(ignore, 'includepat', None)
2094 includepat = getattr(ignore, 'includepat', None)
2095 if includepat is not None:
2095 if includepat is not None:
2096 ui.write("%s\n" % includepat)
2096 ui.write("%s\n" % includepat)
2097 else:
2097 else:
2098 raise util.Abort(_("no ignore patterns found"))
2098 raise util.Abort(_("no ignore patterns found"))
2099
2099
2100 @command('debugindex',
2100 @command('debugindex',
2101 [('c', 'changelog', False, _('open changelog')),
2101 [('c', 'changelog', False, _('open changelog')),
2102 ('m', 'manifest', False, _('open manifest')),
2102 ('m', 'manifest', False, _('open manifest')),
2103 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2103 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2104 _('[-f FORMAT] -c|-m|FILE'))
2104 _('[-f FORMAT] -c|-m|FILE'))
2105 def debugindex(ui, repo, file_=None, **opts):
2105 def debugindex(ui, repo, file_=None, **opts):
2106 """dump the contents of an index file"""
2106 """dump the contents of an index file"""
2107 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2107 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2108 format = opts.get('format', 0)
2108 format = opts.get('format', 0)
2109 if format not in (0, 1):
2109 if format not in (0, 1):
2110 raise util.Abort(_("unknown format %d") % format)
2110 raise util.Abort(_("unknown format %d") % format)
2111
2111
2112 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2112 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2113 if generaldelta:
2113 if generaldelta:
2114 basehdr = ' delta'
2114 basehdr = ' delta'
2115 else:
2115 else:
2116 basehdr = ' base'
2116 basehdr = ' base'
2117
2117
2118 if format == 0:
2118 if format == 0:
2119 ui.write(" rev offset length " + basehdr + " linkrev"
2119 ui.write(" rev offset length " + basehdr + " linkrev"
2120 " nodeid p1 p2\n")
2120 " nodeid p1 p2\n")
2121 elif format == 1:
2121 elif format == 1:
2122 ui.write(" rev flag offset length"
2122 ui.write(" rev flag offset length"
2123 " size " + basehdr + " link p1 p2"
2123 " size " + basehdr + " link p1 p2"
2124 " nodeid\n")
2124 " nodeid\n")
2125
2125
2126 for i in r:
2126 for i in r:
2127 node = r.node(i)
2127 node = r.node(i)
2128 if generaldelta:
2128 if generaldelta:
2129 base = r.deltaparent(i)
2129 base = r.deltaparent(i)
2130 else:
2130 else:
2131 base = r.chainbase(i)
2131 base = r.chainbase(i)
2132 if format == 0:
2132 if format == 0:
2133 try:
2133 try:
2134 pp = r.parents(node)
2134 pp = r.parents(node)
2135 except Exception:
2135 except Exception:
2136 pp = [nullid, nullid]
2136 pp = [nullid, nullid]
2137 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2137 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2138 i, r.start(i), r.length(i), base, r.linkrev(i),
2138 i, r.start(i), r.length(i), base, r.linkrev(i),
2139 short(node), short(pp[0]), short(pp[1])))
2139 short(node), short(pp[0]), short(pp[1])))
2140 elif format == 1:
2140 elif format == 1:
2141 pr = r.parentrevs(i)
2141 pr = r.parentrevs(i)
2142 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2142 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2143 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2143 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2144 base, r.linkrev(i), pr[0], pr[1], short(node)))
2144 base, r.linkrev(i), pr[0], pr[1], short(node)))
2145
2145
2146 @command('debugindexdot', [], _('FILE'))
2146 @command('debugindexdot', [], _('FILE'))
2147 def debugindexdot(ui, repo, file_):
2147 def debugindexdot(ui, repo, file_):
2148 """dump an index DAG as a graphviz dot file"""
2148 """dump an index DAG as a graphviz dot file"""
2149 r = None
2149 r = None
2150 if repo:
2150 if repo:
2151 filelog = repo.file(file_)
2151 filelog = repo.file(file_)
2152 if len(filelog):
2152 if len(filelog):
2153 r = filelog
2153 r = filelog
2154 if not r:
2154 if not r:
2155 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2155 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2156 ui.write(("digraph G {\n"))
2156 ui.write(("digraph G {\n"))
2157 for i in r:
2157 for i in r:
2158 node = r.node(i)
2158 node = r.node(i)
2159 pp = r.parents(node)
2159 pp = r.parents(node)
2160 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2160 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2161 if pp[1] != nullid:
2161 if pp[1] != nullid:
2162 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2162 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2163 ui.write("}\n")
2163 ui.write("}\n")
2164
2164
2165 @command('debuginstall', [], '')
2165 @command('debuginstall', [], '')
2166 def debuginstall(ui):
2166 def debuginstall(ui):
2167 '''test Mercurial installation
2167 '''test Mercurial installation
2168
2168
2169 Returns 0 on success.
2169 Returns 0 on success.
2170 '''
2170 '''
2171
2171
2172 def writetemp(contents):
2172 def writetemp(contents):
2173 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2173 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2174 f = os.fdopen(fd, "wb")
2174 f = os.fdopen(fd, "wb")
2175 f.write(contents)
2175 f.write(contents)
2176 f.close()
2176 f.close()
2177 return name
2177 return name
2178
2178
2179 problems = 0
2179 problems = 0
2180
2180
2181 # encoding
2181 # encoding
2182 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2182 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2183 try:
2183 try:
2184 encoding.fromlocal("test")
2184 encoding.fromlocal("test")
2185 except util.Abort, inst:
2185 except util.Abort, inst:
2186 ui.write(" %s\n" % inst)
2186 ui.write(" %s\n" % inst)
2187 ui.write(_(" (check that your locale is properly set)\n"))
2187 ui.write(_(" (check that your locale is properly set)\n"))
2188 problems += 1
2188 problems += 1
2189
2189
2190 # Python
2190 # Python
2191 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2191 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2192 ui.status(_("checking Python version (%s)\n")
2192 ui.status(_("checking Python version (%s)\n")
2193 % ("%s.%s.%s" % sys.version_info[:3]))
2193 % ("%s.%s.%s" % sys.version_info[:3]))
2194 ui.status(_("checking Python lib (%s)...\n")
2194 ui.status(_("checking Python lib (%s)...\n")
2195 % os.path.dirname(os.__file__))
2195 % os.path.dirname(os.__file__))
2196
2196
2197 # compiled modules
2197 # compiled modules
2198 ui.status(_("checking installed modules (%s)...\n")
2198 ui.status(_("checking installed modules (%s)...\n")
2199 % os.path.dirname(__file__))
2199 % os.path.dirname(__file__))
2200 try:
2200 try:
2201 import bdiff, mpatch, base85, osutil
2201 import bdiff, mpatch, base85, osutil
2202 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2202 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2203 except Exception, inst:
2203 except Exception, inst:
2204 ui.write(" %s\n" % inst)
2204 ui.write(" %s\n" % inst)
2205 ui.write(_(" One or more extensions could not be found"))
2205 ui.write(_(" One or more extensions could not be found"))
2206 ui.write(_(" (check that you compiled the extensions)\n"))
2206 ui.write(_(" (check that you compiled the extensions)\n"))
2207 problems += 1
2207 problems += 1
2208
2208
2209 # templates
2209 # templates
2210 import templater
2210 import templater
2211 p = templater.templatepath()
2211 p = templater.templatepath()
2212 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2212 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2213 if p:
2213 if p:
2214 m = templater.templatepath("map-cmdline.default")
2214 m = templater.templatepath("map-cmdline.default")
2215 if m:
2215 if m:
2216 # template found, check if it is working
2216 # template found, check if it is working
2217 try:
2217 try:
2218 templater.templater(m)
2218 templater.templater(m)
2219 except Exception, inst:
2219 except Exception, inst:
2220 ui.write(" %s\n" % inst)
2220 ui.write(" %s\n" % inst)
2221 p = None
2221 p = None
2222 else:
2222 else:
2223 ui.write(_(" template 'default' not found\n"))
2223 ui.write(_(" template 'default' not found\n"))
2224 p = None
2224 p = None
2225 else:
2225 else:
2226 ui.write(_(" no template directories found\n"))
2226 ui.write(_(" no template directories found\n"))
2227 if not p:
2227 if not p:
2228 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2228 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2229 problems += 1
2229 problems += 1
2230
2230
2231 # editor
2231 # editor
2232 ui.status(_("checking commit editor...\n"))
2232 ui.status(_("checking commit editor...\n"))
2233 editor = ui.geteditor()
2233 editor = ui.geteditor()
2234 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2234 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2235 if not cmdpath:
2235 if not cmdpath:
2236 if editor == 'vi':
2236 if editor == 'vi':
2237 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2237 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2238 ui.write(_(" (specify a commit editor in your configuration"
2238 ui.write(_(" (specify a commit editor in your configuration"
2239 " file)\n"))
2239 " file)\n"))
2240 else:
2240 else:
2241 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2241 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2242 ui.write(_(" (specify a commit editor in your configuration"
2242 ui.write(_(" (specify a commit editor in your configuration"
2243 " file)\n"))
2243 " file)\n"))
2244 problems += 1
2244 problems += 1
2245
2245
2246 # check username
2246 # check username
2247 ui.status(_("checking username...\n"))
2247 ui.status(_("checking username...\n"))
2248 try:
2248 try:
2249 ui.username()
2249 ui.username()
2250 except util.Abort, e:
2250 except util.Abort, e:
2251 ui.write(" %s\n" % e)
2251 ui.write(" %s\n" % e)
2252 ui.write(_(" (specify a username in your configuration file)\n"))
2252 ui.write(_(" (specify a username in your configuration file)\n"))
2253 problems += 1
2253 problems += 1
2254
2254
2255 if not problems:
2255 if not problems:
2256 ui.status(_("no problems detected\n"))
2256 ui.status(_("no problems detected\n"))
2257 else:
2257 else:
2258 ui.write(_("%s problems detected,"
2258 ui.write(_("%s problems detected,"
2259 " please check your install!\n") % problems)
2259 " please check your install!\n") % problems)
2260
2260
2261 return problems
2261 return problems
2262
2262
2263 @command('debugknown', [], _('REPO ID...'))
2263 @command('debugknown', [], _('REPO ID...'))
2264 def debugknown(ui, repopath, *ids, **opts):
2264 def debugknown(ui, repopath, *ids, **opts):
2265 """test whether node ids are known to a repo
2265 """test whether node ids are known to a repo
2266
2266
2267 Every ID must be a full-length hex node id string. Returns a list of 0s
2267 Every ID must be a full-length hex node id string. Returns a list of 0s
2268 and 1s indicating unknown/known.
2268 and 1s indicating unknown/known.
2269 """
2269 """
2270 repo = hg.peer(ui, opts, repopath)
2270 repo = hg.peer(ui, opts, repopath)
2271 if not repo.capable('known'):
2271 if not repo.capable('known'):
2272 raise util.Abort("known() not supported by target repository")
2272 raise util.Abort("known() not supported by target repository")
2273 flags = repo.known([bin(s) for s in ids])
2273 flags = repo.known([bin(s) for s in ids])
2274 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2274 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2275
2275
2276 @command('debuglabelcomplete', [], _('LABEL...'))
2276 @command('debuglabelcomplete', [], _('LABEL...'))
2277 def debuglabelcomplete(ui, repo, *args):
2277 def debuglabelcomplete(ui, repo, *args):
2278 '''complete "labels" - tags, open branch names, bookmark names'''
2278 '''complete "labels" - tags, open branch names, bookmark names'''
2279
2279
2280 labels = set()
2280 labels = set()
2281 labels.update(t[0] for t in repo.tagslist())
2281 labels.update(t[0] for t in repo.tagslist())
2282 labels.update(repo._bookmarks.keys())
2282 labels.update(repo._bookmarks.keys())
2283 labels.update(tag for (tag, heads, tip, closed)
2283 labels.update(tag for (tag, heads, tip, closed)
2284 in repo.branchmap().iterbranches() if not closed)
2284 in repo.branchmap().iterbranches() if not closed)
2285 completions = set()
2285 completions = set()
2286 if not args:
2286 if not args:
2287 args = ['']
2287 args = ['']
2288 for a in args:
2288 for a in args:
2289 completions.update(l for l in labels if l.startswith(a))
2289 completions.update(l for l in labels if l.startswith(a))
2290 ui.write('\n'.join(sorted(completions)))
2290 ui.write('\n'.join(sorted(completions)))
2291 ui.write('\n')
2291 ui.write('\n')
2292
2292
2293 @command('debugobsolete',
2293 @command('debugobsolete',
2294 [('', 'flags', 0, _('markers flag')),
2294 [('', 'flags', 0, _('markers flag')),
2295 ] + commitopts2,
2295 ] + commitopts2,
2296 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2296 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2297 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2297 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2298 """create arbitrary obsolete marker
2298 """create arbitrary obsolete marker
2299
2299
2300 With no arguments, displays the list of obsolescence markers."""
2300 With no arguments, displays the list of obsolescence markers."""
2301 def parsenodeid(s):
2301 def parsenodeid(s):
2302 try:
2302 try:
2303 # We do not use revsingle/revrange functions here to accept
2303 # We do not use revsingle/revrange functions here to accept
2304 # arbitrary node identifiers, possibly not present in the
2304 # arbitrary node identifiers, possibly not present in the
2305 # local repository.
2305 # local repository.
2306 n = bin(s)
2306 n = bin(s)
2307 if len(n) != len(nullid):
2307 if len(n) != len(nullid):
2308 raise TypeError()
2308 raise TypeError()
2309 return n
2309 return n
2310 except TypeError:
2310 except TypeError:
2311 raise util.Abort('changeset references must be full hexadecimal '
2311 raise util.Abort('changeset references must be full hexadecimal '
2312 'node identifiers')
2312 'node identifiers')
2313
2313
2314 if precursor is not None:
2314 if precursor is not None:
2315 metadata = {}
2315 metadata = {}
2316 if 'date' in opts:
2316 if 'date' in opts:
2317 metadata['date'] = opts['date']
2317 metadata['date'] = opts['date']
2318 metadata['user'] = opts['user'] or ui.username()
2318 metadata['user'] = opts['user'] or ui.username()
2319 succs = tuple(parsenodeid(succ) for succ in successors)
2319 succs = tuple(parsenodeid(succ) for succ in successors)
2320 l = repo.lock()
2320 l = repo.lock()
2321 try:
2321 try:
2322 tr = repo.transaction('debugobsolete')
2322 tr = repo.transaction('debugobsolete')
2323 try:
2323 try:
2324 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2324 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2325 opts['flags'], metadata)
2325 opts['flags'], metadata)
2326 tr.close()
2326 tr.close()
2327 finally:
2327 finally:
2328 tr.release()
2328 tr.release()
2329 finally:
2329 finally:
2330 l.release()
2330 l.release()
2331 else:
2331 else:
2332 for m in obsolete.allmarkers(repo):
2332 for m in obsolete.allmarkers(repo):
2333 cmdutil.showmarker(ui, m)
2333 cmdutil.showmarker(ui, m)
2334
2334
2335 @command('debugpathcomplete',
2335 @command('debugpathcomplete',
2336 [('f', 'full', None, _('complete an entire path')),
2336 [('f', 'full', None, _('complete an entire path')),
2337 ('n', 'normal', None, _('show only normal files')),
2337 ('n', 'normal', None, _('show only normal files')),
2338 ('a', 'added', None, _('show only added files')),
2338 ('a', 'added', None, _('show only added files')),
2339 ('r', 'removed', None, _('show only removed files'))],
2339 ('r', 'removed', None, _('show only removed files'))],
2340 _('FILESPEC...'))
2340 _('FILESPEC...'))
2341 def debugpathcomplete(ui, repo, *specs, **opts):
2341 def debugpathcomplete(ui, repo, *specs, **opts):
2342 '''complete part or all of a tracked path
2342 '''complete part or all of a tracked path
2343
2343
2344 This command supports shells that offer path name completion. It
2344 This command supports shells that offer path name completion. It
2345 currently completes only files already known to the dirstate.
2345 currently completes only files already known to the dirstate.
2346
2346
2347 Completion extends only to the next path segment unless
2347 Completion extends only to the next path segment unless
2348 --full is specified, in which case entire paths are used.'''
2348 --full is specified, in which case entire paths are used.'''
2349
2349
2350 def complete(path, acceptable):
2350 def complete(path, acceptable):
2351 dirstate = repo.dirstate
2351 dirstate = repo.dirstate
2352 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2352 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2353 rootdir = repo.root + os.sep
2353 rootdir = repo.root + os.sep
2354 if spec != repo.root and not spec.startswith(rootdir):
2354 if spec != repo.root and not spec.startswith(rootdir):
2355 return [], []
2355 return [], []
2356 if os.path.isdir(spec):
2356 if os.path.isdir(spec):
2357 spec += '/'
2357 spec += '/'
2358 spec = spec[len(rootdir):]
2358 spec = spec[len(rootdir):]
2359 fixpaths = os.sep != '/'
2359 fixpaths = os.sep != '/'
2360 if fixpaths:
2360 if fixpaths:
2361 spec = spec.replace(os.sep, '/')
2361 spec = spec.replace(os.sep, '/')
2362 speclen = len(spec)
2362 speclen = len(spec)
2363 fullpaths = opts['full']
2363 fullpaths = opts['full']
2364 files, dirs = set(), set()
2364 files, dirs = set(), set()
2365 adddir, addfile = dirs.add, files.add
2365 adddir, addfile = dirs.add, files.add
2366 for f, st in dirstate.iteritems():
2366 for f, st in dirstate.iteritems():
2367 if f.startswith(spec) and st[0] in acceptable:
2367 if f.startswith(spec) and st[0] in acceptable:
2368 if fixpaths:
2368 if fixpaths:
2369 f = f.replace('/', os.sep)
2369 f = f.replace('/', os.sep)
2370 if fullpaths:
2370 if fullpaths:
2371 addfile(f)
2371 addfile(f)
2372 continue
2372 continue
2373 s = f.find(os.sep, speclen)
2373 s = f.find(os.sep, speclen)
2374 if s >= 0:
2374 if s >= 0:
2375 adddir(f[:s])
2375 adddir(f[:s])
2376 else:
2376 else:
2377 addfile(f)
2377 addfile(f)
2378 return files, dirs
2378 return files, dirs
2379
2379
2380 acceptable = ''
2380 acceptable = ''
2381 if opts['normal']:
2381 if opts['normal']:
2382 acceptable += 'nm'
2382 acceptable += 'nm'
2383 if opts['added']:
2383 if opts['added']:
2384 acceptable += 'a'
2384 acceptable += 'a'
2385 if opts['removed']:
2385 if opts['removed']:
2386 acceptable += 'r'
2386 acceptable += 'r'
2387 cwd = repo.getcwd()
2387 cwd = repo.getcwd()
2388 if not specs:
2388 if not specs:
2389 specs = ['.']
2389 specs = ['.']
2390
2390
2391 files, dirs = set(), set()
2391 files, dirs = set(), set()
2392 for spec in specs:
2392 for spec in specs:
2393 f, d = complete(spec, acceptable or 'nmar')
2393 f, d = complete(spec, acceptable or 'nmar')
2394 files.update(f)
2394 files.update(f)
2395 dirs.update(d)
2395 dirs.update(d)
2396 files.update(dirs)
2396 files.update(dirs)
2397 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2397 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2398 ui.write('\n')
2398 ui.write('\n')
2399
2399
2400 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2400 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2401 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2401 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2402 '''access the pushkey key/value protocol
2402 '''access the pushkey key/value protocol
2403
2403
2404 With two args, list the keys in the given namespace.
2404 With two args, list the keys in the given namespace.
2405
2405
2406 With five args, set a key to new if it currently is set to old.
2406 With five args, set a key to new if it currently is set to old.
2407 Reports success or failure.
2407 Reports success or failure.
2408 '''
2408 '''
2409
2409
2410 target = hg.peer(ui, {}, repopath)
2410 target = hg.peer(ui, {}, repopath)
2411 if keyinfo:
2411 if keyinfo:
2412 key, old, new = keyinfo
2412 key, old, new = keyinfo
2413 r = target.pushkey(namespace, key, old, new)
2413 r = target.pushkey(namespace, key, old, new)
2414 ui.status(str(r) + '\n')
2414 ui.status(str(r) + '\n')
2415 return not r
2415 return not r
2416 else:
2416 else:
2417 for k, v in sorted(target.listkeys(namespace).iteritems()):
2417 for k, v in sorted(target.listkeys(namespace).iteritems()):
2418 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2418 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2419 v.encode('string-escape')))
2419 v.encode('string-escape')))
2420
2420
2421 @command('debugpvec', [], _('A B'))
2421 @command('debugpvec', [], _('A B'))
2422 def debugpvec(ui, repo, a, b=None):
2422 def debugpvec(ui, repo, a, b=None):
2423 ca = scmutil.revsingle(repo, a)
2423 ca = scmutil.revsingle(repo, a)
2424 cb = scmutil.revsingle(repo, b)
2424 cb = scmutil.revsingle(repo, b)
2425 pa = pvec.ctxpvec(ca)
2425 pa = pvec.ctxpvec(ca)
2426 pb = pvec.ctxpvec(cb)
2426 pb = pvec.ctxpvec(cb)
2427 if pa == pb:
2427 if pa == pb:
2428 rel = "="
2428 rel = "="
2429 elif pa > pb:
2429 elif pa > pb:
2430 rel = ">"
2430 rel = ">"
2431 elif pa < pb:
2431 elif pa < pb:
2432 rel = "<"
2432 rel = "<"
2433 elif pa | pb:
2433 elif pa | pb:
2434 rel = "|"
2434 rel = "|"
2435 ui.write(_("a: %s\n") % pa)
2435 ui.write(_("a: %s\n") % pa)
2436 ui.write(_("b: %s\n") % pb)
2436 ui.write(_("b: %s\n") % pb)
2437 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2437 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2438 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2438 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2439 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2439 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2440 pa.distance(pb), rel))
2440 pa.distance(pb), rel))
2441
2441
2442 @command('debugrebuilddirstate|debugrebuildstate',
2442 @command('debugrebuilddirstate|debugrebuildstate',
2443 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2443 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2444 _('[-r REV]'))
2444 _('[-r REV]'))
2445 def debugrebuilddirstate(ui, repo, rev):
2445 def debugrebuilddirstate(ui, repo, rev):
2446 """rebuild the dirstate as it would look like for the given revision
2446 """rebuild the dirstate as it would look like for the given revision
2447
2447
2448 If no revision is specified the first current parent will be used.
2448 If no revision is specified the first current parent will be used.
2449
2449
2450 The dirstate will be set to the files of the given revision.
2450 The dirstate will be set to the files of the given revision.
2451 The actual working directory content or existing dirstate
2451 The actual working directory content or existing dirstate
2452 information such as adds or removes is not considered.
2452 information such as adds or removes is not considered.
2453
2453
2454 One use of this command is to make the next :hg:`status` invocation
2454 One use of this command is to make the next :hg:`status` invocation
2455 check the actual file content.
2455 check the actual file content.
2456 """
2456 """
2457 ctx = scmutil.revsingle(repo, rev)
2457 ctx = scmutil.revsingle(repo, rev)
2458 wlock = repo.wlock()
2458 wlock = repo.wlock()
2459 try:
2459 try:
2460 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2460 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2461 finally:
2461 finally:
2462 wlock.release()
2462 wlock.release()
2463
2463
2464 @command('debugrename',
2464 @command('debugrename',
2465 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2465 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2466 _('[-r REV] FILE'))
2466 _('[-r REV] FILE'))
2467 def debugrename(ui, repo, file1, *pats, **opts):
2467 def debugrename(ui, repo, file1, *pats, **opts):
2468 """dump rename information"""
2468 """dump rename information"""
2469
2469
2470 ctx = scmutil.revsingle(repo, opts.get('rev'))
2470 ctx = scmutil.revsingle(repo, opts.get('rev'))
2471 m = scmutil.match(ctx, (file1,) + pats, opts)
2471 m = scmutil.match(ctx, (file1,) + pats, opts)
2472 for abs in ctx.walk(m):
2472 for abs in ctx.walk(m):
2473 fctx = ctx[abs]
2473 fctx = ctx[abs]
2474 o = fctx.filelog().renamed(fctx.filenode())
2474 o = fctx.filelog().renamed(fctx.filenode())
2475 rel = m.rel(abs)
2475 rel = m.rel(abs)
2476 if o:
2476 if o:
2477 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2477 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2478 else:
2478 else:
2479 ui.write(_("%s not renamed\n") % rel)
2479 ui.write(_("%s not renamed\n") % rel)
2480
2480
2481 @command('debugrevlog',
2481 @command('debugrevlog',
2482 [('c', 'changelog', False, _('open changelog')),
2482 [('c', 'changelog', False, _('open changelog')),
2483 ('m', 'manifest', False, _('open manifest')),
2483 ('m', 'manifest', False, _('open manifest')),
2484 ('d', 'dump', False, _('dump index data'))],
2484 ('d', 'dump', False, _('dump index data'))],
2485 _('-c|-m|FILE'))
2485 _('-c|-m|FILE'))
2486 def debugrevlog(ui, repo, file_=None, **opts):
2486 def debugrevlog(ui, repo, file_=None, **opts):
2487 """show data and statistics about a revlog"""
2487 """show data and statistics about a revlog"""
2488 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2488 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2489
2489
2490 if opts.get("dump"):
2490 if opts.get("dump"):
2491 numrevs = len(r)
2491 numrevs = len(r)
2492 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2492 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2493 " rawsize totalsize compression heads\n")
2493 " rawsize totalsize compression heads\n")
2494 ts = 0
2494 ts = 0
2495 heads = set()
2495 heads = set()
2496 for rev in xrange(numrevs):
2496 for rev in xrange(numrevs):
2497 dbase = r.deltaparent(rev)
2497 dbase = r.deltaparent(rev)
2498 if dbase == -1:
2498 if dbase == -1:
2499 dbase = rev
2499 dbase = rev
2500 cbase = r.chainbase(rev)
2500 cbase = r.chainbase(rev)
2501 p1, p2 = r.parentrevs(rev)
2501 p1, p2 = r.parentrevs(rev)
2502 rs = r.rawsize(rev)
2502 rs = r.rawsize(rev)
2503 ts = ts + rs
2503 ts = ts + rs
2504 heads -= set(r.parentrevs(rev))
2504 heads -= set(r.parentrevs(rev))
2505 heads.add(rev)
2505 heads.add(rev)
2506 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2506 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
2507 (rev, p1, p2, r.start(rev), r.end(rev),
2507 (rev, p1, p2, r.start(rev), r.end(rev),
2508 r.start(dbase), r.start(cbase),
2508 r.start(dbase), r.start(cbase),
2509 r.start(p1), r.start(p2),
2509 r.start(p1), r.start(p2),
2510 rs, ts, ts / r.end(rev), len(heads)))
2510 rs, ts, ts / r.end(rev), len(heads)))
2511 return 0
2511 return 0
2512
2512
2513 v = r.version
2513 v = r.version
2514 format = v & 0xFFFF
2514 format = v & 0xFFFF
2515 flags = []
2515 flags = []
2516 gdelta = False
2516 gdelta = False
2517 if v & revlog.REVLOGNGINLINEDATA:
2517 if v & revlog.REVLOGNGINLINEDATA:
2518 flags.append('inline')
2518 flags.append('inline')
2519 if v & revlog.REVLOGGENERALDELTA:
2519 if v & revlog.REVLOGGENERALDELTA:
2520 gdelta = True
2520 gdelta = True
2521 flags.append('generaldelta')
2521 flags.append('generaldelta')
2522 if not flags:
2522 if not flags:
2523 flags = ['(none)']
2523 flags = ['(none)']
2524
2524
2525 nummerges = 0
2525 nummerges = 0
2526 numfull = 0
2526 numfull = 0
2527 numprev = 0
2527 numprev = 0
2528 nump1 = 0
2528 nump1 = 0
2529 nump2 = 0
2529 nump2 = 0
2530 numother = 0
2530 numother = 0
2531 nump1prev = 0
2531 nump1prev = 0
2532 nump2prev = 0
2532 nump2prev = 0
2533 chainlengths = []
2533 chainlengths = []
2534
2534
2535 datasize = [None, 0, 0L]
2535 datasize = [None, 0, 0L]
2536 fullsize = [None, 0, 0L]
2536 fullsize = [None, 0, 0L]
2537 deltasize = [None, 0, 0L]
2537 deltasize = [None, 0, 0L]
2538
2538
2539 def addsize(size, l):
2539 def addsize(size, l):
2540 if l[0] is None or size < l[0]:
2540 if l[0] is None or size < l[0]:
2541 l[0] = size
2541 l[0] = size
2542 if size > l[1]:
2542 if size > l[1]:
2543 l[1] = size
2543 l[1] = size
2544 l[2] += size
2544 l[2] += size
2545
2545
2546 numrevs = len(r)
2546 numrevs = len(r)
2547 for rev in xrange(numrevs):
2547 for rev in xrange(numrevs):
2548 p1, p2 = r.parentrevs(rev)
2548 p1, p2 = r.parentrevs(rev)
2549 delta = r.deltaparent(rev)
2549 delta = r.deltaparent(rev)
2550 if format > 0:
2550 if format > 0:
2551 addsize(r.rawsize(rev), datasize)
2551 addsize(r.rawsize(rev), datasize)
2552 if p2 != nullrev:
2552 if p2 != nullrev:
2553 nummerges += 1
2553 nummerges += 1
2554 size = r.length(rev)
2554 size = r.length(rev)
2555 if delta == nullrev:
2555 if delta == nullrev:
2556 chainlengths.append(0)
2556 chainlengths.append(0)
2557 numfull += 1
2557 numfull += 1
2558 addsize(size, fullsize)
2558 addsize(size, fullsize)
2559 else:
2559 else:
2560 chainlengths.append(chainlengths[delta] + 1)
2560 chainlengths.append(chainlengths[delta] + 1)
2561 addsize(size, deltasize)
2561 addsize(size, deltasize)
2562 if delta == rev - 1:
2562 if delta == rev - 1:
2563 numprev += 1
2563 numprev += 1
2564 if delta == p1:
2564 if delta == p1:
2565 nump1prev += 1
2565 nump1prev += 1
2566 elif delta == p2:
2566 elif delta == p2:
2567 nump2prev += 1
2567 nump2prev += 1
2568 elif delta == p1:
2568 elif delta == p1:
2569 nump1 += 1
2569 nump1 += 1
2570 elif delta == p2:
2570 elif delta == p2:
2571 nump2 += 1
2571 nump2 += 1
2572 elif delta != nullrev:
2572 elif delta != nullrev:
2573 numother += 1
2573 numother += 1
2574
2574
2575 # Adjust size min value for empty cases
2575 # Adjust size min value for empty cases
2576 for size in (datasize, fullsize, deltasize):
2576 for size in (datasize, fullsize, deltasize):
2577 if size[0] is None:
2577 if size[0] is None:
2578 size[0] = 0
2578 size[0] = 0
2579
2579
2580 numdeltas = numrevs - numfull
2580 numdeltas = numrevs - numfull
2581 numoprev = numprev - nump1prev - nump2prev
2581 numoprev = numprev - nump1prev - nump2prev
2582 totalrawsize = datasize[2]
2582 totalrawsize = datasize[2]
2583 datasize[2] /= numrevs
2583 datasize[2] /= numrevs
2584 fulltotal = fullsize[2]
2584 fulltotal = fullsize[2]
2585 fullsize[2] /= numfull
2585 fullsize[2] /= numfull
2586 deltatotal = deltasize[2]
2586 deltatotal = deltasize[2]
2587 if numrevs - numfull > 0:
2587 if numrevs - numfull > 0:
2588 deltasize[2] /= numrevs - numfull
2588 deltasize[2] /= numrevs - numfull
2589 totalsize = fulltotal + deltatotal
2589 totalsize = fulltotal + deltatotal
2590 avgchainlen = sum(chainlengths) / numrevs
2590 avgchainlen = sum(chainlengths) / numrevs
2591 compratio = totalrawsize / totalsize
2591 compratio = totalrawsize / totalsize
2592
2592
2593 basedfmtstr = '%%%dd\n'
2593 basedfmtstr = '%%%dd\n'
2594 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2594 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2595
2595
2596 def dfmtstr(max):
2596 def dfmtstr(max):
2597 return basedfmtstr % len(str(max))
2597 return basedfmtstr % len(str(max))
2598 def pcfmtstr(max, padding=0):
2598 def pcfmtstr(max, padding=0):
2599 return basepcfmtstr % (len(str(max)), ' ' * padding)
2599 return basepcfmtstr % (len(str(max)), ' ' * padding)
2600
2600
2601 def pcfmt(value, total):
2601 def pcfmt(value, total):
2602 return (value, 100 * float(value) / total)
2602 return (value, 100 * float(value) / total)
2603
2603
2604 ui.write(('format : %d\n') % format)
2604 ui.write(('format : %d\n') % format)
2605 ui.write(('flags : %s\n') % ', '.join(flags))
2605 ui.write(('flags : %s\n') % ', '.join(flags))
2606
2606
2607 ui.write('\n')
2607 ui.write('\n')
2608 fmt = pcfmtstr(totalsize)
2608 fmt = pcfmtstr(totalsize)
2609 fmt2 = dfmtstr(totalsize)
2609 fmt2 = dfmtstr(totalsize)
2610 ui.write(('revisions : ') + fmt2 % numrevs)
2610 ui.write(('revisions : ') + fmt2 % numrevs)
2611 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2611 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2612 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2612 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2613 ui.write(('revisions : ') + fmt2 % numrevs)
2613 ui.write(('revisions : ') + fmt2 % numrevs)
2614 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2614 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2615 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2615 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2616 ui.write(('revision size : ') + fmt2 % totalsize)
2616 ui.write(('revision size : ') + fmt2 % totalsize)
2617 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2617 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2618 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2618 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2619
2619
2620 ui.write('\n')
2620 ui.write('\n')
2621 fmt = dfmtstr(max(avgchainlen, compratio))
2621 fmt = dfmtstr(max(avgchainlen, compratio))
2622 ui.write(('avg chain length : ') + fmt % avgchainlen)
2622 ui.write(('avg chain length : ') + fmt % avgchainlen)
2623 ui.write(('compression ratio : ') + fmt % compratio)
2623 ui.write(('compression ratio : ') + fmt % compratio)
2624
2624
2625 if format > 0:
2625 if format > 0:
2626 ui.write('\n')
2626 ui.write('\n')
2627 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2627 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2628 % tuple(datasize))
2628 % tuple(datasize))
2629 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2629 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2630 % tuple(fullsize))
2630 % tuple(fullsize))
2631 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2631 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2632 % tuple(deltasize))
2632 % tuple(deltasize))
2633
2633
2634 if numdeltas > 0:
2634 if numdeltas > 0:
2635 ui.write('\n')
2635 ui.write('\n')
2636 fmt = pcfmtstr(numdeltas)
2636 fmt = pcfmtstr(numdeltas)
2637 fmt2 = pcfmtstr(numdeltas, 4)
2637 fmt2 = pcfmtstr(numdeltas, 4)
2638 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2638 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2639 if numprev > 0:
2639 if numprev > 0:
2640 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2640 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2641 numprev))
2641 numprev))
2642 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2642 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2643 numprev))
2643 numprev))
2644 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2644 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2645 numprev))
2645 numprev))
2646 if gdelta:
2646 if gdelta:
2647 ui.write(('deltas against p1 : ')
2647 ui.write(('deltas against p1 : ')
2648 + fmt % pcfmt(nump1, numdeltas))
2648 + fmt % pcfmt(nump1, numdeltas))
2649 ui.write(('deltas against p2 : ')
2649 ui.write(('deltas against p2 : ')
2650 + fmt % pcfmt(nump2, numdeltas))
2650 + fmt % pcfmt(nump2, numdeltas))
2651 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2651 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2652 numdeltas))
2652 numdeltas))
2653
2653
2654 @command('debugrevspec',
2654 @command('debugrevspec',
2655 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2655 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2656 ('REVSPEC'))
2656 ('REVSPEC'))
2657 def debugrevspec(ui, repo, expr, **opts):
2657 def debugrevspec(ui, repo, expr, **opts):
2658 """parse and apply a revision specification
2658 """parse and apply a revision specification
2659
2659
2660 Use --verbose to print the parsed tree before and after aliases
2660 Use --verbose to print the parsed tree before and after aliases
2661 expansion.
2661 expansion.
2662 """
2662 """
2663 if ui.verbose:
2663 if ui.verbose:
2664 tree = revset.parse(expr)[0]
2664 tree = revset.parse(expr)[0]
2665 ui.note(revset.prettyformat(tree), "\n")
2665 ui.note(revset.prettyformat(tree), "\n")
2666 newtree = revset.findaliases(ui, tree)
2666 newtree = revset.findaliases(ui, tree)
2667 if newtree != tree:
2667 if newtree != tree:
2668 ui.note(revset.prettyformat(newtree), "\n")
2668 ui.note(revset.prettyformat(newtree), "\n")
2669 if opts["optimize"]:
2669 if opts["optimize"]:
2670 weight, optimizedtree = revset.optimize(newtree, True)
2670 weight, optimizedtree = revset.optimize(newtree, True)
2671 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2671 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2672 func = revset.match(ui, expr)
2672 func = revset.match(ui, expr)
2673 for c in func(repo, revset.spanset(repo)):
2673 for c in func(repo, revset.spanset(repo)):
2674 ui.write("%s\n" % c)
2674 ui.write("%s\n" % c)
2675
2675
2676 @command('debugsetparents', [], _('REV1 [REV2]'))
2676 @command('debugsetparents', [], _('REV1 [REV2]'))
2677 def debugsetparents(ui, repo, rev1, rev2=None):
2677 def debugsetparents(ui, repo, rev1, rev2=None):
2678 """manually set the parents of the current working directory
2678 """manually set the parents of the current working directory
2679
2679
2680 This is useful for writing repository conversion tools, but should
2680 This is useful for writing repository conversion tools, but should
2681 be used with care.
2681 be used with care.
2682
2682
2683 Returns 0 on success.
2683 Returns 0 on success.
2684 """
2684 """
2685
2685
2686 r1 = scmutil.revsingle(repo, rev1).node()
2686 r1 = scmutil.revsingle(repo, rev1).node()
2687 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2687 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2688
2688
2689 wlock = repo.wlock()
2689 wlock = repo.wlock()
2690 try:
2690 try:
2691 repo.setparents(r1, r2)
2691 repo.setparents(r1, r2)
2692 finally:
2692 finally:
2693 wlock.release()
2693 wlock.release()
2694
2694
2695 @command('debugdirstate|debugstate',
2695 @command('debugdirstate|debugstate',
2696 [('', 'nodates', None, _('do not display the saved mtime')),
2696 [('', 'nodates', None, _('do not display the saved mtime')),
2697 ('', 'datesort', None, _('sort by saved mtime'))],
2697 ('', 'datesort', None, _('sort by saved mtime'))],
2698 _('[OPTION]...'))
2698 _('[OPTION]...'))
2699 def debugstate(ui, repo, nodates=None, datesort=None):
2699 def debugstate(ui, repo, nodates=None, datesort=None):
2700 """show the contents of the current dirstate"""
2700 """show the contents of the current dirstate"""
2701 timestr = ""
2701 timestr = ""
2702 showdate = not nodates
2702 showdate = not nodates
2703 if datesort:
2703 if datesort:
2704 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2704 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2705 else:
2705 else:
2706 keyfunc = None # sort by filename
2706 keyfunc = None # sort by filename
2707 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2707 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2708 if showdate:
2708 if showdate:
2709 if ent[3] == -1:
2709 if ent[3] == -1:
2710 # Pad or slice to locale representation
2710 # Pad or slice to locale representation
2711 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2711 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2712 time.localtime(0)))
2712 time.localtime(0)))
2713 timestr = 'unset'
2713 timestr = 'unset'
2714 timestr = (timestr[:locale_len] +
2714 timestr = (timestr[:locale_len] +
2715 ' ' * (locale_len - len(timestr)))
2715 ' ' * (locale_len - len(timestr)))
2716 else:
2716 else:
2717 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2717 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2718 time.localtime(ent[3]))
2718 time.localtime(ent[3]))
2719 if ent[1] & 020000:
2719 if ent[1] & 020000:
2720 mode = 'lnk'
2720 mode = 'lnk'
2721 else:
2721 else:
2722 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2722 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2723 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2723 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2724 for f in repo.dirstate.copies():
2724 for f in repo.dirstate.copies():
2725 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2725 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2726
2726
2727 @command('debugsub',
2727 @command('debugsub',
2728 [('r', 'rev', '',
2728 [('r', 'rev', '',
2729 _('revision to check'), _('REV'))],
2729 _('revision to check'), _('REV'))],
2730 _('[-r REV] [REV]'))
2730 _('[-r REV] [REV]'))
2731 def debugsub(ui, repo, rev=None):
2731 def debugsub(ui, repo, rev=None):
2732 ctx = scmutil.revsingle(repo, rev, None)
2732 ctx = scmutil.revsingle(repo, rev, None)
2733 for k, v in sorted(ctx.substate.items()):
2733 for k, v in sorted(ctx.substate.items()):
2734 ui.write(('path %s\n') % k)
2734 ui.write(('path %s\n') % k)
2735 ui.write((' source %s\n') % v[0])
2735 ui.write((' source %s\n') % v[0])
2736 ui.write((' revision %s\n') % v[1])
2736 ui.write((' revision %s\n') % v[1])
2737
2737
2738 @command('debugsuccessorssets',
2738 @command('debugsuccessorssets',
2739 [],
2739 [],
2740 _('[REV]'))
2740 _('[REV]'))
2741 def debugsuccessorssets(ui, repo, *revs):
2741 def debugsuccessorssets(ui, repo, *revs):
2742 """show set of successors for revision
2742 """show set of successors for revision
2743
2743
2744 A successors set of changeset A is a consistent group of revisions that
2744 A successors set of changeset A is a consistent group of revisions that
2745 succeed A. It contains non-obsolete changesets only.
2745 succeed A. It contains non-obsolete changesets only.
2746
2746
2747 In most cases a changeset A has a single successors set containing a single
2747 In most cases a changeset A has a single successors set containing a single
2748 successor (changeset A replaced by A').
2748 successor (changeset A replaced by A').
2749
2749
2750 A changeset that is made obsolete with no successors are called "pruned".
2750 A changeset that is made obsolete with no successors are called "pruned".
2751 Such changesets have no successors sets at all.
2751 Such changesets have no successors sets at all.
2752
2752
2753 A changeset that has been "split" will have a successors set containing
2753 A changeset that has been "split" will have a successors set containing
2754 more than one successor.
2754 more than one successor.
2755
2755
2756 A changeset that has been rewritten in multiple different ways is called
2756 A changeset that has been rewritten in multiple different ways is called
2757 "divergent". Such changesets have multiple successor sets (each of which
2757 "divergent". Such changesets have multiple successor sets (each of which
2758 may also be split, i.e. have multiple successors).
2758 may also be split, i.e. have multiple successors).
2759
2759
2760 Results are displayed as follows::
2760 Results are displayed as follows::
2761
2761
2762 <rev1>
2762 <rev1>
2763 <successors-1A>
2763 <successors-1A>
2764 <rev2>
2764 <rev2>
2765 <successors-2A>
2765 <successors-2A>
2766 <successors-2B1> <successors-2B2> <successors-2B3>
2766 <successors-2B1> <successors-2B2> <successors-2B3>
2767
2767
2768 Here rev2 has two possible (i.e. divergent) successors sets. The first
2768 Here rev2 has two possible (i.e. divergent) successors sets. The first
2769 holds one element, whereas the second holds three (i.e. the changeset has
2769 holds one element, whereas the second holds three (i.e. the changeset has
2770 been split).
2770 been split).
2771 """
2771 """
2772 # passed to successorssets caching computation from one call to another
2772 # passed to successorssets caching computation from one call to another
2773 cache = {}
2773 cache = {}
2774 ctx2str = str
2774 ctx2str = str
2775 node2str = short
2775 node2str = short
2776 if ui.debug():
2776 if ui.debug():
2777 def ctx2str(ctx):
2777 def ctx2str(ctx):
2778 return ctx.hex()
2778 return ctx.hex()
2779 node2str = hex
2779 node2str = hex
2780 for rev in scmutil.revrange(repo, revs):
2780 for rev in scmutil.revrange(repo, revs):
2781 ctx = repo[rev]
2781 ctx = repo[rev]
2782 ui.write('%s\n'% ctx2str(ctx))
2782 ui.write('%s\n'% ctx2str(ctx))
2783 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2783 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2784 if succsset:
2784 if succsset:
2785 ui.write(' ')
2785 ui.write(' ')
2786 ui.write(node2str(succsset[0]))
2786 ui.write(node2str(succsset[0]))
2787 for node in succsset[1:]:
2787 for node in succsset[1:]:
2788 ui.write(' ')
2788 ui.write(' ')
2789 ui.write(node2str(node))
2789 ui.write(node2str(node))
2790 ui.write('\n')
2790 ui.write('\n')
2791
2791
2792 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2792 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2793 def debugwalk(ui, repo, *pats, **opts):
2793 def debugwalk(ui, repo, *pats, **opts):
2794 """show how files match on given patterns"""
2794 """show how files match on given patterns"""
2795 m = scmutil.match(repo[None], pats, opts)
2795 m = scmutil.match(repo[None], pats, opts)
2796 items = list(repo.walk(m))
2796 items = list(repo.walk(m))
2797 if not items:
2797 if not items:
2798 return
2798 return
2799 f = lambda fn: fn
2799 f = lambda fn: fn
2800 if ui.configbool('ui', 'slash') and os.sep != '/':
2800 if ui.configbool('ui', 'slash') and os.sep != '/':
2801 f = lambda fn: util.normpath(fn)
2801 f = lambda fn: util.normpath(fn)
2802 fmt = 'f %%-%ds %%-%ds %%s' % (
2802 fmt = 'f %%-%ds %%-%ds %%s' % (
2803 max([len(abs) for abs in items]),
2803 max([len(abs) for abs in items]),
2804 max([len(m.rel(abs)) for abs in items]))
2804 max([len(m.rel(abs)) for abs in items]))
2805 for abs in items:
2805 for abs in items:
2806 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2806 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2807 ui.write("%s\n" % line.rstrip())
2807 ui.write("%s\n" % line.rstrip())
2808
2808
2809 @command('debugwireargs',
2809 @command('debugwireargs',
2810 [('', 'three', '', 'three'),
2810 [('', 'three', '', 'three'),
2811 ('', 'four', '', 'four'),
2811 ('', 'four', '', 'four'),
2812 ('', 'five', '', 'five'),
2812 ('', 'five', '', 'five'),
2813 ] + remoteopts,
2813 ] + remoteopts,
2814 _('REPO [OPTIONS]... [ONE [TWO]]'))
2814 _('REPO [OPTIONS]... [ONE [TWO]]'))
2815 def debugwireargs(ui, repopath, *vals, **opts):
2815 def debugwireargs(ui, repopath, *vals, **opts):
2816 repo = hg.peer(ui, opts, repopath)
2816 repo = hg.peer(ui, opts, repopath)
2817 for opt in remoteopts:
2817 for opt in remoteopts:
2818 del opts[opt[1]]
2818 del opts[opt[1]]
2819 args = {}
2819 args = {}
2820 for k, v in opts.iteritems():
2820 for k, v in opts.iteritems():
2821 if v:
2821 if v:
2822 args[k] = v
2822 args[k] = v
2823 # run twice to check that we don't mess up the stream for the next command
2823 # run twice to check that we don't mess up the stream for the next command
2824 res1 = repo.debugwireargs(*vals, **args)
2824 res1 = repo.debugwireargs(*vals, **args)
2825 res2 = repo.debugwireargs(*vals, **args)
2825 res2 = repo.debugwireargs(*vals, **args)
2826 ui.write("%s\n" % res1)
2826 ui.write("%s\n" % res1)
2827 if res1 != res2:
2827 if res1 != res2:
2828 ui.warn("%s\n" % res2)
2828 ui.warn("%s\n" % res2)
2829
2829
2830 @command('^diff',
2830 @command('^diff',
2831 [('r', 'rev', [], _('revision'), _('REV')),
2831 [('r', 'rev', [], _('revision'), _('REV')),
2832 ('c', 'change', '', _('change made by revision'), _('REV'))
2832 ('c', 'change', '', _('change made by revision'), _('REV'))
2833 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2833 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2834 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2834 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2835 def diff(ui, repo, *pats, **opts):
2835 def diff(ui, repo, *pats, **opts):
2836 """diff repository (or selected files)
2836 """diff repository (or selected files)
2837
2837
2838 Show differences between revisions for the specified files.
2838 Show differences between revisions for the specified files.
2839
2839
2840 Differences between files are shown using the unified diff format.
2840 Differences between files are shown using the unified diff format.
2841
2841
2842 .. note::
2842 .. note::
2843
2843
2844 diff may generate unexpected results for merges, as it will
2844 diff may generate unexpected results for merges, as it will
2845 default to comparing against the working directory's first
2845 default to comparing against the working directory's first
2846 parent changeset if no revisions are specified.
2846 parent changeset if no revisions are specified.
2847
2847
2848 When two revision arguments are given, then changes are shown
2848 When two revision arguments are given, then changes are shown
2849 between those revisions. If only one revision is specified then
2849 between those revisions. If only one revision is specified then
2850 that revision is compared to the working directory, and, when no
2850 that revision is compared to the working directory, and, when no
2851 revisions are specified, the working directory files are compared
2851 revisions are specified, the working directory files are compared
2852 to its parent.
2852 to its parent.
2853
2853
2854 Alternatively you can specify -c/--change with a revision to see
2854 Alternatively you can specify -c/--change with a revision to see
2855 the changes in that changeset relative to its first parent.
2855 the changes in that changeset relative to its first parent.
2856
2856
2857 Without the -a/--text option, diff will avoid generating diffs of
2857 Without the -a/--text option, diff will avoid generating diffs of
2858 files it detects as binary. With -a, diff will generate a diff
2858 files it detects as binary. With -a, diff will generate a diff
2859 anyway, probably with undesirable results.
2859 anyway, probably with undesirable results.
2860
2860
2861 Use the -g/--git option to generate diffs in the git extended diff
2861 Use the -g/--git option to generate diffs in the git extended diff
2862 format. For more information, read :hg:`help diffs`.
2862 format. For more information, read :hg:`help diffs`.
2863
2863
2864 .. container:: verbose
2864 .. container:: verbose
2865
2865
2866 Examples:
2866 Examples:
2867
2867
2868 - compare a file in the current working directory to its parent::
2868 - compare a file in the current working directory to its parent::
2869
2869
2870 hg diff foo.c
2870 hg diff foo.c
2871
2871
2872 - compare two historical versions of a directory, with rename info::
2872 - compare two historical versions of a directory, with rename info::
2873
2873
2874 hg diff --git -r 1.0:1.2 lib/
2874 hg diff --git -r 1.0:1.2 lib/
2875
2875
2876 - get change stats relative to the last change on some date::
2876 - get change stats relative to the last change on some date::
2877
2877
2878 hg diff --stat -r "date('may 2')"
2878 hg diff --stat -r "date('may 2')"
2879
2879
2880 - diff all newly-added files that contain a keyword::
2880 - diff all newly-added files that contain a keyword::
2881
2881
2882 hg diff "set:added() and grep(GNU)"
2882 hg diff "set:added() and grep(GNU)"
2883
2883
2884 - compare a revision and its parents::
2884 - compare a revision and its parents::
2885
2885
2886 hg diff -c 9353 # compare against first parent
2886 hg diff -c 9353 # compare against first parent
2887 hg diff -r 9353^:9353 # same using revset syntax
2887 hg diff -r 9353^:9353 # same using revset syntax
2888 hg diff -r 9353^2:9353 # compare against the second parent
2888 hg diff -r 9353^2:9353 # compare against the second parent
2889
2889
2890 Returns 0 on success.
2890 Returns 0 on success.
2891 """
2891 """
2892
2892
2893 revs = opts.get('rev')
2893 revs = opts.get('rev')
2894 change = opts.get('change')
2894 change = opts.get('change')
2895 stat = opts.get('stat')
2895 stat = opts.get('stat')
2896 reverse = opts.get('reverse')
2896 reverse = opts.get('reverse')
2897
2897
2898 if revs and change:
2898 if revs and change:
2899 msg = _('cannot specify --rev and --change at the same time')
2899 msg = _('cannot specify --rev and --change at the same time')
2900 raise util.Abort(msg)
2900 raise util.Abort(msg)
2901 elif change:
2901 elif change:
2902 node2 = scmutil.revsingle(repo, change, None).node()
2902 node2 = scmutil.revsingle(repo, change, None).node()
2903 node1 = repo[node2].p1().node()
2903 node1 = repo[node2].p1().node()
2904 else:
2904 else:
2905 node1, node2 = scmutil.revpair(repo, revs)
2905 node1, node2 = scmutil.revpair(repo, revs)
2906
2906
2907 if reverse:
2907 if reverse:
2908 node1, node2 = node2, node1
2908 node1, node2 = node2, node1
2909
2909
2910 diffopts = patch.diffopts(ui, opts)
2910 diffopts = patch.diffopts(ui, opts)
2911 m = scmutil.match(repo[node2], pats, opts)
2911 m = scmutil.match(repo[node2], pats, opts)
2912 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2912 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2913 listsubrepos=opts.get('subrepos'))
2913 listsubrepos=opts.get('subrepos'))
2914
2914
2915 @command('^export',
2915 @command('^export',
2916 [('o', 'output', '',
2916 [('o', 'output', '',
2917 _('print output to file with formatted name'), _('FORMAT')),
2917 _('print output to file with formatted name'), _('FORMAT')),
2918 ('', 'switch-parent', None, _('diff against the second parent')),
2918 ('', 'switch-parent', None, _('diff against the second parent')),
2919 ('r', 'rev', [], _('revisions to export'), _('REV')),
2919 ('r', 'rev', [], _('revisions to export'), _('REV')),
2920 ] + diffopts,
2920 ] + diffopts,
2921 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
2921 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
2922 def export(ui, repo, *changesets, **opts):
2922 def export(ui, repo, *changesets, **opts):
2923 """dump the header and diffs for one or more changesets
2923 """dump the header and diffs for one or more changesets
2924
2924
2925 Print the changeset header and diffs for one or more revisions.
2925 Print the changeset header and diffs for one or more revisions.
2926 If no revision is given, the parent of the working directory is used.
2926 If no revision is given, the parent of the working directory is used.
2927
2927
2928 The information shown in the changeset header is: author, date,
2928 The information shown in the changeset header is: author, date,
2929 branch name (if non-default), changeset hash, parent(s) and commit
2929 branch name (if non-default), changeset hash, parent(s) and commit
2930 comment.
2930 comment.
2931
2931
2932 .. note::
2932 .. note::
2933
2933
2934 export may generate unexpected diff output for merge
2934 export may generate unexpected diff output for merge
2935 changesets, as it will compare the merge changeset against its
2935 changesets, as it will compare the merge changeset against its
2936 first parent only.
2936 first parent only.
2937
2937
2938 Output may be to a file, in which case the name of the file is
2938 Output may be to a file, in which case the name of the file is
2939 given using a format string. The formatting rules are as follows:
2939 given using a format string. The formatting rules are as follows:
2940
2940
2941 :``%%``: literal "%" character
2941 :``%%``: literal "%" character
2942 :``%H``: changeset hash (40 hexadecimal digits)
2942 :``%H``: changeset hash (40 hexadecimal digits)
2943 :``%N``: number of patches being generated
2943 :``%N``: number of patches being generated
2944 :``%R``: changeset revision number
2944 :``%R``: changeset revision number
2945 :``%b``: basename of the exporting repository
2945 :``%b``: basename of the exporting repository
2946 :``%h``: short-form changeset hash (12 hexadecimal digits)
2946 :``%h``: short-form changeset hash (12 hexadecimal digits)
2947 :``%m``: first line of the commit message (only alphanumeric characters)
2947 :``%m``: first line of the commit message (only alphanumeric characters)
2948 :``%n``: zero-padded sequence number, starting at 1
2948 :``%n``: zero-padded sequence number, starting at 1
2949 :``%r``: zero-padded changeset revision number
2949 :``%r``: zero-padded changeset revision number
2950
2950
2951 Without the -a/--text option, export will avoid generating diffs
2951 Without the -a/--text option, export will avoid generating diffs
2952 of files it detects as binary. With -a, export will generate a
2952 of files it detects as binary. With -a, export will generate a
2953 diff anyway, probably with undesirable results.
2953 diff anyway, probably with undesirable results.
2954
2954
2955 Use the -g/--git option to generate diffs in the git extended diff
2955 Use the -g/--git option to generate diffs in the git extended diff
2956 format. See :hg:`help diffs` for more information.
2956 format. See :hg:`help diffs` for more information.
2957
2957
2958 With the --switch-parent option, the diff will be against the
2958 With the --switch-parent option, the diff will be against the
2959 second parent. It can be useful to review a merge.
2959 second parent. It can be useful to review a merge.
2960
2960
2961 .. container:: verbose
2961 .. container:: verbose
2962
2962
2963 Examples:
2963 Examples:
2964
2964
2965 - use export and import to transplant a bugfix to the current
2965 - use export and import to transplant a bugfix to the current
2966 branch::
2966 branch::
2967
2967
2968 hg export -r 9353 | hg import -
2968 hg export -r 9353 | hg import -
2969
2969
2970 - export all the changesets between two revisions to a file with
2970 - export all the changesets between two revisions to a file with
2971 rename information::
2971 rename information::
2972
2972
2973 hg export --git -r 123:150 > changes.txt
2973 hg export --git -r 123:150 > changes.txt
2974
2974
2975 - split outgoing changes into a series of patches with
2975 - split outgoing changes into a series of patches with
2976 descriptive names::
2976 descriptive names::
2977
2977
2978 hg export -r "outgoing()" -o "%n-%m.patch"
2978 hg export -r "outgoing()" -o "%n-%m.patch"
2979
2979
2980 Returns 0 on success.
2980 Returns 0 on success.
2981 """
2981 """
2982 changesets += tuple(opts.get('rev', []))
2982 changesets += tuple(opts.get('rev', []))
2983 if not changesets:
2983 if not changesets:
2984 changesets = ['.']
2984 changesets = ['.']
2985 revs = scmutil.revrange(repo, changesets)
2985 revs = scmutil.revrange(repo, changesets)
2986 if not revs:
2986 if not revs:
2987 raise util.Abort(_("export requires at least one changeset"))
2987 raise util.Abort(_("export requires at least one changeset"))
2988 if len(revs) > 1:
2988 if len(revs) > 1:
2989 ui.note(_('exporting patches:\n'))
2989 ui.note(_('exporting patches:\n'))
2990 else:
2990 else:
2991 ui.note(_('exporting patch:\n'))
2991 ui.note(_('exporting patch:\n'))
2992 cmdutil.export(repo, revs, template=opts.get('output'),
2992 cmdutil.export(repo, revs, template=opts.get('output'),
2993 switch_parent=opts.get('switch_parent'),
2993 switch_parent=opts.get('switch_parent'),
2994 opts=patch.diffopts(ui, opts))
2994 opts=patch.diffopts(ui, opts))
2995
2995
2996 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2996 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2997 def forget(ui, repo, *pats, **opts):
2997 def forget(ui, repo, *pats, **opts):
2998 """forget the specified files on the next commit
2998 """forget the specified files on the next commit
2999
2999
3000 Mark the specified files so they will no longer be tracked
3000 Mark the specified files so they will no longer be tracked
3001 after the next commit.
3001 after the next commit.
3002
3002
3003 This only removes files from the current branch, not from the
3003 This only removes files from the current branch, not from the
3004 entire project history, and it does not delete them from the
3004 entire project history, and it does not delete them from the
3005 working directory.
3005 working directory.
3006
3006
3007 To undo a forget before the next commit, see :hg:`add`.
3007 To undo a forget before the next commit, see :hg:`add`.
3008
3008
3009 .. container:: verbose
3009 .. container:: verbose
3010
3010
3011 Examples:
3011 Examples:
3012
3012
3013 - forget newly-added binary files::
3013 - forget newly-added binary files::
3014
3014
3015 hg forget "set:added() and binary()"
3015 hg forget "set:added() and binary()"
3016
3016
3017 - forget files that would be excluded by .hgignore::
3017 - forget files that would be excluded by .hgignore::
3018
3018
3019 hg forget "set:hgignore()"
3019 hg forget "set:hgignore()"
3020
3020
3021 Returns 0 on success.
3021 Returns 0 on success.
3022 """
3022 """
3023
3023
3024 if not pats:
3024 if not pats:
3025 raise util.Abort(_('no files specified'))
3025 raise util.Abort(_('no files specified'))
3026
3026
3027 m = scmutil.match(repo[None], pats, opts)
3027 m = scmutil.match(repo[None], pats, opts)
3028 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3028 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3029 return rejected and 1 or 0
3029 return rejected and 1 or 0
3030
3030
3031 @command(
3031 @command(
3032 'graft',
3032 'graft',
3033 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3033 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3034 ('c', 'continue', False, _('resume interrupted graft')),
3034 ('c', 'continue', False, _('resume interrupted graft')),
3035 ('e', 'edit', False, _('invoke editor on commit messages')),
3035 ('e', 'edit', False, _('invoke editor on commit messages')),
3036 ('', 'log', None, _('append graft info to log message')),
3036 ('', 'log', None, _('append graft info to log message')),
3037 ('D', 'currentdate', False,
3037 ('D', 'currentdate', False,
3038 _('record the current date as commit date')),
3038 _('record the current date as commit date')),
3039 ('U', 'currentuser', False,
3039 ('U', 'currentuser', False,
3040 _('record the current user as committer'), _('DATE'))]
3040 _('record the current user as committer'), _('DATE'))]
3041 + commitopts2 + mergetoolopts + dryrunopts,
3041 + commitopts2 + mergetoolopts + dryrunopts,
3042 _('[OPTION]... [-r] REV...'))
3042 _('[OPTION]... [-r] REV...'))
3043 def graft(ui, repo, *revs, **opts):
3043 def graft(ui, repo, *revs, **opts):
3044 '''copy changes from other branches onto the current branch
3044 '''copy changes from other branches onto the current branch
3045
3045
3046 This command uses Mercurial's merge logic to copy individual
3046 This command uses Mercurial's merge logic to copy individual
3047 changes from other branches without merging branches in the
3047 changes from other branches without merging branches in the
3048 history graph. This is sometimes known as 'backporting' or
3048 history graph. This is sometimes known as 'backporting' or
3049 'cherry-picking'. By default, graft will copy user, date, and
3049 'cherry-picking'. By default, graft will copy user, date, and
3050 description from the source changesets.
3050 description from the source changesets.
3051
3051
3052 Changesets that are ancestors of the current revision, that have
3052 Changesets that are ancestors of the current revision, that have
3053 already been grafted, or that are merges will be skipped.
3053 already been grafted, or that are merges will be skipped.
3054
3054
3055 If --log is specified, log messages will have a comment appended
3055 If --log is specified, log messages will have a comment appended
3056 of the form::
3056 of the form::
3057
3057
3058 (grafted from CHANGESETHASH)
3058 (grafted from CHANGESETHASH)
3059
3059
3060 If a graft merge results in conflicts, the graft process is
3060 If a graft merge results in conflicts, the graft process is
3061 interrupted so that the current merge can be manually resolved.
3061 interrupted so that the current merge can be manually resolved.
3062 Once all conflicts are addressed, the graft process can be
3062 Once all conflicts are addressed, the graft process can be
3063 continued with the -c/--continue option.
3063 continued with the -c/--continue option.
3064
3064
3065 .. note::
3065 .. note::
3066
3066
3067 The -c/--continue option does not reapply earlier options.
3067 The -c/--continue option does not reapply earlier options.
3068
3068
3069 .. container:: verbose
3069 .. container:: verbose
3070
3070
3071 Examples:
3071 Examples:
3072
3072
3073 - copy a single change to the stable branch and edit its description::
3073 - copy a single change to the stable branch and edit its description::
3074
3074
3075 hg update stable
3075 hg update stable
3076 hg graft --edit 9393
3076 hg graft --edit 9393
3077
3077
3078 - graft a range of changesets with one exception, updating dates::
3078 - graft a range of changesets with one exception, updating dates::
3079
3079
3080 hg graft -D "2085::2093 and not 2091"
3080 hg graft -D "2085::2093 and not 2091"
3081
3081
3082 - continue a graft after resolving conflicts::
3082 - continue a graft after resolving conflicts::
3083
3083
3084 hg graft -c
3084 hg graft -c
3085
3085
3086 - show the source of a grafted changeset::
3086 - show the source of a grafted changeset::
3087
3087
3088 hg log --debug -r .
3088 hg log --debug -r .
3089
3089
3090 Returns 0 on successful completion.
3090 Returns 0 on successful completion.
3091 '''
3091 '''
3092
3092
3093 revs = list(revs)
3093 revs = list(revs)
3094 revs.extend(opts['rev'])
3094 revs.extend(opts['rev'])
3095
3095
3096 if not opts.get('user') and opts.get('currentuser'):
3096 if not opts.get('user') and opts.get('currentuser'):
3097 opts['user'] = ui.username()
3097 opts['user'] = ui.username()
3098 if not opts.get('date') and opts.get('currentdate'):
3098 if not opts.get('date') and opts.get('currentdate'):
3099 opts['date'] = "%d %d" % util.makedate()
3099 opts['date'] = "%d %d" % util.makedate()
3100
3100
3101 editor = None
3101 editor = None
3102 if opts.get('edit'):
3102 if opts.get('edit'):
3103 editor = cmdutil.commitforceeditor
3103 editor = cmdutil.commitforceeditor
3104
3104
3105 cont = False
3105 cont = False
3106 if opts['continue']:
3106 if opts['continue']:
3107 cont = True
3107 cont = True
3108 if revs:
3108 if revs:
3109 raise util.Abort(_("can't specify --continue and revisions"))
3109 raise util.Abort(_("can't specify --continue and revisions"))
3110 # read in unfinished revisions
3110 # read in unfinished revisions
3111 try:
3111 try:
3112 nodes = repo.opener.read('graftstate').splitlines()
3112 nodes = repo.opener.read('graftstate').splitlines()
3113 revs = [repo[node].rev() for node in nodes]
3113 revs = [repo[node].rev() for node in nodes]
3114 except IOError, inst:
3114 except IOError, inst:
3115 if inst.errno != errno.ENOENT:
3115 if inst.errno != errno.ENOENT:
3116 raise
3116 raise
3117 raise util.Abort(_("no graft state found, can't continue"))
3117 raise util.Abort(_("no graft state found, can't continue"))
3118 else:
3118 else:
3119 cmdutil.checkunfinished(repo)
3119 cmdutil.checkunfinished(repo)
3120 cmdutil.bailifchanged(repo)
3120 cmdutil.bailifchanged(repo)
3121 if not revs:
3121 if not revs:
3122 raise util.Abort(_('no revisions specified'))
3122 raise util.Abort(_('no revisions specified'))
3123 revs = scmutil.revrange(repo, revs)
3123 revs = scmutil.revrange(repo, revs)
3124
3124
3125 # check for merges
3125 # check for merges
3126 for rev in repo.revs('%ld and merge()', revs):
3126 for rev in repo.revs('%ld and merge()', revs):
3127 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3127 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3128 revs.remove(rev)
3128 revs.remove(rev)
3129 if not revs:
3129 if not revs:
3130 return -1
3130 return -1
3131
3131
3132 # check for ancestors of dest branch
3132 # check for ancestors of dest branch
3133 crev = repo['.'].rev()
3133 crev = repo['.'].rev()
3134 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3134 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3135 # don't mutate while iterating, create a copy
3135 # don't mutate while iterating, create a copy
3136 for rev in list(revs):
3136 for rev in list(revs):
3137 if rev in ancestors:
3137 if rev in ancestors:
3138 ui.warn(_('skipping ancestor revision %s\n') % rev)
3138 ui.warn(_('skipping ancestor revision %s\n') % rev)
3139 revs.remove(rev)
3139 revs.remove(rev)
3140 if not revs:
3140 if not revs:
3141 return -1
3141 return -1
3142
3142
3143 # analyze revs for earlier grafts
3143 # analyze revs for earlier grafts
3144 ids = {}
3144 ids = {}
3145 for ctx in repo.set("%ld", revs):
3145 for ctx in repo.set("%ld", revs):
3146 ids[ctx.hex()] = ctx.rev()
3146 ids[ctx.hex()] = ctx.rev()
3147 n = ctx.extra().get('source')
3147 n = ctx.extra().get('source')
3148 if n:
3148 if n:
3149 ids[n] = ctx.rev()
3149 ids[n] = ctx.rev()
3150
3150
3151 # check ancestors for earlier grafts
3151 # check ancestors for earlier grafts
3152 ui.debug('scanning for duplicate grafts\n')
3152 ui.debug('scanning for duplicate grafts\n')
3153
3153
3154 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3154 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3155 ctx = repo[rev]
3155 ctx = repo[rev]
3156 n = ctx.extra().get('source')
3156 n = ctx.extra().get('source')
3157 if n in ids:
3157 if n in ids:
3158 r = repo[n].rev()
3158 r = repo[n].rev()
3159 if r in revs:
3159 if r in revs:
3160 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3160 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3161 % (r, rev))
3161 % (r, rev))
3162 revs.remove(r)
3162 revs.remove(r)
3163 elif ids[n] in revs:
3163 elif ids[n] in revs:
3164 ui.warn(_('skipping already grafted revision %s '
3164 ui.warn(_('skipping already grafted revision %s '
3165 '(%s also has origin %d)\n') % (ids[n], rev, r))
3165 '(%s also has origin %d)\n') % (ids[n], rev, r))
3166 revs.remove(ids[n])
3166 revs.remove(ids[n])
3167 elif ctx.hex() in ids:
3167 elif ctx.hex() in ids:
3168 r = ids[ctx.hex()]
3168 r = ids[ctx.hex()]
3169 ui.warn(_('skipping already grafted revision %s '
3169 ui.warn(_('skipping already grafted revision %s '
3170 '(was grafted from %d)\n') % (r, rev))
3170 '(was grafted from %d)\n') % (r, rev))
3171 revs.remove(r)
3171 revs.remove(r)
3172 if not revs:
3172 if not revs:
3173 return -1
3173 return -1
3174
3174
3175 wlock = repo.wlock()
3175 wlock = repo.wlock()
3176 try:
3176 try:
3177 current = repo['.']
3177 current = repo['.']
3178 for pos, ctx in enumerate(repo.set("%ld", revs)):
3178 for pos, ctx in enumerate(repo.set("%ld", revs)):
3179
3179
3180 ui.status(_('grafting revision %s\n') % ctx.rev())
3180 ui.status(_('grafting revision %s\n') % ctx.rev())
3181 if opts.get('dry_run'):
3181 if opts.get('dry_run'):
3182 continue
3182 continue
3183
3183
3184 source = ctx.extra().get('source')
3184 source = ctx.extra().get('source')
3185 if not source:
3185 if not source:
3186 source = ctx.hex()
3186 source = ctx.hex()
3187 extra = {'source': source}
3187 extra = {'source': source}
3188 user = ctx.user()
3188 user = ctx.user()
3189 if opts.get('user'):
3189 if opts.get('user'):
3190 user = opts['user']
3190 user = opts['user']
3191 date = ctx.date()
3191 date = ctx.date()
3192 if opts.get('date'):
3192 if opts.get('date'):
3193 date = opts['date']
3193 date = opts['date']
3194 message = ctx.description()
3194 message = ctx.description()
3195 if opts.get('log'):
3195 if opts.get('log'):
3196 message += '\n(grafted from %s)' % ctx.hex()
3196 message += '\n(grafted from %s)' % ctx.hex()
3197
3197
3198 # we don't merge the first commit when continuing
3198 # we don't merge the first commit when continuing
3199 if not cont:
3199 if not cont:
3200 # perform the graft merge with p1(rev) as 'ancestor'
3200 # perform the graft merge with p1(rev) as 'ancestor'
3201 try:
3201 try:
3202 # ui.forcemerge is an internal variable, do not document
3202 # ui.forcemerge is an internal variable, do not document
3203 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3203 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3204 'graft')
3204 'graft')
3205 stats = mergemod.update(repo, ctx.node(), True, True, False,
3205 stats = mergemod.update(repo, ctx.node(), True, True, False,
3206 ctx.p1().node())
3206 ctx.p1().node())
3207 finally:
3207 finally:
3208 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3208 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3209 # report any conflicts
3209 # report any conflicts
3210 if stats and stats[3] > 0:
3210 if stats and stats[3] > 0:
3211 # write out state for --continue
3211 # write out state for --continue
3212 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3212 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3213 repo.opener.write('graftstate', ''.join(nodelines))
3213 repo.opener.write('graftstate', ''.join(nodelines))
3214 raise util.Abort(
3214 raise util.Abort(
3215 _("unresolved conflicts, can't continue"),
3215 _("unresolved conflicts, can't continue"),
3216 hint=_('use hg resolve and hg graft --continue'))
3216 hint=_('use hg resolve and hg graft --continue'))
3217 else:
3217 else:
3218 cont = False
3218 cont = False
3219
3219
3220 # drop the second merge parent
3220 # drop the second merge parent
3221 repo.setparents(current.node(), nullid)
3221 repo.setparents(current.node(), nullid)
3222 repo.dirstate.write()
3222 repo.dirstate.write()
3223 # fix up dirstate for copies and renames
3223 # fix up dirstate for copies and renames
3224 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3224 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3225
3225
3226 # commit
3226 # commit
3227 node = repo.commit(text=message, user=user,
3227 node = repo.commit(text=message, user=user,
3228 date=date, extra=extra, editor=editor)
3228 date=date, extra=extra, editor=editor)
3229 if node is None:
3229 if node is None:
3230 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3230 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3231 else:
3231 else:
3232 current = repo[node]
3232 current = repo[node]
3233 finally:
3233 finally:
3234 wlock.release()
3234 wlock.release()
3235
3235
3236 # remove state when we complete successfully
3236 # remove state when we complete successfully
3237 if not opts.get('dry_run'):
3237 if not opts.get('dry_run'):
3238 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3238 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3239
3239
3240 return 0
3240 return 0
3241
3241
3242 @command('grep',
3242 @command('grep',
3243 [('0', 'print0', None, _('end fields with NUL')),
3243 [('0', 'print0', None, _('end fields with NUL')),
3244 ('', 'all', None, _('print all revisions that match')),
3244 ('', 'all', None, _('print all revisions that match')),
3245 ('a', 'text', None, _('treat all files as text')),
3245 ('a', 'text', None, _('treat all files as text')),
3246 ('f', 'follow', None,
3246 ('f', 'follow', None,
3247 _('follow changeset history,'
3247 _('follow changeset history,'
3248 ' or file history across copies and renames')),
3248 ' or file history across copies and renames')),
3249 ('i', 'ignore-case', None, _('ignore case when matching')),
3249 ('i', 'ignore-case', None, _('ignore case when matching')),
3250 ('l', 'files-with-matches', None,
3250 ('l', 'files-with-matches', None,
3251 _('print only filenames and revisions that match')),
3251 _('print only filenames and revisions that match')),
3252 ('n', 'line-number', None, _('print matching line numbers')),
3252 ('n', 'line-number', None, _('print matching line numbers')),
3253 ('r', 'rev', [],
3253 ('r', 'rev', [],
3254 _('only search files changed within revision range'), _('REV')),
3254 _('only search files changed within revision range'), _('REV')),
3255 ('u', 'user', None, _('list the author (long with -v)')),
3255 ('u', 'user', None, _('list the author (long with -v)')),
3256 ('d', 'date', None, _('list the date (short with -q)')),
3256 ('d', 'date', None, _('list the date (short with -q)')),
3257 ] + walkopts,
3257 ] + walkopts,
3258 _('[OPTION]... PATTERN [FILE]...'))
3258 _('[OPTION]... PATTERN [FILE]...'))
3259 def grep(ui, repo, pattern, *pats, **opts):
3259 def grep(ui, repo, pattern, *pats, **opts):
3260 """search for a pattern in specified files and revisions
3260 """search for a pattern in specified files and revisions
3261
3261
3262 Search revisions of files for a regular expression.
3262 Search revisions of files for a regular expression.
3263
3263
3264 This command behaves differently than Unix grep. It only accepts
3264 This command behaves differently than Unix grep. It only accepts
3265 Python/Perl regexps. It searches repository history, not the
3265 Python/Perl regexps. It searches repository history, not the
3266 working directory. It always prints the revision number in which a
3266 working directory. It always prints the revision number in which a
3267 match appears.
3267 match appears.
3268
3268
3269 By default, grep only prints output for the first revision of a
3269 By default, grep only prints output for the first revision of a
3270 file in which it finds a match. To get it to print every revision
3270 file in which it finds a match. To get it to print every revision
3271 that contains a change in match status ("-" for a match that
3271 that contains a change in match status ("-" for a match that
3272 becomes a non-match, or "+" for a non-match that becomes a match),
3272 becomes a non-match, or "+" for a non-match that becomes a match),
3273 use the --all flag.
3273 use the --all flag.
3274
3274
3275 Returns 0 if a match is found, 1 otherwise.
3275 Returns 0 if a match is found, 1 otherwise.
3276 """
3276 """
3277 reflags = re.M
3277 reflags = re.M
3278 if opts.get('ignore_case'):
3278 if opts.get('ignore_case'):
3279 reflags |= re.I
3279 reflags |= re.I
3280 try:
3280 try:
3281 regexp = util.compilere(pattern, reflags)
3281 regexp = util.compilere(pattern, reflags)
3282 except re.error, inst:
3282 except re.error, inst:
3283 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3283 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3284 return 1
3284 return 1
3285 sep, eol = ':', '\n'
3285 sep, eol = ':', '\n'
3286 if opts.get('print0'):
3286 if opts.get('print0'):
3287 sep = eol = '\0'
3287 sep = eol = '\0'
3288
3288
3289 getfile = util.lrucachefunc(repo.file)
3289 getfile = util.lrucachefunc(repo.file)
3290
3290
3291 def matchlines(body):
3291 def matchlines(body):
3292 begin = 0
3292 begin = 0
3293 linenum = 0
3293 linenum = 0
3294 while begin < len(body):
3294 while begin < len(body):
3295 match = regexp.search(body, begin)
3295 match = regexp.search(body, begin)
3296 if not match:
3296 if not match:
3297 break
3297 break
3298 mstart, mend = match.span()
3298 mstart, mend = match.span()
3299 linenum += body.count('\n', begin, mstart) + 1
3299 linenum += body.count('\n', begin, mstart) + 1
3300 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3300 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3301 begin = body.find('\n', mend) + 1 or len(body) + 1
3301 begin = body.find('\n', mend) + 1 or len(body) + 1
3302 lend = begin - 1
3302 lend = begin - 1
3303 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3303 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3304
3304
3305 class linestate(object):
3305 class linestate(object):
3306 def __init__(self, line, linenum, colstart, colend):
3306 def __init__(self, line, linenum, colstart, colend):
3307 self.line = line
3307 self.line = line
3308 self.linenum = linenum
3308 self.linenum = linenum
3309 self.colstart = colstart
3309 self.colstart = colstart
3310 self.colend = colend
3310 self.colend = colend
3311
3311
3312 def __hash__(self):
3312 def __hash__(self):
3313 return hash((self.linenum, self.line))
3313 return hash((self.linenum, self.line))
3314
3314
3315 def __eq__(self, other):
3315 def __eq__(self, other):
3316 return self.line == other.line
3316 return self.line == other.line
3317
3317
3318 matches = {}
3318 matches = {}
3319 copies = {}
3319 copies = {}
3320 def grepbody(fn, rev, body):
3320 def grepbody(fn, rev, body):
3321 matches[rev].setdefault(fn, [])
3321 matches[rev].setdefault(fn, [])
3322 m = matches[rev][fn]
3322 m = matches[rev][fn]
3323 for lnum, cstart, cend, line in matchlines(body):
3323 for lnum, cstart, cend, line in matchlines(body):
3324 s = linestate(line, lnum, cstart, cend)
3324 s = linestate(line, lnum, cstart, cend)
3325 m.append(s)
3325 m.append(s)
3326
3326
3327 def difflinestates(a, b):
3327 def difflinestates(a, b):
3328 sm = difflib.SequenceMatcher(None, a, b)
3328 sm = difflib.SequenceMatcher(None, a, b)
3329 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3329 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3330 if tag == 'insert':
3330 if tag == 'insert':
3331 for i in xrange(blo, bhi):
3331 for i in xrange(blo, bhi):
3332 yield ('+', b[i])
3332 yield ('+', b[i])
3333 elif tag == 'delete':
3333 elif tag == 'delete':
3334 for i in xrange(alo, ahi):
3334 for i in xrange(alo, ahi):
3335 yield ('-', a[i])
3335 yield ('-', a[i])
3336 elif tag == 'replace':
3336 elif tag == 'replace':
3337 for i in xrange(alo, ahi):
3337 for i in xrange(alo, ahi):
3338 yield ('-', a[i])
3338 yield ('-', a[i])
3339 for i in xrange(blo, bhi):
3339 for i in xrange(blo, bhi):
3340 yield ('+', b[i])
3340 yield ('+', b[i])
3341
3341
3342 def display(fn, ctx, pstates, states):
3342 def display(fn, ctx, pstates, states):
3343 rev = ctx.rev()
3343 rev = ctx.rev()
3344 datefunc = ui.quiet and util.shortdate or util.datestr
3344 datefunc = ui.quiet and util.shortdate or util.datestr
3345 found = False
3345 found = False
3346 filerevmatches = {}
3346 filerevmatches = {}
3347 @util.cachefunc
3347 def binary():
3348 def binary():
3348 flog = getfile(fn)
3349 flog = getfile(fn)
3349 return util.binary(flog.read(ctx.filenode(fn)))
3350 return util.binary(flog.read(ctx.filenode(fn)))
3350
3351
3351 if opts.get('all'):
3352 if opts.get('all'):
3352 iter = difflinestates(pstates, states)
3353 iter = difflinestates(pstates, states)
3353 else:
3354 else:
3354 iter = [('', l) for l in states]
3355 iter = [('', l) for l in states]
3355 for change, l in iter:
3356 for change, l in iter:
3356 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3357 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3357 before, match, after = None, None, None
3358 before, match, after = None, None, None
3358
3359
3359 if opts.get('line_number'):
3360 if opts.get('line_number'):
3360 cols.append((str(l.linenum), 'grep.linenumber'))
3361 cols.append((str(l.linenum), 'grep.linenumber'))
3361 if opts.get('all'):
3362 if opts.get('all'):
3362 cols.append((change, 'grep.change'))
3363 cols.append((change, 'grep.change'))
3363 if opts.get('user'):
3364 if opts.get('user'):
3364 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3365 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3365 if opts.get('date'):
3366 if opts.get('date'):
3366 cols.append((datefunc(ctx.date()), 'grep.date'))
3367 cols.append((datefunc(ctx.date()), 'grep.date'))
3367 if opts.get('files_with_matches'):
3368 if opts.get('files_with_matches'):
3368 c = (fn, rev)
3369 c = (fn, rev)
3369 if c in filerevmatches:
3370 if c in filerevmatches:
3370 continue
3371 continue
3371 filerevmatches[c] = 1
3372 filerevmatches[c] = 1
3372 else:
3373 else:
3373 before = l.line[:l.colstart]
3374 before = l.line[:l.colstart]
3374 match = l.line[l.colstart:l.colend]
3375 match = l.line[l.colstart:l.colend]
3375 after = l.line[l.colend:]
3376 after = l.line[l.colend:]
3376 for col, label in cols[:-1]:
3377 for col, label in cols[:-1]:
3377 ui.write(col, label=label)
3378 ui.write(col, label=label)
3378 ui.write(sep, label='grep.sep')
3379 ui.write(sep, label='grep.sep')
3379 ui.write(cols[-1][0], label=cols[-1][1])
3380 ui.write(cols[-1][0], label=cols[-1][1])
3380 if before is not None:
3381 if before is not None:
3381 ui.write(sep, label='grep.sep')
3382 ui.write(sep, label='grep.sep')
3382 if not opts.get('text') and binary():
3383 if not opts.get('text') and binary():
3383 ui.write(" Binary file matches")
3384 ui.write(" Binary file matches")
3384 else:
3385 else:
3385 ui.write(before)
3386 ui.write(before)
3386 ui.write(match, label='grep.match')
3387 ui.write(match, label='grep.match')
3387 ui.write(after)
3388 ui.write(after)
3388 ui.write(eol)
3389 ui.write(eol)
3389 found = True
3390 found = True
3390 return found
3391 return found
3391
3392
3392 skip = {}
3393 skip = {}
3393 revfiles = {}
3394 revfiles = {}
3394 matchfn = scmutil.match(repo[None], pats, opts)
3395 matchfn = scmutil.match(repo[None], pats, opts)
3395 found = False
3396 found = False
3396 follow = opts.get('follow')
3397 follow = opts.get('follow')
3397
3398
3398 def prep(ctx, fns):
3399 def prep(ctx, fns):
3399 rev = ctx.rev()
3400 rev = ctx.rev()
3400 pctx = ctx.p1()
3401 pctx = ctx.p1()
3401 parent = pctx.rev()
3402 parent = pctx.rev()
3402 matches.setdefault(rev, {})
3403 matches.setdefault(rev, {})
3403 matches.setdefault(parent, {})
3404 matches.setdefault(parent, {})
3404 files = revfiles.setdefault(rev, [])
3405 files = revfiles.setdefault(rev, [])
3405 for fn in fns:
3406 for fn in fns:
3406 flog = getfile(fn)
3407 flog = getfile(fn)
3407 try:
3408 try:
3408 fnode = ctx.filenode(fn)
3409 fnode = ctx.filenode(fn)
3409 except error.LookupError:
3410 except error.LookupError:
3410 continue
3411 continue
3411
3412
3412 copied = flog.renamed(fnode)
3413 copied = flog.renamed(fnode)
3413 copy = follow and copied and copied[0]
3414 copy = follow and copied and copied[0]
3414 if copy:
3415 if copy:
3415 copies.setdefault(rev, {})[fn] = copy
3416 copies.setdefault(rev, {})[fn] = copy
3416 if fn in skip:
3417 if fn in skip:
3417 if copy:
3418 if copy:
3418 skip[copy] = True
3419 skip[copy] = True
3419 continue
3420 continue
3420 files.append(fn)
3421 files.append(fn)
3421
3422
3422 if fn not in matches[rev]:
3423 if fn not in matches[rev]:
3423 grepbody(fn, rev, flog.read(fnode))
3424 grepbody(fn, rev, flog.read(fnode))
3424
3425
3425 pfn = copy or fn
3426 pfn = copy or fn
3426 if pfn not in matches[parent]:
3427 if pfn not in matches[parent]:
3427 try:
3428 try:
3428 fnode = pctx.filenode(pfn)
3429 fnode = pctx.filenode(pfn)
3429 grepbody(pfn, parent, flog.read(fnode))
3430 grepbody(pfn, parent, flog.read(fnode))
3430 except error.LookupError:
3431 except error.LookupError:
3431 pass
3432 pass
3432
3433
3433 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3434 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3434 rev = ctx.rev()
3435 rev = ctx.rev()
3435 parent = ctx.p1().rev()
3436 parent = ctx.p1().rev()
3436 for fn in sorted(revfiles.get(rev, [])):
3437 for fn in sorted(revfiles.get(rev, [])):
3437 states = matches[rev][fn]
3438 states = matches[rev][fn]
3438 copy = copies.get(rev, {}).get(fn)
3439 copy = copies.get(rev, {}).get(fn)
3439 if fn in skip:
3440 if fn in skip:
3440 if copy:
3441 if copy:
3441 skip[copy] = True
3442 skip[copy] = True
3442 continue
3443 continue
3443 pstates = matches.get(parent, {}).get(copy or fn, [])
3444 pstates = matches.get(parent, {}).get(copy or fn, [])
3444 if pstates or states:
3445 if pstates or states:
3445 r = display(fn, ctx, pstates, states)
3446 r = display(fn, ctx, pstates, states)
3446 found = found or r
3447 found = found or r
3447 if r and not opts.get('all'):
3448 if r and not opts.get('all'):
3448 skip[fn] = True
3449 skip[fn] = True
3449 if copy:
3450 if copy:
3450 skip[copy] = True
3451 skip[copy] = True
3451 del matches[rev]
3452 del matches[rev]
3452 del revfiles[rev]
3453 del revfiles[rev]
3453
3454
3454 return not found
3455 return not found
3455
3456
3456 @command('heads',
3457 @command('heads',
3457 [('r', 'rev', '',
3458 [('r', 'rev', '',
3458 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3459 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3459 ('t', 'topo', False, _('show topological heads only')),
3460 ('t', 'topo', False, _('show topological heads only')),
3460 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3461 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3461 ('c', 'closed', False, _('show normal and closed branch heads')),
3462 ('c', 'closed', False, _('show normal and closed branch heads')),
3462 ] + templateopts,
3463 ] + templateopts,
3463 _('[-ct] [-r STARTREV] [REV]...'))
3464 _('[-ct] [-r STARTREV] [REV]...'))
3464 def heads(ui, repo, *branchrevs, **opts):
3465 def heads(ui, repo, *branchrevs, **opts):
3465 """show branch heads
3466 """show branch heads
3466
3467
3467 With no arguments, show all open branch heads in the repository.
3468 With no arguments, show all open branch heads in the repository.
3468 Branch heads are changesets that have no descendants on the
3469 Branch heads are changesets that have no descendants on the
3469 same branch. They are where development generally takes place and
3470 same branch. They are where development generally takes place and
3470 are the usual targets for update and merge operations.
3471 are the usual targets for update and merge operations.
3471
3472
3472 If one or more REVs are given, only open branch heads on the
3473 If one or more REVs are given, only open branch heads on the
3473 branches associated with the specified changesets are shown. This
3474 branches associated with the specified changesets are shown. This
3474 means that you can use :hg:`heads .` to see the heads on the
3475 means that you can use :hg:`heads .` to see the heads on the
3475 currently checked-out branch.
3476 currently checked-out branch.
3476
3477
3477 If -c/--closed is specified, also show branch heads marked closed
3478 If -c/--closed is specified, also show branch heads marked closed
3478 (see :hg:`commit --close-branch`).
3479 (see :hg:`commit --close-branch`).
3479
3480
3480 If STARTREV is specified, only those heads that are descendants of
3481 If STARTREV is specified, only those heads that are descendants of
3481 STARTREV will be displayed.
3482 STARTREV will be displayed.
3482
3483
3483 If -t/--topo is specified, named branch mechanics will be ignored and only
3484 If -t/--topo is specified, named branch mechanics will be ignored and only
3484 topological heads (changesets with no children) will be shown.
3485 topological heads (changesets with no children) will be shown.
3485
3486
3486 Returns 0 if matching heads are found, 1 if not.
3487 Returns 0 if matching heads are found, 1 if not.
3487 """
3488 """
3488
3489
3489 start = None
3490 start = None
3490 if 'rev' in opts:
3491 if 'rev' in opts:
3491 start = scmutil.revsingle(repo, opts['rev'], None).node()
3492 start = scmutil.revsingle(repo, opts['rev'], None).node()
3492
3493
3493 if opts.get('topo'):
3494 if opts.get('topo'):
3494 heads = [repo[h] for h in repo.heads(start)]
3495 heads = [repo[h] for h in repo.heads(start)]
3495 else:
3496 else:
3496 heads = []
3497 heads = []
3497 for branch in repo.branchmap():
3498 for branch in repo.branchmap():
3498 heads += repo.branchheads(branch, start, opts.get('closed'))
3499 heads += repo.branchheads(branch, start, opts.get('closed'))
3499 heads = [repo[h] for h in heads]
3500 heads = [repo[h] for h in heads]
3500
3501
3501 if branchrevs:
3502 if branchrevs:
3502 branches = set(repo[br].branch() for br in branchrevs)
3503 branches = set(repo[br].branch() for br in branchrevs)
3503 heads = [h for h in heads if h.branch() in branches]
3504 heads = [h for h in heads if h.branch() in branches]
3504
3505
3505 if opts.get('active') and branchrevs:
3506 if opts.get('active') and branchrevs:
3506 dagheads = repo.heads(start)
3507 dagheads = repo.heads(start)
3507 heads = [h for h in heads if h.node() in dagheads]
3508 heads = [h for h in heads if h.node() in dagheads]
3508
3509
3509 if branchrevs:
3510 if branchrevs:
3510 haveheads = set(h.branch() for h in heads)
3511 haveheads = set(h.branch() for h in heads)
3511 if branches - haveheads:
3512 if branches - haveheads:
3512 headless = ', '.join(b for b in branches - haveheads)
3513 headless = ', '.join(b for b in branches - haveheads)
3513 msg = _('no open branch heads found on branches %s')
3514 msg = _('no open branch heads found on branches %s')
3514 if opts.get('rev'):
3515 if opts.get('rev'):
3515 msg += _(' (started at %s)') % opts['rev']
3516 msg += _(' (started at %s)') % opts['rev']
3516 ui.warn((msg + '\n') % headless)
3517 ui.warn((msg + '\n') % headless)
3517
3518
3518 if not heads:
3519 if not heads:
3519 return 1
3520 return 1
3520
3521
3521 heads = sorted(heads, key=lambda x: -x.rev())
3522 heads = sorted(heads, key=lambda x: -x.rev())
3522 displayer = cmdutil.show_changeset(ui, repo, opts)
3523 displayer = cmdutil.show_changeset(ui, repo, opts)
3523 for ctx in heads:
3524 for ctx in heads:
3524 displayer.show(ctx)
3525 displayer.show(ctx)
3525 displayer.close()
3526 displayer.close()
3526
3527
3527 @command('help',
3528 @command('help',
3528 [('e', 'extension', None, _('show only help for extensions')),
3529 [('e', 'extension', None, _('show only help for extensions')),
3529 ('c', 'command', None, _('show only help for commands')),
3530 ('c', 'command', None, _('show only help for commands')),
3530 ('k', 'keyword', '', _('show topics matching keyword')),
3531 ('k', 'keyword', '', _('show topics matching keyword')),
3531 ],
3532 ],
3532 _('[-ec] [TOPIC]'))
3533 _('[-ec] [TOPIC]'))
3533 def help_(ui, name=None, **opts):
3534 def help_(ui, name=None, **opts):
3534 """show help for a given topic or a help overview
3535 """show help for a given topic or a help overview
3535
3536
3536 With no arguments, print a list of commands with short help messages.
3537 With no arguments, print a list of commands with short help messages.
3537
3538
3538 Given a topic, extension, or command name, print help for that
3539 Given a topic, extension, or command name, print help for that
3539 topic.
3540 topic.
3540
3541
3541 Returns 0 if successful.
3542 Returns 0 if successful.
3542 """
3543 """
3543
3544
3544 textwidth = min(ui.termwidth(), 80) - 2
3545 textwidth = min(ui.termwidth(), 80) - 2
3545
3546
3546 keep = ui.verbose and ['verbose'] or []
3547 keep = ui.verbose and ['verbose'] or []
3547 text = help.help_(ui, name, **opts)
3548 text = help.help_(ui, name, **opts)
3548
3549
3549 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3550 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3550 if 'verbose' in pruned:
3551 if 'verbose' in pruned:
3551 keep.append('omitted')
3552 keep.append('omitted')
3552 else:
3553 else:
3553 keep.append('notomitted')
3554 keep.append('notomitted')
3554 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3555 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3555 ui.write(formatted)
3556 ui.write(formatted)
3556
3557
3557
3558
3558 @command('identify|id',
3559 @command('identify|id',
3559 [('r', 'rev', '',
3560 [('r', 'rev', '',
3560 _('identify the specified revision'), _('REV')),
3561 _('identify the specified revision'), _('REV')),
3561 ('n', 'num', None, _('show local revision number')),
3562 ('n', 'num', None, _('show local revision number')),
3562 ('i', 'id', None, _('show global revision id')),
3563 ('i', 'id', None, _('show global revision id')),
3563 ('b', 'branch', None, _('show branch')),
3564 ('b', 'branch', None, _('show branch')),
3564 ('t', 'tags', None, _('show tags')),
3565 ('t', 'tags', None, _('show tags')),
3565 ('B', 'bookmarks', None, _('show bookmarks')),
3566 ('B', 'bookmarks', None, _('show bookmarks')),
3566 ] + remoteopts,
3567 ] + remoteopts,
3567 _('[-nibtB] [-r REV] [SOURCE]'))
3568 _('[-nibtB] [-r REV] [SOURCE]'))
3568 def identify(ui, repo, source=None, rev=None,
3569 def identify(ui, repo, source=None, rev=None,
3569 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3570 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3570 """identify the working copy or specified revision
3571 """identify the working copy or specified revision
3571
3572
3572 Print a summary identifying the repository state at REV using one or
3573 Print a summary identifying the repository state at REV using one or
3573 two parent hash identifiers, followed by a "+" if the working
3574 two parent hash identifiers, followed by a "+" if the working
3574 directory has uncommitted changes, the branch name (if not default),
3575 directory has uncommitted changes, the branch name (if not default),
3575 a list of tags, and a list of bookmarks.
3576 a list of tags, and a list of bookmarks.
3576
3577
3577 When REV is not given, print a summary of the current state of the
3578 When REV is not given, print a summary of the current state of the
3578 repository.
3579 repository.
3579
3580
3580 Specifying a path to a repository root or Mercurial bundle will
3581 Specifying a path to a repository root or Mercurial bundle will
3581 cause lookup to operate on that repository/bundle.
3582 cause lookup to operate on that repository/bundle.
3582
3583
3583 .. container:: verbose
3584 .. container:: verbose
3584
3585
3585 Examples:
3586 Examples:
3586
3587
3587 - generate a build identifier for the working directory::
3588 - generate a build identifier for the working directory::
3588
3589
3589 hg id --id > build-id.dat
3590 hg id --id > build-id.dat
3590
3591
3591 - find the revision corresponding to a tag::
3592 - find the revision corresponding to a tag::
3592
3593
3593 hg id -n -r 1.3
3594 hg id -n -r 1.3
3594
3595
3595 - check the most recent revision of a remote repository::
3596 - check the most recent revision of a remote repository::
3596
3597
3597 hg id -r tip http://selenic.com/hg/
3598 hg id -r tip http://selenic.com/hg/
3598
3599
3599 Returns 0 if successful.
3600 Returns 0 if successful.
3600 """
3601 """
3601
3602
3602 if not repo and not source:
3603 if not repo and not source:
3603 raise util.Abort(_("there is no Mercurial repository here "
3604 raise util.Abort(_("there is no Mercurial repository here "
3604 "(.hg not found)"))
3605 "(.hg not found)"))
3605
3606
3606 hexfunc = ui.debugflag and hex or short
3607 hexfunc = ui.debugflag and hex or short
3607 default = not (num or id or branch or tags or bookmarks)
3608 default = not (num or id or branch or tags or bookmarks)
3608 output = []
3609 output = []
3609 revs = []
3610 revs = []
3610
3611
3611 if source:
3612 if source:
3612 source, branches = hg.parseurl(ui.expandpath(source))
3613 source, branches = hg.parseurl(ui.expandpath(source))
3613 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3614 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3614 repo = peer.local()
3615 repo = peer.local()
3615 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3616 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3616
3617
3617 if not repo:
3618 if not repo:
3618 if num or branch or tags:
3619 if num or branch or tags:
3619 raise util.Abort(
3620 raise util.Abort(
3620 _("can't query remote revision number, branch, or tags"))
3621 _("can't query remote revision number, branch, or tags"))
3621 if not rev and revs:
3622 if not rev and revs:
3622 rev = revs[0]
3623 rev = revs[0]
3623 if not rev:
3624 if not rev:
3624 rev = "tip"
3625 rev = "tip"
3625
3626
3626 remoterev = peer.lookup(rev)
3627 remoterev = peer.lookup(rev)
3627 if default or id:
3628 if default or id:
3628 output = [hexfunc(remoterev)]
3629 output = [hexfunc(remoterev)]
3629
3630
3630 def getbms():
3631 def getbms():
3631 bms = []
3632 bms = []
3632
3633
3633 if 'bookmarks' in peer.listkeys('namespaces'):
3634 if 'bookmarks' in peer.listkeys('namespaces'):
3634 hexremoterev = hex(remoterev)
3635 hexremoterev = hex(remoterev)
3635 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3636 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3636 if bmr == hexremoterev]
3637 if bmr == hexremoterev]
3637
3638
3638 return sorted(bms)
3639 return sorted(bms)
3639
3640
3640 if bookmarks:
3641 if bookmarks:
3641 output.extend(getbms())
3642 output.extend(getbms())
3642 elif default and not ui.quiet:
3643 elif default and not ui.quiet:
3643 # multiple bookmarks for a single parent separated by '/'
3644 # multiple bookmarks for a single parent separated by '/'
3644 bm = '/'.join(getbms())
3645 bm = '/'.join(getbms())
3645 if bm:
3646 if bm:
3646 output.append(bm)
3647 output.append(bm)
3647 else:
3648 else:
3648 if not rev:
3649 if not rev:
3649 ctx = repo[None]
3650 ctx = repo[None]
3650 parents = ctx.parents()
3651 parents = ctx.parents()
3651 changed = ""
3652 changed = ""
3652 if default or id or num:
3653 if default or id or num:
3653 if (util.any(repo.status())
3654 if (util.any(repo.status())
3654 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3655 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3655 changed = '+'
3656 changed = '+'
3656 if default or id:
3657 if default or id:
3657 output = ["%s%s" %
3658 output = ["%s%s" %
3658 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3659 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3659 if num:
3660 if num:
3660 output.append("%s%s" %
3661 output.append("%s%s" %
3661 ('+'.join([str(p.rev()) for p in parents]), changed))
3662 ('+'.join([str(p.rev()) for p in parents]), changed))
3662 else:
3663 else:
3663 ctx = scmutil.revsingle(repo, rev)
3664 ctx = scmutil.revsingle(repo, rev)
3664 if default or id:
3665 if default or id:
3665 output = [hexfunc(ctx.node())]
3666 output = [hexfunc(ctx.node())]
3666 if num:
3667 if num:
3667 output.append(str(ctx.rev()))
3668 output.append(str(ctx.rev()))
3668
3669
3669 if default and not ui.quiet:
3670 if default and not ui.quiet:
3670 b = ctx.branch()
3671 b = ctx.branch()
3671 if b != 'default':
3672 if b != 'default':
3672 output.append("(%s)" % b)
3673 output.append("(%s)" % b)
3673
3674
3674 # multiple tags for a single parent separated by '/'
3675 # multiple tags for a single parent separated by '/'
3675 t = '/'.join(ctx.tags())
3676 t = '/'.join(ctx.tags())
3676 if t:
3677 if t:
3677 output.append(t)
3678 output.append(t)
3678
3679
3679 # multiple bookmarks for a single parent separated by '/'
3680 # multiple bookmarks for a single parent separated by '/'
3680 bm = '/'.join(ctx.bookmarks())
3681 bm = '/'.join(ctx.bookmarks())
3681 if bm:
3682 if bm:
3682 output.append(bm)
3683 output.append(bm)
3683 else:
3684 else:
3684 if branch:
3685 if branch:
3685 output.append(ctx.branch())
3686 output.append(ctx.branch())
3686
3687
3687 if tags:
3688 if tags:
3688 output.extend(ctx.tags())
3689 output.extend(ctx.tags())
3689
3690
3690 if bookmarks:
3691 if bookmarks:
3691 output.extend(ctx.bookmarks())
3692 output.extend(ctx.bookmarks())
3692
3693
3693 ui.write("%s\n" % ' '.join(output))
3694 ui.write("%s\n" % ' '.join(output))
3694
3695
3695 @command('import|patch',
3696 @command('import|patch',
3696 [('p', 'strip', 1,
3697 [('p', 'strip', 1,
3697 _('directory strip option for patch. This has the same '
3698 _('directory strip option for patch. This has the same '
3698 'meaning as the corresponding patch option'), _('NUM')),
3699 'meaning as the corresponding patch option'), _('NUM')),
3699 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3700 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3700 ('e', 'edit', False, _('invoke editor on commit messages')),
3701 ('e', 'edit', False, _('invoke editor on commit messages')),
3701 ('f', 'force', None,
3702 ('f', 'force', None,
3702 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3703 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3703 ('', 'no-commit', None,
3704 ('', 'no-commit', None,
3704 _("don't commit, just update the working directory")),
3705 _("don't commit, just update the working directory")),
3705 ('', 'bypass', None,
3706 ('', 'bypass', None,
3706 _("apply patch without touching the working directory")),
3707 _("apply patch without touching the working directory")),
3707 ('', 'exact', None,
3708 ('', 'exact', None,
3708 _('apply patch to the nodes from which it was generated')),
3709 _('apply patch to the nodes from which it was generated')),
3709 ('', 'import-branch', None,
3710 ('', 'import-branch', None,
3710 _('use any branch information in patch (implied by --exact)'))] +
3711 _('use any branch information in patch (implied by --exact)'))] +
3711 commitopts + commitopts2 + similarityopts,
3712 commitopts + commitopts2 + similarityopts,
3712 _('[OPTION]... PATCH...'))
3713 _('[OPTION]... PATCH...'))
3713 def import_(ui, repo, patch1=None, *patches, **opts):
3714 def import_(ui, repo, patch1=None, *patches, **opts):
3714 """import an ordered set of patches
3715 """import an ordered set of patches
3715
3716
3716 Import a list of patches and commit them individually (unless
3717 Import a list of patches and commit them individually (unless
3717 --no-commit is specified).
3718 --no-commit is specified).
3718
3719
3719 Because import first applies changes to the working directory,
3720 Because import first applies changes to the working directory,
3720 import will abort if there are outstanding changes.
3721 import will abort if there are outstanding changes.
3721
3722
3722 You can import a patch straight from a mail message. Even patches
3723 You can import a patch straight from a mail message. Even patches
3723 as attachments work (to use the body part, it must have type
3724 as attachments work (to use the body part, it must have type
3724 text/plain or text/x-patch). From and Subject headers of email
3725 text/plain or text/x-patch). From and Subject headers of email
3725 message are used as default committer and commit message. All
3726 message are used as default committer and commit message. All
3726 text/plain body parts before first diff are added to commit
3727 text/plain body parts before first diff are added to commit
3727 message.
3728 message.
3728
3729
3729 If the imported patch was generated by :hg:`export`, user and
3730 If the imported patch was generated by :hg:`export`, user and
3730 description from patch override values from message headers and
3731 description from patch override values from message headers and
3731 body. Values given on command line with -m/--message and -u/--user
3732 body. Values given on command line with -m/--message and -u/--user
3732 override these.
3733 override these.
3733
3734
3734 If --exact is specified, import will set the working directory to
3735 If --exact is specified, import will set the working directory to
3735 the parent of each patch before applying it, and will abort if the
3736 the parent of each patch before applying it, and will abort if the
3736 resulting changeset has a different ID than the one recorded in
3737 resulting changeset has a different ID than the one recorded in
3737 the patch. This may happen due to character set problems or other
3738 the patch. This may happen due to character set problems or other
3738 deficiencies in the text patch format.
3739 deficiencies in the text patch format.
3739
3740
3740 Use --bypass to apply and commit patches directly to the
3741 Use --bypass to apply and commit patches directly to the
3741 repository, not touching the working directory. Without --exact,
3742 repository, not touching the working directory. Without --exact,
3742 patches will be applied on top of the working directory parent
3743 patches will be applied on top of the working directory parent
3743 revision.
3744 revision.
3744
3745
3745 With -s/--similarity, hg will attempt to discover renames and
3746 With -s/--similarity, hg will attempt to discover renames and
3746 copies in the patch in the same way as :hg:`addremove`.
3747 copies in the patch in the same way as :hg:`addremove`.
3747
3748
3748 To read a patch from standard input, use "-" as the patch name. If
3749 To read a patch from standard input, use "-" as the patch name. If
3749 a URL is specified, the patch will be downloaded from it.
3750 a URL is specified, the patch will be downloaded from it.
3750 See :hg:`help dates` for a list of formats valid for -d/--date.
3751 See :hg:`help dates` for a list of formats valid for -d/--date.
3751
3752
3752 .. container:: verbose
3753 .. container:: verbose
3753
3754
3754 Examples:
3755 Examples:
3755
3756
3756 - import a traditional patch from a website and detect renames::
3757 - import a traditional patch from a website and detect renames::
3757
3758
3758 hg import -s 80 http://example.com/bugfix.patch
3759 hg import -s 80 http://example.com/bugfix.patch
3759
3760
3760 - import a changeset from an hgweb server::
3761 - import a changeset from an hgweb server::
3761
3762
3762 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3763 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3763
3764
3764 - import all the patches in an Unix-style mbox::
3765 - import all the patches in an Unix-style mbox::
3765
3766
3766 hg import incoming-patches.mbox
3767 hg import incoming-patches.mbox
3767
3768
3768 - attempt to exactly restore an exported changeset (not always
3769 - attempt to exactly restore an exported changeset (not always
3769 possible)::
3770 possible)::
3770
3771
3771 hg import --exact proposed-fix.patch
3772 hg import --exact proposed-fix.patch
3772
3773
3773 Returns 0 on success.
3774 Returns 0 on success.
3774 """
3775 """
3775
3776
3776 if not patch1:
3777 if not patch1:
3777 raise util.Abort(_('need at least one patch to import'))
3778 raise util.Abort(_('need at least one patch to import'))
3778
3779
3779 patches = (patch1,) + patches
3780 patches = (patch1,) + patches
3780
3781
3781 date = opts.get('date')
3782 date = opts.get('date')
3782 if date:
3783 if date:
3783 opts['date'] = util.parsedate(date)
3784 opts['date'] = util.parsedate(date)
3784
3785
3785 update = not opts.get('bypass')
3786 update = not opts.get('bypass')
3786 if not update and opts.get('no_commit'):
3787 if not update and opts.get('no_commit'):
3787 raise util.Abort(_('cannot use --no-commit with --bypass'))
3788 raise util.Abort(_('cannot use --no-commit with --bypass'))
3788 try:
3789 try:
3789 sim = float(opts.get('similarity') or 0)
3790 sim = float(opts.get('similarity') or 0)
3790 except ValueError:
3791 except ValueError:
3791 raise util.Abort(_('similarity must be a number'))
3792 raise util.Abort(_('similarity must be a number'))
3792 if sim < 0 or sim > 100:
3793 if sim < 0 or sim > 100:
3793 raise util.Abort(_('similarity must be between 0 and 100'))
3794 raise util.Abort(_('similarity must be between 0 and 100'))
3794 if sim and not update:
3795 if sim and not update:
3795 raise util.Abort(_('cannot use --similarity with --bypass'))
3796 raise util.Abort(_('cannot use --similarity with --bypass'))
3796
3797
3797 if update:
3798 if update:
3798 cmdutil.checkunfinished(repo)
3799 cmdutil.checkunfinished(repo)
3799 if (opts.get('exact') or not opts.get('force')) and update:
3800 if (opts.get('exact') or not opts.get('force')) and update:
3800 cmdutil.bailifchanged(repo)
3801 cmdutil.bailifchanged(repo)
3801
3802
3802 base = opts["base"]
3803 base = opts["base"]
3803 wlock = lock = tr = None
3804 wlock = lock = tr = None
3804 msgs = []
3805 msgs = []
3805
3806
3806
3807
3807 try:
3808 try:
3808 try:
3809 try:
3809 wlock = repo.wlock()
3810 wlock = repo.wlock()
3810 if not opts.get('no_commit'):
3811 if not opts.get('no_commit'):
3811 lock = repo.lock()
3812 lock = repo.lock()
3812 tr = repo.transaction('import')
3813 tr = repo.transaction('import')
3813 parents = repo.parents()
3814 parents = repo.parents()
3814 for patchurl in patches:
3815 for patchurl in patches:
3815 if patchurl == '-':
3816 if patchurl == '-':
3816 ui.status(_('applying patch from stdin\n'))
3817 ui.status(_('applying patch from stdin\n'))
3817 patchfile = ui.fin
3818 patchfile = ui.fin
3818 patchurl = 'stdin' # for error message
3819 patchurl = 'stdin' # for error message
3819 else:
3820 else:
3820 patchurl = os.path.join(base, patchurl)
3821 patchurl = os.path.join(base, patchurl)
3821 ui.status(_('applying %s\n') % patchurl)
3822 ui.status(_('applying %s\n') % patchurl)
3822 patchfile = hg.openpath(ui, patchurl)
3823 patchfile = hg.openpath(ui, patchurl)
3823
3824
3824 haspatch = False
3825 haspatch = False
3825 for hunk in patch.split(patchfile):
3826 for hunk in patch.split(patchfile):
3826 (msg, node) = cmdutil.tryimportone(ui, repo, hunk, parents,
3827 (msg, node) = cmdutil.tryimportone(ui, repo, hunk, parents,
3827 opts, msgs, hg.clean)
3828 opts, msgs, hg.clean)
3828 if msg:
3829 if msg:
3829 haspatch = True
3830 haspatch = True
3830 ui.note(msg + '\n')
3831 ui.note(msg + '\n')
3831 if update or opts.get('exact'):
3832 if update or opts.get('exact'):
3832 parents = repo.parents()
3833 parents = repo.parents()
3833 else:
3834 else:
3834 parents = [repo[node]]
3835 parents = [repo[node]]
3835
3836
3836 if not haspatch:
3837 if not haspatch:
3837 raise util.Abort(_('%s: no diffs found') % patchurl)
3838 raise util.Abort(_('%s: no diffs found') % patchurl)
3838
3839
3839 if tr:
3840 if tr:
3840 tr.close()
3841 tr.close()
3841 if msgs:
3842 if msgs:
3842 repo.savecommitmessage('\n* * *\n'.join(msgs))
3843 repo.savecommitmessage('\n* * *\n'.join(msgs))
3843 except: # re-raises
3844 except: # re-raises
3844 # wlock.release() indirectly calls dirstate.write(): since
3845 # wlock.release() indirectly calls dirstate.write(): since
3845 # we're crashing, we do not want to change the working dir
3846 # we're crashing, we do not want to change the working dir
3846 # parent after all, so make sure it writes nothing
3847 # parent after all, so make sure it writes nothing
3847 repo.dirstate.invalidate()
3848 repo.dirstate.invalidate()
3848 raise
3849 raise
3849 finally:
3850 finally:
3850 if tr:
3851 if tr:
3851 tr.release()
3852 tr.release()
3852 release(lock, wlock)
3853 release(lock, wlock)
3853
3854
3854 @command('incoming|in',
3855 @command('incoming|in',
3855 [('f', 'force', None,
3856 [('f', 'force', None,
3856 _('run even if remote repository is unrelated')),
3857 _('run even if remote repository is unrelated')),
3857 ('n', 'newest-first', None, _('show newest record first')),
3858 ('n', 'newest-first', None, _('show newest record first')),
3858 ('', 'bundle', '',
3859 ('', 'bundle', '',
3859 _('file to store the bundles into'), _('FILE')),
3860 _('file to store the bundles into'), _('FILE')),
3860 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3861 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3861 ('B', 'bookmarks', False, _("compare bookmarks")),
3862 ('B', 'bookmarks', False, _("compare bookmarks")),
3862 ('b', 'branch', [],
3863 ('b', 'branch', [],
3863 _('a specific branch you would like to pull'), _('BRANCH')),
3864 _('a specific branch you would like to pull'), _('BRANCH')),
3864 ] + logopts + remoteopts + subrepoopts,
3865 ] + logopts + remoteopts + subrepoopts,
3865 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3866 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3866 def incoming(ui, repo, source="default", **opts):
3867 def incoming(ui, repo, source="default", **opts):
3867 """show new changesets found in source
3868 """show new changesets found in source
3868
3869
3869 Show new changesets found in the specified path/URL or the default
3870 Show new changesets found in the specified path/URL or the default
3870 pull location. These are the changesets that would have been pulled
3871 pull location. These are the changesets that would have been pulled
3871 if a pull at the time you issued this command.
3872 if a pull at the time you issued this command.
3872
3873
3873 For remote repository, using --bundle avoids downloading the
3874 For remote repository, using --bundle avoids downloading the
3874 changesets twice if the incoming is followed by a pull.
3875 changesets twice if the incoming is followed by a pull.
3875
3876
3876 See pull for valid source format details.
3877 See pull for valid source format details.
3877
3878
3878 .. container:: verbose
3879 .. container:: verbose
3879
3880
3880 Examples:
3881 Examples:
3881
3882
3882 - show incoming changes with patches and full description::
3883 - show incoming changes with patches and full description::
3883
3884
3884 hg incoming -vp
3885 hg incoming -vp
3885
3886
3886 - show incoming changes excluding merges, store a bundle::
3887 - show incoming changes excluding merges, store a bundle::
3887
3888
3888 hg in -vpM --bundle incoming.hg
3889 hg in -vpM --bundle incoming.hg
3889 hg pull incoming.hg
3890 hg pull incoming.hg
3890
3891
3891 - briefly list changes inside a bundle::
3892 - briefly list changes inside a bundle::
3892
3893
3893 hg in changes.hg -T "{desc|firstline}\\n"
3894 hg in changes.hg -T "{desc|firstline}\\n"
3894
3895
3895 Returns 0 if there are incoming changes, 1 otherwise.
3896 Returns 0 if there are incoming changes, 1 otherwise.
3896 """
3897 """
3897 if opts.get('graph'):
3898 if opts.get('graph'):
3898 cmdutil.checkunsupportedgraphflags([], opts)
3899 cmdutil.checkunsupportedgraphflags([], opts)
3899 def display(other, chlist, displayer):
3900 def display(other, chlist, displayer):
3900 revdag = cmdutil.graphrevs(other, chlist, opts)
3901 revdag = cmdutil.graphrevs(other, chlist, opts)
3901 showparents = [ctx.node() for ctx in repo[None].parents()]
3902 showparents = [ctx.node() for ctx in repo[None].parents()]
3902 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3903 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3903 graphmod.asciiedges)
3904 graphmod.asciiedges)
3904
3905
3905 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3906 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3906 return 0
3907 return 0
3907
3908
3908 if opts.get('bundle') and opts.get('subrepos'):
3909 if opts.get('bundle') and opts.get('subrepos'):
3909 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3910 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3910
3911
3911 if opts.get('bookmarks'):
3912 if opts.get('bookmarks'):
3912 source, branches = hg.parseurl(ui.expandpath(source),
3913 source, branches = hg.parseurl(ui.expandpath(source),
3913 opts.get('branch'))
3914 opts.get('branch'))
3914 other = hg.peer(repo, opts, source)
3915 other = hg.peer(repo, opts, source)
3915 if 'bookmarks' not in other.listkeys('namespaces'):
3916 if 'bookmarks' not in other.listkeys('namespaces'):
3916 ui.warn(_("remote doesn't support bookmarks\n"))
3917 ui.warn(_("remote doesn't support bookmarks\n"))
3917 return 0
3918 return 0
3918 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3919 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3919 return bookmarks.diff(ui, repo, other)
3920 return bookmarks.diff(ui, repo, other)
3920
3921
3921 repo._subtoppath = ui.expandpath(source)
3922 repo._subtoppath = ui.expandpath(source)
3922 try:
3923 try:
3923 return hg.incoming(ui, repo, source, opts)
3924 return hg.incoming(ui, repo, source, opts)
3924 finally:
3925 finally:
3925 del repo._subtoppath
3926 del repo._subtoppath
3926
3927
3927
3928
3928 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3929 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3929 def init(ui, dest=".", **opts):
3930 def init(ui, dest=".", **opts):
3930 """create a new repository in the given directory
3931 """create a new repository in the given directory
3931
3932
3932 Initialize a new repository in the given directory. If the given
3933 Initialize a new repository in the given directory. If the given
3933 directory does not exist, it will be created.
3934 directory does not exist, it will be created.
3934
3935
3935 If no directory is given, the current directory is used.
3936 If no directory is given, the current directory is used.
3936
3937
3937 It is possible to specify an ``ssh://`` URL as the destination.
3938 It is possible to specify an ``ssh://`` URL as the destination.
3938 See :hg:`help urls` for more information.
3939 See :hg:`help urls` for more information.
3939
3940
3940 Returns 0 on success.
3941 Returns 0 on success.
3941 """
3942 """
3942 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3943 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3943
3944
3944 @command('locate',
3945 @command('locate',
3945 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3946 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3946 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3947 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3947 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3948 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3948 ] + walkopts,
3949 ] + walkopts,
3949 _('[OPTION]... [PATTERN]...'))
3950 _('[OPTION]... [PATTERN]...'))
3950 def locate(ui, repo, *pats, **opts):
3951 def locate(ui, repo, *pats, **opts):
3951 """locate files matching specific patterns
3952 """locate files matching specific patterns
3952
3953
3953 Print files under Mercurial control in the working directory whose
3954 Print files under Mercurial control in the working directory whose
3954 names match the given patterns.
3955 names match the given patterns.
3955
3956
3956 By default, this command searches all directories in the working
3957 By default, this command searches all directories in the working
3957 directory. To search just the current directory and its
3958 directory. To search just the current directory and its
3958 subdirectories, use "--include .".
3959 subdirectories, use "--include .".
3959
3960
3960 If no patterns are given to match, this command prints the names
3961 If no patterns are given to match, this command prints the names
3961 of all files under Mercurial control in the working directory.
3962 of all files under Mercurial control in the working directory.
3962
3963
3963 If you want to feed the output of this command into the "xargs"
3964 If you want to feed the output of this command into the "xargs"
3964 command, use the -0 option to both this command and "xargs". This
3965 command, use the -0 option to both this command and "xargs". This
3965 will avoid the problem of "xargs" treating single filenames that
3966 will avoid the problem of "xargs" treating single filenames that
3966 contain whitespace as multiple filenames.
3967 contain whitespace as multiple filenames.
3967
3968
3968 Returns 0 if a match is found, 1 otherwise.
3969 Returns 0 if a match is found, 1 otherwise.
3969 """
3970 """
3970 end = opts.get('print0') and '\0' or '\n'
3971 end = opts.get('print0') and '\0' or '\n'
3971 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3972 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3972
3973
3973 ret = 1
3974 ret = 1
3974 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3975 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3975 m.bad = lambda x, y: False
3976 m.bad = lambda x, y: False
3976 for abs in repo[rev].walk(m):
3977 for abs in repo[rev].walk(m):
3977 if not rev and abs not in repo.dirstate:
3978 if not rev and abs not in repo.dirstate:
3978 continue
3979 continue
3979 if opts.get('fullpath'):
3980 if opts.get('fullpath'):
3980 ui.write(repo.wjoin(abs), end)
3981 ui.write(repo.wjoin(abs), end)
3981 else:
3982 else:
3982 ui.write(((pats and m.rel(abs)) or abs), end)
3983 ui.write(((pats and m.rel(abs)) or abs), end)
3983 ret = 0
3984 ret = 0
3984
3985
3985 return ret
3986 return ret
3986
3987
3987 @command('^log|history',
3988 @command('^log|history',
3988 [('f', 'follow', None,
3989 [('f', 'follow', None,
3989 _('follow changeset history, or file history across copies and renames')),
3990 _('follow changeset history, or file history across copies and renames')),
3990 ('', 'follow-first', None,
3991 ('', 'follow-first', None,
3991 _('only follow the first parent of merge changesets (DEPRECATED)')),
3992 _('only follow the first parent of merge changesets (DEPRECATED)')),
3992 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3993 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3993 ('C', 'copies', None, _('show copied files')),
3994 ('C', 'copies', None, _('show copied files')),
3994 ('k', 'keyword', [],
3995 ('k', 'keyword', [],
3995 _('do case-insensitive search for a given text'), _('TEXT')),
3996 _('do case-insensitive search for a given text'), _('TEXT')),
3996 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3997 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3997 ('', 'removed', None, _('include revisions where files were removed')),
3998 ('', 'removed', None, _('include revisions where files were removed')),
3998 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3999 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3999 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4000 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4000 ('', 'only-branch', [],
4001 ('', 'only-branch', [],
4001 _('show only changesets within the given named branch (DEPRECATED)'),
4002 _('show only changesets within the given named branch (DEPRECATED)'),
4002 _('BRANCH')),
4003 _('BRANCH')),
4003 ('b', 'branch', [],
4004 ('b', 'branch', [],
4004 _('show changesets within the given named branch'), _('BRANCH')),
4005 _('show changesets within the given named branch'), _('BRANCH')),
4005 ('P', 'prune', [],
4006 ('P', 'prune', [],
4006 _('do not display revision or any of its ancestors'), _('REV')),
4007 _('do not display revision or any of its ancestors'), _('REV')),
4007 ] + logopts + walkopts,
4008 ] + logopts + walkopts,
4008 _('[OPTION]... [FILE]'))
4009 _('[OPTION]... [FILE]'))
4009 def log(ui, repo, *pats, **opts):
4010 def log(ui, repo, *pats, **opts):
4010 """show revision history of entire repository or files
4011 """show revision history of entire repository or files
4011
4012
4012 Print the revision history of the specified files or the entire
4013 Print the revision history of the specified files or the entire
4013 project.
4014 project.
4014
4015
4015 If no revision range is specified, the default is ``tip:0`` unless
4016 If no revision range is specified, the default is ``tip:0`` unless
4016 --follow is set, in which case the working directory parent is
4017 --follow is set, in which case the working directory parent is
4017 used as the starting revision.
4018 used as the starting revision.
4018
4019
4019 File history is shown without following rename or copy history of
4020 File history is shown without following rename or copy history of
4020 files. Use -f/--follow with a filename to follow history across
4021 files. Use -f/--follow with a filename to follow history across
4021 renames and copies. --follow without a filename will only show
4022 renames and copies. --follow without a filename will only show
4022 ancestors or descendants of the starting revision.
4023 ancestors or descendants of the starting revision.
4023
4024
4024 By default this command prints revision number and changeset id,
4025 By default this command prints revision number and changeset id,
4025 tags, non-trivial parents, user, date and time, and a summary for
4026 tags, non-trivial parents, user, date and time, and a summary for
4026 each commit. When the -v/--verbose switch is used, the list of
4027 each commit. When the -v/--verbose switch is used, the list of
4027 changed files and full commit message are shown.
4028 changed files and full commit message are shown.
4028
4029
4029 With --graph the revisions are shown as an ASCII art DAG with the most
4030 With --graph the revisions are shown as an ASCII art DAG with the most
4030 recent changeset at the top.
4031 recent changeset at the top.
4031 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4032 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4032 and '+' represents a fork where the changeset from the lines below is a
4033 and '+' represents a fork where the changeset from the lines below is a
4033 parent of the 'o' merge on the same same line.
4034 parent of the 'o' merge on the same same line.
4034
4035
4035 .. note::
4036 .. note::
4036
4037
4037 log -p/--patch may generate unexpected diff output for merge
4038 log -p/--patch may generate unexpected diff output for merge
4038 changesets, as it will only compare the merge changeset against
4039 changesets, as it will only compare the merge changeset against
4039 its first parent. Also, only files different from BOTH parents
4040 its first parent. Also, only files different from BOTH parents
4040 will appear in files:.
4041 will appear in files:.
4041
4042
4042 .. note::
4043 .. note::
4043
4044
4044 for performance reasons, log FILE may omit duplicate changes
4045 for performance reasons, log FILE may omit duplicate changes
4045 made on branches and will not show deletions. To see all
4046 made on branches and will not show deletions. To see all
4046 changes including duplicates and deletions, use the --removed
4047 changes including duplicates and deletions, use the --removed
4047 switch.
4048 switch.
4048
4049
4049 .. container:: verbose
4050 .. container:: verbose
4050
4051
4051 Some examples:
4052 Some examples:
4052
4053
4053 - changesets with full descriptions and file lists::
4054 - changesets with full descriptions and file lists::
4054
4055
4055 hg log -v
4056 hg log -v
4056
4057
4057 - changesets ancestral to the working directory::
4058 - changesets ancestral to the working directory::
4058
4059
4059 hg log -f
4060 hg log -f
4060
4061
4061 - last 10 commits on the current branch::
4062 - last 10 commits on the current branch::
4062
4063
4063 hg log -l 10 -b .
4064 hg log -l 10 -b .
4064
4065
4065 - changesets showing all modifications of a file, including removals::
4066 - changesets showing all modifications of a file, including removals::
4066
4067
4067 hg log --removed file.c
4068 hg log --removed file.c
4068
4069
4069 - all changesets that touch a directory, with diffs, excluding merges::
4070 - all changesets that touch a directory, with diffs, excluding merges::
4070
4071
4071 hg log -Mp lib/
4072 hg log -Mp lib/
4072
4073
4073 - all revision numbers that match a keyword::
4074 - all revision numbers that match a keyword::
4074
4075
4075 hg log -k bug --template "{rev}\\n"
4076 hg log -k bug --template "{rev}\\n"
4076
4077
4077 - check if a given changeset is included is a tagged release::
4078 - check if a given changeset is included is a tagged release::
4078
4079
4079 hg log -r "a21ccf and ancestor(1.9)"
4080 hg log -r "a21ccf and ancestor(1.9)"
4080
4081
4081 - find all changesets by some user in a date range::
4082 - find all changesets by some user in a date range::
4082
4083
4083 hg log -k alice -d "may 2008 to jul 2008"
4084 hg log -k alice -d "may 2008 to jul 2008"
4084
4085
4085 - summary of all changesets after the last tag::
4086 - summary of all changesets after the last tag::
4086
4087
4087 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4088 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4088
4089
4089 See :hg:`help dates` for a list of formats valid for -d/--date.
4090 See :hg:`help dates` for a list of formats valid for -d/--date.
4090
4091
4091 See :hg:`help revisions` and :hg:`help revsets` for more about
4092 See :hg:`help revisions` and :hg:`help revsets` for more about
4092 specifying revisions.
4093 specifying revisions.
4093
4094
4094 See :hg:`help templates` for more about pre-packaged styles and
4095 See :hg:`help templates` for more about pre-packaged styles and
4095 specifying custom templates.
4096 specifying custom templates.
4096
4097
4097 Returns 0 on success.
4098 Returns 0 on success.
4098 """
4099 """
4099 if opts.get('graph'):
4100 if opts.get('graph'):
4100 return cmdutil.graphlog(ui, repo, *pats, **opts)
4101 return cmdutil.graphlog(ui, repo, *pats, **opts)
4101
4102
4102 matchfn = scmutil.match(repo[None], pats, opts)
4103 matchfn = scmutil.match(repo[None], pats, opts)
4103 limit = cmdutil.loglimit(opts)
4104 limit = cmdutil.loglimit(opts)
4104 count = 0
4105 count = 0
4105
4106
4106 getrenamed, endrev = None, None
4107 getrenamed, endrev = None, None
4107 if opts.get('copies'):
4108 if opts.get('copies'):
4108 if opts.get('rev'):
4109 if opts.get('rev'):
4109 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4110 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4110 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4111 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4111
4112
4112 df = False
4113 df = False
4113 if opts.get("date"):
4114 if opts.get("date"):
4114 df = util.matchdate(opts["date"])
4115 df = util.matchdate(opts["date"])
4115
4116
4116 branches = opts.get('branch', []) + opts.get('only_branch', [])
4117 branches = opts.get('branch', []) + opts.get('only_branch', [])
4117 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4118 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4118
4119
4119 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4120 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4120 def prep(ctx, fns):
4121 def prep(ctx, fns):
4121 rev = ctx.rev()
4122 rev = ctx.rev()
4122 parents = [p for p in repo.changelog.parentrevs(rev)
4123 parents = [p for p in repo.changelog.parentrevs(rev)
4123 if p != nullrev]
4124 if p != nullrev]
4124 if opts.get('no_merges') and len(parents) == 2:
4125 if opts.get('no_merges') and len(parents) == 2:
4125 return
4126 return
4126 if opts.get('only_merges') and len(parents) != 2:
4127 if opts.get('only_merges') and len(parents) != 2:
4127 return
4128 return
4128 if opts.get('branch') and ctx.branch() not in opts['branch']:
4129 if opts.get('branch') and ctx.branch() not in opts['branch']:
4129 return
4130 return
4130 if df and not df(ctx.date()[0]):
4131 if df and not df(ctx.date()[0]):
4131 return
4132 return
4132
4133
4133 lower = encoding.lower
4134 lower = encoding.lower
4134 if opts.get('user'):
4135 if opts.get('user'):
4135 luser = lower(ctx.user())
4136 luser = lower(ctx.user())
4136 for k in [lower(x) for x in opts['user']]:
4137 for k in [lower(x) for x in opts['user']]:
4137 if (k in luser):
4138 if (k in luser):
4138 break
4139 break
4139 else:
4140 else:
4140 return
4141 return
4141 if opts.get('keyword'):
4142 if opts.get('keyword'):
4142 luser = lower(ctx.user())
4143 luser = lower(ctx.user())
4143 ldesc = lower(ctx.description())
4144 ldesc = lower(ctx.description())
4144 lfiles = lower(" ".join(ctx.files()))
4145 lfiles = lower(" ".join(ctx.files()))
4145 for k in [lower(x) for x in opts['keyword']]:
4146 for k in [lower(x) for x in opts['keyword']]:
4146 if (k in luser or k in ldesc or k in lfiles):
4147 if (k in luser or k in ldesc or k in lfiles):
4147 break
4148 break
4148 else:
4149 else:
4149 return
4150 return
4150
4151
4151 copies = None
4152 copies = None
4152 if getrenamed is not None and rev:
4153 if getrenamed is not None and rev:
4153 copies = []
4154 copies = []
4154 for fn in ctx.files():
4155 for fn in ctx.files():
4155 rename = getrenamed(fn, rev)
4156 rename = getrenamed(fn, rev)
4156 if rename:
4157 if rename:
4157 copies.append((fn, rename[0]))
4158 copies.append((fn, rename[0]))
4158
4159
4159 revmatchfn = None
4160 revmatchfn = None
4160 if opts.get('patch') or opts.get('stat'):
4161 if opts.get('patch') or opts.get('stat'):
4161 if opts.get('follow') or opts.get('follow_first'):
4162 if opts.get('follow') or opts.get('follow_first'):
4162 # note: this might be wrong when following through merges
4163 # note: this might be wrong when following through merges
4163 revmatchfn = scmutil.match(repo[None], fns, default='path')
4164 revmatchfn = scmutil.match(repo[None], fns, default='path')
4164 else:
4165 else:
4165 revmatchfn = matchfn
4166 revmatchfn = matchfn
4166
4167
4167 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4168 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4168
4169
4169 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4170 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4170 if displayer.flush(ctx.rev()):
4171 if displayer.flush(ctx.rev()):
4171 count += 1
4172 count += 1
4172 if count == limit:
4173 if count == limit:
4173 break
4174 break
4174 displayer.close()
4175 displayer.close()
4175
4176
4176 @command('manifest',
4177 @command('manifest',
4177 [('r', 'rev', '', _('revision to display'), _('REV')),
4178 [('r', 'rev', '', _('revision to display'), _('REV')),
4178 ('', 'all', False, _("list files from all revisions"))],
4179 ('', 'all', False, _("list files from all revisions"))],
4179 _('[-r REV]'))
4180 _('[-r REV]'))
4180 def manifest(ui, repo, node=None, rev=None, **opts):
4181 def manifest(ui, repo, node=None, rev=None, **opts):
4181 """output the current or given revision of the project manifest
4182 """output the current or given revision of the project manifest
4182
4183
4183 Print a list of version controlled files for the given revision.
4184 Print a list of version controlled files for the given revision.
4184 If no revision is given, the first parent of the working directory
4185 If no revision is given, the first parent of the working directory
4185 is used, or the null revision if no revision is checked out.
4186 is used, or the null revision if no revision is checked out.
4186
4187
4187 With -v, print file permissions, symlink and executable bits.
4188 With -v, print file permissions, symlink and executable bits.
4188 With --debug, print file revision hashes.
4189 With --debug, print file revision hashes.
4189
4190
4190 If option --all is specified, the list of all files from all revisions
4191 If option --all is specified, the list of all files from all revisions
4191 is printed. This includes deleted and renamed files.
4192 is printed. This includes deleted and renamed files.
4192
4193
4193 Returns 0 on success.
4194 Returns 0 on success.
4194 """
4195 """
4195
4196
4196 fm = ui.formatter('manifest', opts)
4197 fm = ui.formatter('manifest', opts)
4197
4198
4198 if opts.get('all'):
4199 if opts.get('all'):
4199 if rev or node:
4200 if rev or node:
4200 raise util.Abort(_("can't specify a revision with --all"))
4201 raise util.Abort(_("can't specify a revision with --all"))
4201
4202
4202 res = []
4203 res = []
4203 prefix = "data/"
4204 prefix = "data/"
4204 suffix = ".i"
4205 suffix = ".i"
4205 plen = len(prefix)
4206 plen = len(prefix)
4206 slen = len(suffix)
4207 slen = len(suffix)
4207 lock = repo.lock()
4208 lock = repo.lock()
4208 try:
4209 try:
4209 for fn, b, size in repo.store.datafiles():
4210 for fn, b, size in repo.store.datafiles():
4210 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4211 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4211 res.append(fn[plen:-slen])
4212 res.append(fn[plen:-slen])
4212 finally:
4213 finally:
4213 lock.release()
4214 lock.release()
4214 for f in res:
4215 for f in res:
4215 fm.startitem()
4216 fm.startitem()
4216 fm.write("path", '%s\n', f)
4217 fm.write("path", '%s\n', f)
4217 fm.end()
4218 fm.end()
4218 return
4219 return
4219
4220
4220 if rev and node:
4221 if rev and node:
4221 raise util.Abort(_("please specify just one revision"))
4222 raise util.Abort(_("please specify just one revision"))
4222
4223
4223 if not node:
4224 if not node:
4224 node = rev
4225 node = rev
4225
4226
4226 char = {'l': '@', 'x': '*', '': ''}
4227 char = {'l': '@', 'x': '*', '': ''}
4227 mode = {'l': '644', 'x': '755', '': '644'}
4228 mode = {'l': '644', 'x': '755', '': '644'}
4228 ctx = scmutil.revsingle(repo, node)
4229 ctx = scmutil.revsingle(repo, node)
4229 mf = ctx.manifest()
4230 mf = ctx.manifest()
4230 for f in ctx:
4231 for f in ctx:
4231 fm.startitem()
4232 fm.startitem()
4232 fl = ctx[f].flags()
4233 fl = ctx[f].flags()
4233 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4234 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4234 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4235 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4235 fm.write('path', '%s\n', f)
4236 fm.write('path', '%s\n', f)
4236 fm.end()
4237 fm.end()
4237
4238
4238 @command('^merge',
4239 @command('^merge',
4239 [('f', 'force', None,
4240 [('f', 'force', None,
4240 _('force a merge including outstanding changes (DEPRECATED)')),
4241 _('force a merge including outstanding changes (DEPRECATED)')),
4241 ('r', 'rev', '', _('revision to merge'), _('REV')),
4242 ('r', 'rev', '', _('revision to merge'), _('REV')),
4242 ('P', 'preview', None,
4243 ('P', 'preview', None,
4243 _('review revisions to merge (no merge is performed)'))
4244 _('review revisions to merge (no merge is performed)'))
4244 ] + mergetoolopts,
4245 ] + mergetoolopts,
4245 _('[-P] [-f] [[-r] REV]'))
4246 _('[-P] [-f] [[-r] REV]'))
4246 def merge(ui, repo, node=None, **opts):
4247 def merge(ui, repo, node=None, **opts):
4247 """merge working directory with another revision
4248 """merge working directory with another revision
4248
4249
4249 The current working directory is updated with all changes made in
4250 The current working directory is updated with all changes made in
4250 the requested revision since the last common predecessor revision.
4251 the requested revision since the last common predecessor revision.
4251
4252
4252 Files that changed between either parent are marked as changed for
4253 Files that changed between either parent are marked as changed for
4253 the next commit and a commit must be performed before any further
4254 the next commit and a commit must be performed before any further
4254 updates to the repository are allowed. The next commit will have
4255 updates to the repository are allowed. The next commit will have
4255 two parents.
4256 two parents.
4256
4257
4257 ``--tool`` can be used to specify the merge tool used for file
4258 ``--tool`` can be used to specify the merge tool used for file
4258 merges. It overrides the HGMERGE environment variable and your
4259 merges. It overrides the HGMERGE environment variable and your
4259 configuration files. See :hg:`help merge-tools` for options.
4260 configuration files. See :hg:`help merge-tools` for options.
4260
4261
4261 If no revision is specified, the working directory's parent is a
4262 If no revision is specified, the working directory's parent is a
4262 head revision, and the current branch contains exactly one other
4263 head revision, and the current branch contains exactly one other
4263 head, the other head is merged with by default. Otherwise, an
4264 head, the other head is merged with by default. Otherwise, an
4264 explicit revision with which to merge with must be provided.
4265 explicit revision with which to merge with must be provided.
4265
4266
4266 :hg:`resolve` must be used to resolve unresolved files.
4267 :hg:`resolve` must be used to resolve unresolved files.
4267
4268
4268 To undo an uncommitted merge, use :hg:`update --clean .` which
4269 To undo an uncommitted merge, use :hg:`update --clean .` which
4269 will check out a clean copy of the original merge parent, losing
4270 will check out a clean copy of the original merge parent, losing
4270 all changes.
4271 all changes.
4271
4272
4272 Returns 0 on success, 1 if there are unresolved files.
4273 Returns 0 on success, 1 if there are unresolved files.
4273 """
4274 """
4274
4275
4275 if opts.get('rev') and node:
4276 if opts.get('rev') and node:
4276 raise util.Abort(_("please specify just one revision"))
4277 raise util.Abort(_("please specify just one revision"))
4277 if not node:
4278 if not node:
4278 node = opts.get('rev')
4279 node = opts.get('rev')
4279
4280
4280 if node:
4281 if node:
4281 node = scmutil.revsingle(repo, node).node()
4282 node = scmutil.revsingle(repo, node).node()
4282
4283
4283 if not node and repo._bookmarkcurrent:
4284 if not node and repo._bookmarkcurrent:
4284 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4285 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4285 curhead = repo[repo._bookmarkcurrent].node()
4286 curhead = repo[repo._bookmarkcurrent].node()
4286 if len(bmheads) == 2:
4287 if len(bmheads) == 2:
4287 if curhead == bmheads[0]:
4288 if curhead == bmheads[0]:
4288 node = bmheads[1]
4289 node = bmheads[1]
4289 else:
4290 else:
4290 node = bmheads[0]
4291 node = bmheads[0]
4291 elif len(bmheads) > 2:
4292 elif len(bmheads) > 2:
4292 raise util.Abort(_("multiple matching bookmarks to merge - "
4293 raise util.Abort(_("multiple matching bookmarks to merge - "
4293 "please merge with an explicit rev or bookmark"),
4294 "please merge with an explicit rev or bookmark"),
4294 hint=_("run 'hg heads' to see all heads"))
4295 hint=_("run 'hg heads' to see all heads"))
4295 elif len(bmheads) <= 1:
4296 elif len(bmheads) <= 1:
4296 raise util.Abort(_("no matching bookmark to merge - "
4297 raise util.Abort(_("no matching bookmark to merge - "
4297 "please merge with an explicit rev or bookmark"),
4298 "please merge with an explicit rev or bookmark"),
4298 hint=_("run 'hg heads' to see all heads"))
4299 hint=_("run 'hg heads' to see all heads"))
4299
4300
4300 if not node and not repo._bookmarkcurrent:
4301 if not node and not repo._bookmarkcurrent:
4301 branch = repo[None].branch()
4302 branch = repo[None].branch()
4302 bheads = repo.branchheads(branch)
4303 bheads = repo.branchheads(branch)
4303 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4304 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4304
4305
4305 if len(nbhs) > 2:
4306 if len(nbhs) > 2:
4306 raise util.Abort(_("branch '%s' has %d heads - "
4307 raise util.Abort(_("branch '%s' has %d heads - "
4307 "please merge with an explicit rev")
4308 "please merge with an explicit rev")
4308 % (branch, len(bheads)),
4309 % (branch, len(bheads)),
4309 hint=_("run 'hg heads .' to see heads"))
4310 hint=_("run 'hg heads .' to see heads"))
4310
4311
4311 parent = repo.dirstate.p1()
4312 parent = repo.dirstate.p1()
4312 if len(nbhs) <= 1:
4313 if len(nbhs) <= 1:
4313 if len(bheads) > 1:
4314 if len(bheads) > 1:
4314 raise util.Abort(_("heads are bookmarked - "
4315 raise util.Abort(_("heads are bookmarked - "
4315 "please merge with an explicit rev"),
4316 "please merge with an explicit rev"),
4316 hint=_("run 'hg heads' to see all heads"))
4317 hint=_("run 'hg heads' to see all heads"))
4317 if len(repo.heads()) > 1:
4318 if len(repo.heads()) > 1:
4318 raise util.Abort(_("branch '%s' has one head - "
4319 raise util.Abort(_("branch '%s' has one head - "
4319 "please merge with an explicit rev")
4320 "please merge with an explicit rev")
4320 % branch,
4321 % branch,
4321 hint=_("run 'hg heads' to see all heads"))
4322 hint=_("run 'hg heads' to see all heads"))
4322 msg, hint = _('nothing to merge'), None
4323 msg, hint = _('nothing to merge'), None
4323 if parent != repo.lookup(branch):
4324 if parent != repo.lookup(branch):
4324 hint = _("use 'hg update' instead")
4325 hint = _("use 'hg update' instead")
4325 raise util.Abort(msg, hint=hint)
4326 raise util.Abort(msg, hint=hint)
4326
4327
4327 if parent not in bheads:
4328 if parent not in bheads:
4328 raise util.Abort(_('working directory not at a head revision'),
4329 raise util.Abort(_('working directory not at a head revision'),
4329 hint=_("use 'hg update' or merge with an "
4330 hint=_("use 'hg update' or merge with an "
4330 "explicit revision"))
4331 "explicit revision"))
4331 if parent == nbhs[0]:
4332 if parent == nbhs[0]:
4332 node = nbhs[-1]
4333 node = nbhs[-1]
4333 else:
4334 else:
4334 node = nbhs[0]
4335 node = nbhs[0]
4335
4336
4336 if opts.get('preview'):
4337 if opts.get('preview'):
4337 # find nodes that are ancestors of p2 but not of p1
4338 # find nodes that are ancestors of p2 but not of p1
4338 p1 = repo.lookup('.')
4339 p1 = repo.lookup('.')
4339 p2 = repo.lookup(node)
4340 p2 = repo.lookup(node)
4340 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4341 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4341
4342
4342 displayer = cmdutil.show_changeset(ui, repo, opts)
4343 displayer = cmdutil.show_changeset(ui, repo, opts)
4343 for node in nodes:
4344 for node in nodes:
4344 displayer.show(repo[node])
4345 displayer.show(repo[node])
4345 displayer.close()
4346 displayer.close()
4346 return 0
4347 return 0
4347
4348
4348 try:
4349 try:
4349 # ui.forcemerge is an internal variable, do not document
4350 # ui.forcemerge is an internal variable, do not document
4350 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4351 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4351 return hg.merge(repo, node, force=opts.get('force'))
4352 return hg.merge(repo, node, force=opts.get('force'))
4352 finally:
4353 finally:
4353 ui.setconfig('ui', 'forcemerge', '', 'merge')
4354 ui.setconfig('ui', 'forcemerge', '', 'merge')
4354
4355
4355 @command('outgoing|out',
4356 @command('outgoing|out',
4356 [('f', 'force', None, _('run even when the destination is unrelated')),
4357 [('f', 'force', None, _('run even when the destination is unrelated')),
4357 ('r', 'rev', [],
4358 ('r', 'rev', [],
4358 _('a changeset intended to be included in the destination'), _('REV')),
4359 _('a changeset intended to be included in the destination'), _('REV')),
4359 ('n', 'newest-first', None, _('show newest record first')),
4360 ('n', 'newest-first', None, _('show newest record first')),
4360 ('B', 'bookmarks', False, _('compare bookmarks')),
4361 ('B', 'bookmarks', False, _('compare bookmarks')),
4361 ('b', 'branch', [], _('a specific branch you would like to push'),
4362 ('b', 'branch', [], _('a specific branch you would like to push'),
4362 _('BRANCH')),
4363 _('BRANCH')),
4363 ] + logopts + remoteopts + subrepoopts,
4364 ] + logopts + remoteopts + subrepoopts,
4364 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4365 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4365 def outgoing(ui, repo, dest=None, **opts):
4366 def outgoing(ui, repo, dest=None, **opts):
4366 """show changesets not found in the destination
4367 """show changesets not found in the destination
4367
4368
4368 Show changesets not found in the specified destination repository
4369 Show changesets not found in the specified destination repository
4369 or the default push location. These are the changesets that would
4370 or the default push location. These are the changesets that would
4370 be pushed if a push was requested.
4371 be pushed if a push was requested.
4371
4372
4372 See pull for details of valid destination formats.
4373 See pull for details of valid destination formats.
4373
4374
4374 Returns 0 if there are outgoing changes, 1 otherwise.
4375 Returns 0 if there are outgoing changes, 1 otherwise.
4375 """
4376 """
4376 if opts.get('graph'):
4377 if opts.get('graph'):
4377 cmdutil.checkunsupportedgraphflags([], opts)
4378 cmdutil.checkunsupportedgraphflags([], opts)
4378 o = hg._outgoing(ui, repo, dest, opts)
4379 o = hg._outgoing(ui, repo, dest, opts)
4379 if o is None:
4380 if o is None:
4380 return
4381 return
4381
4382
4382 revdag = cmdutil.graphrevs(repo, o, opts)
4383 revdag = cmdutil.graphrevs(repo, o, opts)
4383 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4384 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4384 showparents = [ctx.node() for ctx in repo[None].parents()]
4385 showparents = [ctx.node() for ctx in repo[None].parents()]
4385 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4386 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4386 graphmod.asciiedges)
4387 graphmod.asciiedges)
4387 return 0
4388 return 0
4388
4389
4389 if opts.get('bookmarks'):
4390 if opts.get('bookmarks'):
4390 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4391 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4391 dest, branches = hg.parseurl(dest, opts.get('branch'))
4392 dest, branches = hg.parseurl(dest, opts.get('branch'))
4392 other = hg.peer(repo, opts, dest)
4393 other = hg.peer(repo, opts, dest)
4393 if 'bookmarks' not in other.listkeys('namespaces'):
4394 if 'bookmarks' not in other.listkeys('namespaces'):
4394 ui.warn(_("remote doesn't support bookmarks\n"))
4395 ui.warn(_("remote doesn't support bookmarks\n"))
4395 return 0
4396 return 0
4396 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4397 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4397 return bookmarks.diff(ui, other, repo)
4398 return bookmarks.diff(ui, other, repo)
4398
4399
4399 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4400 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4400 try:
4401 try:
4401 return hg.outgoing(ui, repo, dest, opts)
4402 return hg.outgoing(ui, repo, dest, opts)
4402 finally:
4403 finally:
4403 del repo._subtoppath
4404 del repo._subtoppath
4404
4405
4405 @command('parents',
4406 @command('parents',
4406 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4407 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4407 ] + templateopts,
4408 ] + templateopts,
4408 _('[-r REV] [FILE]'))
4409 _('[-r REV] [FILE]'))
4409 def parents(ui, repo, file_=None, **opts):
4410 def parents(ui, repo, file_=None, **opts):
4410 """show the parents of the working directory or revision
4411 """show the parents of the working directory or revision
4411
4412
4412 Print the working directory's parent revisions. If a revision is
4413 Print the working directory's parent revisions. If a revision is
4413 given via -r/--rev, the parent of that revision will be printed.
4414 given via -r/--rev, the parent of that revision will be printed.
4414 If a file argument is given, the revision in which the file was
4415 If a file argument is given, the revision in which the file was
4415 last changed (before the working directory revision or the
4416 last changed (before the working directory revision or the
4416 argument to --rev if given) is printed.
4417 argument to --rev if given) is printed.
4417
4418
4418 Returns 0 on success.
4419 Returns 0 on success.
4419 """
4420 """
4420
4421
4421 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4422 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4422
4423
4423 if file_:
4424 if file_:
4424 m = scmutil.match(ctx, (file_,), opts)
4425 m = scmutil.match(ctx, (file_,), opts)
4425 if m.anypats() or len(m.files()) != 1:
4426 if m.anypats() or len(m.files()) != 1:
4426 raise util.Abort(_('can only specify an explicit filename'))
4427 raise util.Abort(_('can only specify an explicit filename'))
4427 file_ = m.files()[0]
4428 file_ = m.files()[0]
4428 filenodes = []
4429 filenodes = []
4429 for cp in ctx.parents():
4430 for cp in ctx.parents():
4430 if not cp:
4431 if not cp:
4431 continue
4432 continue
4432 try:
4433 try:
4433 filenodes.append(cp.filenode(file_))
4434 filenodes.append(cp.filenode(file_))
4434 except error.LookupError:
4435 except error.LookupError:
4435 pass
4436 pass
4436 if not filenodes:
4437 if not filenodes:
4437 raise util.Abort(_("'%s' not found in manifest!") % file_)
4438 raise util.Abort(_("'%s' not found in manifest!") % file_)
4438 p = []
4439 p = []
4439 for fn in filenodes:
4440 for fn in filenodes:
4440 fctx = repo.filectx(file_, fileid=fn)
4441 fctx = repo.filectx(file_, fileid=fn)
4441 p.append(fctx.node())
4442 p.append(fctx.node())
4442 else:
4443 else:
4443 p = [cp.node() for cp in ctx.parents()]
4444 p = [cp.node() for cp in ctx.parents()]
4444
4445
4445 displayer = cmdutil.show_changeset(ui, repo, opts)
4446 displayer = cmdutil.show_changeset(ui, repo, opts)
4446 for n in p:
4447 for n in p:
4447 if n != nullid:
4448 if n != nullid:
4448 displayer.show(repo[n])
4449 displayer.show(repo[n])
4449 displayer.close()
4450 displayer.close()
4450
4451
4451 @command('paths', [], _('[NAME]'))
4452 @command('paths', [], _('[NAME]'))
4452 def paths(ui, repo, search=None):
4453 def paths(ui, repo, search=None):
4453 """show aliases for remote repositories
4454 """show aliases for remote repositories
4454
4455
4455 Show definition of symbolic path name NAME. If no name is given,
4456 Show definition of symbolic path name NAME. If no name is given,
4456 show definition of all available names.
4457 show definition of all available names.
4457
4458
4458 Option -q/--quiet suppresses all output when searching for NAME
4459 Option -q/--quiet suppresses all output when searching for NAME
4459 and shows only the path names when listing all definitions.
4460 and shows only the path names when listing all definitions.
4460
4461
4461 Path names are defined in the [paths] section of your
4462 Path names are defined in the [paths] section of your
4462 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4463 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4463 repository, ``.hg/hgrc`` is used, too.
4464 repository, ``.hg/hgrc`` is used, too.
4464
4465
4465 The path names ``default`` and ``default-push`` have a special
4466 The path names ``default`` and ``default-push`` have a special
4466 meaning. When performing a push or pull operation, they are used
4467 meaning. When performing a push or pull operation, they are used
4467 as fallbacks if no location is specified on the command-line.
4468 as fallbacks if no location is specified on the command-line.
4468 When ``default-push`` is set, it will be used for push and
4469 When ``default-push`` is set, it will be used for push and
4469 ``default`` will be used for pull; otherwise ``default`` is used
4470 ``default`` will be used for pull; otherwise ``default`` is used
4470 as the fallback for both. When cloning a repository, the clone
4471 as the fallback for both. When cloning a repository, the clone
4471 source is written as ``default`` in ``.hg/hgrc``. Note that
4472 source is written as ``default`` in ``.hg/hgrc``. Note that
4472 ``default`` and ``default-push`` apply to all inbound (e.g.
4473 ``default`` and ``default-push`` apply to all inbound (e.g.
4473 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4474 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4474 :hg:`bundle`) operations.
4475 :hg:`bundle`) operations.
4475
4476
4476 See :hg:`help urls` for more information.
4477 See :hg:`help urls` for more information.
4477
4478
4478 Returns 0 on success.
4479 Returns 0 on success.
4479 """
4480 """
4480 if search:
4481 if search:
4481 for name, path in ui.configitems("paths"):
4482 for name, path in ui.configitems("paths"):
4482 if name == search:
4483 if name == search:
4483 ui.status("%s\n" % util.hidepassword(path))
4484 ui.status("%s\n" % util.hidepassword(path))
4484 return
4485 return
4485 if not ui.quiet:
4486 if not ui.quiet:
4486 ui.warn(_("not found!\n"))
4487 ui.warn(_("not found!\n"))
4487 return 1
4488 return 1
4488 else:
4489 else:
4489 for name, path in ui.configitems("paths"):
4490 for name, path in ui.configitems("paths"):
4490 if ui.quiet:
4491 if ui.quiet:
4491 ui.write("%s\n" % name)
4492 ui.write("%s\n" % name)
4492 else:
4493 else:
4493 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4494 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4494
4495
4495 @command('phase',
4496 @command('phase',
4496 [('p', 'public', False, _('set changeset phase to public')),
4497 [('p', 'public', False, _('set changeset phase to public')),
4497 ('d', 'draft', False, _('set changeset phase to draft')),
4498 ('d', 'draft', False, _('set changeset phase to draft')),
4498 ('s', 'secret', False, _('set changeset phase to secret')),
4499 ('s', 'secret', False, _('set changeset phase to secret')),
4499 ('f', 'force', False, _('allow to move boundary backward')),
4500 ('f', 'force', False, _('allow to move boundary backward')),
4500 ('r', 'rev', [], _('target revision'), _('REV')),
4501 ('r', 'rev', [], _('target revision'), _('REV')),
4501 ],
4502 ],
4502 _('[-p|-d|-s] [-f] [-r] REV...'))
4503 _('[-p|-d|-s] [-f] [-r] REV...'))
4503 def phase(ui, repo, *revs, **opts):
4504 def phase(ui, repo, *revs, **opts):
4504 """set or show the current phase name
4505 """set or show the current phase name
4505
4506
4506 With no argument, show the phase name of specified revisions.
4507 With no argument, show the phase name of specified revisions.
4507
4508
4508 With one of -p/--public, -d/--draft or -s/--secret, change the
4509 With one of -p/--public, -d/--draft or -s/--secret, change the
4509 phase value of the specified revisions.
4510 phase value of the specified revisions.
4510
4511
4511 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4512 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4512 lower phase to an higher phase. Phases are ordered as follows::
4513 lower phase to an higher phase. Phases are ordered as follows::
4513
4514
4514 public < draft < secret
4515 public < draft < secret
4515
4516
4516 Returns 0 on success, 1 if no phases were changed or some could not
4517 Returns 0 on success, 1 if no phases were changed or some could not
4517 be changed.
4518 be changed.
4518 """
4519 """
4519 # search for a unique phase argument
4520 # search for a unique phase argument
4520 targetphase = None
4521 targetphase = None
4521 for idx, name in enumerate(phases.phasenames):
4522 for idx, name in enumerate(phases.phasenames):
4522 if opts[name]:
4523 if opts[name]:
4523 if targetphase is not None:
4524 if targetphase is not None:
4524 raise util.Abort(_('only one phase can be specified'))
4525 raise util.Abort(_('only one phase can be specified'))
4525 targetphase = idx
4526 targetphase = idx
4526
4527
4527 # look for specified revision
4528 # look for specified revision
4528 revs = list(revs)
4529 revs = list(revs)
4529 revs.extend(opts['rev'])
4530 revs.extend(opts['rev'])
4530 if not revs:
4531 if not revs:
4531 raise util.Abort(_('no revisions specified'))
4532 raise util.Abort(_('no revisions specified'))
4532
4533
4533 revs = scmutil.revrange(repo, revs)
4534 revs = scmutil.revrange(repo, revs)
4534
4535
4535 lock = None
4536 lock = None
4536 ret = 0
4537 ret = 0
4537 if targetphase is None:
4538 if targetphase is None:
4538 # display
4539 # display
4539 for r in revs:
4540 for r in revs:
4540 ctx = repo[r]
4541 ctx = repo[r]
4541 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4542 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4542 else:
4543 else:
4543 lock = repo.lock()
4544 lock = repo.lock()
4544 try:
4545 try:
4545 # set phase
4546 # set phase
4546 if not revs:
4547 if not revs:
4547 raise util.Abort(_('empty revision set'))
4548 raise util.Abort(_('empty revision set'))
4548 nodes = [repo[r].node() for r in revs]
4549 nodes = [repo[r].node() for r in revs]
4549 olddata = repo._phasecache.getphaserevs(repo)[:]
4550 olddata = repo._phasecache.getphaserevs(repo)[:]
4550 phases.advanceboundary(repo, targetphase, nodes)
4551 phases.advanceboundary(repo, targetphase, nodes)
4551 if opts['force']:
4552 if opts['force']:
4552 phases.retractboundary(repo, targetphase, nodes)
4553 phases.retractboundary(repo, targetphase, nodes)
4553 finally:
4554 finally:
4554 lock.release()
4555 lock.release()
4555 # moving revision from public to draft may hide them
4556 # moving revision from public to draft may hide them
4556 # We have to check result on an unfiltered repository
4557 # We have to check result on an unfiltered repository
4557 unfi = repo.unfiltered()
4558 unfi = repo.unfiltered()
4558 newdata = repo._phasecache.getphaserevs(unfi)
4559 newdata = repo._phasecache.getphaserevs(unfi)
4559 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4560 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4560 cl = unfi.changelog
4561 cl = unfi.changelog
4561 rejected = [n for n in nodes
4562 rejected = [n for n in nodes
4562 if newdata[cl.rev(n)] < targetphase]
4563 if newdata[cl.rev(n)] < targetphase]
4563 if rejected:
4564 if rejected:
4564 ui.warn(_('cannot move %i changesets to a higher '
4565 ui.warn(_('cannot move %i changesets to a higher '
4565 'phase, use --force\n') % len(rejected))
4566 'phase, use --force\n') % len(rejected))
4566 ret = 1
4567 ret = 1
4567 if changes:
4568 if changes:
4568 msg = _('phase changed for %i changesets\n') % changes
4569 msg = _('phase changed for %i changesets\n') % changes
4569 if ret:
4570 if ret:
4570 ui.status(msg)
4571 ui.status(msg)
4571 else:
4572 else:
4572 ui.note(msg)
4573 ui.note(msg)
4573 else:
4574 else:
4574 ui.warn(_('no phases changed\n'))
4575 ui.warn(_('no phases changed\n'))
4575 ret = 1
4576 ret = 1
4576 return ret
4577 return ret
4577
4578
4578 def postincoming(ui, repo, modheads, optupdate, checkout):
4579 def postincoming(ui, repo, modheads, optupdate, checkout):
4579 if modheads == 0:
4580 if modheads == 0:
4580 return
4581 return
4581 if optupdate:
4582 if optupdate:
4582 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4583 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4583 try:
4584 try:
4584 ret = hg.update(repo, checkout)
4585 ret = hg.update(repo, checkout)
4585 except util.Abort, inst:
4586 except util.Abort, inst:
4586 ui.warn(_("not updating: %s\n") % str(inst))
4587 ui.warn(_("not updating: %s\n") % str(inst))
4587 if inst.hint:
4588 if inst.hint:
4588 ui.warn(_("(%s)\n") % inst.hint)
4589 ui.warn(_("(%s)\n") % inst.hint)
4589 return 0
4590 return 0
4590 if not ret and not checkout:
4591 if not ret and not checkout:
4591 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4592 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4592 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4593 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4593 return ret
4594 return ret
4594 if modheads > 1:
4595 if modheads > 1:
4595 currentbranchheads = len(repo.branchheads())
4596 currentbranchheads = len(repo.branchheads())
4596 if currentbranchheads == modheads:
4597 if currentbranchheads == modheads:
4597 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4598 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4598 elif currentbranchheads > 1:
4599 elif currentbranchheads > 1:
4599 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4600 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4600 "merge)\n"))
4601 "merge)\n"))
4601 else:
4602 else:
4602 ui.status(_("(run 'hg heads' to see heads)\n"))
4603 ui.status(_("(run 'hg heads' to see heads)\n"))
4603 else:
4604 else:
4604 ui.status(_("(run 'hg update' to get a working copy)\n"))
4605 ui.status(_("(run 'hg update' to get a working copy)\n"))
4605
4606
4606 @command('^pull',
4607 @command('^pull',
4607 [('u', 'update', None,
4608 [('u', 'update', None,
4608 _('update to new branch head if changesets were pulled')),
4609 _('update to new branch head if changesets were pulled')),
4609 ('f', 'force', None, _('run even when remote repository is unrelated')),
4610 ('f', 'force', None, _('run even when remote repository is unrelated')),
4610 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4611 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4611 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4612 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4612 ('b', 'branch', [], _('a specific branch you would like to pull'),
4613 ('b', 'branch', [], _('a specific branch you would like to pull'),
4613 _('BRANCH')),
4614 _('BRANCH')),
4614 ] + remoteopts,
4615 ] + remoteopts,
4615 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4616 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4616 def pull(ui, repo, source="default", **opts):
4617 def pull(ui, repo, source="default", **opts):
4617 """pull changes from the specified source
4618 """pull changes from the specified source
4618
4619
4619 Pull changes from a remote repository to a local one.
4620 Pull changes from a remote repository to a local one.
4620
4621
4621 This finds all changes from the repository at the specified path
4622 This finds all changes from the repository at the specified path
4622 or URL and adds them to a local repository (the current one unless
4623 or URL and adds them to a local repository (the current one unless
4623 -R is specified). By default, this does not update the copy of the
4624 -R is specified). By default, this does not update the copy of the
4624 project in the working directory.
4625 project in the working directory.
4625
4626
4626 Use :hg:`incoming` if you want to see what would have been added
4627 Use :hg:`incoming` if you want to see what would have been added
4627 by a pull at the time you issued this command. If you then decide
4628 by a pull at the time you issued this command. If you then decide
4628 to add those changes to the repository, you should use :hg:`pull
4629 to add those changes to the repository, you should use :hg:`pull
4629 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4630 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4630
4631
4631 If SOURCE is omitted, the 'default' path will be used.
4632 If SOURCE is omitted, the 'default' path will be used.
4632 See :hg:`help urls` for more information.
4633 See :hg:`help urls` for more information.
4633
4634
4634 Returns 0 on success, 1 if an update had unresolved files.
4635 Returns 0 on success, 1 if an update had unresolved files.
4635 """
4636 """
4636 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4637 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4637 other = hg.peer(repo, opts, source)
4638 other = hg.peer(repo, opts, source)
4638 try:
4639 try:
4639 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4640 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4640 revs, checkout = hg.addbranchrevs(repo, other, branches,
4641 revs, checkout = hg.addbranchrevs(repo, other, branches,
4641 opts.get('rev'))
4642 opts.get('rev'))
4642
4643
4643 remotebookmarks = other.listkeys('bookmarks')
4644 remotebookmarks = other.listkeys('bookmarks')
4644
4645
4645 if opts.get('bookmark'):
4646 if opts.get('bookmark'):
4646 if not revs:
4647 if not revs:
4647 revs = []
4648 revs = []
4648 for b in opts['bookmark']:
4649 for b in opts['bookmark']:
4649 if b not in remotebookmarks:
4650 if b not in remotebookmarks:
4650 raise util.Abort(_('remote bookmark %s not found!') % b)
4651 raise util.Abort(_('remote bookmark %s not found!') % b)
4651 revs.append(remotebookmarks[b])
4652 revs.append(remotebookmarks[b])
4652
4653
4653 if revs:
4654 if revs:
4654 try:
4655 try:
4655 revs = [other.lookup(rev) for rev in revs]
4656 revs = [other.lookup(rev) for rev in revs]
4656 except error.CapabilityError:
4657 except error.CapabilityError:
4657 err = _("other repository doesn't support revision lookup, "
4658 err = _("other repository doesn't support revision lookup, "
4658 "so a rev cannot be specified.")
4659 "so a rev cannot be specified.")
4659 raise util.Abort(err)
4660 raise util.Abort(err)
4660
4661
4661 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4662 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4662 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4663 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4663 if checkout:
4664 if checkout:
4664 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4665 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4665 repo._subtoppath = source
4666 repo._subtoppath = source
4666 try:
4667 try:
4667 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4668 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4668
4669
4669 finally:
4670 finally:
4670 del repo._subtoppath
4671 del repo._subtoppath
4671
4672
4672 # update specified bookmarks
4673 # update specified bookmarks
4673 if opts.get('bookmark'):
4674 if opts.get('bookmark'):
4674 marks = repo._bookmarks
4675 marks = repo._bookmarks
4675 for b in opts['bookmark']:
4676 for b in opts['bookmark']:
4676 # explicit pull overrides local bookmark if any
4677 # explicit pull overrides local bookmark if any
4677 ui.status(_("importing bookmark %s\n") % b)
4678 ui.status(_("importing bookmark %s\n") % b)
4678 marks[b] = repo[remotebookmarks[b]].node()
4679 marks[b] = repo[remotebookmarks[b]].node()
4679 marks.write()
4680 marks.write()
4680 finally:
4681 finally:
4681 other.close()
4682 other.close()
4682 return ret
4683 return ret
4683
4684
4684 @command('^push',
4685 @command('^push',
4685 [('f', 'force', None, _('force push')),
4686 [('f', 'force', None, _('force push')),
4686 ('r', 'rev', [],
4687 ('r', 'rev', [],
4687 _('a changeset intended to be included in the destination'),
4688 _('a changeset intended to be included in the destination'),
4688 _('REV')),
4689 _('REV')),
4689 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4690 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4690 ('b', 'branch', [],
4691 ('b', 'branch', [],
4691 _('a specific branch you would like to push'), _('BRANCH')),
4692 _('a specific branch you would like to push'), _('BRANCH')),
4692 ('', 'new-branch', False, _('allow pushing a new branch')),
4693 ('', 'new-branch', False, _('allow pushing a new branch')),
4693 ] + remoteopts,
4694 ] + remoteopts,
4694 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4695 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4695 def push(ui, repo, dest=None, **opts):
4696 def push(ui, repo, dest=None, **opts):
4696 """push changes to the specified destination
4697 """push changes to the specified destination
4697
4698
4698 Push changesets from the local repository to the specified
4699 Push changesets from the local repository to the specified
4699 destination.
4700 destination.
4700
4701
4701 This operation is symmetrical to pull: it is identical to a pull
4702 This operation is symmetrical to pull: it is identical to a pull
4702 in the destination repository from the current one.
4703 in the destination repository from the current one.
4703
4704
4704 By default, push will not allow creation of new heads at the
4705 By default, push will not allow creation of new heads at the
4705 destination, since multiple heads would make it unclear which head
4706 destination, since multiple heads would make it unclear which head
4706 to use. In this situation, it is recommended to pull and merge
4707 to use. In this situation, it is recommended to pull and merge
4707 before pushing.
4708 before pushing.
4708
4709
4709 Use --new-branch if you want to allow push to create a new named
4710 Use --new-branch if you want to allow push to create a new named
4710 branch that is not present at the destination. This allows you to
4711 branch that is not present at the destination. This allows you to
4711 only create a new branch without forcing other changes.
4712 only create a new branch without forcing other changes.
4712
4713
4713 .. note::
4714 .. note::
4714
4715
4715 Extra care should be taken with the -f/--force option,
4716 Extra care should be taken with the -f/--force option,
4716 which will push all new heads on all branches, an action which will
4717 which will push all new heads on all branches, an action which will
4717 almost always cause confusion for collaborators.
4718 almost always cause confusion for collaborators.
4718
4719
4719 If -r/--rev is used, the specified revision and all its ancestors
4720 If -r/--rev is used, the specified revision and all its ancestors
4720 will be pushed to the remote repository.
4721 will be pushed to the remote repository.
4721
4722
4722 If -B/--bookmark is used, the specified bookmarked revision, its
4723 If -B/--bookmark is used, the specified bookmarked revision, its
4723 ancestors, and the bookmark will be pushed to the remote
4724 ancestors, and the bookmark will be pushed to the remote
4724 repository.
4725 repository.
4725
4726
4726 Please see :hg:`help urls` for important details about ``ssh://``
4727 Please see :hg:`help urls` for important details about ``ssh://``
4727 URLs. If DESTINATION is omitted, a default path will be used.
4728 URLs. If DESTINATION is omitted, a default path will be used.
4728
4729
4729 Returns 0 if push was successful, 1 if nothing to push.
4730 Returns 0 if push was successful, 1 if nothing to push.
4730 """
4731 """
4731
4732
4732 if opts.get('bookmark'):
4733 if opts.get('bookmark'):
4733 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4734 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4734 for b in opts['bookmark']:
4735 for b in opts['bookmark']:
4735 # translate -B options to -r so changesets get pushed
4736 # translate -B options to -r so changesets get pushed
4736 if b in repo._bookmarks:
4737 if b in repo._bookmarks:
4737 opts.setdefault('rev', []).append(b)
4738 opts.setdefault('rev', []).append(b)
4738 else:
4739 else:
4739 # if we try to push a deleted bookmark, translate it to null
4740 # if we try to push a deleted bookmark, translate it to null
4740 # this lets simultaneous -r, -b options continue working
4741 # this lets simultaneous -r, -b options continue working
4741 opts.setdefault('rev', []).append("null")
4742 opts.setdefault('rev', []).append("null")
4742
4743
4743 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4744 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4744 dest, branches = hg.parseurl(dest, opts.get('branch'))
4745 dest, branches = hg.parseurl(dest, opts.get('branch'))
4745 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4746 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4746 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4747 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4747 try:
4748 try:
4748 other = hg.peer(repo, opts, dest)
4749 other = hg.peer(repo, opts, dest)
4749 except error.RepoError:
4750 except error.RepoError:
4750 if dest == "default-push":
4751 if dest == "default-push":
4751 raise util.Abort(_("default repository not configured!"),
4752 raise util.Abort(_("default repository not configured!"),
4752 hint=_('see the "path" section in "hg help config"'))
4753 hint=_('see the "path" section in "hg help config"'))
4753 else:
4754 else:
4754 raise
4755 raise
4755
4756
4756 if revs:
4757 if revs:
4757 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4758 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4758
4759
4759 repo._subtoppath = dest
4760 repo._subtoppath = dest
4760 try:
4761 try:
4761 # push subrepos depth-first for coherent ordering
4762 # push subrepos depth-first for coherent ordering
4762 c = repo['']
4763 c = repo['']
4763 subs = c.substate # only repos that are committed
4764 subs = c.substate # only repos that are committed
4764 for s in sorted(subs):
4765 for s in sorted(subs):
4765 if c.sub(s).push(opts) == 0:
4766 if c.sub(s).push(opts) == 0:
4766 return False
4767 return False
4767 finally:
4768 finally:
4768 del repo._subtoppath
4769 del repo._subtoppath
4769 result = repo.push(other, opts.get('force'), revs=revs,
4770 result = repo.push(other, opts.get('force'), revs=revs,
4770 newbranch=opts.get('new_branch'))
4771 newbranch=opts.get('new_branch'))
4771
4772
4772 result = not result
4773 result = not result
4773
4774
4774 if opts.get('bookmark'):
4775 if opts.get('bookmark'):
4775 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4776 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4776 if bresult == 2:
4777 if bresult == 2:
4777 return 2
4778 return 2
4778 if not result and bresult:
4779 if not result and bresult:
4779 result = 2
4780 result = 2
4780
4781
4781 return result
4782 return result
4782
4783
4783 @command('recover', [])
4784 @command('recover', [])
4784 def recover(ui, repo):
4785 def recover(ui, repo):
4785 """roll back an interrupted transaction
4786 """roll back an interrupted transaction
4786
4787
4787 Recover from an interrupted commit or pull.
4788 Recover from an interrupted commit or pull.
4788
4789
4789 This command tries to fix the repository status after an
4790 This command tries to fix the repository status after an
4790 interrupted operation. It should only be necessary when Mercurial
4791 interrupted operation. It should only be necessary when Mercurial
4791 suggests it.
4792 suggests it.
4792
4793
4793 Returns 0 if successful, 1 if nothing to recover or verify fails.
4794 Returns 0 if successful, 1 if nothing to recover or verify fails.
4794 """
4795 """
4795 if repo.recover():
4796 if repo.recover():
4796 return hg.verify(repo)
4797 return hg.verify(repo)
4797 return 1
4798 return 1
4798
4799
4799 @command('^remove|rm',
4800 @command('^remove|rm',
4800 [('A', 'after', None, _('record delete for missing files')),
4801 [('A', 'after', None, _('record delete for missing files')),
4801 ('f', 'force', None,
4802 ('f', 'force', None,
4802 _('remove (and delete) file even if added or modified')),
4803 _('remove (and delete) file even if added or modified')),
4803 ] + walkopts,
4804 ] + walkopts,
4804 _('[OPTION]... FILE...'))
4805 _('[OPTION]... FILE...'))
4805 def remove(ui, repo, *pats, **opts):
4806 def remove(ui, repo, *pats, **opts):
4806 """remove the specified files on the next commit
4807 """remove the specified files on the next commit
4807
4808
4808 Schedule the indicated files for removal from the current branch.
4809 Schedule the indicated files for removal from the current branch.
4809
4810
4810 This command schedules the files to be removed at the next commit.
4811 This command schedules the files to be removed at the next commit.
4811 To undo a remove before that, see :hg:`revert`. To undo added
4812 To undo a remove before that, see :hg:`revert`. To undo added
4812 files, see :hg:`forget`.
4813 files, see :hg:`forget`.
4813
4814
4814 .. container:: verbose
4815 .. container:: verbose
4815
4816
4816 -A/--after can be used to remove only files that have already
4817 -A/--after can be used to remove only files that have already
4817 been deleted, -f/--force can be used to force deletion, and -Af
4818 been deleted, -f/--force can be used to force deletion, and -Af
4818 can be used to remove files from the next revision without
4819 can be used to remove files from the next revision without
4819 deleting them from the working directory.
4820 deleting them from the working directory.
4820
4821
4821 The following table details the behavior of remove for different
4822 The following table details the behavior of remove for different
4822 file states (columns) and option combinations (rows). The file
4823 file states (columns) and option combinations (rows). The file
4823 states are Added [A], Clean [C], Modified [M] and Missing [!]
4824 states are Added [A], Clean [C], Modified [M] and Missing [!]
4824 (as reported by :hg:`status`). The actions are Warn, Remove
4825 (as reported by :hg:`status`). The actions are Warn, Remove
4825 (from branch) and Delete (from disk):
4826 (from branch) and Delete (from disk):
4826
4827
4827 ========= == == == ==
4828 ========= == == == ==
4828 opt/state A C M !
4829 opt/state A C M !
4829 ========= == == == ==
4830 ========= == == == ==
4830 none W RD W R
4831 none W RD W R
4831 -f R RD RD R
4832 -f R RD RD R
4832 -A W W W R
4833 -A W W W R
4833 -Af R R R R
4834 -Af R R R R
4834 ========= == == == ==
4835 ========= == == == ==
4835
4836
4836 Note that remove never deletes files in Added [A] state from the
4837 Note that remove never deletes files in Added [A] state from the
4837 working directory, not even if option --force is specified.
4838 working directory, not even if option --force is specified.
4838
4839
4839 Returns 0 on success, 1 if any warnings encountered.
4840 Returns 0 on success, 1 if any warnings encountered.
4840 """
4841 """
4841
4842
4842 ret = 0
4843 ret = 0
4843 after, force = opts.get('after'), opts.get('force')
4844 after, force = opts.get('after'), opts.get('force')
4844 if not pats and not after:
4845 if not pats and not after:
4845 raise util.Abort(_('no files specified'))
4846 raise util.Abort(_('no files specified'))
4846
4847
4847 m = scmutil.match(repo[None], pats, opts)
4848 m = scmutil.match(repo[None], pats, opts)
4848 s = repo.status(match=m, clean=True)
4849 s = repo.status(match=m, clean=True)
4849 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4850 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4850
4851
4851 # warn about failure to delete explicit files/dirs
4852 # warn about failure to delete explicit files/dirs
4852 wctx = repo[None]
4853 wctx = repo[None]
4853 for f in m.files():
4854 for f in m.files():
4854 if f in repo.dirstate or f in wctx.dirs():
4855 if f in repo.dirstate or f in wctx.dirs():
4855 continue
4856 continue
4856 if os.path.exists(m.rel(f)):
4857 if os.path.exists(m.rel(f)):
4857 if os.path.isdir(m.rel(f)):
4858 if os.path.isdir(m.rel(f)):
4858 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4859 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4859 else:
4860 else:
4860 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4861 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4861 # missing files will generate a warning elsewhere
4862 # missing files will generate a warning elsewhere
4862 ret = 1
4863 ret = 1
4863
4864
4864 if force:
4865 if force:
4865 list = modified + deleted + clean + added
4866 list = modified + deleted + clean + added
4866 elif after:
4867 elif after:
4867 list = deleted
4868 list = deleted
4868 for f in modified + added + clean:
4869 for f in modified + added + clean:
4869 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4870 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4870 ret = 1
4871 ret = 1
4871 else:
4872 else:
4872 list = deleted + clean
4873 list = deleted + clean
4873 for f in modified:
4874 for f in modified:
4874 ui.warn(_('not removing %s: file is modified (use -f'
4875 ui.warn(_('not removing %s: file is modified (use -f'
4875 ' to force removal)\n') % m.rel(f))
4876 ' to force removal)\n') % m.rel(f))
4876 ret = 1
4877 ret = 1
4877 for f in added:
4878 for f in added:
4878 ui.warn(_('not removing %s: file has been marked for add'
4879 ui.warn(_('not removing %s: file has been marked for add'
4879 ' (use forget to undo)\n') % m.rel(f))
4880 ' (use forget to undo)\n') % m.rel(f))
4880 ret = 1
4881 ret = 1
4881
4882
4882 for f in sorted(list):
4883 for f in sorted(list):
4883 if ui.verbose or not m.exact(f):
4884 if ui.verbose or not m.exact(f):
4884 ui.status(_('removing %s\n') % m.rel(f))
4885 ui.status(_('removing %s\n') % m.rel(f))
4885
4886
4886 wlock = repo.wlock()
4887 wlock = repo.wlock()
4887 try:
4888 try:
4888 if not after:
4889 if not after:
4889 for f in list:
4890 for f in list:
4890 if f in added:
4891 if f in added:
4891 continue # we never unlink added files on remove
4892 continue # we never unlink added files on remove
4892 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4893 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4893 repo[None].forget(list)
4894 repo[None].forget(list)
4894 finally:
4895 finally:
4895 wlock.release()
4896 wlock.release()
4896
4897
4897 return ret
4898 return ret
4898
4899
4899 @command('rename|move|mv',
4900 @command('rename|move|mv',
4900 [('A', 'after', None, _('record a rename that has already occurred')),
4901 [('A', 'after', None, _('record a rename that has already occurred')),
4901 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4902 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4902 ] + walkopts + dryrunopts,
4903 ] + walkopts + dryrunopts,
4903 _('[OPTION]... SOURCE... DEST'))
4904 _('[OPTION]... SOURCE... DEST'))
4904 def rename(ui, repo, *pats, **opts):
4905 def rename(ui, repo, *pats, **opts):
4905 """rename files; equivalent of copy + remove
4906 """rename files; equivalent of copy + remove
4906
4907
4907 Mark dest as copies of sources; mark sources for deletion. If dest
4908 Mark dest as copies of sources; mark sources for deletion. If dest
4908 is a directory, copies are put in that directory. If dest is a
4909 is a directory, copies are put in that directory. If dest is a
4909 file, there can only be one source.
4910 file, there can only be one source.
4910
4911
4911 By default, this command copies the contents of files as they
4912 By default, this command copies the contents of files as they
4912 exist in the working directory. If invoked with -A/--after, the
4913 exist in the working directory. If invoked with -A/--after, the
4913 operation is recorded, but no copying is performed.
4914 operation is recorded, but no copying is performed.
4914
4915
4915 This command takes effect at the next commit. To undo a rename
4916 This command takes effect at the next commit. To undo a rename
4916 before that, see :hg:`revert`.
4917 before that, see :hg:`revert`.
4917
4918
4918 Returns 0 on success, 1 if errors are encountered.
4919 Returns 0 on success, 1 if errors are encountered.
4919 """
4920 """
4920 wlock = repo.wlock(False)
4921 wlock = repo.wlock(False)
4921 try:
4922 try:
4922 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4923 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4923 finally:
4924 finally:
4924 wlock.release()
4925 wlock.release()
4925
4926
4926 @command('resolve',
4927 @command('resolve',
4927 [('a', 'all', None, _('select all unresolved files')),
4928 [('a', 'all', None, _('select all unresolved files')),
4928 ('l', 'list', None, _('list state of files needing merge')),
4929 ('l', 'list', None, _('list state of files needing merge')),
4929 ('m', 'mark', None, _('mark files as resolved')),
4930 ('m', 'mark', None, _('mark files as resolved')),
4930 ('u', 'unmark', None, _('mark files as unresolved')),
4931 ('u', 'unmark', None, _('mark files as unresolved')),
4931 ('n', 'no-status', None, _('hide status prefix'))]
4932 ('n', 'no-status', None, _('hide status prefix'))]
4932 + mergetoolopts + walkopts,
4933 + mergetoolopts + walkopts,
4933 _('[OPTION]... [FILE]...'))
4934 _('[OPTION]... [FILE]...'))
4934 def resolve(ui, repo, *pats, **opts):
4935 def resolve(ui, repo, *pats, **opts):
4935 """redo merges or set/view the merge status of files
4936 """redo merges or set/view the merge status of files
4936
4937
4937 Merges with unresolved conflicts are often the result of
4938 Merges with unresolved conflicts are often the result of
4938 non-interactive merging using the ``internal:merge`` configuration
4939 non-interactive merging using the ``internal:merge`` configuration
4939 setting, or a command-line merge tool like ``diff3``. The resolve
4940 setting, or a command-line merge tool like ``diff3``. The resolve
4940 command is used to manage the files involved in a merge, after
4941 command is used to manage the files involved in a merge, after
4941 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4942 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4942 working directory must have two parents). See :hg:`help
4943 working directory must have two parents). See :hg:`help
4943 merge-tools` for information on configuring merge tools.
4944 merge-tools` for information on configuring merge tools.
4944
4945
4945 The resolve command can be used in the following ways:
4946 The resolve command can be used in the following ways:
4946
4947
4947 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4948 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4948 files, discarding any previous merge attempts. Re-merging is not
4949 files, discarding any previous merge attempts. Re-merging is not
4949 performed for files already marked as resolved. Use ``--all/-a``
4950 performed for files already marked as resolved. Use ``--all/-a``
4950 to select all unresolved files. ``--tool`` can be used to specify
4951 to select all unresolved files. ``--tool`` can be used to specify
4951 the merge tool used for the given files. It overrides the HGMERGE
4952 the merge tool used for the given files. It overrides the HGMERGE
4952 environment variable and your configuration files. Previous file
4953 environment variable and your configuration files. Previous file
4953 contents are saved with a ``.orig`` suffix.
4954 contents are saved with a ``.orig`` suffix.
4954
4955
4955 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4956 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4956 (e.g. after having manually fixed-up the files). The default is
4957 (e.g. after having manually fixed-up the files). The default is
4957 to mark all unresolved files.
4958 to mark all unresolved files.
4958
4959
4959 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4960 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4960 default is to mark all resolved files.
4961 default is to mark all resolved files.
4961
4962
4962 - :hg:`resolve -l`: list files which had or still have conflicts.
4963 - :hg:`resolve -l`: list files which had or still have conflicts.
4963 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4964 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4964
4965
4965 Note that Mercurial will not let you commit files with unresolved
4966 Note that Mercurial will not let you commit files with unresolved
4966 merge conflicts. You must use :hg:`resolve -m ...` before you can
4967 merge conflicts. You must use :hg:`resolve -m ...` before you can
4967 commit after a conflicting merge.
4968 commit after a conflicting merge.
4968
4969
4969 Returns 0 on success, 1 if any files fail a resolve attempt.
4970 Returns 0 on success, 1 if any files fail a resolve attempt.
4970 """
4971 """
4971
4972
4972 all, mark, unmark, show, nostatus = \
4973 all, mark, unmark, show, nostatus = \
4973 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4974 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4974
4975
4975 if (show and (mark or unmark)) or (mark and unmark):
4976 if (show and (mark or unmark)) or (mark and unmark):
4976 raise util.Abort(_("too many options specified"))
4977 raise util.Abort(_("too many options specified"))
4977 if pats and all:
4978 if pats and all:
4978 raise util.Abort(_("can't specify --all and patterns"))
4979 raise util.Abort(_("can't specify --all and patterns"))
4979 if not (all or pats or show or mark or unmark):
4980 if not (all or pats or show or mark or unmark):
4980 raise util.Abort(_('no files or directories specified; '
4981 raise util.Abort(_('no files or directories specified; '
4981 'use --all to remerge all files'))
4982 'use --all to remerge all files'))
4982
4983
4983 ms = mergemod.mergestate(repo)
4984 ms = mergemod.mergestate(repo)
4984 m = scmutil.match(repo[None], pats, opts)
4985 m = scmutil.match(repo[None], pats, opts)
4985 ret = 0
4986 ret = 0
4986
4987
4987 for f in ms:
4988 for f in ms:
4988 if m(f):
4989 if m(f):
4989 if show:
4990 if show:
4990 if nostatus:
4991 if nostatus:
4991 ui.write("%s\n" % f)
4992 ui.write("%s\n" % f)
4992 else:
4993 else:
4993 ui.write("%s %s\n" % (ms[f].upper(), f),
4994 ui.write("%s %s\n" % (ms[f].upper(), f),
4994 label='resolve.' +
4995 label='resolve.' +
4995 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4996 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4996 elif mark:
4997 elif mark:
4997 ms.mark(f, "r")
4998 ms.mark(f, "r")
4998 elif unmark:
4999 elif unmark:
4999 ms.mark(f, "u")
5000 ms.mark(f, "u")
5000 else:
5001 else:
5001 wctx = repo[None]
5002 wctx = repo[None]
5002
5003
5003 # backup pre-resolve (merge uses .orig for its own purposes)
5004 # backup pre-resolve (merge uses .orig for its own purposes)
5004 a = repo.wjoin(f)
5005 a = repo.wjoin(f)
5005 util.copyfile(a, a + ".resolve")
5006 util.copyfile(a, a + ".resolve")
5006
5007
5007 try:
5008 try:
5008 # resolve file
5009 # resolve file
5009 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5010 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
5010 'resolve')
5011 'resolve')
5011 if ms.resolve(f, wctx):
5012 if ms.resolve(f, wctx):
5012 ret = 1
5013 ret = 1
5013 finally:
5014 finally:
5014 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5015 ui.setconfig('ui', 'forcemerge', '', 'resolve')
5015 ms.commit()
5016 ms.commit()
5016
5017
5017 # replace filemerge's .orig file with our resolve file
5018 # replace filemerge's .orig file with our resolve file
5018 util.rename(a + ".resolve", a + ".orig")
5019 util.rename(a + ".resolve", a + ".orig")
5019
5020
5020 ms.commit()
5021 ms.commit()
5021 return ret
5022 return ret
5022
5023
5023 @command('revert',
5024 @command('revert',
5024 [('a', 'all', None, _('revert all changes when no arguments given')),
5025 [('a', 'all', None, _('revert all changes when no arguments given')),
5025 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5026 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5026 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5027 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5027 ('C', 'no-backup', None, _('do not save backup copies of files')),
5028 ('C', 'no-backup', None, _('do not save backup copies of files')),
5028 ] + walkopts + dryrunopts,
5029 ] + walkopts + dryrunopts,
5029 _('[OPTION]... [-r REV] [NAME]...'))
5030 _('[OPTION]... [-r REV] [NAME]...'))
5030 def revert(ui, repo, *pats, **opts):
5031 def revert(ui, repo, *pats, **opts):
5031 """restore files to their checkout state
5032 """restore files to their checkout state
5032
5033
5033 .. note::
5034 .. note::
5034
5035
5035 To check out earlier revisions, you should use :hg:`update REV`.
5036 To check out earlier revisions, you should use :hg:`update REV`.
5036 To cancel an uncommitted merge (and lose your changes),
5037 To cancel an uncommitted merge (and lose your changes),
5037 use :hg:`update --clean .`.
5038 use :hg:`update --clean .`.
5038
5039
5039 With no revision specified, revert the specified files or directories
5040 With no revision specified, revert the specified files or directories
5040 to the contents they had in the parent of the working directory.
5041 to the contents they had in the parent of the working directory.
5041 This restores the contents of files to an unmodified
5042 This restores the contents of files to an unmodified
5042 state and unschedules adds, removes, copies, and renames. If the
5043 state and unschedules adds, removes, copies, and renames. If the
5043 working directory has two parents, you must explicitly specify a
5044 working directory has two parents, you must explicitly specify a
5044 revision.
5045 revision.
5045
5046
5046 Using the -r/--rev or -d/--date options, revert the given files or
5047 Using the -r/--rev or -d/--date options, revert the given files or
5047 directories to their states as of a specific revision. Because
5048 directories to their states as of a specific revision. Because
5048 revert does not change the working directory parents, this will
5049 revert does not change the working directory parents, this will
5049 cause these files to appear modified. This can be helpful to "back
5050 cause these files to appear modified. This can be helpful to "back
5050 out" some or all of an earlier change. See :hg:`backout` for a
5051 out" some or all of an earlier change. See :hg:`backout` for a
5051 related method.
5052 related method.
5052
5053
5053 Modified files are saved with a .orig suffix before reverting.
5054 Modified files are saved with a .orig suffix before reverting.
5054 To disable these backups, use --no-backup.
5055 To disable these backups, use --no-backup.
5055
5056
5056 See :hg:`help dates` for a list of formats valid for -d/--date.
5057 See :hg:`help dates` for a list of formats valid for -d/--date.
5057
5058
5058 Returns 0 on success.
5059 Returns 0 on success.
5059 """
5060 """
5060
5061
5061 if opts.get("date"):
5062 if opts.get("date"):
5062 if opts.get("rev"):
5063 if opts.get("rev"):
5063 raise util.Abort(_("you can't specify a revision and a date"))
5064 raise util.Abort(_("you can't specify a revision and a date"))
5064 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5065 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5065
5066
5066 parent, p2 = repo.dirstate.parents()
5067 parent, p2 = repo.dirstate.parents()
5067 if not opts.get('rev') and p2 != nullid:
5068 if not opts.get('rev') and p2 != nullid:
5068 # revert after merge is a trap for new users (issue2915)
5069 # revert after merge is a trap for new users (issue2915)
5069 raise util.Abort(_('uncommitted merge with no revision specified'),
5070 raise util.Abort(_('uncommitted merge with no revision specified'),
5070 hint=_('use "hg update" or see "hg help revert"'))
5071 hint=_('use "hg update" or see "hg help revert"'))
5071
5072
5072 ctx = scmutil.revsingle(repo, opts.get('rev'))
5073 ctx = scmutil.revsingle(repo, opts.get('rev'))
5073
5074
5074 if not pats and not opts.get('all'):
5075 if not pats and not opts.get('all'):
5075 msg = _("no files or directories specified")
5076 msg = _("no files or directories specified")
5076 if p2 != nullid:
5077 if p2 != nullid:
5077 hint = _("uncommitted merge, use --all to discard all changes,"
5078 hint = _("uncommitted merge, use --all to discard all changes,"
5078 " or 'hg update -C .' to abort the merge")
5079 " or 'hg update -C .' to abort the merge")
5079 raise util.Abort(msg, hint=hint)
5080 raise util.Abort(msg, hint=hint)
5080 dirty = util.any(repo.status())
5081 dirty = util.any(repo.status())
5081 node = ctx.node()
5082 node = ctx.node()
5082 if node != parent:
5083 if node != parent:
5083 if dirty:
5084 if dirty:
5084 hint = _("uncommitted changes, use --all to discard all"
5085 hint = _("uncommitted changes, use --all to discard all"
5085 " changes, or 'hg update %s' to update") % ctx.rev()
5086 " changes, or 'hg update %s' to update") % ctx.rev()
5086 else:
5087 else:
5087 hint = _("use --all to revert all files,"
5088 hint = _("use --all to revert all files,"
5088 " or 'hg update %s' to update") % ctx.rev()
5089 " or 'hg update %s' to update") % ctx.rev()
5089 elif dirty:
5090 elif dirty:
5090 hint = _("uncommitted changes, use --all to discard all changes")
5091 hint = _("uncommitted changes, use --all to discard all changes")
5091 else:
5092 else:
5092 hint = _("use --all to revert all files")
5093 hint = _("use --all to revert all files")
5093 raise util.Abort(msg, hint=hint)
5094 raise util.Abort(msg, hint=hint)
5094
5095
5095 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5096 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5096
5097
5097 @command('rollback', dryrunopts +
5098 @command('rollback', dryrunopts +
5098 [('f', 'force', False, _('ignore safety measures'))])
5099 [('f', 'force', False, _('ignore safety measures'))])
5099 def rollback(ui, repo, **opts):
5100 def rollback(ui, repo, **opts):
5100 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5101 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5101
5102
5102 Please use :hg:`commit --amend` instead of rollback to correct
5103 Please use :hg:`commit --amend` instead of rollback to correct
5103 mistakes in the last commit.
5104 mistakes in the last commit.
5104
5105
5105 This command should be used with care. There is only one level of
5106 This command should be used with care. There is only one level of
5106 rollback, and there is no way to undo a rollback. It will also
5107 rollback, and there is no way to undo a rollback. It will also
5107 restore the dirstate at the time of the last transaction, losing
5108 restore the dirstate at the time of the last transaction, losing
5108 any dirstate changes since that time. This command does not alter
5109 any dirstate changes since that time. This command does not alter
5109 the working directory.
5110 the working directory.
5110
5111
5111 Transactions are used to encapsulate the effects of all commands
5112 Transactions are used to encapsulate the effects of all commands
5112 that create new changesets or propagate existing changesets into a
5113 that create new changesets or propagate existing changesets into a
5113 repository.
5114 repository.
5114
5115
5115 .. container:: verbose
5116 .. container:: verbose
5116
5117
5117 For example, the following commands are transactional, and their
5118 For example, the following commands are transactional, and their
5118 effects can be rolled back:
5119 effects can be rolled back:
5119
5120
5120 - commit
5121 - commit
5121 - import
5122 - import
5122 - pull
5123 - pull
5123 - push (with this repository as the destination)
5124 - push (with this repository as the destination)
5124 - unbundle
5125 - unbundle
5125
5126
5126 To avoid permanent data loss, rollback will refuse to rollback a
5127 To avoid permanent data loss, rollback will refuse to rollback a
5127 commit transaction if it isn't checked out. Use --force to
5128 commit transaction if it isn't checked out. Use --force to
5128 override this protection.
5129 override this protection.
5129
5130
5130 This command is not intended for use on public repositories. Once
5131 This command is not intended for use on public repositories. Once
5131 changes are visible for pull by other users, rolling a transaction
5132 changes are visible for pull by other users, rolling a transaction
5132 back locally is ineffective (someone else may already have pulled
5133 back locally is ineffective (someone else may already have pulled
5133 the changes). Furthermore, a race is possible with readers of the
5134 the changes). Furthermore, a race is possible with readers of the
5134 repository; for example an in-progress pull from the repository
5135 repository; for example an in-progress pull from the repository
5135 may fail if a rollback is performed.
5136 may fail if a rollback is performed.
5136
5137
5137 Returns 0 on success, 1 if no rollback data is available.
5138 Returns 0 on success, 1 if no rollback data is available.
5138 """
5139 """
5139 return repo.rollback(dryrun=opts.get('dry_run'),
5140 return repo.rollback(dryrun=opts.get('dry_run'),
5140 force=opts.get('force'))
5141 force=opts.get('force'))
5141
5142
5142 @command('root', [])
5143 @command('root', [])
5143 def root(ui, repo):
5144 def root(ui, repo):
5144 """print the root (top) of the current working directory
5145 """print the root (top) of the current working directory
5145
5146
5146 Print the root directory of the current repository.
5147 Print the root directory of the current repository.
5147
5148
5148 Returns 0 on success.
5149 Returns 0 on success.
5149 """
5150 """
5150 ui.write(repo.root + "\n")
5151 ui.write(repo.root + "\n")
5151
5152
5152 @command('^serve',
5153 @command('^serve',
5153 [('A', 'accesslog', '', _('name of access log file to write to'),
5154 [('A', 'accesslog', '', _('name of access log file to write to'),
5154 _('FILE')),
5155 _('FILE')),
5155 ('d', 'daemon', None, _('run server in background')),
5156 ('d', 'daemon', None, _('run server in background')),
5156 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5157 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5157 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5158 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5158 # use string type, then we can check if something was passed
5159 # use string type, then we can check if something was passed
5159 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5160 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5160 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5161 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5161 _('ADDR')),
5162 _('ADDR')),
5162 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5163 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5163 _('PREFIX')),
5164 _('PREFIX')),
5164 ('n', 'name', '',
5165 ('n', 'name', '',
5165 _('name to show in web pages (default: working directory)'), _('NAME')),
5166 _('name to show in web pages (default: working directory)'), _('NAME')),
5166 ('', 'web-conf', '',
5167 ('', 'web-conf', '',
5167 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5168 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5168 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5169 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5169 _('FILE')),
5170 _('FILE')),
5170 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5171 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5171 ('', 'stdio', None, _('for remote clients')),
5172 ('', 'stdio', None, _('for remote clients')),
5172 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5173 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5173 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5174 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5174 ('', 'style', '', _('template style to use'), _('STYLE')),
5175 ('', 'style', '', _('template style to use'), _('STYLE')),
5175 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5176 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5176 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5177 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5177 _('[OPTION]...'))
5178 _('[OPTION]...'))
5178 def serve(ui, repo, **opts):
5179 def serve(ui, repo, **opts):
5179 """start stand-alone webserver
5180 """start stand-alone webserver
5180
5181
5181 Start a local HTTP repository browser and pull server. You can use
5182 Start a local HTTP repository browser and pull server. You can use
5182 this for ad-hoc sharing and browsing of repositories. It is
5183 this for ad-hoc sharing and browsing of repositories. It is
5183 recommended to use a real web server to serve a repository for
5184 recommended to use a real web server to serve a repository for
5184 longer periods of time.
5185 longer periods of time.
5185
5186
5186 Please note that the server does not implement access control.
5187 Please note that the server does not implement access control.
5187 This means that, by default, anybody can read from the server and
5188 This means that, by default, anybody can read from the server and
5188 nobody can write to it by default. Set the ``web.allow_push``
5189 nobody can write to it by default. Set the ``web.allow_push``
5189 option to ``*`` to allow everybody to push to the server. You
5190 option to ``*`` to allow everybody to push to the server. You
5190 should use a real web server if you need to authenticate users.
5191 should use a real web server if you need to authenticate users.
5191
5192
5192 By default, the server logs accesses to stdout and errors to
5193 By default, the server logs accesses to stdout and errors to
5193 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5194 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5194 files.
5195 files.
5195
5196
5196 To have the server choose a free port number to listen on, specify
5197 To have the server choose a free port number to listen on, specify
5197 a port number of 0; in this case, the server will print the port
5198 a port number of 0; in this case, the server will print the port
5198 number it uses.
5199 number it uses.
5199
5200
5200 Returns 0 on success.
5201 Returns 0 on success.
5201 """
5202 """
5202
5203
5203 if opts["stdio"] and opts["cmdserver"]:
5204 if opts["stdio"] and opts["cmdserver"]:
5204 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5205 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5205
5206
5206 def checkrepo():
5207 def checkrepo():
5207 if repo is None:
5208 if repo is None:
5208 raise error.RepoError(_("there is no Mercurial repository here"
5209 raise error.RepoError(_("there is no Mercurial repository here"
5209 " (.hg not found)"))
5210 " (.hg not found)"))
5210
5211
5211 if opts["stdio"]:
5212 if opts["stdio"]:
5212 checkrepo()
5213 checkrepo()
5213 s = sshserver.sshserver(ui, repo)
5214 s = sshserver.sshserver(ui, repo)
5214 s.serve_forever()
5215 s.serve_forever()
5215
5216
5216 if opts["cmdserver"]:
5217 if opts["cmdserver"]:
5217 s = commandserver.server(ui, repo, opts["cmdserver"])
5218 s = commandserver.server(ui, repo, opts["cmdserver"])
5218 return s.serve()
5219 return s.serve()
5219
5220
5220 # this way we can check if something was given in the command-line
5221 # this way we can check if something was given in the command-line
5221 if opts.get('port'):
5222 if opts.get('port'):
5222 opts['port'] = util.getport(opts.get('port'))
5223 opts['port'] = util.getport(opts.get('port'))
5223
5224
5224 baseui = repo and repo.baseui or ui
5225 baseui = repo and repo.baseui or ui
5225 optlist = ("name templates style address port prefix ipv6"
5226 optlist = ("name templates style address port prefix ipv6"
5226 " accesslog errorlog certificate encoding")
5227 " accesslog errorlog certificate encoding")
5227 for o in optlist.split():
5228 for o in optlist.split():
5228 val = opts.get(o, '')
5229 val = opts.get(o, '')
5229 if val in (None, ''): # should check against default options instead
5230 if val in (None, ''): # should check against default options instead
5230 continue
5231 continue
5231 baseui.setconfig("web", o, val, 'serve')
5232 baseui.setconfig("web", o, val, 'serve')
5232 if repo and repo.ui != baseui:
5233 if repo and repo.ui != baseui:
5233 repo.ui.setconfig("web", o, val, 'serve')
5234 repo.ui.setconfig("web", o, val, 'serve')
5234
5235
5235 o = opts.get('web_conf') or opts.get('webdir_conf')
5236 o = opts.get('web_conf') or opts.get('webdir_conf')
5236 if not o:
5237 if not o:
5237 if not repo:
5238 if not repo:
5238 raise error.RepoError(_("there is no Mercurial repository"
5239 raise error.RepoError(_("there is no Mercurial repository"
5239 " here (.hg not found)"))
5240 " here (.hg not found)"))
5240 o = repo
5241 o = repo
5241
5242
5242 app = hgweb.hgweb(o, baseui=baseui)
5243 app = hgweb.hgweb(o, baseui=baseui)
5243 service = httpservice(ui, app, opts)
5244 service = httpservice(ui, app, opts)
5244 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5245 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5245
5246
5246 class httpservice(object):
5247 class httpservice(object):
5247 def __init__(self, ui, app, opts):
5248 def __init__(self, ui, app, opts):
5248 self.ui = ui
5249 self.ui = ui
5249 self.app = app
5250 self.app = app
5250 self.opts = opts
5251 self.opts = opts
5251
5252
5252 def init(self):
5253 def init(self):
5253 util.setsignalhandler()
5254 util.setsignalhandler()
5254 self.httpd = hgweb_server.create_server(self.ui, self.app)
5255 self.httpd = hgweb_server.create_server(self.ui, self.app)
5255
5256
5256 if self.opts['port'] and not self.ui.verbose:
5257 if self.opts['port'] and not self.ui.verbose:
5257 return
5258 return
5258
5259
5259 if self.httpd.prefix:
5260 if self.httpd.prefix:
5260 prefix = self.httpd.prefix.strip('/') + '/'
5261 prefix = self.httpd.prefix.strip('/') + '/'
5261 else:
5262 else:
5262 prefix = ''
5263 prefix = ''
5263
5264
5264 port = ':%d' % self.httpd.port
5265 port = ':%d' % self.httpd.port
5265 if port == ':80':
5266 if port == ':80':
5266 port = ''
5267 port = ''
5267
5268
5268 bindaddr = self.httpd.addr
5269 bindaddr = self.httpd.addr
5269 if bindaddr == '0.0.0.0':
5270 if bindaddr == '0.0.0.0':
5270 bindaddr = '*'
5271 bindaddr = '*'
5271 elif ':' in bindaddr: # IPv6
5272 elif ':' in bindaddr: # IPv6
5272 bindaddr = '[%s]' % bindaddr
5273 bindaddr = '[%s]' % bindaddr
5273
5274
5274 fqaddr = self.httpd.fqaddr
5275 fqaddr = self.httpd.fqaddr
5275 if ':' in fqaddr:
5276 if ':' in fqaddr:
5276 fqaddr = '[%s]' % fqaddr
5277 fqaddr = '[%s]' % fqaddr
5277 if self.opts['port']:
5278 if self.opts['port']:
5278 write = self.ui.status
5279 write = self.ui.status
5279 else:
5280 else:
5280 write = self.ui.write
5281 write = self.ui.write
5281 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5282 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5282 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5283 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5283
5284
5284 def run(self):
5285 def run(self):
5285 self.httpd.serve_forever()
5286 self.httpd.serve_forever()
5286
5287
5287
5288
5288 @command('^status|st',
5289 @command('^status|st',
5289 [('A', 'all', None, _('show status of all files')),
5290 [('A', 'all', None, _('show status of all files')),
5290 ('m', 'modified', None, _('show only modified files')),
5291 ('m', 'modified', None, _('show only modified files')),
5291 ('a', 'added', None, _('show only added files')),
5292 ('a', 'added', None, _('show only added files')),
5292 ('r', 'removed', None, _('show only removed files')),
5293 ('r', 'removed', None, _('show only removed files')),
5293 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5294 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5294 ('c', 'clean', None, _('show only files without changes')),
5295 ('c', 'clean', None, _('show only files without changes')),
5295 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5296 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5296 ('i', 'ignored', None, _('show only ignored files')),
5297 ('i', 'ignored', None, _('show only ignored files')),
5297 ('n', 'no-status', None, _('hide status prefix')),
5298 ('n', 'no-status', None, _('hide status prefix')),
5298 ('C', 'copies', None, _('show source of copied files')),
5299 ('C', 'copies', None, _('show source of copied files')),
5299 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5300 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5300 ('', 'rev', [], _('show difference from revision'), _('REV')),
5301 ('', 'rev', [], _('show difference from revision'), _('REV')),
5301 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5302 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5302 ] + walkopts + subrepoopts,
5303 ] + walkopts + subrepoopts,
5303 _('[OPTION]... [FILE]...'))
5304 _('[OPTION]... [FILE]...'))
5304 def status(ui, repo, *pats, **opts):
5305 def status(ui, repo, *pats, **opts):
5305 """show changed files in the working directory
5306 """show changed files in the working directory
5306
5307
5307 Show status of files in the repository. If names are given, only
5308 Show status of files in the repository. If names are given, only
5308 files that match are shown. Files that are clean or ignored or
5309 files that match are shown. Files that are clean or ignored or
5309 the source of a copy/move operation, are not listed unless
5310 the source of a copy/move operation, are not listed unless
5310 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5311 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5311 Unless options described with "show only ..." are given, the
5312 Unless options described with "show only ..." are given, the
5312 options -mardu are used.
5313 options -mardu are used.
5313
5314
5314 Option -q/--quiet hides untracked (unknown and ignored) files
5315 Option -q/--quiet hides untracked (unknown and ignored) files
5315 unless explicitly requested with -u/--unknown or -i/--ignored.
5316 unless explicitly requested with -u/--unknown or -i/--ignored.
5316
5317
5317 .. note::
5318 .. note::
5318
5319
5319 status may appear to disagree with diff if permissions have
5320 status may appear to disagree with diff if permissions have
5320 changed or a merge has occurred. The standard diff format does
5321 changed or a merge has occurred. The standard diff format does
5321 not report permission changes and diff only reports changes
5322 not report permission changes and diff only reports changes
5322 relative to one merge parent.
5323 relative to one merge parent.
5323
5324
5324 If one revision is given, it is used as the base revision.
5325 If one revision is given, it is used as the base revision.
5325 If two revisions are given, the differences between them are
5326 If two revisions are given, the differences between them are
5326 shown. The --change option can also be used as a shortcut to list
5327 shown. The --change option can also be used as a shortcut to list
5327 the changed files of a revision from its first parent.
5328 the changed files of a revision from its first parent.
5328
5329
5329 The codes used to show the status of files are::
5330 The codes used to show the status of files are::
5330
5331
5331 M = modified
5332 M = modified
5332 A = added
5333 A = added
5333 R = removed
5334 R = removed
5334 C = clean
5335 C = clean
5335 ! = missing (deleted by non-hg command, but still tracked)
5336 ! = missing (deleted by non-hg command, but still tracked)
5336 ? = not tracked
5337 ? = not tracked
5337 I = ignored
5338 I = ignored
5338 = origin of the previous file (with --copies)
5339 = origin of the previous file (with --copies)
5339
5340
5340 .. container:: verbose
5341 .. container:: verbose
5341
5342
5342 Examples:
5343 Examples:
5343
5344
5344 - show changes in the working directory relative to a
5345 - show changes in the working directory relative to a
5345 changeset::
5346 changeset::
5346
5347
5347 hg status --rev 9353
5348 hg status --rev 9353
5348
5349
5349 - show all changes including copies in an existing changeset::
5350 - show all changes including copies in an existing changeset::
5350
5351
5351 hg status --copies --change 9353
5352 hg status --copies --change 9353
5352
5353
5353 - get a NUL separated list of added files, suitable for xargs::
5354 - get a NUL separated list of added files, suitable for xargs::
5354
5355
5355 hg status -an0
5356 hg status -an0
5356
5357
5357 Returns 0 on success.
5358 Returns 0 on success.
5358 """
5359 """
5359
5360
5360 revs = opts.get('rev')
5361 revs = opts.get('rev')
5361 change = opts.get('change')
5362 change = opts.get('change')
5362
5363
5363 if revs and change:
5364 if revs and change:
5364 msg = _('cannot specify --rev and --change at the same time')
5365 msg = _('cannot specify --rev and --change at the same time')
5365 raise util.Abort(msg)
5366 raise util.Abort(msg)
5366 elif change:
5367 elif change:
5367 node2 = scmutil.revsingle(repo, change, None).node()
5368 node2 = scmutil.revsingle(repo, change, None).node()
5368 node1 = repo[node2].p1().node()
5369 node1 = repo[node2].p1().node()
5369 else:
5370 else:
5370 node1, node2 = scmutil.revpair(repo, revs)
5371 node1, node2 = scmutil.revpair(repo, revs)
5371
5372
5372 cwd = (pats and repo.getcwd()) or ''
5373 cwd = (pats and repo.getcwd()) or ''
5373 end = opts.get('print0') and '\0' or '\n'
5374 end = opts.get('print0') and '\0' or '\n'
5374 copy = {}
5375 copy = {}
5375 states = 'modified added removed deleted unknown ignored clean'.split()
5376 states = 'modified added removed deleted unknown ignored clean'.split()
5376 show = [k for k in states if opts.get(k)]
5377 show = [k for k in states if opts.get(k)]
5377 if opts.get('all'):
5378 if opts.get('all'):
5378 show += ui.quiet and (states[:4] + ['clean']) or states
5379 show += ui.quiet and (states[:4] + ['clean']) or states
5379 if not show:
5380 if not show:
5380 show = ui.quiet and states[:4] or states[:5]
5381 show = ui.quiet and states[:4] or states[:5]
5381
5382
5382 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5383 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5383 'ignored' in show, 'clean' in show, 'unknown' in show,
5384 'ignored' in show, 'clean' in show, 'unknown' in show,
5384 opts.get('subrepos'))
5385 opts.get('subrepos'))
5385 changestates = zip(states, 'MAR!?IC', stat)
5386 changestates = zip(states, 'MAR!?IC', stat)
5386
5387
5387 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5388 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5388 copy = copies.pathcopies(repo[node1], repo[node2])
5389 copy = copies.pathcopies(repo[node1], repo[node2])
5389
5390
5390 fm = ui.formatter('status', opts)
5391 fm = ui.formatter('status', opts)
5391 fmt = '%s' + end
5392 fmt = '%s' + end
5392 showchar = not opts.get('no_status')
5393 showchar = not opts.get('no_status')
5393
5394
5394 for state, char, files in changestates:
5395 for state, char, files in changestates:
5395 if state in show:
5396 if state in show:
5396 label = 'status.' + state
5397 label = 'status.' + state
5397 for f in files:
5398 for f in files:
5398 fm.startitem()
5399 fm.startitem()
5399 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5400 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5400 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5401 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5401 if f in copy:
5402 if f in copy:
5402 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5403 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5403 label='status.copied')
5404 label='status.copied')
5404 fm.end()
5405 fm.end()
5405
5406
5406 @command('^summary|sum',
5407 @command('^summary|sum',
5407 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5408 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5408 def summary(ui, repo, **opts):
5409 def summary(ui, repo, **opts):
5409 """summarize working directory state
5410 """summarize working directory state
5410
5411
5411 This generates a brief summary of the working directory state,
5412 This generates a brief summary of the working directory state,
5412 including parents, branch, commit status, and available updates.
5413 including parents, branch, commit status, and available updates.
5413
5414
5414 With the --remote option, this will check the default paths for
5415 With the --remote option, this will check the default paths for
5415 incoming and outgoing changes. This can be time-consuming.
5416 incoming and outgoing changes. This can be time-consuming.
5416
5417
5417 Returns 0 on success.
5418 Returns 0 on success.
5418 """
5419 """
5419
5420
5420 ctx = repo[None]
5421 ctx = repo[None]
5421 parents = ctx.parents()
5422 parents = ctx.parents()
5422 pnode = parents[0].node()
5423 pnode = parents[0].node()
5423 marks = []
5424 marks = []
5424
5425
5425 for p in parents:
5426 for p in parents:
5426 # label with log.changeset (instead of log.parent) since this
5427 # label with log.changeset (instead of log.parent) since this
5427 # shows a working directory parent *changeset*:
5428 # shows a working directory parent *changeset*:
5428 # i18n: column positioning for "hg summary"
5429 # i18n: column positioning for "hg summary"
5429 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5430 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5430 label='log.changeset changeset.%s' % p.phasestr())
5431 label='log.changeset changeset.%s' % p.phasestr())
5431 ui.write(' '.join(p.tags()), label='log.tag')
5432 ui.write(' '.join(p.tags()), label='log.tag')
5432 if p.bookmarks():
5433 if p.bookmarks():
5433 marks.extend(p.bookmarks())
5434 marks.extend(p.bookmarks())
5434 if p.rev() == -1:
5435 if p.rev() == -1:
5435 if not len(repo):
5436 if not len(repo):
5436 ui.write(_(' (empty repository)'))
5437 ui.write(_(' (empty repository)'))
5437 else:
5438 else:
5438 ui.write(_(' (no revision checked out)'))
5439 ui.write(_(' (no revision checked out)'))
5439 ui.write('\n')
5440 ui.write('\n')
5440 if p.description():
5441 if p.description():
5441 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5442 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5442 label='log.summary')
5443 label='log.summary')
5443
5444
5444 branch = ctx.branch()
5445 branch = ctx.branch()
5445 bheads = repo.branchheads(branch)
5446 bheads = repo.branchheads(branch)
5446 # i18n: column positioning for "hg summary"
5447 # i18n: column positioning for "hg summary"
5447 m = _('branch: %s\n') % branch
5448 m = _('branch: %s\n') % branch
5448 if branch != 'default':
5449 if branch != 'default':
5449 ui.write(m, label='log.branch')
5450 ui.write(m, label='log.branch')
5450 else:
5451 else:
5451 ui.status(m, label='log.branch')
5452 ui.status(m, label='log.branch')
5452
5453
5453 if marks:
5454 if marks:
5454 current = repo._bookmarkcurrent
5455 current = repo._bookmarkcurrent
5455 # i18n: column positioning for "hg summary"
5456 # i18n: column positioning for "hg summary"
5456 ui.write(_('bookmarks:'), label='log.bookmark')
5457 ui.write(_('bookmarks:'), label='log.bookmark')
5457 if current is not None:
5458 if current is not None:
5458 if current in marks:
5459 if current in marks:
5459 ui.write(' *' + current, label='bookmarks.current')
5460 ui.write(' *' + current, label='bookmarks.current')
5460 marks.remove(current)
5461 marks.remove(current)
5461 else:
5462 else:
5462 ui.write(' [%s]' % current, label='bookmarks.current')
5463 ui.write(' [%s]' % current, label='bookmarks.current')
5463 for m in marks:
5464 for m in marks:
5464 ui.write(' ' + m, label='log.bookmark')
5465 ui.write(' ' + m, label='log.bookmark')
5465 ui.write('\n', label='log.bookmark')
5466 ui.write('\n', label='log.bookmark')
5466
5467
5467 st = list(repo.status(unknown=True))[:6]
5468 st = list(repo.status(unknown=True))[:6]
5468
5469
5469 c = repo.dirstate.copies()
5470 c = repo.dirstate.copies()
5470 copied, renamed = [], []
5471 copied, renamed = [], []
5471 for d, s in c.iteritems():
5472 for d, s in c.iteritems():
5472 if s in st[2]:
5473 if s in st[2]:
5473 st[2].remove(s)
5474 st[2].remove(s)
5474 renamed.append(d)
5475 renamed.append(d)
5475 else:
5476 else:
5476 copied.append(d)
5477 copied.append(d)
5477 if d in st[1]:
5478 if d in st[1]:
5478 st[1].remove(d)
5479 st[1].remove(d)
5479 st.insert(3, renamed)
5480 st.insert(3, renamed)
5480 st.insert(4, copied)
5481 st.insert(4, copied)
5481
5482
5482 ms = mergemod.mergestate(repo)
5483 ms = mergemod.mergestate(repo)
5483 st.append([f for f in ms if ms[f] == 'u'])
5484 st.append([f for f in ms if ms[f] == 'u'])
5484
5485
5485 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5486 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5486 st.append(subs)
5487 st.append(subs)
5487
5488
5488 labels = [ui.label(_('%d modified'), 'status.modified'),
5489 labels = [ui.label(_('%d modified'), 'status.modified'),
5489 ui.label(_('%d added'), 'status.added'),
5490 ui.label(_('%d added'), 'status.added'),
5490 ui.label(_('%d removed'), 'status.removed'),
5491 ui.label(_('%d removed'), 'status.removed'),
5491 ui.label(_('%d renamed'), 'status.copied'),
5492 ui.label(_('%d renamed'), 'status.copied'),
5492 ui.label(_('%d copied'), 'status.copied'),
5493 ui.label(_('%d copied'), 'status.copied'),
5493 ui.label(_('%d deleted'), 'status.deleted'),
5494 ui.label(_('%d deleted'), 'status.deleted'),
5494 ui.label(_('%d unknown'), 'status.unknown'),
5495 ui.label(_('%d unknown'), 'status.unknown'),
5495 ui.label(_('%d ignored'), 'status.ignored'),
5496 ui.label(_('%d ignored'), 'status.ignored'),
5496 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5497 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5497 ui.label(_('%d subrepos'), 'status.modified')]
5498 ui.label(_('%d subrepos'), 'status.modified')]
5498 t = []
5499 t = []
5499 for s, l in zip(st, labels):
5500 for s, l in zip(st, labels):
5500 if s:
5501 if s:
5501 t.append(l % len(s))
5502 t.append(l % len(s))
5502
5503
5503 t = ', '.join(t)
5504 t = ', '.join(t)
5504 cleanworkdir = False
5505 cleanworkdir = False
5505
5506
5506 if repo.vfs.exists('updatestate'):
5507 if repo.vfs.exists('updatestate'):
5507 t += _(' (interrupted update)')
5508 t += _(' (interrupted update)')
5508 elif len(parents) > 1:
5509 elif len(parents) > 1:
5509 t += _(' (merge)')
5510 t += _(' (merge)')
5510 elif branch != parents[0].branch():
5511 elif branch != parents[0].branch():
5511 t += _(' (new branch)')
5512 t += _(' (new branch)')
5512 elif (parents[0].closesbranch() and
5513 elif (parents[0].closesbranch() and
5513 pnode in repo.branchheads(branch, closed=True)):
5514 pnode in repo.branchheads(branch, closed=True)):
5514 t += _(' (head closed)')
5515 t += _(' (head closed)')
5515 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5516 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5516 t += _(' (clean)')
5517 t += _(' (clean)')
5517 cleanworkdir = True
5518 cleanworkdir = True
5518 elif pnode not in bheads:
5519 elif pnode not in bheads:
5519 t += _(' (new branch head)')
5520 t += _(' (new branch head)')
5520
5521
5521 if cleanworkdir:
5522 if cleanworkdir:
5522 # i18n: column positioning for "hg summary"
5523 # i18n: column positioning for "hg summary"
5523 ui.status(_('commit: %s\n') % t.strip())
5524 ui.status(_('commit: %s\n') % t.strip())
5524 else:
5525 else:
5525 # i18n: column positioning for "hg summary"
5526 # i18n: column positioning for "hg summary"
5526 ui.write(_('commit: %s\n') % t.strip())
5527 ui.write(_('commit: %s\n') % t.strip())
5527
5528
5528 # all ancestors of branch heads - all ancestors of parent = new csets
5529 # all ancestors of branch heads - all ancestors of parent = new csets
5529 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5530 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5530 bheads))
5531 bheads))
5531
5532
5532 if new == 0:
5533 if new == 0:
5533 # i18n: column positioning for "hg summary"
5534 # i18n: column positioning for "hg summary"
5534 ui.status(_('update: (current)\n'))
5535 ui.status(_('update: (current)\n'))
5535 elif pnode not in bheads:
5536 elif pnode not in bheads:
5536 # i18n: column positioning for "hg summary"
5537 # i18n: column positioning for "hg summary"
5537 ui.write(_('update: %d new changesets (update)\n') % new)
5538 ui.write(_('update: %d new changesets (update)\n') % new)
5538 else:
5539 else:
5539 # i18n: column positioning for "hg summary"
5540 # i18n: column positioning for "hg summary"
5540 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5541 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5541 (new, len(bheads)))
5542 (new, len(bheads)))
5542
5543
5543 cmdutil.summaryhooks(ui, repo)
5544 cmdutil.summaryhooks(ui, repo)
5544
5545
5545 if opts.get('remote'):
5546 if opts.get('remote'):
5546 t = []
5547 t = []
5547 source, branches = hg.parseurl(ui.expandpath('default'))
5548 source, branches = hg.parseurl(ui.expandpath('default'))
5548 sbranch = branches[0]
5549 sbranch = branches[0]
5549 other = hg.peer(repo, {}, source)
5550 other = hg.peer(repo, {}, source)
5550 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5551 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5551 if revs:
5552 if revs:
5552 revs = [other.lookup(rev) for rev in revs]
5553 revs = [other.lookup(rev) for rev in revs]
5553 ui.debug('comparing with %s\n' % util.hidepassword(source))
5554 ui.debug('comparing with %s\n' % util.hidepassword(source))
5554 repo.ui.pushbuffer()
5555 repo.ui.pushbuffer()
5555 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5556 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5556 _common, incoming, _rheads = commoninc
5557 _common, incoming, _rheads = commoninc
5557 repo.ui.popbuffer()
5558 repo.ui.popbuffer()
5558 if incoming:
5559 if incoming:
5559 t.append(_('1 or more incoming'))
5560 t.append(_('1 or more incoming'))
5560
5561
5561 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5562 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5562 dbranch = branches[0]
5563 dbranch = branches[0]
5563 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5564 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5564 if source != dest:
5565 if source != dest:
5565 other = hg.peer(repo, {}, dest)
5566 other = hg.peer(repo, {}, dest)
5566 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5567 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5567 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5568 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5568 commoninc = None
5569 commoninc = None
5569 if revs:
5570 if revs:
5570 revs = [repo.lookup(rev) for rev in revs]
5571 revs = [repo.lookup(rev) for rev in revs]
5571 repo.ui.pushbuffer()
5572 repo.ui.pushbuffer()
5572 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs,
5573 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs,
5573 commoninc=commoninc)
5574 commoninc=commoninc)
5574 repo.ui.popbuffer()
5575 repo.ui.popbuffer()
5575 o = outgoing.missing
5576 o = outgoing.missing
5576 if o:
5577 if o:
5577 t.append(_('%d outgoing') % len(o))
5578 t.append(_('%d outgoing') % len(o))
5578 if 'bookmarks' in other.listkeys('namespaces'):
5579 if 'bookmarks' in other.listkeys('namespaces'):
5579 lmarks = repo.listkeys('bookmarks')
5580 lmarks = repo.listkeys('bookmarks')
5580 rmarks = other.listkeys('bookmarks')
5581 rmarks = other.listkeys('bookmarks')
5581 diff = set(rmarks) - set(lmarks)
5582 diff = set(rmarks) - set(lmarks)
5582 if len(diff) > 0:
5583 if len(diff) > 0:
5583 t.append(_('%d incoming bookmarks') % len(diff))
5584 t.append(_('%d incoming bookmarks') % len(diff))
5584 diff = set(lmarks) - set(rmarks)
5585 diff = set(lmarks) - set(rmarks)
5585 if len(diff) > 0:
5586 if len(diff) > 0:
5586 t.append(_('%d outgoing bookmarks') % len(diff))
5587 t.append(_('%d outgoing bookmarks') % len(diff))
5587
5588
5588 if t:
5589 if t:
5589 # i18n: column positioning for "hg summary"
5590 # i18n: column positioning for "hg summary"
5590 ui.write(_('remote: %s\n') % (', '.join(t)))
5591 ui.write(_('remote: %s\n') % (', '.join(t)))
5591 else:
5592 else:
5592 # i18n: column positioning for "hg summary"
5593 # i18n: column positioning for "hg summary"
5593 ui.status(_('remote: (synced)\n'))
5594 ui.status(_('remote: (synced)\n'))
5594
5595
5595 @command('tag',
5596 @command('tag',
5596 [('f', 'force', None, _('force tag')),
5597 [('f', 'force', None, _('force tag')),
5597 ('l', 'local', None, _('make the tag local')),
5598 ('l', 'local', None, _('make the tag local')),
5598 ('r', 'rev', '', _('revision to tag'), _('REV')),
5599 ('r', 'rev', '', _('revision to tag'), _('REV')),
5599 ('', 'remove', None, _('remove a tag')),
5600 ('', 'remove', None, _('remove a tag')),
5600 # -l/--local is already there, commitopts cannot be used
5601 # -l/--local is already there, commitopts cannot be used
5601 ('e', 'edit', None, _('edit commit message')),
5602 ('e', 'edit', None, _('edit commit message')),
5602 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5603 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5603 ] + commitopts2,
5604 ] + commitopts2,
5604 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5605 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5605 def tag(ui, repo, name1, *names, **opts):
5606 def tag(ui, repo, name1, *names, **opts):
5606 """add one or more tags for the current or given revision
5607 """add one or more tags for the current or given revision
5607
5608
5608 Name a particular revision using <name>.
5609 Name a particular revision using <name>.
5609
5610
5610 Tags are used to name particular revisions of the repository and are
5611 Tags are used to name particular revisions of the repository and are
5611 very useful to compare different revisions, to go back to significant
5612 very useful to compare different revisions, to go back to significant
5612 earlier versions or to mark branch points as releases, etc. Changing
5613 earlier versions or to mark branch points as releases, etc. Changing
5613 an existing tag is normally disallowed; use -f/--force to override.
5614 an existing tag is normally disallowed; use -f/--force to override.
5614
5615
5615 If no revision is given, the parent of the working directory is
5616 If no revision is given, the parent of the working directory is
5616 used.
5617 used.
5617
5618
5618 To facilitate version control, distribution, and merging of tags,
5619 To facilitate version control, distribution, and merging of tags,
5619 they are stored as a file named ".hgtags" which is managed similarly
5620 they are stored as a file named ".hgtags" which is managed similarly
5620 to other project files and can be hand-edited if necessary. This
5621 to other project files and can be hand-edited if necessary. This
5621 also means that tagging creates a new commit. The file
5622 also means that tagging creates a new commit. The file
5622 ".hg/localtags" is used for local tags (not shared among
5623 ".hg/localtags" is used for local tags (not shared among
5623 repositories).
5624 repositories).
5624
5625
5625 Tag commits are usually made at the head of a branch. If the parent
5626 Tag commits are usually made at the head of a branch. If the parent
5626 of the working directory is not a branch head, :hg:`tag` aborts; use
5627 of the working directory is not a branch head, :hg:`tag` aborts; use
5627 -f/--force to force the tag commit to be based on a non-head
5628 -f/--force to force the tag commit to be based on a non-head
5628 changeset.
5629 changeset.
5629
5630
5630 See :hg:`help dates` for a list of formats valid for -d/--date.
5631 See :hg:`help dates` for a list of formats valid for -d/--date.
5631
5632
5632 Since tag names have priority over branch names during revision
5633 Since tag names have priority over branch names during revision
5633 lookup, using an existing branch name as a tag name is discouraged.
5634 lookup, using an existing branch name as a tag name is discouraged.
5634
5635
5635 Returns 0 on success.
5636 Returns 0 on success.
5636 """
5637 """
5637 wlock = lock = None
5638 wlock = lock = None
5638 try:
5639 try:
5639 wlock = repo.wlock()
5640 wlock = repo.wlock()
5640 lock = repo.lock()
5641 lock = repo.lock()
5641 rev_ = "."
5642 rev_ = "."
5642 names = [t.strip() for t in (name1,) + names]
5643 names = [t.strip() for t in (name1,) + names]
5643 if len(names) != len(set(names)):
5644 if len(names) != len(set(names)):
5644 raise util.Abort(_('tag names must be unique'))
5645 raise util.Abort(_('tag names must be unique'))
5645 for n in names:
5646 for n in names:
5646 scmutil.checknewlabel(repo, n, 'tag')
5647 scmutil.checknewlabel(repo, n, 'tag')
5647 if not n:
5648 if not n:
5648 raise util.Abort(_('tag names cannot consist entirely of '
5649 raise util.Abort(_('tag names cannot consist entirely of '
5649 'whitespace'))
5650 'whitespace'))
5650 if opts.get('rev') and opts.get('remove'):
5651 if opts.get('rev') and opts.get('remove'):
5651 raise util.Abort(_("--rev and --remove are incompatible"))
5652 raise util.Abort(_("--rev and --remove are incompatible"))
5652 if opts.get('rev'):
5653 if opts.get('rev'):
5653 rev_ = opts['rev']
5654 rev_ = opts['rev']
5654 message = opts.get('message')
5655 message = opts.get('message')
5655 if opts.get('remove'):
5656 if opts.get('remove'):
5656 expectedtype = opts.get('local') and 'local' or 'global'
5657 expectedtype = opts.get('local') and 'local' or 'global'
5657 for n in names:
5658 for n in names:
5658 if not repo.tagtype(n):
5659 if not repo.tagtype(n):
5659 raise util.Abort(_("tag '%s' does not exist") % n)
5660 raise util.Abort(_("tag '%s' does not exist") % n)
5660 if repo.tagtype(n) != expectedtype:
5661 if repo.tagtype(n) != expectedtype:
5661 if expectedtype == 'global':
5662 if expectedtype == 'global':
5662 raise util.Abort(_("tag '%s' is not a global tag") % n)
5663 raise util.Abort(_("tag '%s' is not a global tag") % n)
5663 else:
5664 else:
5664 raise util.Abort(_("tag '%s' is not a local tag") % n)
5665 raise util.Abort(_("tag '%s' is not a local tag") % n)
5665 rev_ = nullid
5666 rev_ = nullid
5666 if not message:
5667 if not message:
5667 # we don't translate commit messages
5668 # we don't translate commit messages
5668 message = 'Removed tag %s' % ', '.join(names)
5669 message = 'Removed tag %s' % ', '.join(names)
5669 elif not opts.get('force'):
5670 elif not opts.get('force'):
5670 for n in names:
5671 for n in names:
5671 if n in repo.tags():
5672 if n in repo.tags():
5672 raise util.Abort(_("tag '%s' already exists "
5673 raise util.Abort(_("tag '%s' already exists "
5673 "(use -f to force)") % n)
5674 "(use -f to force)") % n)
5674 if not opts.get('local'):
5675 if not opts.get('local'):
5675 p1, p2 = repo.dirstate.parents()
5676 p1, p2 = repo.dirstate.parents()
5676 if p2 != nullid:
5677 if p2 != nullid:
5677 raise util.Abort(_('uncommitted merge'))
5678 raise util.Abort(_('uncommitted merge'))
5678 bheads = repo.branchheads()
5679 bheads = repo.branchheads()
5679 if not opts.get('force') and bheads and p1 not in bheads:
5680 if not opts.get('force') and bheads and p1 not in bheads:
5680 raise util.Abort(_('not at a branch head (use -f to force)'))
5681 raise util.Abort(_('not at a branch head (use -f to force)'))
5681 r = scmutil.revsingle(repo, rev_).node()
5682 r = scmutil.revsingle(repo, rev_).node()
5682
5683
5683 if not message:
5684 if not message:
5684 # we don't translate commit messages
5685 # we don't translate commit messages
5685 message = ('Added tag %s for changeset %s' %
5686 message = ('Added tag %s for changeset %s' %
5686 (', '.join(names), short(r)))
5687 (', '.join(names), short(r)))
5687
5688
5688 date = opts.get('date')
5689 date = opts.get('date')
5689 if date:
5690 if date:
5690 date = util.parsedate(date)
5691 date = util.parsedate(date)
5691
5692
5692 if opts.get('edit'):
5693 if opts.get('edit'):
5693 message = ui.edit(message, ui.username())
5694 message = ui.edit(message, ui.username())
5694 repo.savecommitmessage(message)
5695 repo.savecommitmessage(message)
5695
5696
5696 # don't allow tagging the null rev
5697 # don't allow tagging the null rev
5697 if (not opts.get('remove') and
5698 if (not opts.get('remove') and
5698 scmutil.revsingle(repo, rev_).rev() == nullrev):
5699 scmutil.revsingle(repo, rev_).rev() == nullrev):
5699 raise util.Abort(_("cannot tag null revision"))
5700 raise util.Abort(_("cannot tag null revision"))
5700
5701
5701 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5702 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5702 finally:
5703 finally:
5703 release(lock, wlock)
5704 release(lock, wlock)
5704
5705
5705 @command('tags', [], '')
5706 @command('tags', [], '')
5706 def tags(ui, repo, **opts):
5707 def tags(ui, repo, **opts):
5707 """list repository tags
5708 """list repository tags
5708
5709
5709 This lists both regular and local tags. When the -v/--verbose
5710 This lists both regular and local tags. When the -v/--verbose
5710 switch is used, a third column "local" is printed for local tags.
5711 switch is used, a third column "local" is printed for local tags.
5711
5712
5712 Returns 0 on success.
5713 Returns 0 on success.
5713 """
5714 """
5714
5715
5715 fm = ui.formatter('tags', opts)
5716 fm = ui.formatter('tags', opts)
5716 hexfunc = ui.debugflag and hex or short
5717 hexfunc = ui.debugflag and hex or short
5717 tagtype = ""
5718 tagtype = ""
5718
5719
5719 for t, n in reversed(repo.tagslist()):
5720 for t, n in reversed(repo.tagslist()):
5720 hn = hexfunc(n)
5721 hn = hexfunc(n)
5721 label = 'tags.normal'
5722 label = 'tags.normal'
5722 tagtype = ''
5723 tagtype = ''
5723 if repo.tagtype(t) == 'local':
5724 if repo.tagtype(t) == 'local':
5724 label = 'tags.local'
5725 label = 'tags.local'
5725 tagtype = 'local'
5726 tagtype = 'local'
5726
5727
5727 fm.startitem()
5728 fm.startitem()
5728 fm.write('tag', '%s', t, label=label)
5729 fm.write('tag', '%s', t, label=label)
5729 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5730 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5730 fm.condwrite(not ui.quiet, 'rev id', fmt,
5731 fm.condwrite(not ui.quiet, 'rev id', fmt,
5731 repo.changelog.rev(n), hn, label=label)
5732 repo.changelog.rev(n), hn, label=label)
5732 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5733 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5733 tagtype, label=label)
5734 tagtype, label=label)
5734 fm.plain('\n')
5735 fm.plain('\n')
5735 fm.end()
5736 fm.end()
5736
5737
5737 @command('tip',
5738 @command('tip',
5738 [('p', 'patch', None, _('show patch')),
5739 [('p', 'patch', None, _('show patch')),
5739 ('g', 'git', None, _('use git extended diff format')),
5740 ('g', 'git', None, _('use git extended diff format')),
5740 ] + templateopts,
5741 ] + templateopts,
5741 _('[-p] [-g]'))
5742 _('[-p] [-g]'))
5742 def tip(ui, repo, **opts):
5743 def tip(ui, repo, **opts):
5743 """show the tip revision (DEPRECATED)
5744 """show the tip revision (DEPRECATED)
5744
5745
5745 The tip revision (usually just called the tip) is the changeset
5746 The tip revision (usually just called the tip) is the changeset
5746 most recently added to the repository (and therefore the most
5747 most recently added to the repository (and therefore the most
5747 recently changed head).
5748 recently changed head).
5748
5749
5749 If you have just made a commit, that commit will be the tip. If
5750 If you have just made a commit, that commit will be the tip. If
5750 you have just pulled changes from another repository, the tip of
5751 you have just pulled changes from another repository, the tip of
5751 that repository becomes the current tip. The "tip" tag is special
5752 that repository becomes the current tip. The "tip" tag is special
5752 and cannot be renamed or assigned to a different changeset.
5753 and cannot be renamed or assigned to a different changeset.
5753
5754
5754 This command is deprecated, please use :hg:`heads` instead.
5755 This command is deprecated, please use :hg:`heads` instead.
5755
5756
5756 Returns 0 on success.
5757 Returns 0 on success.
5757 """
5758 """
5758 displayer = cmdutil.show_changeset(ui, repo, opts)
5759 displayer = cmdutil.show_changeset(ui, repo, opts)
5759 displayer.show(repo['tip'])
5760 displayer.show(repo['tip'])
5760 displayer.close()
5761 displayer.close()
5761
5762
5762 @command('unbundle',
5763 @command('unbundle',
5763 [('u', 'update', None,
5764 [('u', 'update', None,
5764 _('update to new branch head if changesets were unbundled'))],
5765 _('update to new branch head if changesets were unbundled'))],
5765 _('[-u] FILE...'))
5766 _('[-u] FILE...'))
5766 def unbundle(ui, repo, fname1, *fnames, **opts):
5767 def unbundle(ui, repo, fname1, *fnames, **opts):
5767 """apply one or more changegroup files
5768 """apply one or more changegroup files
5768
5769
5769 Apply one or more compressed changegroup files generated by the
5770 Apply one or more compressed changegroup files generated by the
5770 bundle command.
5771 bundle command.
5771
5772
5772 Returns 0 on success, 1 if an update has unresolved files.
5773 Returns 0 on success, 1 if an update has unresolved files.
5773 """
5774 """
5774 fnames = (fname1,) + fnames
5775 fnames = (fname1,) + fnames
5775
5776
5776 lock = repo.lock()
5777 lock = repo.lock()
5777 wc = repo['.']
5778 wc = repo['.']
5778 try:
5779 try:
5779 for fname in fnames:
5780 for fname in fnames:
5780 f = hg.openpath(ui, fname)
5781 f = hg.openpath(ui, fname)
5781 gen = changegroup.readbundle(f, fname)
5782 gen = changegroup.readbundle(f, fname)
5782 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5783 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5783 finally:
5784 finally:
5784 lock.release()
5785 lock.release()
5785 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5786 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5786 return postincoming(ui, repo, modheads, opts.get('update'), None)
5787 return postincoming(ui, repo, modheads, opts.get('update'), None)
5787
5788
5788 @command('^update|up|checkout|co',
5789 @command('^update|up|checkout|co',
5789 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5790 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5790 ('c', 'check', None,
5791 ('c', 'check', None,
5791 _('update across branches if no uncommitted changes')),
5792 _('update across branches if no uncommitted changes')),
5792 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5793 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5793 ('r', 'rev', '', _('revision'), _('REV'))],
5794 ('r', 'rev', '', _('revision'), _('REV'))],
5794 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5795 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5795 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5796 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5796 """update working directory (or switch revisions)
5797 """update working directory (or switch revisions)
5797
5798
5798 Update the repository's working directory to the specified
5799 Update the repository's working directory to the specified
5799 changeset. If no changeset is specified, update to the tip of the
5800 changeset. If no changeset is specified, update to the tip of the
5800 current named branch and move the current bookmark (see :hg:`help
5801 current named branch and move the current bookmark (see :hg:`help
5801 bookmarks`).
5802 bookmarks`).
5802
5803
5803 Update sets the working directory's parent revision to the specified
5804 Update sets the working directory's parent revision to the specified
5804 changeset (see :hg:`help parents`).
5805 changeset (see :hg:`help parents`).
5805
5806
5806 If the changeset is not a descendant or ancestor of the working
5807 If the changeset is not a descendant or ancestor of the working
5807 directory's parent, the update is aborted. With the -c/--check
5808 directory's parent, the update is aborted. With the -c/--check
5808 option, the working directory is checked for uncommitted changes; if
5809 option, the working directory is checked for uncommitted changes; if
5809 none are found, the working directory is updated to the specified
5810 none are found, the working directory is updated to the specified
5810 changeset.
5811 changeset.
5811
5812
5812 .. container:: verbose
5813 .. container:: verbose
5813
5814
5814 The following rules apply when the working directory contains
5815 The following rules apply when the working directory contains
5815 uncommitted changes:
5816 uncommitted changes:
5816
5817
5817 1. If neither -c/--check nor -C/--clean is specified, and if
5818 1. If neither -c/--check nor -C/--clean is specified, and if
5818 the requested changeset is an ancestor or descendant of
5819 the requested changeset is an ancestor or descendant of
5819 the working directory's parent, the uncommitted changes
5820 the working directory's parent, the uncommitted changes
5820 are merged into the requested changeset and the merged
5821 are merged into the requested changeset and the merged
5821 result is left uncommitted. If the requested changeset is
5822 result is left uncommitted. If the requested changeset is
5822 not an ancestor or descendant (that is, it is on another
5823 not an ancestor or descendant (that is, it is on another
5823 branch), the update is aborted and the uncommitted changes
5824 branch), the update is aborted and the uncommitted changes
5824 are preserved.
5825 are preserved.
5825
5826
5826 2. With the -c/--check option, the update is aborted and the
5827 2. With the -c/--check option, the update is aborted and the
5827 uncommitted changes are preserved.
5828 uncommitted changes are preserved.
5828
5829
5829 3. With the -C/--clean option, uncommitted changes are discarded and
5830 3. With the -C/--clean option, uncommitted changes are discarded and
5830 the working directory is updated to the requested changeset.
5831 the working directory is updated to the requested changeset.
5831
5832
5832 To cancel an uncommitted merge (and lose your changes), use
5833 To cancel an uncommitted merge (and lose your changes), use
5833 :hg:`update --clean .`.
5834 :hg:`update --clean .`.
5834
5835
5835 Use null as the changeset to remove the working directory (like
5836 Use null as the changeset to remove the working directory (like
5836 :hg:`clone -U`).
5837 :hg:`clone -U`).
5837
5838
5838 If you want to revert just one file to an older revision, use
5839 If you want to revert just one file to an older revision, use
5839 :hg:`revert [-r REV] NAME`.
5840 :hg:`revert [-r REV] NAME`.
5840
5841
5841 See :hg:`help dates` for a list of formats valid for -d/--date.
5842 See :hg:`help dates` for a list of formats valid for -d/--date.
5842
5843
5843 Returns 0 on success, 1 if there are unresolved files.
5844 Returns 0 on success, 1 if there are unresolved files.
5844 """
5845 """
5845 if rev and node:
5846 if rev and node:
5846 raise util.Abort(_("please specify just one revision"))
5847 raise util.Abort(_("please specify just one revision"))
5847
5848
5848 if rev is None or rev == '':
5849 if rev is None or rev == '':
5849 rev = node
5850 rev = node
5850
5851
5851 cmdutil.clearunfinished(repo)
5852 cmdutil.clearunfinished(repo)
5852
5853
5853 # with no argument, we also move the current bookmark, if any
5854 # with no argument, we also move the current bookmark, if any
5854 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5855 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5855
5856
5856 # if we defined a bookmark, we have to remember the original bookmark name
5857 # if we defined a bookmark, we have to remember the original bookmark name
5857 brev = rev
5858 brev = rev
5858 rev = scmutil.revsingle(repo, rev, rev).rev()
5859 rev = scmutil.revsingle(repo, rev, rev).rev()
5859
5860
5860 if check and clean:
5861 if check and clean:
5861 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5862 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5862
5863
5863 if date:
5864 if date:
5864 if rev is not None:
5865 if rev is not None:
5865 raise util.Abort(_("you can't specify a revision and a date"))
5866 raise util.Abort(_("you can't specify a revision and a date"))
5866 rev = cmdutil.finddate(ui, repo, date)
5867 rev = cmdutil.finddate(ui, repo, date)
5867
5868
5868 if check:
5869 if check:
5869 c = repo[None]
5870 c = repo[None]
5870 if c.dirty(merge=False, branch=False, missing=True):
5871 if c.dirty(merge=False, branch=False, missing=True):
5871 raise util.Abort(_("uncommitted changes"))
5872 raise util.Abort(_("uncommitted changes"))
5872 if rev is None:
5873 if rev is None:
5873 rev = repo[repo[None].branch()].rev()
5874 rev = repo[repo[None].branch()].rev()
5874 mergemod._checkunknown(repo, repo[None], repo[rev])
5875 mergemod._checkunknown(repo, repo[None], repo[rev])
5875
5876
5876 if clean:
5877 if clean:
5877 ret = hg.clean(repo, rev)
5878 ret = hg.clean(repo, rev)
5878 else:
5879 else:
5879 ret = hg.update(repo, rev)
5880 ret = hg.update(repo, rev)
5880
5881
5881 if not ret and movemarkfrom:
5882 if not ret and movemarkfrom:
5882 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5883 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5883 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5884 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5884 elif brev in repo._bookmarks:
5885 elif brev in repo._bookmarks:
5885 bookmarks.setcurrent(repo, brev)
5886 bookmarks.setcurrent(repo, brev)
5886 elif brev:
5887 elif brev:
5887 bookmarks.unsetcurrent(repo)
5888 bookmarks.unsetcurrent(repo)
5888
5889
5889 return ret
5890 return ret
5890
5891
5891 @command('verify', [])
5892 @command('verify', [])
5892 def verify(ui, repo):
5893 def verify(ui, repo):
5893 """verify the integrity of the repository
5894 """verify the integrity of the repository
5894
5895
5895 Verify the integrity of the current repository.
5896 Verify the integrity of the current repository.
5896
5897
5897 This will perform an extensive check of the repository's
5898 This will perform an extensive check of the repository's
5898 integrity, validating the hashes and checksums of each entry in
5899 integrity, validating the hashes and checksums of each entry in
5899 the changelog, manifest, and tracked files, as well as the
5900 the changelog, manifest, and tracked files, as well as the
5900 integrity of their crosslinks and indices.
5901 integrity of their crosslinks and indices.
5901
5902
5902 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5903 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5903 for more information about recovery from corruption of the
5904 for more information about recovery from corruption of the
5904 repository.
5905 repository.
5905
5906
5906 Returns 0 on success, 1 if errors are encountered.
5907 Returns 0 on success, 1 if errors are encountered.
5907 """
5908 """
5908 return hg.verify(repo)
5909 return hg.verify(repo)
5909
5910
5910 @command('version', [])
5911 @command('version', [])
5911 def version_(ui):
5912 def version_(ui):
5912 """output version and copyright information"""
5913 """output version and copyright information"""
5913 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5914 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5914 % util.version())
5915 % util.version())
5915 ui.status(_(
5916 ui.status(_(
5916 "(see http://mercurial.selenic.com for more information)\n"
5917 "(see http://mercurial.selenic.com for more information)\n"
5917 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
5918 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
5918 "This is free software; see the source for copying conditions. "
5919 "This is free software; see the source for copying conditions. "
5919 "There is NO\nwarranty; "
5920 "There is NO\nwarranty; "
5920 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5921 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5921 ))
5922 ))
5922
5923
5923 norepo = ("clone init version help debugcommands debugcomplete"
5924 norepo = ("clone init version help debugcommands debugcomplete"
5924 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5925 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5925 " debugknown debuggetbundle debugbundle")
5926 " debugknown debuggetbundle debugbundle")
5926 optionalrepo = ("identify paths serve config showconfig debugancestor debugdag"
5927 optionalrepo = ("identify paths serve config showconfig debugancestor debugdag"
5927 " debugdata debugindex debugindexdot debugrevlog")
5928 " debugdata debugindex debugindexdot debugrevlog")
5928 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5929 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5929 " remove resolve status debugwalk")
5930 " remove resolve status debugwalk")
General Comments 0
You need to be logged in to leave comments. Login now