##// END OF EJS Templates
backout: improve confusing 'cannot backout change on a different branch' abort...
Mads Kiilerich -
r20791:8dd867bd default
parent child Browse files
Show More
@@ -1,5912 +1,5912
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 on a different branch'))
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 def binary():
3347 def binary():
3348 flog = getfile(fn)
3348 flog = getfile(fn)
3349 return util.binary(flog.read(ctx.filenode(fn)))
3349 return util.binary(flog.read(ctx.filenode(fn)))
3350
3350
3351 if opts.get('all'):
3351 if opts.get('all'):
3352 iter = difflinestates(pstates, states)
3352 iter = difflinestates(pstates, states)
3353 else:
3353 else:
3354 iter = [('', l) for l in states]
3354 iter = [('', l) for l in states]
3355 for change, l in iter:
3355 for change, l in iter:
3356 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3356 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3357 before, match, after = None, None, None
3357 before, match, after = None, None, None
3358
3358
3359 if opts.get('line_number'):
3359 if opts.get('line_number'):
3360 cols.append((str(l.linenum), 'grep.linenumber'))
3360 cols.append((str(l.linenum), 'grep.linenumber'))
3361 if opts.get('all'):
3361 if opts.get('all'):
3362 cols.append((change, 'grep.change'))
3362 cols.append((change, 'grep.change'))
3363 if opts.get('user'):
3363 if opts.get('user'):
3364 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3364 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3365 if opts.get('date'):
3365 if opts.get('date'):
3366 cols.append((datefunc(ctx.date()), 'grep.date'))
3366 cols.append((datefunc(ctx.date()), 'grep.date'))
3367 if opts.get('files_with_matches'):
3367 if opts.get('files_with_matches'):
3368 c = (fn, rev)
3368 c = (fn, rev)
3369 if c in filerevmatches:
3369 if c in filerevmatches:
3370 continue
3370 continue
3371 filerevmatches[c] = 1
3371 filerevmatches[c] = 1
3372 else:
3372 else:
3373 before = l.line[:l.colstart]
3373 before = l.line[:l.colstart]
3374 match = l.line[l.colstart:l.colend]
3374 match = l.line[l.colstart:l.colend]
3375 after = l.line[l.colend:]
3375 after = l.line[l.colend:]
3376 for col, label in cols[:-1]:
3376 for col, label in cols[:-1]:
3377 ui.write(col, label=label)
3377 ui.write(col, label=label)
3378 ui.write(sep, label='grep.sep')
3378 ui.write(sep, label='grep.sep')
3379 ui.write(cols[-1][0], label=cols[-1][1])
3379 ui.write(cols[-1][0], label=cols[-1][1])
3380 if before is not None:
3380 if before is not None:
3381 ui.write(sep, label='grep.sep')
3381 ui.write(sep, label='grep.sep')
3382 if not opts.get('text') and binary():
3382 if not opts.get('text') and binary():
3383 ui.write(" Binary file matches")
3383 ui.write(" Binary file matches")
3384 else:
3384 else:
3385 ui.write(before)
3385 ui.write(before)
3386 ui.write(match, label='grep.match')
3386 ui.write(match, label='grep.match')
3387 ui.write(after)
3387 ui.write(after)
3388 ui.write(eol)
3388 ui.write(eol)
3389 found = True
3389 found = True
3390 return found
3390 return found
3391
3391
3392 skip = {}
3392 skip = {}
3393 revfiles = {}
3393 revfiles = {}
3394 matchfn = scmutil.match(repo[None], pats, opts)
3394 matchfn = scmutil.match(repo[None], pats, opts)
3395 found = False
3395 found = False
3396 follow = opts.get('follow')
3396 follow = opts.get('follow')
3397
3397
3398 def prep(ctx, fns):
3398 def prep(ctx, fns):
3399 rev = ctx.rev()
3399 rev = ctx.rev()
3400 pctx = ctx.p1()
3400 pctx = ctx.p1()
3401 parent = pctx.rev()
3401 parent = pctx.rev()
3402 matches.setdefault(rev, {})
3402 matches.setdefault(rev, {})
3403 matches.setdefault(parent, {})
3403 matches.setdefault(parent, {})
3404 files = revfiles.setdefault(rev, [])
3404 files = revfiles.setdefault(rev, [])
3405 for fn in fns:
3405 for fn in fns:
3406 flog = getfile(fn)
3406 flog = getfile(fn)
3407 try:
3407 try:
3408 fnode = ctx.filenode(fn)
3408 fnode = ctx.filenode(fn)
3409 except error.LookupError:
3409 except error.LookupError:
3410 continue
3410 continue
3411
3411
3412 copied = flog.renamed(fnode)
3412 copied = flog.renamed(fnode)
3413 copy = follow and copied and copied[0]
3413 copy = follow and copied and copied[0]
3414 if copy:
3414 if copy:
3415 copies.setdefault(rev, {})[fn] = copy
3415 copies.setdefault(rev, {})[fn] = copy
3416 if fn in skip:
3416 if fn in skip:
3417 if copy:
3417 if copy:
3418 skip[copy] = True
3418 skip[copy] = True
3419 continue
3419 continue
3420 files.append(fn)
3420 files.append(fn)
3421
3421
3422 if fn not in matches[rev]:
3422 if fn not in matches[rev]:
3423 grepbody(fn, rev, flog.read(fnode))
3423 grepbody(fn, rev, flog.read(fnode))
3424
3424
3425 pfn = copy or fn
3425 pfn = copy or fn
3426 if pfn not in matches[parent]:
3426 if pfn not in matches[parent]:
3427 try:
3427 try:
3428 fnode = pctx.filenode(pfn)
3428 fnode = pctx.filenode(pfn)
3429 grepbody(pfn, parent, flog.read(fnode))
3429 grepbody(pfn, parent, flog.read(fnode))
3430 except error.LookupError:
3430 except error.LookupError:
3431 pass
3431 pass
3432
3432
3433 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3433 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3434 rev = ctx.rev()
3434 rev = ctx.rev()
3435 parent = ctx.p1().rev()
3435 parent = ctx.p1().rev()
3436 for fn in sorted(revfiles.get(rev, [])):
3436 for fn in sorted(revfiles.get(rev, [])):
3437 states = matches[rev][fn]
3437 states = matches[rev][fn]
3438 copy = copies.get(rev, {}).get(fn)
3438 copy = copies.get(rev, {}).get(fn)
3439 if fn in skip:
3439 if fn in skip:
3440 if copy:
3440 if copy:
3441 skip[copy] = True
3441 skip[copy] = True
3442 continue
3442 continue
3443 pstates = matches.get(parent, {}).get(copy or fn, [])
3443 pstates = matches.get(parent, {}).get(copy or fn, [])
3444 if pstates or states:
3444 if pstates or states:
3445 r = display(fn, ctx, pstates, states)
3445 r = display(fn, ctx, pstates, states)
3446 found = found or r
3446 found = found or r
3447 if r and not opts.get('all'):
3447 if r and not opts.get('all'):
3448 skip[fn] = True
3448 skip[fn] = True
3449 if copy:
3449 if copy:
3450 skip[copy] = True
3450 skip[copy] = True
3451 del matches[rev]
3451 del matches[rev]
3452 del revfiles[rev]
3452 del revfiles[rev]
3453
3453
3454 return not found
3454 return not found
3455
3455
3456 @command('heads',
3456 @command('heads',
3457 [('r', 'rev', '',
3457 [('r', 'rev', '',
3458 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3458 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3459 ('t', 'topo', False, _('show topological heads only')),
3459 ('t', 'topo', False, _('show topological heads only')),
3460 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3460 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3461 ('c', 'closed', False, _('show normal and closed branch heads')),
3461 ('c', 'closed', False, _('show normal and closed branch heads')),
3462 ] + templateopts,
3462 ] + templateopts,
3463 _('[-ct] [-r STARTREV] [REV]...'))
3463 _('[-ct] [-r STARTREV] [REV]...'))
3464 def heads(ui, repo, *branchrevs, **opts):
3464 def heads(ui, repo, *branchrevs, **opts):
3465 """show branch heads
3465 """show branch heads
3466
3466
3467 With no arguments, show all open branch heads in the repository.
3467 With no arguments, show all open branch heads in the repository.
3468 Branch heads are changesets that have no descendants on the
3468 Branch heads are changesets that have no descendants on the
3469 same branch. They are where development generally takes place and
3469 same branch. They are where development generally takes place and
3470 are the usual targets for update and merge operations.
3470 are the usual targets for update and merge operations.
3471
3471
3472 If one or more REVs are given, only open branch heads on the
3472 If one or more REVs are given, only open branch heads on the
3473 branches associated with the specified changesets are shown. This
3473 branches associated with the specified changesets are shown. This
3474 means that you can use :hg:`heads .` to see the heads on the
3474 means that you can use :hg:`heads .` to see the heads on the
3475 currently checked-out branch.
3475 currently checked-out branch.
3476
3476
3477 If -c/--closed is specified, also show branch heads marked closed
3477 If -c/--closed is specified, also show branch heads marked closed
3478 (see :hg:`commit --close-branch`).
3478 (see :hg:`commit --close-branch`).
3479
3479
3480 If STARTREV is specified, only those heads that are descendants of
3480 If STARTREV is specified, only those heads that are descendants of
3481 STARTREV will be displayed.
3481 STARTREV will be displayed.
3482
3482
3483 If -t/--topo is specified, named branch mechanics will be ignored and only
3483 If -t/--topo is specified, named branch mechanics will be ignored and only
3484 topological heads (changesets with no children) will be shown.
3484 topological heads (changesets with no children) will be shown.
3485
3485
3486 Returns 0 if matching heads are found, 1 if not.
3486 Returns 0 if matching heads are found, 1 if not.
3487 """
3487 """
3488
3488
3489 start = None
3489 start = None
3490 if 'rev' in opts:
3490 if 'rev' in opts:
3491 start = scmutil.revsingle(repo, opts['rev'], None).node()
3491 start = scmutil.revsingle(repo, opts['rev'], None).node()
3492
3492
3493 if opts.get('topo'):
3493 if opts.get('topo'):
3494 heads = [repo[h] for h in repo.heads(start)]
3494 heads = [repo[h] for h in repo.heads(start)]
3495 else:
3495 else:
3496 heads = []
3496 heads = []
3497 for branch in repo.branchmap():
3497 for branch in repo.branchmap():
3498 heads += repo.branchheads(branch, start, opts.get('closed'))
3498 heads += repo.branchheads(branch, start, opts.get('closed'))
3499 heads = [repo[h] for h in heads]
3499 heads = [repo[h] for h in heads]
3500
3500
3501 if branchrevs:
3501 if branchrevs:
3502 branches = set(repo[br].branch() for br in branchrevs)
3502 branches = set(repo[br].branch() for br in branchrevs)
3503 heads = [h for h in heads if h.branch() in branches]
3503 heads = [h for h in heads if h.branch() in branches]
3504
3504
3505 if opts.get('active') and branchrevs:
3505 if opts.get('active') and branchrevs:
3506 dagheads = repo.heads(start)
3506 dagheads = repo.heads(start)
3507 heads = [h for h in heads if h.node() in dagheads]
3507 heads = [h for h in heads if h.node() in dagheads]
3508
3508
3509 if branchrevs:
3509 if branchrevs:
3510 haveheads = set(h.branch() for h in heads)
3510 haveheads = set(h.branch() for h in heads)
3511 if branches - haveheads:
3511 if branches - haveheads:
3512 headless = ', '.join(b for b in branches - haveheads)
3512 headless = ', '.join(b for b in branches - haveheads)
3513 msg = _('no open branch heads found on branches %s')
3513 msg = _('no open branch heads found on branches %s')
3514 if opts.get('rev'):
3514 if opts.get('rev'):
3515 msg += _(' (started at %s)') % opts['rev']
3515 msg += _(' (started at %s)') % opts['rev']
3516 ui.warn((msg + '\n') % headless)
3516 ui.warn((msg + '\n') % headless)
3517
3517
3518 if not heads:
3518 if not heads:
3519 return 1
3519 return 1
3520
3520
3521 heads = sorted(heads, key=lambda x: -x.rev())
3521 heads = sorted(heads, key=lambda x: -x.rev())
3522 displayer = cmdutil.show_changeset(ui, repo, opts)
3522 displayer = cmdutil.show_changeset(ui, repo, opts)
3523 for ctx in heads:
3523 for ctx in heads:
3524 displayer.show(ctx)
3524 displayer.show(ctx)
3525 displayer.close()
3525 displayer.close()
3526
3526
3527 @command('help',
3527 @command('help',
3528 [('e', 'extension', None, _('show only help for extensions')),
3528 [('e', 'extension', None, _('show only help for extensions')),
3529 ('c', 'command', None, _('show only help for commands')),
3529 ('c', 'command', None, _('show only help for commands')),
3530 ('k', 'keyword', '', _('show topics matching keyword')),
3530 ('k', 'keyword', '', _('show topics matching keyword')),
3531 ],
3531 ],
3532 _('[-ec] [TOPIC]'))
3532 _('[-ec] [TOPIC]'))
3533 def help_(ui, name=None, **opts):
3533 def help_(ui, name=None, **opts):
3534 """show help for a given topic or a help overview
3534 """show help for a given topic or a help overview
3535
3535
3536 With no arguments, print a list of commands with short help messages.
3536 With no arguments, print a list of commands with short help messages.
3537
3537
3538 Given a topic, extension, or command name, print help for that
3538 Given a topic, extension, or command name, print help for that
3539 topic.
3539 topic.
3540
3540
3541 Returns 0 if successful.
3541 Returns 0 if successful.
3542 """
3542 """
3543
3543
3544 textwidth = min(ui.termwidth(), 80) - 2
3544 textwidth = min(ui.termwidth(), 80) - 2
3545
3545
3546 keep = ui.verbose and ['verbose'] or []
3546 keep = ui.verbose and ['verbose'] or []
3547 text = help.help_(ui, name, **opts)
3547 text = help.help_(ui, name, **opts)
3548
3548
3549 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3549 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3550 if 'verbose' in pruned:
3550 if 'verbose' in pruned:
3551 keep.append('omitted')
3551 keep.append('omitted')
3552 else:
3552 else:
3553 keep.append('notomitted')
3553 keep.append('notomitted')
3554 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3554 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3555 ui.write(formatted)
3555 ui.write(formatted)
3556
3556
3557
3557
3558 @command('identify|id',
3558 @command('identify|id',
3559 [('r', 'rev', '',
3559 [('r', 'rev', '',
3560 _('identify the specified revision'), _('REV')),
3560 _('identify the specified revision'), _('REV')),
3561 ('n', 'num', None, _('show local revision number')),
3561 ('n', 'num', None, _('show local revision number')),
3562 ('i', 'id', None, _('show global revision id')),
3562 ('i', 'id', None, _('show global revision id')),
3563 ('b', 'branch', None, _('show branch')),
3563 ('b', 'branch', None, _('show branch')),
3564 ('t', 'tags', None, _('show tags')),
3564 ('t', 'tags', None, _('show tags')),
3565 ('B', 'bookmarks', None, _('show bookmarks')),
3565 ('B', 'bookmarks', None, _('show bookmarks')),
3566 ] + remoteopts,
3566 ] + remoteopts,
3567 _('[-nibtB] [-r REV] [SOURCE]'))
3567 _('[-nibtB] [-r REV] [SOURCE]'))
3568 def identify(ui, repo, source=None, rev=None,
3568 def identify(ui, repo, source=None, rev=None,
3569 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3569 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3570 """identify the working copy or specified revision
3570 """identify the working copy or specified revision
3571
3571
3572 Print a summary identifying the repository state at REV using one or
3572 Print a summary identifying the repository state at REV using one or
3573 two parent hash identifiers, followed by a "+" if the working
3573 two parent hash identifiers, followed by a "+" if the working
3574 directory has uncommitted changes, the branch name (if not default),
3574 directory has uncommitted changes, the branch name (if not default),
3575 a list of tags, and a list of bookmarks.
3575 a list of tags, and a list of bookmarks.
3576
3576
3577 When REV is not given, print a summary of the current state of the
3577 When REV is not given, print a summary of the current state of the
3578 repository.
3578 repository.
3579
3579
3580 Specifying a path to a repository root or Mercurial bundle will
3580 Specifying a path to a repository root or Mercurial bundle will
3581 cause lookup to operate on that repository/bundle.
3581 cause lookup to operate on that repository/bundle.
3582
3582
3583 .. container:: verbose
3583 .. container:: verbose
3584
3584
3585 Examples:
3585 Examples:
3586
3586
3587 - generate a build identifier for the working directory::
3587 - generate a build identifier for the working directory::
3588
3588
3589 hg id --id > build-id.dat
3589 hg id --id > build-id.dat
3590
3590
3591 - find the revision corresponding to a tag::
3591 - find the revision corresponding to a tag::
3592
3592
3593 hg id -n -r 1.3
3593 hg id -n -r 1.3
3594
3594
3595 - check the most recent revision of a remote repository::
3595 - check the most recent revision of a remote repository::
3596
3596
3597 hg id -r tip http://selenic.com/hg/
3597 hg id -r tip http://selenic.com/hg/
3598
3598
3599 Returns 0 if successful.
3599 Returns 0 if successful.
3600 """
3600 """
3601
3601
3602 if not repo and not source:
3602 if not repo and not source:
3603 raise util.Abort(_("there is no Mercurial repository here "
3603 raise util.Abort(_("there is no Mercurial repository here "
3604 "(.hg not found)"))
3604 "(.hg not found)"))
3605
3605
3606 hexfunc = ui.debugflag and hex or short
3606 hexfunc = ui.debugflag and hex or short
3607 default = not (num or id or branch or tags or bookmarks)
3607 default = not (num or id or branch or tags or bookmarks)
3608 output = []
3608 output = []
3609 revs = []
3609 revs = []
3610
3610
3611 if source:
3611 if source:
3612 source, branches = hg.parseurl(ui.expandpath(source))
3612 source, branches = hg.parseurl(ui.expandpath(source))
3613 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3613 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3614 repo = peer.local()
3614 repo = peer.local()
3615 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3615 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3616
3616
3617 if not repo:
3617 if not repo:
3618 if num or branch or tags:
3618 if num or branch or tags:
3619 raise util.Abort(
3619 raise util.Abort(
3620 _("can't query remote revision number, branch, or tags"))
3620 _("can't query remote revision number, branch, or tags"))
3621 if not rev and revs:
3621 if not rev and revs:
3622 rev = revs[0]
3622 rev = revs[0]
3623 if not rev:
3623 if not rev:
3624 rev = "tip"
3624 rev = "tip"
3625
3625
3626 remoterev = peer.lookup(rev)
3626 remoterev = peer.lookup(rev)
3627 if default or id:
3627 if default or id:
3628 output = [hexfunc(remoterev)]
3628 output = [hexfunc(remoterev)]
3629
3629
3630 def getbms():
3630 def getbms():
3631 bms = []
3631 bms = []
3632
3632
3633 if 'bookmarks' in peer.listkeys('namespaces'):
3633 if 'bookmarks' in peer.listkeys('namespaces'):
3634 hexremoterev = hex(remoterev)
3634 hexremoterev = hex(remoterev)
3635 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3635 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3636 if bmr == hexremoterev]
3636 if bmr == hexremoterev]
3637
3637
3638 return sorted(bms)
3638 return sorted(bms)
3639
3639
3640 if bookmarks:
3640 if bookmarks:
3641 output.extend(getbms())
3641 output.extend(getbms())
3642 elif default and not ui.quiet:
3642 elif default and not ui.quiet:
3643 # multiple bookmarks for a single parent separated by '/'
3643 # multiple bookmarks for a single parent separated by '/'
3644 bm = '/'.join(getbms())
3644 bm = '/'.join(getbms())
3645 if bm:
3645 if bm:
3646 output.append(bm)
3646 output.append(bm)
3647 else:
3647 else:
3648 if not rev:
3648 if not rev:
3649 ctx = repo[None]
3649 ctx = repo[None]
3650 parents = ctx.parents()
3650 parents = ctx.parents()
3651 changed = ""
3651 changed = ""
3652 if default or id or num:
3652 if default or id or num:
3653 if (util.any(repo.status())
3653 if (util.any(repo.status())
3654 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3654 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3655 changed = '+'
3655 changed = '+'
3656 if default or id:
3656 if default or id:
3657 output = ["%s%s" %
3657 output = ["%s%s" %
3658 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3658 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3659 if num:
3659 if num:
3660 output.append("%s%s" %
3660 output.append("%s%s" %
3661 ('+'.join([str(p.rev()) for p in parents]), changed))
3661 ('+'.join([str(p.rev()) for p in parents]), changed))
3662 else:
3662 else:
3663 ctx = scmutil.revsingle(repo, rev)
3663 ctx = scmutil.revsingle(repo, rev)
3664 if default or id:
3664 if default or id:
3665 output = [hexfunc(ctx.node())]
3665 output = [hexfunc(ctx.node())]
3666 if num:
3666 if num:
3667 output.append(str(ctx.rev()))
3667 output.append(str(ctx.rev()))
3668
3668
3669 if default and not ui.quiet:
3669 if default and not ui.quiet:
3670 b = ctx.branch()
3670 b = ctx.branch()
3671 if b != 'default':
3671 if b != 'default':
3672 output.append("(%s)" % b)
3672 output.append("(%s)" % b)
3673
3673
3674 # multiple tags for a single parent separated by '/'
3674 # multiple tags for a single parent separated by '/'
3675 t = '/'.join(ctx.tags())
3675 t = '/'.join(ctx.tags())
3676 if t:
3676 if t:
3677 output.append(t)
3677 output.append(t)
3678
3678
3679 # multiple bookmarks for a single parent separated by '/'
3679 # multiple bookmarks for a single parent separated by '/'
3680 bm = '/'.join(ctx.bookmarks())
3680 bm = '/'.join(ctx.bookmarks())
3681 if bm:
3681 if bm:
3682 output.append(bm)
3682 output.append(bm)
3683 else:
3683 else:
3684 if branch:
3684 if branch:
3685 output.append(ctx.branch())
3685 output.append(ctx.branch())
3686
3686
3687 if tags:
3687 if tags:
3688 output.extend(ctx.tags())
3688 output.extend(ctx.tags())
3689
3689
3690 if bookmarks:
3690 if bookmarks:
3691 output.extend(ctx.bookmarks())
3691 output.extend(ctx.bookmarks())
3692
3692
3693 ui.write("%s\n" % ' '.join(output))
3693 ui.write("%s\n" % ' '.join(output))
3694
3694
3695 @command('import|patch',
3695 @command('import|patch',
3696 [('p', 'strip', 1,
3696 [('p', 'strip', 1,
3697 _('directory strip option for patch. This has the same '
3697 _('directory strip option for patch. This has the same '
3698 'meaning as the corresponding patch option'), _('NUM')),
3698 'meaning as the corresponding patch option'), _('NUM')),
3699 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3699 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3700 ('e', 'edit', False, _('invoke editor on commit messages')),
3700 ('e', 'edit', False, _('invoke editor on commit messages')),
3701 ('f', 'force', None,
3701 ('f', 'force', None,
3702 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3702 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3703 ('', 'no-commit', None,
3703 ('', 'no-commit', None,
3704 _("don't commit, just update the working directory")),
3704 _("don't commit, just update the working directory")),
3705 ('', 'bypass', None,
3705 ('', 'bypass', None,
3706 _("apply patch without touching the working directory")),
3706 _("apply patch without touching the working directory")),
3707 ('', 'exact', None,
3707 ('', 'exact', None,
3708 _('apply patch to the nodes from which it was generated')),
3708 _('apply patch to the nodes from which it was generated')),
3709 ('', 'import-branch', None,
3709 ('', 'import-branch', None,
3710 _('use any branch information in patch (implied by --exact)'))] +
3710 _('use any branch information in patch (implied by --exact)'))] +
3711 commitopts + commitopts2 + similarityopts,
3711 commitopts + commitopts2 + similarityopts,
3712 _('[OPTION]... PATCH...'))
3712 _('[OPTION]... PATCH...'))
3713 def import_(ui, repo, patch1=None, *patches, **opts):
3713 def import_(ui, repo, patch1=None, *patches, **opts):
3714 """import an ordered set of patches
3714 """import an ordered set of patches
3715
3715
3716 Import a list of patches and commit them individually (unless
3716 Import a list of patches and commit them individually (unless
3717 --no-commit is specified).
3717 --no-commit is specified).
3718
3718
3719 Because import first applies changes to the working directory,
3719 Because import first applies changes to the working directory,
3720 import will abort if there are outstanding changes.
3720 import will abort if there are outstanding changes.
3721
3721
3722 You can import a patch straight from a mail message. Even patches
3722 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
3723 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
3724 text/plain or text/x-patch). From and Subject headers of email
3725 message are used as default committer and commit message. All
3725 message are used as default committer and commit message. All
3726 text/plain body parts before first diff are added to commit
3726 text/plain body parts before first diff are added to commit
3727 message.
3727 message.
3728
3728
3729 If the imported patch was generated by :hg:`export`, user and
3729 If the imported patch was generated by :hg:`export`, user and
3730 description from patch override values from message headers and
3730 description from patch override values from message headers and
3731 body. Values given on command line with -m/--message and -u/--user
3731 body. Values given on command line with -m/--message and -u/--user
3732 override these.
3732 override these.
3733
3733
3734 If --exact is specified, import will set the working directory to
3734 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
3735 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
3736 resulting changeset has a different ID than the one recorded in
3737 the patch. This may happen due to character set problems or other
3737 the patch. This may happen due to character set problems or other
3738 deficiencies in the text patch format.
3738 deficiencies in the text patch format.
3739
3739
3740 Use --bypass to apply and commit patches directly to the
3740 Use --bypass to apply and commit patches directly to the
3741 repository, not touching the working directory. Without --exact,
3741 repository, not touching the working directory. Without --exact,
3742 patches will be applied on top of the working directory parent
3742 patches will be applied on top of the working directory parent
3743 revision.
3743 revision.
3744
3744
3745 With -s/--similarity, hg will attempt to discover renames and
3745 With -s/--similarity, hg will attempt to discover renames and
3746 copies in the patch in the same way as :hg:`addremove`.
3746 copies in the patch in the same way as :hg:`addremove`.
3747
3747
3748 To read a patch from standard input, use "-" as the patch name. If
3748 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.
3749 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.
3750 See :hg:`help dates` for a list of formats valid for -d/--date.
3751
3751
3752 .. container:: verbose
3752 .. container:: verbose
3753
3753
3754 Examples:
3754 Examples:
3755
3755
3756 - import a traditional patch from a website and detect renames::
3756 - import a traditional patch from a website and detect renames::
3757
3757
3758 hg import -s 80 http://example.com/bugfix.patch
3758 hg import -s 80 http://example.com/bugfix.patch
3759
3759
3760 - import a changeset from an hgweb server::
3760 - import a changeset from an hgweb server::
3761
3761
3762 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3762 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3763
3763
3764 - import all the patches in an Unix-style mbox::
3764 - import all the patches in an Unix-style mbox::
3765
3765
3766 hg import incoming-patches.mbox
3766 hg import incoming-patches.mbox
3767
3767
3768 - attempt to exactly restore an exported changeset (not always
3768 - attempt to exactly restore an exported changeset (not always
3769 possible)::
3769 possible)::
3770
3770
3771 hg import --exact proposed-fix.patch
3771 hg import --exact proposed-fix.patch
3772
3772
3773 Returns 0 on success.
3773 Returns 0 on success.
3774 """
3774 """
3775
3775
3776 if not patch1:
3776 if not patch1:
3777 raise util.Abort(_('need at least one patch to import'))
3777 raise util.Abort(_('need at least one patch to import'))
3778
3778
3779 patches = (patch1,) + patches
3779 patches = (patch1,) + patches
3780
3780
3781 date = opts.get('date')
3781 date = opts.get('date')
3782 if date:
3782 if date:
3783 opts['date'] = util.parsedate(date)
3783 opts['date'] = util.parsedate(date)
3784
3784
3785 update = not opts.get('bypass')
3785 update = not opts.get('bypass')
3786 if not update and opts.get('no_commit'):
3786 if not update and opts.get('no_commit'):
3787 raise util.Abort(_('cannot use --no-commit with --bypass'))
3787 raise util.Abort(_('cannot use --no-commit with --bypass'))
3788 try:
3788 try:
3789 sim = float(opts.get('similarity') or 0)
3789 sim = float(opts.get('similarity') or 0)
3790 except ValueError:
3790 except ValueError:
3791 raise util.Abort(_('similarity must be a number'))
3791 raise util.Abort(_('similarity must be a number'))
3792 if sim < 0 or sim > 100:
3792 if sim < 0 or sim > 100:
3793 raise util.Abort(_('similarity must be between 0 and 100'))
3793 raise util.Abort(_('similarity must be between 0 and 100'))
3794 if sim and not update:
3794 if sim and not update:
3795 raise util.Abort(_('cannot use --similarity with --bypass'))
3795 raise util.Abort(_('cannot use --similarity with --bypass'))
3796
3796
3797 if update:
3797 if update:
3798 cmdutil.checkunfinished(repo)
3798 cmdutil.checkunfinished(repo)
3799 if (opts.get('exact') or not opts.get('force')) and update:
3799 if (opts.get('exact') or not opts.get('force')) and update:
3800 cmdutil.bailifchanged(repo)
3800 cmdutil.bailifchanged(repo)
3801
3801
3802 base = opts["base"]
3802 base = opts["base"]
3803 wlock = lock = tr = None
3803 wlock = lock = tr = None
3804 msgs = []
3804 msgs = []
3805
3805
3806
3806
3807 try:
3807 try:
3808 try:
3808 try:
3809 wlock = repo.wlock()
3809 wlock = repo.wlock()
3810 if not opts.get('no_commit'):
3810 if not opts.get('no_commit'):
3811 lock = repo.lock()
3811 lock = repo.lock()
3812 tr = repo.transaction('import')
3812 tr = repo.transaction('import')
3813 parents = repo.parents()
3813 parents = repo.parents()
3814 for patchurl in patches:
3814 for patchurl in patches:
3815 if patchurl == '-':
3815 if patchurl == '-':
3816 ui.status(_('applying patch from stdin\n'))
3816 ui.status(_('applying patch from stdin\n'))
3817 patchfile = ui.fin
3817 patchfile = ui.fin
3818 patchurl = 'stdin' # for error message
3818 patchurl = 'stdin' # for error message
3819 else:
3819 else:
3820 patchurl = os.path.join(base, patchurl)
3820 patchurl = os.path.join(base, patchurl)
3821 ui.status(_('applying %s\n') % patchurl)
3821 ui.status(_('applying %s\n') % patchurl)
3822 patchfile = hg.openpath(ui, patchurl)
3822 patchfile = hg.openpath(ui, patchurl)
3823
3823
3824 haspatch = False
3824 haspatch = False
3825 for hunk in patch.split(patchfile):
3825 for hunk in patch.split(patchfile):
3826 (msg, node) = cmdutil.tryimportone(ui, repo, hunk, parents,
3826 (msg, node) = cmdutil.tryimportone(ui, repo, hunk, parents,
3827 opts, msgs, hg.clean)
3827 opts, msgs, hg.clean)
3828 if msg:
3828 if msg:
3829 haspatch = True
3829 haspatch = True
3830 ui.note(msg + '\n')
3830 ui.note(msg + '\n')
3831 if update or opts.get('exact'):
3831 if update or opts.get('exact'):
3832 parents = repo.parents()
3832 parents = repo.parents()
3833 else:
3833 else:
3834 parents = [repo[node]]
3834 parents = [repo[node]]
3835
3835
3836 if not haspatch:
3836 if not haspatch:
3837 raise util.Abort(_('%s: no diffs found') % patchurl)
3837 raise util.Abort(_('%s: no diffs found') % patchurl)
3838
3838
3839 if tr:
3839 if tr:
3840 tr.close()
3840 tr.close()
3841 if msgs:
3841 if msgs:
3842 repo.savecommitmessage('\n* * *\n'.join(msgs))
3842 repo.savecommitmessage('\n* * *\n'.join(msgs))
3843 except: # re-raises
3843 except: # re-raises
3844 # wlock.release() indirectly calls dirstate.write(): since
3844 # wlock.release() indirectly calls dirstate.write(): since
3845 # we're crashing, we do not want to change the working dir
3845 # we're crashing, we do not want to change the working dir
3846 # parent after all, so make sure it writes nothing
3846 # parent after all, so make sure it writes nothing
3847 repo.dirstate.invalidate()
3847 repo.dirstate.invalidate()
3848 raise
3848 raise
3849 finally:
3849 finally:
3850 if tr:
3850 if tr:
3851 tr.release()
3851 tr.release()
3852 release(lock, wlock)
3852 release(lock, wlock)
3853
3853
3854 @command('incoming|in',
3854 @command('incoming|in',
3855 [('f', 'force', None,
3855 [('f', 'force', None,
3856 _('run even if remote repository is unrelated')),
3856 _('run even if remote repository is unrelated')),
3857 ('n', 'newest-first', None, _('show newest record first')),
3857 ('n', 'newest-first', None, _('show newest record first')),
3858 ('', 'bundle', '',
3858 ('', 'bundle', '',
3859 _('file to store the bundles into'), _('FILE')),
3859 _('file to store the bundles into'), _('FILE')),
3860 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3860 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3861 ('B', 'bookmarks', False, _("compare bookmarks")),
3861 ('B', 'bookmarks', False, _("compare bookmarks")),
3862 ('b', 'branch', [],
3862 ('b', 'branch', [],
3863 _('a specific branch you would like to pull'), _('BRANCH')),
3863 _('a specific branch you would like to pull'), _('BRANCH')),
3864 ] + logopts + remoteopts + subrepoopts,
3864 ] + logopts + remoteopts + subrepoopts,
3865 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3865 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3866 def incoming(ui, repo, source="default", **opts):
3866 def incoming(ui, repo, source="default", **opts):
3867 """show new changesets found in source
3867 """show new changesets found in source
3868
3868
3869 Show new changesets found in the specified path/URL or the default
3869 Show new changesets found in the specified path/URL or the default
3870 pull location. These are the changesets that would have been pulled
3870 pull location. These are the changesets that would have been pulled
3871 if a pull at the time you issued this command.
3871 if a pull at the time you issued this command.
3872
3872
3873 For remote repository, using --bundle avoids downloading the
3873 For remote repository, using --bundle avoids downloading the
3874 changesets twice if the incoming is followed by a pull.
3874 changesets twice if the incoming is followed by a pull.
3875
3875
3876 See pull for valid source format details.
3876 See pull for valid source format details.
3877
3877
3878 Returns 0 if there are incoming changes, 1 otherwise.
3878 Returns 0 if there are incoming changes, 1 otherwise.
3879 """
3879 """
3880 if opts.get('graph'):
3880 if opts.get('graph'):
3881 cmdutil.checkunsupportedgraphflags([], opts)
3881 cmdutil.checkunsupportedgraphflags([], opts)
3882 def display(other, chlist, displayer):
3882 def display(other, chlist, displayer):
3883 revdag = cmdutil.graphrevs(other, chlist, opts)
3883 revdag = cmdutil.graphrevs(other, chlist, opts)
3884 showparents = [ctx.node() for ctx in repo[None].parents()]
3884 showparents = [ctx.node() for ctx in repo[None].parents()]
3885 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3885 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3886 graphmod.asciiedges)
3886 graphmod.asciiedges)
3887
3887
3888 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3888 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3889 return 0
3889 return 0
3890
3890
3891 if opts.get('bundle') and opts.get('subrepos'):
3891 if opts.get('bundle') and opts.get('subrepos'):
3892 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3892 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3893
3893
3894 if opts.get('bookmarks'):
3894 if opts.get('bookmarks'):
3895 source, branches = hg.parseurl(ui.expandpath(source),
3895 source, branches = hg.parseurl(ui.expandpath(source),
3896 opts.get('branch'))
3896 opts.get('branch'))
3897 other = hg.peer(repo, opts, source)
3897 other = hg.peer(repo, opts, source)
3898 if 'bookmarks' not in other.listkeys('namespaces'):
3898 if 'bookmarks' not in other.listkeys('namespaces'):
3899 ui.warn(_("remote doesn't support bookmarks\n"))
3899 ui.warn(_("remote doesn't support bookmarks\n"))
3900 return 0
3900 return 0
3901 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3901 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3902 return bookmarks.diff(ui, repo, other)
3902 return bookmarks.diff(ui, repo, other)
3903
3903
3904 repo._subtoppath = ui.expandpath(source)
3904 repo._subtoppath = ui.expandpath(source)
3905 try:
3905 try:
3906 return hg.incoming(ui, repo, source, opts)
3906 return hg.incoming(ui, repo, source, opts)
3907 finally:
3907 finally:
3908 del repo._subtoppath
3908 del repo._subtoppath
3909
3909
3910
3910
3911 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3911 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3912 def init(ui, dest=".", **opts):
3912 def init(ui, dest=".", **opts):
3913 """create a new repository in the given directory
3913 """create a new repository in the given directory
3914
3914
3915 Initialize a new repository in the given directory. If the given
3915 Initialize a new repository in the given directory. If the given
3916 directory does not exist, it will be created.
3916 directory does not exist, it will be created.
3917
3917
3918 If no directory is given, the current directory is used.
3918 If no directory is given, the current directory is used.
3919
3919
3920 It is possible to specify an ``ssh://`` URL as the destination.
3920 It is possible to specify an ``ssh://`` URL as the destination.
3921 See :hg:`help urls` for more information.
3921 See :hg:`help urls` for more information.
3922
3922
3923 Returns 0 on success.
3923 Returns 0 on success.
3924 """
3924 """
3925 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3925 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3926
3926
3927 @command('locate',
3927 @command('locate',
3928 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3928 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3929 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3929 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3930 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3930 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3931 ] + walkopts,
3931 ] + walkopts,
3932 _('[OPTION]... [PATTERN]...'))
3932 _('[OPTION]... [PATTERN]...'))
3933 def locate(ui, repo, *pats, **opts):
3933 def locate(ui, repo, *pats, **opts):
3934 """locate files matching specific patterns
3934 """locate files matching specific patterns
3935
3935
3936 Print files under Mercurial control in the working directory whose
3936 Print files under Mercurial control in the working directory whose
3937 names match the given patterns.
3937 names match the given patterns.
3938
3938
3939 By default, this command searches all directories in the working
3939 By default, this command searches all directories in the working
3940 directory. To search just the current directory and its
3940 directory. To search just the current directory and its
3941 subdirectories, use "--include .".
3941 subdirectories, use "--include .".
3942
3942
3943 If no patterns are given to match, this command prints the names
3943 If no patterns are given to match, this command prints the names
3944 of all files under Mercurial control in the working directory.
3944 of all files under Mercurial control in the working directory.
3945
3945
3946 If you want to feed the output of this command into the "xargs"
3946 If you want to feed the output of this command into the "xargs"
3947 command, use the -0 option to both this command and "xargs". This
3947 command, use the -0 option to both this command and "xargs". This
3948 will avoid the problem of "xargs" treating single filenames that
3948 will avoid the problem of "xargs" treating single filenames that
3949 contain whitespace as multiple filenames.
3949 contain whitespace as multiple filenames.
3950
3950
3951 Returns 0 if a match is found, 1 otherwise.
3951 Returns 0 if a match is found, 1 otherwise.
3952 """
3952 """
3953 end = opts.get('print0') and '\0' or '\n'
3953 end = opts.get('print0') and '\0' or '\n'
3954 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3954 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3955
3955
3956 ret = 1
3956 ret = 1
3957 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3957 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3958 m.bad = lambda x, y: False
3958 m.bad = lambda x, y: False
3959 for abs in repo[rev].walk(m):
3959 for abs in repo[rev].walk(m):
3960 if not rev and abs not in repo.dirstate:
3960 if not rev and abs not in repo.dirstate:
3961 continue
3961 continue
3962 if opts.get('fullpath'):
3962 if opts.get('fullpath'):
3963 ui.write(repo.wjoin(abs), end)
3963 ui.write(repo.wjoin(abs), end)
3964 else:
3964 else:
3965 ui.write(((pats and m.rel(abs)) or abs), end)
3965 ui.write(((pats and m.rel(abs)) or abs), end)
3966 ret = 0
3966 ret = 0
3967
3967
3968 return ret
3968 return ret
3969
3969
3970 @command('^log|history',
3970 @command('^log|history',
3971 [('f', 'follow', None,
3971 [('f', 'follow', None,
3972 _('follow changeset history, or file history across copies and renames')),
3972 _('follow changeset history, or file history across copies and renames')),
3973 ('', 'follow-first', None,
3973 ('', 'follow-first', None,
3974 _('only follow the first parent of merge changesets (DEPRECATED)')),
3974 _('only follow the first parent of merge changesets (DEPRECATED)')),
3975 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3975 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3976 ('C', 'copies', None, _('show copied files')),
3976 ('C', 'copies', None, _('show copied files')),
3977 ('k', 'keyword', [],
3977 ('k', 'keyword', [],
3978 _('do case-insensitive search for a given text'), _('TEXT')),
3978 _('do case-insensitive search for a given text'), _('TEXT')),
3979 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3979 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3980 ('', 'removed', None, _('include revisions where files were removed')),
3980 ('', 'removed', None, _('include revisions where files were removed')),
3981 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3981 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3982 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3982 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3983 ('', 'only-branch', [],
3983 ('', 'only-branch', [],
3984 _('show only changesets within the given named branch (DEPRECATED)'),
3984 _('show only changesets within the given named branch (DEPRECATED)'),
3985 _('BRANCH')),
3985 _('BRANCH')),
3986 ('b', 'branch', [],
3986 ('b', 'branch', [],
3987 _('show changesets within the given named branch'), _('BRANCH')),
3987 _('show changesets within the given named branch'), _('BRANCH')),
3988 ('P', 'prune', [],
3988 ('P', 'prune', [],
3989 _('do not display revision or any of its ancestors'), _('REV')),
3989 _('do not display revision or any of its ancestors'), _('REV')),
3990 ] + logopts + walkopts,
3990 ] + logopts + walkopts,
3991 _('[OPTION]... [FILE]'))
3991 _('[OPTION]... [FILE]'))
3992 def log(ui, repo, *pats, **opts):
3992 def log(ui, repo, *pats, **opts):
3993 """show revision history of entire repository or files
3993 """show revision history of entire repository or files
3994
3994
3995 Print the revision history of the specified files or the entire
3995 Print the revision history of the specified files or the entire
3996 project.
3996 project.
3997
3997
3998 If no revision range is specified, the default is ``tip:0`` unless
3998 If no revision range is specified, the default is ``tip:0`` unless
3999 --follow is set, in which case the working directory parent is
3999 --follow is set, in which case the working directory parent is
4000 used as the starting revision.
4000 used as the starting revision.
4001
4001
4002 File history is shown without following rename or copy history of
4002 File history is shown without following rename or copy history of
4003 files. Use -f/--follow with a filename to follow history across
4003 files. Use -f/--follow with a filename to follow history across
4004 renames and copies. --follow without a filename will only show
4004 renames and copies. --follow without a filename will only show
4005 ancestors or descendants of the starting revision.
4005 ancestors or descendants of the starting revision.
4006
4006
4007 By default this command prints revision number and changeset id,
4007 By default this command prints revision number and changeset id,
4008 tags, non-trivial parents, user, date and time, and a summary for
4008 tags, non-trivial parents, user, date and time, and a summary for
4009 each commit. When the -v/--verbose switch is used, the list of
4009 each commit. When the -v/--verbose switch is used, the list of
4010 changed files and full commit message are shown.
4010 changed files and full commit message are shown.
4011
4011
4012 With --graph the revisions are shown as an ASCII art DAG with the most
4012 With --graph the revisions are shown as an ASCII art DAG with the most
4013 recent changeset at the top.
4013 recent changeset at the top.
4014 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4014 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4015 and '+' represents a fork where the changeset from the lines below is a
4015 and '+' represents a fork where the changeset from the lines below is a
4016 parent of the 'o' merge on the same same line.
4016 parent of the 'o' merge on the same same line.
4017
4017
4018 .. note::
4018 .. note::
4019
4019
4020 log -p/--patch may generate unexpected diff output for merge
4020 log -p/--patch may generate unexpected diff output for merge
4021 changesets, as it will only compare the merge changeset against
4021 changesets, as it will only compare the merge changeset against
4022 its first parent. Also, only files different from BOTH parents
4022 its first parent. Also, only files different from BOTH parents
4023 will appear in files:.
4023 will appear in files:.
4024
4024
4025 .. note::
4025 .. note::
4026
4026
4027 for performance reasons, log FILE may omit duplicate changes
4027 for performance reasons, log FILE may omit duplicate changes
4028 made on branches and will not show deletions. To see all
4028 made on branches and will not show deletions. To see all
4029 changes including duplicates and deletions, use the --removed
4029 changes including duplicates and deletions, use the --removed
4030 switch.
4030 switch.
4031
4031
4032 .. container:: verbose
4032 .. container:: verbose
4033
4033
4034 Some examples:
4034 Some examples:
4035
4035
4036 - changesets with full descriptions and file lists::
4036 - changesets with full descriptions and file lists::
4037
4037
4038 hg log -v
4038 hg log -v
4039
4039
4040 - changesets ancestral to the working directory::
4040 - changesets ancestral to the working directory::
4041
4041
4042 hg log -f
4042 hg log -f
4043
4043
4044 - last 10 commits on the current branch::
4044 - last 10 commits on the current branch::
4045
4045
4046 hg log -l 10 -b .
4046 hg log -l 10 -b .
4047
4047
4048 - changesets showing all modifications of a file, including removals::
4048 - changesets showing all modifications of a file, including removals::
4049
4049
4050 hg log --removed file.c
4050 hg log --removed file.c
4051
4051
4052 - all changesets that touch a directory, with diffs, excluding merges::
4052 - all changesets that touch a directory, with diffs, excluding merges::
4053
4053
4054 hg log -Mp lib/
4054 hg log -Mp lib/
4055
4055
4056 - all revision numbers that match a keyword::
4056 - all revision numbers that match a keyword::
4057
4057
4058 hg log -k bug --template "{rev}\\n"
4058 hg log -k bug --template "{rev}\\n"
4059
4059
4060 - check if a given changeset is included is a tagged release::
4060 - check if a given changeset is included is a tagged release::
4061
4061
4062 hg log -r "a21ccf and ancestor(1.9)"
4062 hg log -r "a21ccf and ancestor(1.9)"
4063
4063
4064 - find all changesets by some user in a date range::
4064 - find all changesets by some user in a date range::
4065
4065
4066 hg log -k alice -d "may 2008 to jul 2008"
4066 hg log -k alice -d "may 2008 to jul 2008"
4067
4067
4068 - summary of all changesets after the last tag::
4068 - summary of all changesets after the last tag::
4069
4069
4070 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4070 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4071
4071
4072 See :hg:`help dates` for a list of formats valid for -d/--date.
4072 See :hg:`help dates` for a list of formats valid for -d/--date.
4073
4073
4074 See :hg:`help revisions` and :hg:`help revsets` for more about
4074 See :hg:`help revisions` and :hg:`help revsets` for more about
4075 specifying revisions.
4075 specifying revisions.
4076
4076
4077 See :hg:`help templates` for more about pre-packaged styles and
4077 See :hg:`help templates` for more about pre-packaged styles and
4078 specifying custom templates.
4078 specifying custom templates.
4079
4079
4080 Returns 0 on success.
4080 Returns 0 on success.
4081 """
4081 """
4082 if opts.get('graph'):
4082 if opts.get('graph'):
4083 return cmdutil.graphlog(ui, repo, *pats, **opts)
4083 return cmdutil.graphlog(ui, repo, *pats, **opts)
4084
4084
4085 matchfn = scmutil.match(repo[None], pats, opts)
4085 matchfn = scmutil.match(repo[None], pats, opts)
4086 limit = cmdutil.loglimit(opts)
4086 limit = cmdutil.loglimit(opts)
4087 count = 0
4087 count = 0
4088
4088
4089 getrenamed, endrev = None, None
4089 getrenamed, endrev = None, None
4090 if opts.get('copies'):
4090 if opts.get('copies'):
4091 if opts.get('rev'):
4091 if opts.get('rev'):
4092 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4092 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
4093 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4093 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4094
4094
4095 df = False
4095 df = False
4096 if opts.get("date"):
4096 if opts.get("date"):
4097 df = util.matchdate(opts["date"])
4097 df = util.matchdate(opts["date"])
4098
4098
4099 branches = opts.get('branch', []) + opts.get('only_branch', [])
4099 branches = opts.get('branch', []) + opts.get('only_branch', [])
4100 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4100 opts['branch'] = [repo.lookupbranch(b) for b in branches]
4101
4101
4102 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4102 displayer = cmdutil.show_changeset(ui, repo, opts, True)
4103 def prep(ctx, fns):
4103 def prep(ctx, fns):
4104 rev = ctx.rev()
4104 rev = ctx.rev()
4105 parents = [p for p in repo.changelog.parentrevs(rev)
4105 parents = [p for p in repo.changelog.parentrevs(rev)
4106 if p != nullrev]
4106 if p != nullrev]
4107 if opts.get('no_merges') and len(parents) == 2:
4107 if opts.get('no_merges') and len(parents) == 2:
4108 return
4108 return
4109 if opts.get('only_merges') and len(parents) != 2:
4109 if opts.get('only_merges') and len(parents) != 2:
4110 return
4110 return
4111 if opts.get('branch') and ctx.branch() not in opts['branch']:
4111 if opts.get('branch') and ctx.branch() not in opts['branch']:
4112 return
4112 return
4113 if df and not df(ctx.date()[0]):
4113 if df and not df(ctx.date()[0]):
4114 return
4114 return
4115
4115
4116 lower = encoding.lower
4116 lower = encoding.lower
4117 if opts.get('user'):
4117 if opts.get('user'):
4118 luser = lower(ctx.user())
4118 luser = lower(ctx.user())
4119 for k in [lower(x) for x in opts['user']]:
4119 for k in [lower(x) for x in opts['user']]:
4120 if (k in luser):
4120 if (k in luser):
4121 break
4121 break
4122 else:
4122 else:
4123 return
4123 return
4124 if opts.get('keyword'):
4124 if opts.get('keyword'):
4125 luser = lower(ctx.user())
4125 luser = lower(ctx.user())
4126 ldesc = lower(ctx.description())
4126 ldesc = lower(ctx.description())
4127 lfiles = lower(" ".join(ctx.files()))
4127 lfiles = lower(" ".join(ctx.files()))
4128 for k in [lower(x) for x in opts['keyword']]:
4128 for k in [lower(x) for x in opts['keyword']]:
4129 if (k in luser or k in ldesc or k in lfiles):
4129 if (k in luser or k in ldesc or k in lfiles):
4130 break
4130 break
4131 else:
4131 else:
4132 return
4132 return
4133
4133
4134 copies = None
4134 copies = None
4135 if getrenamed is not None and rev:
4135 if getrenamed is not None and rev:
4136 copies = []
4136 copies = []
4137 for fn in ctx.files():
4137 for fn in ctx.files():
4138 rename = getrenamed(fn, rev)
4138 rename = getrenamed(fn, rev)
4139 if rename:
4139 if rename:
4140 copies.append((fn, rename[0]))
4140 copies.append((fn, rename[0]))
4141
4141
4142 revmatchfn = None
4142 revmatchfn = None
4143 if opts.get('patch') or opts.get('stat'):
4143 if opts.get('patch') or opts.get('stat'):
4144 if opts.get('follow') or opts.get('follow_first'):
4144 if opts.get('follow') or opts.get('follow_first'):
4145 # note: this might be wrong when following through merges
4145 # note: this might be wrong when following through merges
4146 revmatchfn = scmutil.match(repo[None], fns, default='path')
4146 revmatchfn = scmutil.match(repo[None], fns, default='path')
4147 else:
4147 else:
4148 revmatchfn = matchfn
4148 revmatchfn = matchfn
4149
4149
4150 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4150 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4151
4151
4152 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4152 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
4153 if displayer.flush(ctx.rev()):
4153 if displayer.flush(ctx.rev()):
4154 count += 1
4154 count += 1
4155 if count == limit:
4155 if count == limit:
4156 break
4156 break
4157 displayer.close()
4157 displayer.close()
4158
4158
4159 @command('manifest',
4159 @command('manifest',
4160 [('r', 'rev', '', _('revision to display'), _('REV')),
4160 [('r', 'rev', '', _('revision to display'), _('REV')),
4161 ('', 'all', False, _("list files from all revisions"))],
4161 ('', 'all', False, _("list files from all revisions"))],
4162 _('[-r REV]'))
4162 _('[-r REV]'))
4163 def manifest(ui, repo, node=None, rev=None, **opts):
4163 def manifest(ui, repo, node=None, rev=None, **opts):
4164 """output the current or given revision of the project manifest
4164 """output the current or given revision of the project manifest
4165
4165
4166 Print a list of version controlled files for the given revision.
4166 Print a list of version controlled files for the given revision.
4167 If no revision is given, the first parent of the working directory
4167 If no revision is given, the first parent of the working directory
4168 is used, or the null revision if no revision is checked out.
4168 is used, or the null revision if no revision is checked out.
4169
4169
4170 With -v, print file permissions, symlink and executable bits.
4170 With -v, print file permissions, symlink and executable bits.
4171 With --debug, print file revision hashes.
4171 With --debug, print file revision hashes.
4172
4172
4173 If option --all is specified, the list of all files from all revisions
4173 If option --all is specified, the list of all files from all revisions
4174 is printed. This includes deleted and renamed files.
4174 is printed. This includes deleted and renamed files.
4175
4175
4176 Returns 0 on success.
4176 Returns 0 on success.
4177 """
4177 """
4178
4178
4179 fm = ui.formatter('manifest', opts)
4179 fm = ui.formatter('manifest', opts)
4180
4180
4181 if opts.get('all'):
4181 if opts.get('all'):
4182 if rev or node:
4182 if rev or node:
4183 raise util.Abort(_("can't specify a revision with --all"))
4183 raise util.Abort(_("can't specify a revision with --all"))
4184
4184
4185 res = []
4185 res = []
4186 prefix = "data/"
4186 prefix = "data/"
4187 suffix = ".i"
4187 suffix = ".i"
4188 plen = len(prefix)
4188 plen = len(prefix)
4189 slen = len(suffix)
4189 slen = len(suffix)
4190 lock = repo.lock()
4190 lock = repo.lock()
4191 try:
4191 try:
4192 for fn, b, size in repo.store.datafiles():
4192 for fn, b, size in repo.store.datafiles():
4193 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4193 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4194 res.append(fn[plen:-slen])
4194 res.append(fn[plen:-slen])
4195 finally:
4195 finally:
4196 lock.release()
4196 lock.release()
4197 for f in res:
4197 for f in res:
4198 fm.startitem()
4198 fm.startitem()
4199 fm.write("path", '%s\n', f)
4199 fm.write("path", '%s\n', f)
4200 fm.end()
4200 fm.end()
4201 return
4201 return
4202
4202
4203 if rev and node:
4203 if rev and node:
4204 raise util.Abort(_("please specify just one revision"))
4204 raise util.Abort(_("please specify just one revision"))
4205
4205
4206 if not node:
4206 if not node:
4207 node = rev
4207 node = rev
4208
4208
4209 char = {'l': '@', 'x': '*', '': ''}
4209 char = {'l': '@', 'x': '*', '': ''}
4210 mode = {'l': '644', 'x': '755', '': '644'}
4210 mode = {'l': '644', 'x': '755', '': '644'}
4211 ctx = scmutil.revsingle(repo, node)
4211 ctx = scmutil.revsingle(repo, node)
4212 mf = ctx.manifest()
4212 mf = ctx.manifest()
4213 for f in ctx:
4213 for f in ctx:
4214 fm.startitem()
4214 fm.startitem()
4215 fl = ctx[f].flags()
4215 fl = ctx[f].flags()
4216 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4216 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4217 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4217 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4218 fm.write('path', '%s\n', f)
4218 fm.write('path', '%s\n', f)
4219 fm.end()
4219 fm.end()
4220
4220
4221 @command('^merge',
4221 @command('^merge',
4222 [('f', 'force', None,
4222 [('f', 'force', None,
4223 _('force a merge including outstanding changes (DEPRECATED)')),
4223 _('force a merge including outstanding changes (DEPRECATED)')),
4224 ('r', 'rev', '', _('revision to merge'), _('REV')),
4224 ('r', 'rev', '', _('revision to merge'), _('REV')),
4225 ('P', 'preview', None,
4225 ('P', 'preview', None,
4226 _('review revisions to merge (no merge is performed)'))
4226 _('review revisions to merge (no merge is performed)'))
4227 ] + mergetoolopts,
4227 ] + mergetoolopts,
4228 _('[-P] [-f] [[-r] REV]'))
4228 _('[-P] [-f] [[-r] REV]'))
4229 def merge(ui, repo, node=None, **opts):
4229 def merge(ui, repo, node=None, **opts):
4230 """merge working directory with another revision
4230 """merge working directory with another revision
4231
4231
4232 The current working directory is updated with all changes made in
4232 The current working directory is updated with all changes made in
4233 the requested revision since the last common predecessor revision.
4233 the requested revision since the last common predecessor revision.
4234
4234
4235 Files that changed between either parent are marked as changed for
4235 Files that changed between either parent are marked as changed for
4236 the next commit and a commit must be performed before any further
4236 the next commit and a commit must be performed before any further
4237 updates to the repository are allowed. The next commit will have
4237 updates to the repository are allowed. The next commit will have
4238 two parents.
4238 two parents.
4239
4239
4240 ``--tool`` can be used to specify the merge tool used for file
4240 ``--tool`` can be used to specify the merge tool used for file
4241 merges. It overrides the HGMERGE environment variable and your
4241 merges. It overrides the HGMERGE environment variable and your
4242 configuration files. See :hg:`help merge-tools` for options.
4242 configuration files. See :hg:`help merge-tools` for options.
4243
4243
4244 If no revision is specified, the working directory's parent is a
4244 If no revision is specified, the working directory's parent is a
4245 head revision, and the current branch contains exactly one other
4245 head revision, and the current branch contains exactly one other
4246 head, the other head is merged with by default. Otherwise, an
4246 head, the other head is merged with by default. Otherwise, an
4247 explicit revision with which to merge with must be provided.
4247 explicit revision with which to merge with must be provided.
4248
4248
4249 :hg:`resolve` must be used to resolve unresolved files.
4249 :hg:`resolve` must be used to resolve unresolved files.
4250
4250
4251 To undo an uncommitted merge, use :hg:`update --clean .` which
4251 To undo an uncommitted merge, use :hg:`update --clean .` which
4252 will check out a clean copy of the original merge parent, losing
4252 will check out a clean copy of the original merge parent, losing
4253 all changes.
4253 all changes.
4254
4254
4255 Returns 0 on success, 1 if there are unresolved files.
4255 Returns 0 on success, 1 if there are unresolved files.
4256 """
4256 """
4257
4257
4258 if opts.get('rev') and node:
4258 if opts.get('rev') and node:
4259 raise util.Abort(_("please specify just one revision"))
4259 raise util.Abort(_("please specify just one revision"))
4260 if not node:
4260 if not node:
4261 node = opts.get('rev')
4261 node = opts.get('rev')
4262
4262
4263 if node:
4263 if node:
4264 node = scmutil.revsingle(repo, node).node()
4264 node = scmutil.revsingle(repo, node).node()
4265
4265
4266 if not node and repo._bookmarkcurrent:
4266 if not node and repo._bookmarkcurrent:
4267 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4267 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4268 curhead = repo[repo._bookmarkcurrent].node()
4268 curhead = repo[repo._bookmarkcurrent].node()
4269 if len(bmheads) == 2:
4269 if len(bmheads) == 2:
4270 if curhead == bmheads[0]:
4270 if curhead == bmheads[0]:
4271 node = bmheads[1]
4271 node = bmheads[1]
4272 else:
4272 else:
4273 node = bmheads[0]
4273 node = bmheads[0]
4274 elif len(bmheads) > 2:
4274 elif len(bmheads) > 2:
4275 raise util.Abort(_("multiple matching bookmarks to merge - "
4275 raise util.Abort(_("multiple matching bookmarks to merge - "
4276 "please merge with an explicit rev or bookmark"),
4276 "please merge with an explicit rev or bookmark"),
4277 hint=_("run 'hg heads' to see all heads"))
4277 hint=_("run 'hg heads' to see all heads"))
4278 elif len(bmheads) <= 1:
4278 elif len(bmheads) <= 1:
4279 raise util.Abort(_("no matching bookmark to merge - "
4279 raise util.Abort(_("no matching bookmark to merge - "
4280 "please merge with an explicit rev or bookmark"),
4280 "please merge with an explicit rev or bookmark"),
4281 hint=_("run 'hg heads' to see all heads"))
4281 hint=_("run 'hg heads' to see all heads"))
4282
4282
4283 if not node and not repo._bookmarkcurrent:
4283 if not node and not repo._bookmarkcurrent:
4284 branch = repo[None].branch()
4284 branch = repo[None].branch()
4285 bheads = repo.branchheads(branch)
4285 bheads = repo.branchheads(branch)
4286 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4286 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4287
4287
4288 if len(nbhs) > 2:
4288 if len(nbhs) > 2:
4289 raise util.Abort(_("branch '%s' has %d heads - "
4289 raise util.Abort(_("branch '%s' has %d heads - "
4290 "please merge with an explicit rev")
4290 "please merge with an explicit rev")
4291 % (branch, len(bheads)),
4291 % (branch, len(bheads)),
4292 hint=_("run 'hg heads .' to see heads"))
4292 hint=_("run 'hg heads .' to see heads"))
4293
4293
4294 parent = repo.dirstate.p1()
4294 parent = repo.dirstate.p1()
4295 if len(nbhs) <= 1:
4295 if len(nbhs) <= 1:
4296 if len(bheads) > 1:
4296 if len(bheads) > 1:
4297 raise util.Abort(_("heads are bookmarked - "
4297 raise util.Abort(_("heads are bookmarked - "
4298 "please merge with an explicit rev"),
4298 "please merge with an explicit rev"),
4299 hint=_("run 'hg heads' to see all heads"))
4299 hint=_("run 'hg heads' to see all heads"))
4300 if len(repo.heads()) > 1:
4300 if len(repo.heads()) > 1:
4301 raise util.Abort(_("branch '%s' has one head - "
4301 raise util.Abort(_("branch '%s' has one head - "
4302 "please merge with an explicit rev")
4302 "please merge with an explicit rev")
4303 % branch,
4303 % branch,
4304 hint=_("run 'hg heads' to see all heads"))
4304 hint=_("run 'hg heads' to see all heads"))
4305 msg, hint = _('nothing to merge'), None
4305 msg, hint = _('nothing to merge'), None
4306 if parent != repo.lookup(branch):
4306 if parent != repo.lookup(branch):
4307 hint = _("use 'hg update' instead")
4307 hint = _("use 'hg update' instead")
4308 raise util.Abort(msg, hint=hint)
4308 raise util.Abort(msg, hint=hint)
4309
4309
4310 if parent not in bheads:
4310 if parent not in bheads:
4311 raise util.Abort(_('working directory not at a head revision'),
4311 raise util.Abort(_('working directory not at a head revision'),
4312 hint=_("use 'hg update' or merge with an "
4312 hint=_("use 'hg update' or merge with an "
4313 "explicit revision"))
4313 "explicit revision"))
4314 if parent == nbhs[0]:
4314 if parent == nbhs[0]:
4315 node = nbhs[-1]
4315 node = nbhs[-1]
4316 else:
4316 else:
4317 node = nbhs[0]
4317 node = nbhs[0]
4318
4318
4319 if opts.get('preview'):
4319 if opts.get('preview'):
4320 # find nodes that are ancestors of p2 but not of p1
4320 # find nodes that are ancestors of p2 but not of p1
4321 p1 = repo.lookup('.')
4321 p1 = repo.lookup('.')
4322 p2 = repo.lookup(node)
4322 p2 = repo.lookup(node)
4323 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4323 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4324
4324
4325 displayer = cmdutil.show_changeset(ui, repo, opts)
4325 displayer = cmdutil.show_changeset(ui, repo, opts)
4326 for node in nodes:
4326 for node in nodes:
4327 displayer.show(repo[node])
4327 displayer.show(repo[node])
4328 displayer.close()
4328 displayer.close()
4329 return 0
4329 return 0
4330
4330
4331 try:
4331 try:
4332 # ui.forcemerge is an internal variable, do not document
4332 # ui.forcemerge is an internal variable, do not document
4333 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4333 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4334 return hg.merge(repo, node, force=opts.get('force'))
4334 return hg.merge(repo, node, force=opts.get('force'))
4335 finally:
4335 finally:
4336 ui.setconfig('ui', 'forcemerge', '', 'merge')
4336 ui.setconfig('ui', 'forcemerge', '', 'merge')
4337
4337
4338 @command('outgoing|out',
4338 @command('outgoing|out',
4339 [('f', 'force', None, _('run even when the destination is unrelated')),
4339 [('f', 'force', None, _('run even when the destination is unrelated')),
4340 ('r', 'rev', [],
4340 ('r', 'rev', [],
4341 _('a changeset intended to be included in the destination'), _('REV')),
4341 _('a changeset intended to be included in the destination'), _('REV')),
4342 ('n', 'newest-first', None, _('show newest record first')),
4342 ('n', 'newest-first', None, _('show newest record first')),
4343 ('B', 'bookmarks', False, _('compare bookmarks')),
4343 ('B', 'bookmarks', False, _('compare bookmarks')),
4344 ('b', 'branch', [], _('a specific branch you would like to push'),
4344 ('b', 'branch', [], _('a specific branch you would like to push'),
4345 _('BRANCH')),
4345 _('BRANCH')),
4346 ] + logopts + remoteopts + subrepoopts,
4346 ] + logopts + remoteopts + subrepoopts,
4347 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4347 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4348 def outgoing(ui, repo, dest=None, **opts):
4348 def outgoing(ui, repo, dest=None, **opts):
4349 """show changesets not found in the destination
4349 """show changesets not found in the destination
4350
4350
4351 Show changesets not found in the specified destination repository
4351 Show changesets not found in the specified destination repository
4352 or the default push location. These are the changesets that would
4352 or the default push location. These are the changesets that would
4353 be pushed if a push was requested.
4353 be pushed if a push was requested.
4354
4354
4355 See pull for details of valid destination formats.
4355 See pull for details of valid destination formats.
4356
4356
4357 Returns 0 if there are outgoing changes, 1 otherwise.
4357 Returns 0 if there are outgoing changes, 1 otherwise.
4358 """
4358 """
4359 if opts.get('graph'):
4359 if opts.get('graph'):
4360 cmdutil.checkunsupportedgraphflags([], opts)
4360 cmdutil.checkunsupportedgraphflags([], opts)
4361 o = hg._outgoing(ui, repo, dest, opts)
4361 o = hg._outgoing(ui, repo, dest, opts)
4362 if o is None:
4362 if o is None:
4363 return
4363 return
4364
4364
4365 revdag = cmdutil.graphrevs(repo, o, opts)
4365 revdag = cmdutil.graphrevs(repo, o, opts)
4366 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4366 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4367 showparents = [ctx.node() for ctx in repo[None].parents()]
4367 showparents = [ctx.node() for ctx in repo[None].parents()]
4368 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4368 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4369 graphmod.asciiedges)
4369 graphmod.asciiedges)
4370 return 0
4370 return 0
4371
4371
4372 if opts.get('bookmarks'):
4372 if opts.get('bookmarks'):
4373 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4373 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4374 dest, branches = hg.parseurl(dest, opts.get('branch'))
4374 dest, branches = hg.parseurl(dest, opts.get('branch'))
4375 other = hg.peer(repo, opts, dest)
4375 other = hg.peer(repo, opts, dest)
4376 if 'bookmarks' not in other.listkeys('namespaces'):
4376 if 'bookmarks' not in other.listkeys('namespaces'):
4377 ui.warn(_("remote doesn't support bookmarks\n"))
4377 ui.warn(_("remote doesn't support bookmarks\n"))
4378 return 0
4378 return 0
4379 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4379 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4380 return bookmarks.diff(ui, other, repo)
4380 return bookmarks.diff(ui, other, repo)
4381
4381
4382 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4382 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4383 try:
4383 try:
4384 return hg.outgoing(ui, repo, dest, opts)
4384 return hg.outgoing(ui, repo, dest, opts)
4385 finally:
4385 finally:
4386 del repo._subtoppath
4386 del repo._subtoppath
4387
4387
4388 @command('parents',
4388 @command('parents',
4389 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4389 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4390 ] + templateopts,
4390 ] + templateopts,
4391 _('[-r REV] [FILE]'))
4391 _('[-r REV] [FILE]'))
4392 def parents(ui, repo, file_=None, **opts):
4392 def parents(ui, repo, file_=None, **opts):
4393 """show the parents of the working directory or revision
4393 """show the parents of the working directory or revision
4394
4394
4395 Print the working directory's parent revisions. If a revision is
4395 Print the working directory's parent revisions. If a revision is
4396 given via -r/--rev, the parent of that revision will be printed.
4396 given via -r/--rev, the parent of that revision will be printed.
4397 If a file argument is given, the revision in which the file was
4397 If a file argument is given, the revision in which the file was
4398 last changed (before the working directory revision or the
4398 last changed (before the working directory revision or the
4399 argument to --rev if given) is printed.
4399 argument to --rev if given) is printed.
4400
4400
4401 Returns 0 on success.
4401 Returns 0 on success.
4402 """
4402 """
4403
4403
4404 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4404 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4405
4405
4406 if file_:
4406 if file_:
4407 m = scmutil.match(ctx, (file_,), opts)
4407 m = scmutil.match(ctx, (file_,), opts)
4408 if m.anypats() or len(m.files()) != 1:
4408 if m.anypats() or len(m.files()) != 1:
4409 raise util.Abort(_('can only specify an explicit filename'))
4409 raise util.Abort(_('can only specify an explicit filename'))
4410 file_ = m.files()[0]
4410 file_ = m.files()[0]
4411 filenodes = []
4411 filenodes = []
4412 for cp in ctx.parents():
4412 for cp in ctx.parents():
4413 if not cp:
4413 if not cp:
4414 continue
4414 continue
4415 try:
4415 try:
4416 filenodes.append(cp.filenode(file_))
4416 filenodes.append(cp.filenode(file_))
4417 except error.LookupError:
4417 except error.LookupError:
4418 pass
4418 pass
4419 if not filenodes:
4419 if not filenodes:
4420 raise util.Abort(_("'%s' not found in manifest!") % file_)
4420 raise util.Abort(_("'%s' not found in manifest!") % file_)
4421 p = []
4421 p = []
4422 for fn in filenodes:
4422 for fn in filenodes:
4423 fctx = repo.filectx(file_, fileid=fn)
4423 fctx = repo.filectx(file_, fileid=fn)
4424 p.append(fctx.node())
4424 p.append(fctx.node())
4425 else:
4425 else:
4426 p = [cp.node() for cp in ctx.parents()]
4426 p = [cp.node() for cp in ctx.parents()]
4427
4427
4428 displayer = cmdutil.show_changeset(ui, repo, opts)
4428 displayer = cmdutil.show_changeset(ui, repo, opts)
4429 for n in p:
4429 for n in p:
4430 if n != nullid:
4430 if n != nullid:
4431 displayer.show(repo[n])
4431 displayer.show(repo[n])
4432 displayer.close()
4432 displayer.close()
4433
4433
4434 @command('paths', [], _('[NAME]'))
4434 @command('paths', [], _('[NAME]'))
4435 def paths(ui, repo, search=None):
4435 def paths(ui, repo, search=None):
4436 """show aliases for remote repositories
4436 """show aliases for remote repositories
4437
4437
4438 Show definition of symbolic path name NAME. If no name is given,
4438 Show definition of symbolic path name NAME. If no name is given,
4439 show definition of all available names.
4439 show definition of all available names.
4440
4440
4441 Option -q/--quiet suppresses all output when searching for NAME
4441 Option -q/--quiet suppresses all output when searching for NAME
4442 and shows only the path names when listing all definitions.
4442 and shows only the path names when listing all definitions.
4443
4443
4444 Path names are defined in the [paths] section of your
4444 Path names are defined in the [paths] section of your
4445 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4445 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4446 repository, ``.hg/hgrc`` is used, too.
4446 repository, ``.hg/hgrc`` is used, too.
4447
4447
4448 The path names ``default`` and ``default-push`` have a special
4448 The path names ``default`` and ``default-push`` have a special
4449 meaning. When performing a push or pull operation, they are used
4449 meaning. When performing a push or pull operation, they are used
4450 as fallbacks if no location is specified on the command-line.
4450 as fallbacks if no location is specified on the command-line.
4451 When ``default-push`` is set, it will be used for push and
4451 When ``default-push`` is set, it will be used for push and
4452 ``default`` will be used for pull; otherwise ``default`` is used
4452 ``default`` will be used for pull; otherwise ``default`` is used
4453 as the fallback for both. When cloning a repository, the clone
4453 as the fallback for both. When cloning a repository, the clone
4454 source is written as ``default`` in ``.hg/hgrc``. Note that
4454 source is written as ``default`` in ``.hg/hgrc``. Note that
4455 ``default`` and ``default-push`` apply to all inbound (e.g.
4455 ``default`` and ``default-push`` apply to all inbound (e.g.
4456 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4456 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4457 :hg:`bundle`) operations.
4457 :hg:`bundle`) operations.
4458
4458
4459 See :hg:`help urls` for more information.
4459 See :hg:`help urls` for more information.
4460
4460
4461 Returns 0 on success.
4461 Returns 0 on success.
4462 """
4462 """
4463 if search:
4463 if search:
4464 for name, path in ui.configitems("paths"):
4464 for name, path in ui.configitems("paths"):
4465 if name == search:
4465 if name == search:
4466 ui.status("%s\n" % util.hidepassword(path))
4466 ui.status("%s\n" % util.hidepassword(path))
4467 return
4467 return
4468 if not ui.quiet:
4468 if not ui.quiet:
4469 ui.warn(_("not found!\n"))
4469 ui.warn(_("not found!\n"))
4470 return 1
4470 return 1
4471 else:
4471 else:
4472 for name, path in ui.configitems("paths"):
4472 for name, path in ui.configitems("paths"):
4473 if ui.quiet:
4473 if ui.quiet:
4474 ui.write("%s\n" % name)
4474 ui.write("%s\n" % name)
4475 else:
4475 else:
4476 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4476 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4477
4477
4478 @command('phase',
4478 @command('phase',
4479 [('p', 'public', False, _('set changeset phase to public')),
4479 [('p', 'public', False, _('set changeset phase to public')),
4480 ('d', 'draft', False, _('set changeset phase to draft')),
4480 ('d', 'draft', False, _('set changeset phase to draft')),
4481 ('s', 'secret', False, _('set changeset phase to secret')),
4481 ('s', 'secret', False, _('set changeset phase to secret')),
4482 ('f', 'force', False, _('allow to move boundary backward')),
4482 ('f', 'force', False, _('allow to move boundary backward')),
4483 ('r', 'rev', [], _('target revision'), _('REV')),
4483 ('r', 'rev', [], _('target revision'), _('REV')),
4484 ],
4484 ],
4485 _('[-p|-d|-s] [-f] [-r] REV...'))
4485 _('[-p|-d|-s] [-f] [-r] REV...'))
4486 def phase(ui, repo, *revs, **opts):
4486 def phase(ui, repo, *revs, **opts):
4487 """set or show the current phase name
4487 """set or show the current phase name
4488
4488
4489 With no argument, show the phase name of specified revisions.
4489 With no argument, show the phase name of specified revisions.
4490
4490
4491 With one of -p/--public, -d/--draft or -s/--secret, change the
4491 With one of -p/--public, -d/--draft or -s/--secret, change the
4492 phase value of the specified revisions.
4492 phase value of the specified revisions.
4493
4493
4494 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4494 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4495 lower phase to an higher phase. Phases are ordered as follows::
4495 lower phase to an higher phase. Phases are ordered as follows::
4496
4496
4497 public < draft < secret
4497 public < draft < secret
4498
4498
4499 Returns 0 on success, 1 if no phases were changed or some could not
4499 Returns 0 on success, 1 if no phases were changed or some could not
4500 be changed.
4500 be changed.
4501 """
4501 """
4502 # search for a unique phase argument
4502 # search for a unique phase argument
4503 targetphase = None
4503 targetphase = None
4504 for idx, name in enumerate(phases.phasenames):
4504 for idx, name in enumerate(phases.phasenames):
4505 if opts[name]:
4505 if opts[name]:
4506 if targetphase is not None:
4506 if targetphase is not None:
4507 raise util.Abort(_('only one phase can be specified'))
4507 raise util.Abort(_('only one phase can be specified'))
4508 targetphase = idx
4508 targetphase = idx
4509
4509
4510 # look for specified revision
4510 # look for specified revision
4511 revs = list(revs)
4511 revs = list(revs)
4512 revs.extend(opts['rev'])
4512 revs.extend(opts['rev'])
4513 if not revs:
4513 if not revs:
4514 raise util.Abort(_('no revisions specified'))
4514 raise util.Abort(_('no revisions specified'))
4515
4515
4516 revs = scmutil.revrange(repo, revs)
4516 revs = scmutil.revrange(repo, revs)
4517
4517
4518 lock = None
4518 lock = None
4519 ret = 0
4519 ret = 0
4520 if targetphase is None:
4520 if targetphase is None:
4521 # display
4521 # display
4522 for r in revs:
4522 for r in revs:
4523 ctx = repo[r]
4523 ctx = repo[r]
4524 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4524 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4525 else:
4525 else:
4526 lock = repo.lock()
4526 lock = repo.lock()
4527 try:
4527 try:
4528 # set phase
4528 # set phase
4529 if not revs:
4529 if not revs:
4530 raise util.Abort(_('empty revision set'))
4530 raise util.Abort(_('empty revision set'))
4531 nodes = [repo[r].node() for r in revs]
4531 nodes = [repo[r].node() for r in revs]
4532 olddata = repo._phasecache.getphaserevs(repo)[:]
4532 olddata = repo._phasecache.getphaserevs(repo)[:]
4533 phases.advanceboundary(repo, targetphase, nodes)
4533 phases.advanceboundary(repo, targetphase, nodes)
4534 if opts['force']:
4534 if opts['force']:
4535 phases.retractboundary(repo, targetphase, nodes)
4535 phases.retractboundary(repo, targetphase, nodes)
4536 finally:
4536 finally:
4537 lock.release()
4537 lock.release()
4538 # moving revision from public to draft may hide them
4538 # moving revision from public to draft may hide them
4539 # We have to check result on an unfiltered repository
4539 # We have to check result on an unfiltered repository
4540 unfi = repo.unfiltered()
4540 unfi = repo.unfiltered()
4541 newdata = repo._phasecache.getphaserevs(unfi)
4541 newdata = repo._phasecache.getphaserevs(unfi)
4542 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4542 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4543 cl = unfi.changelog
4543 cl = unfi.changelog
4544 rejected = [n for n in nodes
4544 rejected = [n for n in nodes
4545 if newdata[cl.rev(n)] < targetphase]
4545 if newdata[cl.rev(n)] < targetphase]
4546 if rejected:
4546 if rejected:
4547 ui.warn(_('cannot move %i changesets to a higher '
4547 ui.warn(_('cannot move %i changesets to a higher '
4548 'phase, use --force\n') % len(rejected))
4548 'phase, use --force\n') % len(rejected))
4549 ret = 1
4549 ret = 1
4550 if changes:
4550 if changes:
4551 msg = _('phase changed for %i changesets\n') % changes
4551 msg = _('phase changed for %i changesets\n') % changes
4552 if ret:
4552 if ret:
4553 ui.status(msg)
4553 ui.status(msg)
4554 else:
4554 else:
4555 ui.note(msg)
4555 ui.note(msg)
4556 else:
4556 else:
4557 ui.warn(_('no phases changed\n'))
4557 ui.warn(_('no phases changed\n'))
4558 ret = 1
4558 ret = 1
4559 return ret
4559 return ret
4560
4560
4561 def postincoming(ui, repo, modheads, optupdate, checkout):
4561 def postincoming(ui, repo, modheads, optupdate, checkout):
4562 if modheads == 0:
4562 if modheads == 0:
4563 return
4563 return
4564 if optupdate:
4564 if optupdate:
4565 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4565 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4566 try:
4566 try:
4567 ret = hg.update(repo, checkout)
4567 ret = hg.update(repo, checkout)
4568 except util.Abort, inst:
4568 except util.Abort, inst:
4569 ui.warn(_("not updating: %s\n") % str(inst))
4569 ui.warn(_("not updating: %s\n") % str(inst))
4570 if inst.hint:
4570 if inst.hint:
4571 ui.warn(_("(%s)\n") % inst.hint)
4571 ui.warn(_("(%s)\n") % inst.hint)
4572 return 0
4572 return 0
4573 if not ret and not checkout:
4573 if not ret and not checkout:
4574 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4574 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4575 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4575 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4576 return ret
4576 return ret
4577 if modheads > 1:
4577 if modheads > 1:
4578 currentbranchheads = len(repo.branchheads())
4578 currentbranchheads = len(repo.branchheads())
4579 if currentbranchheads == modheads:
4579 if currentbranchheads == modheads:
4580 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4580 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4581 elif currentbranchheads > 1:
4581 elif currentbranchheads > 1:
4582 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4582 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4583 "merge)\n"))
4583 "merge)\n"))
4584 else:
4584 else:
4585 ui.status(_("(run 'hg heads' to see heads)\n"))
4585 ui.status(_("(run 'hg heads' to see heads)\n"))
4586 else:
4586 else:
4587 ui.status(_("(run 'hg update' to get a working copy)\n"))
4587 ui.status(_("(run 'hg update' to get a working copy)\n"))
4588
4588
4589 @command('^pull',
4589 @command('^pull',
4590 [('u', 'update', None,
4590 [('u', 'update', None,
4591 _('update to new branch head if changesets were pulled')),
4591 _('update to new branch head if changesets were pulled')),
4592 ('f', 'force', None, _('run even when remote repository is unrelated')),
4592 ('f', 'force', None, _('run even when remote repository is unrelated')),
4593 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4593 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4594 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4594 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4595 ('b', 'branch', [], _('a specific branch you would like to pull'),
4595 ('b', 'branch', [], _('a specific branch you would like to pull'),
4596 _('BRANCH')),
4596 _('BRANCH')),
4597 ] + remoteopts,
4597 ] + remoteopts,
4598 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4598 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4599 def pull(ui, repo, source="default", **opts):
4599 def pull(ui, repo, source="default", **opts):
4600 """pull changes from the specified source
4600 """pull changes from the specified source
4601
4601
4602 Pull changes from a remote repository to a local one.
4602 Pull changes from a remote repository to a local one.
4603
4603
4604 This finds all changes from the repository at the specified path
4604 This finds all changes from the repository at the specified path
4605 or URL and adds them to a local repository (the current one unless
4605 or URL and adds them to a local repository (the current one unless
4606 -R is specified). By default, this does not update the copy of the
4606 -R is specified). By default, this does not update the copy of the
4607 project in the working directory.
4607 project in the working directory.
4608
4608
4609 Use :hg:`incoming` if you want to see what would have been added
4609 Use :hg:`incoming` if you want to see what would have been added
4610 by a pull at the time you issued this command. If you then decide
4610 by a pull at the time you issued this command. If you then decide
4611 to add those changes to the repository, you should use :hg:`pull
4611 to add those changes to the repository, you should use :hg:`pull
4612 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4612 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4613
4613
4614 If SOURCE is omitted, the 'default' path will be used.
4614 If SOURCE is omitted, the 'default' path will be used.
4615 See :hg:`help urls` for more information.
4615 See :hg:`help urls` for more information.
4616
4616
4617 Returns 0 on success, 1 if an update had unresolved files.
4617 Returns 0 on success, 1 if an update had unresolved files.
4618 """
4618 """
4619 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4619 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4620 other = hg.peer(repo, opts, source)
4620 other = hg.peer(repo, opts, source)
4621 try:
4621 try:
4622 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4622 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4623 revs, checkout = hg.addbranchrevs(repo, other, branches,
4623 revs, checkout = hg.addbranchrevs(repo, other, branches,
4624 opts.get('rev'))
4624 opts.get('rev'))
4625
4625
4626 remotebookmarks = other.listkeys('bookmarks')
4626 remotebookmarks = other.listkeys('bookmarks')
4627
4627
4628 if opts.get('bookmark'):
4628 if opts.get('bookmark'):
4629 if not revs:
4629 if not revs:
4630 revs = []
4630 revs = []
4631 for b in opts['bookmark']:
4631 for b in opts['bookmark']:
4632 if b not in remotebookmarks:
4632 if b not in remotebookmarks:
4633 raise util.Abort(_('remote bookmark %s not found!') % b)
4633 raise util.Abort(_('remote bookmark %s not found!') % b)
4634 revs.append(remotebookmarks[b])
4634 revs.append(remotebookmarks[b])
4635
4635
4636 if revs:
4636 if revs:
4637 try:
4637 try:
4638 revs = [other.lookup(rev) for rev in revs]
4638 revs = [other.lookup(rev) for rev in revs]
4639 except error.CapabilityError:
4639 except error.CapabilityError:
4640 err = _("other repository doesn't support revision lookup, "
4640 err = _("other repository doesn't support revision lookup, "
4641 "so a rev cannot be specified.")
4641 "so a rev cannot be specified.")
4642 raise util.Abort(err)
4642 raise util.Abort(err)
4643
4643
4644 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4644 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4645 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4645 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4646 if checkout:
4646 if checkout:
4647 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4647 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4648 repo._subtoppath = source
4648 repo._subtoppath = source
4649 try:
4649 try:
4650 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4650 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4651
4651
4652 finally:
4652 finally:
4653 del repo._subtoppath
4653 del repo._subtoppath
4654
4654
4655 # update specified bookmarks
4655 # update specified bookmarks
4656 if opts.get('bookmark'):
4656 if opts.get('bookmark'):
4657 marks = repo._bookmarks
4657 marks = repo._bookmarks
4658 for b in opts['bookmark']:
4658 for b in opts['bookmark']:
4659 # explicit pull overrides local bookmark if any
4659 # explicit pull overrides local bookmark if any
4660 ui.status(_("importing bookmark %s\n") % b)
4660 ui.status(_("importing bookmark %s\n") % b)
4661 marks[b] = repo[remotebookmarks[b]].node()
4661 marks[b] = repo[remotebookmarks[b]].node()
4662 marks.write()
4662 marks.write()
4663 finally:
4663 finally:
4664 other.close()
4664 other.close()
4665 return ret
4665 return ret
4666
4666
4667 @command('^push',
4667 @command('^push',
4668 [('f', 'force', None, _('force push')),
4668 [('f', 'force', None, _('force push')),
4669 ('r', 'rev', [],
4669 ('r', 'rev', [],
4670 _('a changeset intended to be included in the destination'),
4670 _('a changeset intended to be included in the destination'),
4671 _('REV')),
4671 _('REV')),
4672 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4672 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4673 ('b', 'branch', [],
4673 ('b', 'branch', [],
4674 _('a specific branch you would like to push'), _('BRANCH')),
4674 _('a specific branch you would like to push'), _('BRANCH')),
4675 ('', 'new-branch', False, _('allow pushing a new branch')),
4675 ('', 'new-branch', False, _('allow pushing a new branch')),
4676 ] + remoteopts,
4676 ] + remoteopts,
4677 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4677 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4678 def push(ui, repo, dest=None, **opts):
4678 def push(ui, repo, dest=None, **opts):
4679 """push changes to the specified destination
4679 """push changes to the specified destination
4680
4680
4681 Push changesets from the local repository to the specified
4681 Push changesets from the local repository to the specified
4682 destination.
4682 destination.
4683
4683
4684 This operation is symmetrical to pull: it is identical to a pull
4684 This operation is symmetrical to pull: it is identical to a pull
4685 in the destination repository from the current one.
4685 in the destination repository from the current one.
4686
4686
4687 By default, push will not allow creation of new heads at the
4687 By default, push will not allow creation of new heads at the
4688 destination, since multiple heads would make it unclear which head
4688 destination, since multiple heads would make it unclear which head
4689 to use. In this situation, it is recommended to pull and merge
4689 to use. In this situation, it is recommended to pull and merge
4690 before pushing.
4690 before pushing.
4691
4691
4692 Use --new-branch if you want to allow push to create a new named
4692 Use --new-branch if you want to allow push to create a new named
4693 branch that is not present at the destination. This allows you to
4693 branch that is not present at the destination. This allows you to
4694 only create a new branch without forcing other changes.
4694 only create a new branch without forcing other changes.
4695
4695
4696 .. note::
4696 .. note::
4697
4697
4698 Extra care should be taken with the -f/--force option,
4698 Extra care should be taken with the -f/--force option,
4699 which will push all new heads on all branches, an action which will
4699 which will push all new heads on all branches, an action which will
4700 almost always cause confusion for collaborators.
4700 almost always cause confusion for collaborators.
4701
4701
4702 If -r/--rev is used, the specified revision and all its ancestors
4702 If -r/--rev is used, the specified revision and all its ancestors
4703 will be pushed to the remote repository.
4703 will be pushed to the remote repository.
4704
4704
4705 If -B/--bookmark is used, the specified bookmarked revision, its
4705 If -B/--bookmark is used, the specified bookmarked revision, its
4706 ancestors, and the bookmark will be pushed to the remote
4706 ancestors, and the bookmark will be pushed to the remote
4707 repository.
4707 repository.
4708
4708
4709 Please see :hg:`help urls` for important details about ``ssh://``
4709 Please see :hg:`help urls` for important details about ``ssh://``
4710 URLs. If DESTINATION is omitted, a default path will be used.
4710 URLs. If DESTINATION is omitted, a default path will be used.
4711
4711
4712 Returns 0 if push was successful, 1 if nothing to push.
4712 Returns 0 if push was successful, 1 if nothing to push.
4713 """
4713 """
4714
4714
4715 if opts.get('bookmark'):
4715 if opts.get('bookmark'):
4716 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4716 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4717 for b in opts['bookmark']:
4717 for b in opts['bookmark']:
4718 # translate -B options to -r so changesets get pushed
4718 # translate -B options to -r so changesets get pushed
4719 if b in repo._bookmarks:
4719 if b in repo._bookmarks:
4720 opts.setdefault('rev', []).append(b)
4720 opts.setdefault('rev', []).append(b)
4721 else:
4721 else:
4722 # if we try to push a deleted bookmark, translate it to null
4722 # if we try to push a deleted bookmark, translate it to null
4723 # this lets simultaneous -r, -b options continue working
4723 # this lets simultaneous -r, -b options continue working
4724 opts.setdefault('rev', []).append("null")
4724 opts.setdefault('rev', []).append("null")
4725
4725
4726 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4726 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4727 dest, branches = hg.parseurl(dest, opts.get('branch'))
4727 dest, branches = hg.parseurl(dest, opts.get('branch'))
4728 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4728 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4729 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4729 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4730 try:
4730 try:
4731 other = hg.peer(repo, opts, dest)
4731 other = hg.peer(repo, opts, dest)
4732 except error.RepoError:
4732 except error.RepoError:
4733 if dest == "default-push":
4733 if dest == "default-push":
4734 raise util.Abort(_("default repository not configured!"),
4734 raise util.Abort(_("default repository not configured!"),
4735 hint=_('see the "path" section in "hg help config"'))
4735 hint=_('see the "path" section in "hg help config"'))
4736 else:
4736 else:
4737 raise
4737 raise
4738
4738
4739 if revs:
4739 if revs:
4740 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4740 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4741
4741
4742 repo._subtoppath = dest
4742 repo._subtoppath = dest
4743 try:
4743 try:
4744 # push subrepos depth-first for coherent ordering
4744 # push subrepos depth-first for coherent ordering
4745 c = repo['']
4745 c = repo['']
4746 subs = c.substate # only repos that are committed
4746 subs = c.substate # only repos that are committed
4747 for s in sorted(subs):
4747 for s in sorted(subs):
4748 if c.sub(s).push(opts) == 0:
4748 if c.sub(s).push(opts) == 0:
4749 return False
4749 return False
4750 finally:
4750 finally:
4751 del repo._subtoppath
4751 del repo._subtoppath
4752 result = repo.push(other, opts.get('force'), revs=revs,
4752 result = repo.push(other, opts.get('force'), revs=revs,
4753 newbranch=opts.get('new_branch'))
4753 newbranch=opts.get('new_branch'))
4754
4754
4755 result = not result
4755 result = not result
4756
4756
4757 if opts.get('bookmark'):
4757 if opts.get('bookmark'):
4758 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4758 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4759 if bresult == 2:
4759 if bresult == 2:
4760 return 2
4760 return 2
4761 if not result and bresult:
4761 if not result and bresult:
4762 result = 2
4762 result = 2
4763
4763
4764 return result
4764 return result
4765
4765
4766 @command('recover', [])
4766 @command('recover', [])
4767 def recover(ui, repo):
4767 def recover(ui, repo):
4768 """roll back an interrupted transaction
4768 """roll back an interrupted transaction
4769
4769
4770 Recover from an interrupted commit or pull.
4770 Recover from an interrupted commit or pull.
4771
4771
4772 This command tries to fix the repository status after an
4772 This command tries to fix the repository status after an
4773 interrupted operation. It should only be necessary when Mercurial
4773 interrupted operation. It should only be necessary when Mercurial
4774 suggests it.
4774 suggests it.
4775
4775
4776 Returns 0 if successful, 1 if nothing to recover or verify fails.
4776 Returns 0 if successful, 1 if nothing to recover or verify fails.
4777 """
4777 """
4778 if repo.recover():
4778 if repo.recover():
4779 return hg.verify(repo)
4779 return hg.verify(repo)
4780 return 1
4780 return 1
4781
4781
4782 @command('^remove|rm',
4782 @command('^remove|rm',
4783 [('A', 'after', None, _('record delete for missing files')),
4783 [('A', 'after', None, _('record delete for missing files')),
4784 ('f', 'force', None,
4784 ('f', 'force', None,
4785 _('remove (and delete) file even if added or modified')),
4785 _('remove (and delete) file even if added or modified')),
4786 ] + walkopts,
4786 ] + walkopts,
4787 _('[OPTION]... FILE...'))
4787 _('[OPTION]... FILE...'))
4788 def remove(ui, repo, *pats, **opts):
4788 def remove(ui, repo, *pats, **opts):
4789 """remove the specified files on the next commit
4789 """remove the specified files on the next commit
4790
4790
4791 Schedule the indicated files for removal from the current branch.
4791 Schedule the indicated files for removal from the current branch.
4792
4792
4793 This command schedules the files to be removed at the next commit.
4793 This command schedules the files to be removed at the next commit.
4794 To undo a remove before that, see :hg:`revert`. To undo added
4794 To undo a remove before that, see :hg:`revert`. To undo added
4795 files, see :hg:`forget`.
4795 files, see :hg:`forget`.
4796
4796
4797 .. container:: verbose
4797 .. container:: verbose
4798
4798
4799 -A/--after can be used to remove only files that have already
4799 -A/--after can be used to remove only files that have already
4800 been deleted, -f/--force can be used to force deletion, and -Af
4800 been deleted, -f/--force can be used to force deletion, and -Af
4801 can be used to remove files from the next revision without
4801 can be used to remove files from the next revision without
4802 deleting them from the working directory.
4802 deleting them from the working directory.
4803
4803
4804 The following table details the behavior of remove for different
4804 The following table details the behavior of remove for different
4805 file states (columns) and option combinations (rows). The file
4805 file states (columns) and option combinations (rows). The file
4806 states are Added [A], Clean [C], Modified [M] and Missing [!]
4806 states are Added [A], Clean [C], Modified [M] and Missing [!]
4807 (as reported by :hg:`status`). The actions are Warn, Remove
4807 (as reported by :hg:`status`). The actions are Warn, Remove
4808 (from branch) and Delete (from disk):
4808 (from branch) and Delete (from disk):
4809
4809
4810 ========= == == == ==
4810 ========= == == == ==
4811 opt/state A C M !
4811 opt/state A C M !
4812 ========= == == == ==
4812 ========= == == == ==
4813 none W RD W R
4813 none W RD W R
4814 -f R RD RD R
4814 -f R RD RD R
4815 -A W W W R
4815 -A W W W R
4816 -Af R R R R
4816 -Af R R R R
4817 ========= == == == ==
4817 ========= == == == ==
4818
4818
4819 Note that remove never deletes files in Added [A] state from the
4819 Note that remove never deletes files in Added [A] state from the
4820 working directory, not even if option --force is specified.
4820 working directory, not even if option --force is specified.
4821
4821
4822 Returns 0 on success, 1 if any warnings encountered.
4822 Returns 0 on success, 1 if any warnings encountered.
4823 """
4823 """
4824
4824
4825 ret = 0
4825 ret = 0
4826 after, force = opts.get('after'), opts.get('force')
4826 after, force = opts.get('after'), opts.get('force')
4827 if not pats and not after:
4827 if not pats and not after:
4828 raise util.Abort(_('no files specified'))
4828 raise util.Abort(_('no files specified'))
4829
4829
4830 m = scmutil.match(repo[None], pats, opts)
4830 m = scmutil.match(repo[None], pats, opts)
4831 s = repo.status(match=m, clean=True)
4831 s = repo.status(match=m, clean=True)
4832 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4832 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4833
4833
4834 # warn about failure to delete explicit files/dirs
4834 # warn about failure to delete explicit files/dirs
4835 wctx = repo[None]
4835 wctx = repo[None]
4836 for f in m.files():
4836 for f in m.files():
4837 if f in repo.dirstate or f in wctx.dirs():
4837 if f in repo.dirstate or f in wctx.dirs():
4838 continue
4838 continue
4839 if os.path.exists(m.rel(f)):
4839 if os.path.exists(m.rel(f)):
4840 if os.path.isdir(m.rel(f)):
4840 if os.path.isdir(m.rel(f)):
4841 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4841 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4842 else:
4842 else:
4843 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4843 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4844 # missing files will generate a warning elsewhere
4844 # missing files will generate a warning elsewhere
4845 ret = 1
4845 ret = 1
4846
4846
4847 if force:
4847 if force:
4848 list = modified + deleted + clean + added
4848 list = modified + deleted + clean + added
4849 elif after:
4849 elif after:
4850 list = deleted
4850 list = deleted
4851 for f in modified + added + clean:
4851 for f in modified + added + clean:
4852 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4852 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4853 ret = 1
4853 ret = 1
4854 else:
4854 else:
4855 list = deleted + clean
4855 list = deleted + clean
4856 for f in modified:
4856 for f in modified:
4857 ui.warn(_('not removing %s: file is modified (use -f'
4857 ui.warn(_('not removing %s: file is modified (use -f'
4858 ' to force removal)\n') % m.rel(f))
4858 ' to force removal)\n') % m.rel(f))
4859 ret = 1
4859 ret = 1
4860 for f in added:
4860 for f in added:
4861 ui.warn(_('not removing %s: file has been marked for add'
4861 ui.warn(_('not removing %s: file has been marked for add'
4862 ' (use forget to undo)\n') % m.rel(f))
4862 ' (use forget to undo)\n') % m.rel(f))
4863 ret = 1
4863 ret = 1
4864
4864
4865 for f in sorted(list):
4865 for f in sorted(list):
4866 if ui.verbose or not m.exact(f):
4866 if ui.verbose or not m.exact(f):
4867 ui.status(_('removing %s\n') % m.rel(f))
4867 ui.status(_('removing %s\n') % m.rel(f))
4868
4868
4869 wlock = repo.wlock()
4869 wlock = repo.wlock()
4870 try:
4870 try:
4871 if not after:
4871 if not after:
4872 for f in list:
4872 for f in list:
4873 if f in added:
4873 if f in added:
4874 continue # we never unlink added files on remove
4874 continue # we never unlink added files on remove
4875 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4875 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4876 repo[None].forget(list)
4876 repo[None].forget(list)
4877 finally:
4877 finally:
4878 wlock.release()
4878 wlock.release()
4879
4879
4880 return ret
4880 return ret
4881
4881
4882 @command('rename|move|mv',
4882 @command('rename|move|mv',
4883 [('A', 'after', None, _('record a rename that has already occurred')),
4883 [('A', 'after', None, _('record a rename that has already occurred')),
4884 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4884 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4885 ] + walkopts + dryrunopts,
4885 ] + walkopts + dryrunopts,
4886 _('[OPTION]... SOURCE... DEST'))
4886 _('[OPTION]... SOURCE... DEST'))
4887 def rename(ui, repo, *pats, **opts):
4887 def rename(ui, repo, *pats, **opts):
4888 """rename files; equivalent of copy + remove
4888 """rename files; equivalent of copy + remove
4889
4889
4890 Mark dest as copies of sources; mark sources for deletion. If dest
4890 Mark dest as copies of sources; mark sources for deletion. If dest
4891 is a directory, copies are put in that directory. If dest is a
4891 is a directory, copies are put in that directory. If dest is a
4892 file, there can only be one source.
4892 file, there can only be one source.
4893
4893
4894 By default, this command copies the contents of files as they
4894 By default, this command copies the contents of files as they
4895 exist in the working directory. If invoked with -A/--after, the
4895 exist in the working directory. If invoked with -A/--after, the
4896 operation is recorded, but no copying is performed.
4896 operation is recorded, but no copying is performed.
4897
4897
4898 This command takes effect at the next commit. To undo a rename
4898 This command takes effect at the next commit. To undo a rename
4899 before that, see :hg:`revert`.
4899 before that, see :hg:`revert`.
4900
4900
4901 Returns 0 on success, 1 if errors are encountered.
4901 Returns 0 on success, 1 if errors are encountered.
4902 """
4902 """
4903 wlock = repo.wlock(False)
4903 wlock = repo.wlock(False)
4904 try:
4904 try:
4905 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4905 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4906 finally:
4906 finally:
4907 wlock.release()
4907 wlock.release()
4908
4908
4909 @command('resolve',
4909 @command('resolve',
4910 [('a', 'all', None, _('select all unresolved files')),
4910 [('a', 'all', None, _('select all unresolved files')),
4911 ('l', 'list', None, _('list state of files needing merge')),
4911 ('l', 'list', None, _('list state of files needing merge')),
4912 ('m', 'mark', None, _('mark files as resolved')),
4912 ('m', 'mark', None, _('mark files as resolved')),
4913 ('u', 'unmark', None, _('mark files as unresolved')),
4913 ('u', 'unmark', None, _('mark files as unresolved')),
4914 ('n', 'no-status', None, _('hide status prefix'))]
4914 ('n', 'no-status', None, _('hide status prefix'))]
4915 + mergetoolopts + walkopts,
4915 + mergetoolopts + walkopts,
4916 _('[OPTION]... [FILE]...'))
4916 _('[OPTION]... [FILE]...'))
4917 def resolve(ui, repo, *pats, **opts):
4917 def resolve(ui, repo, *pats, **opts):
4918 """redo merges or set/view the merge status of files
4918 """redo merges or set/view the merge status of files
4919
4919
4920 Merges with unresolved conflicts are often the result of
4920 Merges with unresolved conflicts are often the result of
4921 non-interactive merging using the ``internal:merge`` configuration
4921 non-interactive merging using the ``internal:merge`` configuration
4922 setting, or a command-line merge tool like ``diff3``. The resolve
4922 setting, or a command-line merge tool like ``diff3``. The resolve
4923 command is used to manage the files involved in a merge, after
4923 command is used to manage the files involved in a merge, after
4924 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4924 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4925 working directory must have two parents). See :hg:`help
4925 working directory must have two parents). See :hg:`help
4926 merge-tools` for information on configuring merge tools.
4926 merge-tools` for information on configuring merge tools.
4927
4927
4928 The resolve command can be used in the following ways:
4928 The resolve command can be used in the following ways:
4929
4929
4930 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4930 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4931 files, discarding any previous merge attempts. Re-merging is not
4931 files, discarding any previous merge attempts. Re-merging is not
4932 performed for files already marked as resolved. Use ``--all/-a``
4932 performed for files already marked as resolved. Use ``--all/-a``
4933 to select all unresolved files. ``--tool`` can be used to specify
4933 to select all unresolved files. ``--tool`` can be used to specify
4934 the merge tool used for the given files. It overrides the HGMERGE
4934 the merge tool used for the given files. It overrides the HGMERGE
4935 environment variable and your configuration files. Previous file
4935 environment variable and your configuration files. Previous file
4936 contents are saved with a ``.orig`` suffix.
4936 contents are saved with a ``.orig`` suffix.
4937
4937
4938 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4938 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4939 (e.g. after having manually fixed-up the files). The default is
4939 (e.g. after having manually fixed-up the files). The default is
4940 to mark all unresolved files.
4940 to mark all unresolved files.
4941
4941
4942 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4942 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4943 default is to mark all resolved files.
4943 default is to mark all resolved files.
4944
4944
4945 - :hg:`resolve -l`: list files which had or still have conflicts.
4945 - :hg:`resolve -l`: list files which had or still have conflicts.
4946 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4946 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4947
4947
4948 Note that Mercurial will not let you commit files with unresolved
4948 Note that Mercurial will not let you commit files with unresolved
4949 merge conflicts. You must use :hg:`resolve -m ...` before you can
4949 merge conflicts. You must use :hg:`resolve -m ...` before you can
4950 commit after a conflicting merge.
4950 commit after a conflicting merge.
4951
4951
4952 Returns 0 on success, 1 if any files fail a resolve attempt.
4952 Returns 0 on success, 1 if any files fail a resolve attempt.
4953 """
4953 """
4954
4954
4955 all, mark, unmark, show, nostatus = \
4955 all, mark, unmark, show, nostatus = \
4956 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4956 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4957
4957
4958 if (show and (mark or unmark)) or (mark and unmark):
4958 if (show and (mark or unmark)) or (mark and unmark):
4959 raise util.Abort(_("too many options specified"))
4959 raise util.Abort(_("too many options specified"))
4960 if pats and all:
4960 if pats and all:
4961 raise util.Abort(_("can't specify --all and patterns"))
4961 raise util.Abort(_("can't specify --all and patterns"))
4962 if not (all or pats or show or mark or unmark):
4962 if not (all or pats or show or mark or unmark):
4963 raise util.Abort(_('no files or directories specified; '
4963 raise util.Abort(_('no files or directories specified; '
4964 'use --all to remerge all files'))
4964 'use --all to remerge all files'))
4965
4965
4966 ms = mergemod.mergestate(repo)
4966 ms = mergemod.mergestate(repo)
4967 m = scmutil.match(repo[None], pats, opts)
4967 m = scmutil.match(repo[None], pats, opts)
4968 ret = 0
4968 ret = 0
4969
4969
4970 for f in ms:
4970 for f in ms:
4971 if m(f):
4971 if m(f):
4972 if show:
4972 if show:
4973 if nostatus:
4973 if nostatus:
4974 ui.write("%s\n" % f)
4974 ui.write("%s\n" % f)
4975 else:
4975 else:
4976 ui.write("%s %s\n" % (ms[f].upper(), f),
4976 ui.write("%s %s\n" % (ms[f].upper(), f),
4977 label='resolve.' +
4977 label='resolve.' +
4978 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4978 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4979 elif mark:
4979 elif mark:
4980 ms.mark(f, "r")
4980 ms.mark(f, "r")
4981 elif unmark:
4981 elif unmark:
4982 ms.mark(f, "u")
4982 ms.mark(f, "u")
4983 else:
4983 else:
4984 wctx = repo[None]
4984 wctx = repo[None]
4985
4985
4986 # backup pre-resolve (merge uses .orig for its own purposes)
4986 # backup pre-resolve (merge uses .orig for its own purposes)
4987 a = repo.wjoin(f)
4987 a = repo.wjoin(f)
4988 util.copyfile(a, a + ".resolve")
4988 util.copyfile(a, a + ".resolve")
4989
4989
4990 try:
4990 try:
4991 # resolve file
4991 # resolve file
4992 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4992 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4993 'resolve')
4993 'resolve')
4994 if ms.resolve(f, wctx):
4994 if ms.resolve(f, wctx):
4995 ret = 1
4995 ret = 1
4996 finally:
4996 finally:
4997 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4997 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4998 ms.commit()
4998 ms.commit()
4999
4999
5000 # replace filemerge's .orig file with our resolve file
5000 # replace filemerge's .orig file with our resolve file
5001 util.rename(a + ".resolve", a + ".orig")
5001 util.rename(a + ".resolve", a + ".orig")
5002
5002
5003 ms.commit()
5003 ms.commit()
5004 return ret
5004 return ret
5005
5005
5006 @command('revert',
5006 @command('revert',
5007 [('a', 'all', None, _('revert all changes when no arguments given')),
5007 [('a', 'all', None, _('revert all changes when no arguments given')),
5008 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5008 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5009 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5009 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5010 ('C', 'no-backup', None, _('do not save backup copies of files')),
5010 ('C', 'no-backup', None, _('do not save backup copies of files')),
5011 ] + walkopts + dryrunopts,
5011 ] + walkopts + dryrunopts,
5012 _('[OPTION]... [-r REV] [NAME]...'))
5012 _('[OPTION]... [-r REV] [NAME]...'))
5013 def revert(ui, repo, *pats, **opts):
5013 def revert(ui, repo, *pats, **opts):
5014 """restore files to their checkout state
5014 """restore files to their checkout state
5015
5015
5016 .. note::
5016 .. note::
5017
5017
5018 To check out earlier revisions, you should use :hg:`update REV`.
5018 To check out earlier revisions, you should use :hg:`update REV`.
5019 To cancel an uncommitted merge (and lose your changes),
5019 To cancel an uncommitted merge (and lose your changes),
5020 use :hg:`update --clean .`.
5020 use :hg:`update --clean .`.
5021
5021
5022 With no revision specified, revert the specified files or directories
5022 With no revision specified, revert the specified files or directories
5023 to the contents they had in the parent of the working directory.
5023 to the contents they had in the parent of the working directory.
5024 This restores the contents of files to an unmodified
5024 This restores the contents of files to an unmodified
5025 state and unschedules adds, removes, copies, and renames. If the
5025 state and unschedules adds, removes, copies, and renames. If the
5026 working directory has two parents, you must explicitly specify a
5026 working directory has two parents, you must explicitly specify a
5027 revision.
5027 revision.
5028
5028
5029 Using the -r/--rev or -d/--date options, revert the given files or
5029 Using the -r/--rev or -d/--date options, revert the given files or
5030 directories to their states as of a specific revision. Because
5030 directories to their states as of a specific revision. Because
5031 revert does not change the working directory parents, this will
5031 revert does not change the working directory parents, this will
5032 cause these files to appear modified. This can be helpful to "back
5032 cause these files to appear modified. This can be helpful to "back
5033 out" some or all of an earlier change. See :hg:`backout` for a
5033 out" some or all of an earlier change. See :hg:`backout` for a
5034 related method.
5034 related method.
5035
5035
5036 Modified files are saved with a .orig suffix before reverting.
5036 Modified files are saved with a .orig suffix before reverting.
5037 To disable these backups, use --no-backup.
5037 To disable these backups, use --no-backup.
5038
5038
5039 See :hg:`help dates` for a list of formats valid for -d/--date.
5039 See :hg:`help dates` for a list of formats valid for -d/--date.
5040
5040
5041 Returns 0 on success.
5041 Returns 0 on success.
5042 """
5042 """
5043
5043
5044 if opts.get("date"):
5044 if opts.get("date"):
5045 if opts.get("rev"):
5045 if opts.get("rev"):
5046 raise util.Abort(_("you can't specify a revision and a date"))
5046 raise util.Abort(_("you can't specify a revision and a date"))
5047 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5047 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5048
5048
5049 parent, p2 = repo.dirstate.parents()
5049 parent, p2 = repo.dirstate.parents()
5050 if not opts.get('rev') and p2 != nullid:
5050 if not opts.get('rev') and p2 != nullid:
5051 # revert after merge is a trap for new users (issue2915)
5051 # revert after merge is a trap for new users (issue2915)
5052 raise util.Abort(_('uncommitted merge with no revision specified'),
5052 raise util.Abort(_('uncommitted merge with no revision specified'),
5053 hint=_('use "hg update" or see "hg help revert"'))
5053 hint=_('use "hg update" or see "hg help revert"'))
5054
5054
5055 ctx = scmutil.revsingle(repo, opts.get('rev'))
5055 ctx = scmutil.revsingle(repo, opts.get('rev'))
5056
5056
5057 if not pats and not opts.get('all'):
5057 if not pats and not opts.get('all'):
5058 msg = _("no files or directories specified")
5058 msg = _("no files or directories specified")
5059 if p2 != nullid:
5059 if p2 != nullid:
5060 hint = _("uncommitted merge, use --all to discard all changes,"
5060 hint = _("uncommitted merge, use --all to discard all changes,"
5061 " or 'hg update -C .' to abort the merge")
5061 " or 'hg update -C .' to abort the merge")
5062 raise util.Abort(msg, hint=hint)
5062 raise util.Abort(msg, hint=hint)
5063 dirty = util.any(repo.status())
5063 dirty = util.any(repo.status())
5064 node = ctx.node()
5064 node = ctx.node()
5065 if node != parent:
5065 if node != parent:
5066 if dirty:
5066 if dirty:
5067 hint = _("uncommitted changes, use --all to discard all"
5067 hint = _("uncommitted changes, use --all to discard all"
5068 " changes, or 'hg update %s' to update") % ctx.rev()
5068 " changes, or 'hg update %s' to update") % ctx.rev()
5069 else:
5069 else:
5070 hint = _("use --all to revert all files,"
5070 hint = _("use --all to revert all files,"
5071 " or 'hg update %s' to update") % ctx.rev()
5071 " or 'hg update %s' to update") % ctx.rev()
5072 elif dirty:
5072 elif dirty:
5073 hint = _("uncommitted changes, use --all to discard all changes")
5073 hint = _("uncommitted changes, use --all to discard all changes")
5074 else:
5074 else:
5075 hint = _("use --all to revert all files")
5075 hint = _("use --all to revert all files")
5076 raise util.Abort(msg, hint=hint)
5076 raise util.Abort(msg, hint=hint)
5077
5077
5078 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5078 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5079
5079
5080 @command('rollback', dryrunopts +
5080 @command('rollback', dryrunopts +
5081 [('f', 'force', False, _('ignore safety measures'))])
5081 [('f', 'force', False, _('ignore safety measures'))])
5082 def rollback(ui, repo, **opts):
5082 def rollback(ui, repo, **opts):
5083 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5083 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5084
5084
5085 Please use :hg:`commit --amend` instead of rollback to correct
5085 Please use :hg:`commit --amend` instead of rollback to correct
5086 mistakes in the last commit.
5086 mistakes in the last commit.
5087
5087
5088 This command should be used with care. There is only one level of
5088 This command should be used with care. There is only one level of
5089 rollback, and there is no way to undo a rollback. It will also
5089 rollback, and there is no way to undo a rollback. It will also
5090 restore the dirstate at the time of the last transaction, losing
5090 restore the dirstate at the time of the last transaction, losing
5091 any dirstate changes since that time. This command does not alter
5091 any dirstate changes since that time. This command does not alter
5092 the working directory.
5092 the working directory.
5093
5093
5094 Transactions are used to encapsulate the effects of all commands
5094 Transactions are used to encapsulate the effects of all commands
5095 that create new changesets or propagate existing changesets into a
5095 that create new changesets or propagate existing changesets into a
5096 repository.
5096 repository.
5097
5097
5098 .. container:: verbose
5098 .. container:: verbose
5099
5099
5100 For example, the following commands are transactional, and their
5100 For example, the following commands are transactional, and their
5101 effects can be rolled back:
5101 effects can be rolled back:
5102
5102
5103 - commit
5103 - commit
5104 - import
5104 - import
5105 - pull
5105 - pull
5106 - push (with this repository as the destination)
5106 - push (with this repository as the destination)
5107 - unbundle
5107 - unbundle
5108
5108
5109 To avoid permanent data loss, rollback will refuse to rollback a
5109 To avoid permanent data loss, rollback will refuse to rollback a
5110 commit transaction if it isn't checked out. Use --force to
5110 commit transaction if it isn't checked out. Use --force to
5111 override this protection.
5111 override this protection.
5112
5112
5113 This command is not intended for use on public repositories. Once
5113 This command is not intended for use on public repositories. Once
5114 changes are visible for pull by other users, rolling a transaction
5114 changes are visible for pull by other users, rolling a transaction
5115 back locally is ineffective (someone else may already have pulled
5115 back locally is ineffective (someone else may already have pulled
5116 the changes). Furthermore, a race is possible with readers of the
5116 the changes). Furthermore, a race is possible with readers of the
5117 repository; for example an in-progress pull from the repository
5117 repository; for example an in-progress pull from the repository
5118 may fail if a rollback is performed.
5118 may fail if a rollback is performed.
5119
5119
5120 Returns 0 on success, 1 if no rollback data is available.
5120 Returns 0 on success, 1 if no rollback data is available.
5121 """
5121 """
5122 return repo.rollback(dryrun=opts.get('dry_run'),
5122 return repo.rollback(dryrun=opts.get('dry_run'),
5123 force=opts.get('force'))
5123 force=opts.get('force'))
5124
5124
5125 @command('root', [])
5125 @command('root', [])
5126 def root(ui, repo):
5126 def root(ui, repo):
5127 """print the root (top) of the current working directory
5127 """print the root (top) of the current working directory
5128
5128
5129 Print the root directory of the current repository.
5129 Print the root directory of the current repository.
5130
5130
5131 Returns 0 on success.
5131 Returns 0 on success.
5132 """
5132 """
5133 ui.write(repo.root + "\n")
5133 ui.write(repo.root + "\n")
5134
5134
5135 @command('^serve',
5135 @command('^serve',
5136 [('A', 'accesslog', '', _('name of access log file to write to'),
5136 [('A', 'accesslog', '', _('name of access log file to write to'),
5137 _('FILE')),
5137 _('FILE')),
5138 ('d', 'daemon', None, _('run server in background')),
5138 ('d', 'daemon', None, _('run server in background')),
5139 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5139 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5140 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5140 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5141 # use string type, then we can check if something was passed
5141 # use string type, then we can check if something was passed
5142 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5142 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5143 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5143 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5144 _('ADDR')),
5144 _('ADDR')),
5145 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5145 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5146 _('PREFIX')),
5146 _('PREFIX')),
5147 ('n', 'name', '',
5147 ('n', 'name', '',
5148 _('name to show in web pages (default: working directory)'), _('NAME')),
5148 _('name to show in web pages (default: working directory)'), _('NAME')),
5149 ('', 'web-conf', '',
5149 ('', 'web-conf', '',
5150 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5150 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5151 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5151 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5152 _('FILE')),
5152 _('FILE')),
5153 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5153 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5154 ('', 'stdio', None, _('for remote clients')),
5154 ('', 'stdio', None, _('for remote clients')),
5155 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5155 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5156 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5156 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5157 ('', 'style', '', _('template style to use'), _('STYLE')),
5157 ('', 'style', '', _('template style to use'), _('STYLE')),
5158 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5158 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5159 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5159 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5160 _('[OPTION]...'))
5160 _('[OPTION]...'))
5161 def serve(ui, repo, **opts):
5161 def serve(ui, repo, **opts):
5162 """start stand-alone webserver
5162 """start stand-alone webserver
5163
5163
5164 Start a local HTTP repository browser and pull server. You can use
5164 Start a local HTTP repository browser and pull server. You can use
5165 this for ad-hoc sharing and browsing of repositories. It is
5165 this for ad-hoc sharing and browsing of repositories. It is
5166 recommended to use a real web server to serve a repository for
5166 recommended to use a real web server to serve a repository for
5167 longer periods of time.
5167 longer periods of time.
5168
5168
5169 Please note that the server does not implement access control.
5169 Please note that the server does not implement access control.
5170 This means that, by default, anybody can read from the server and
5170 This means that, by default, anybody can read from the server and
5171 nobody can write to it by default. Set the ``web.allow_push``
5171 nobody can write to it by default. Set the ``web.allow_push``
5172 option to ``*`` to allow everybody to push to the server. You
5172 option to ``*`` to allow everybody to push to the server. You
5173 should use a real web server if you need to authenticate users.
5173 should use a real web server if you need to authenticate users.
5174
5174
5175 By default, the server logs accesses to stdout and errors to
5175 By default, the server logs accesses to stdout and errors to
5176 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5176 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5177 files.
5177 files.
5178
5178
5179 To have the server choose a free port number to listen on, specify
5179 To have the server choose a free port number to listen on, specify
5180 a port number of 0; in this case, the server will print the port
5180 a port number of 0; in this case, the server will print the port
5181 number it uses.
5181 number it uses.
5182
5182
5183 Returns 0 on success.
5183 Returns 0 on success.
5184 """
5184 """
5185
5185
5186 if opts["stdio"] and opts["cmdserver"]:
5186 if opts["stdio"] and opts["cmdserver"]:
5187 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5187 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5188
5188
5189 def checkrepo():
5189 def checkrepo():
5190 if repo is None:
5190 if repo is None:
5191 raise error.RepoError(_("there is no Mercurial repository here"
5191 raise error.RepoError(_("there is no Mercurial repository here"
5192 " (.hg not found)"))
5192 " (.hg not found)"))
5193
5193
5194 if opts["stdio"]:
5194 if opts["stdio"]:
5195 checkrepo()
5195 checkrepo()
5196 s = sshserver.sshserver(ui, repo)
5196 s = sshserver.sshserver(ui, repo)
5197 s.serve_forever()
5197 s.serve_forever()
5198
5198
5199 if opts["cmdserver"]:
5199 if opts["cmdserver"]:
5200 s = commandserver.server(ui, repo, opts["cmdserver"])
5200 s = commandserver.server(ui, repo, opts["cmdserver"])
5201 return s.serve()
5201 return s.serve()
5202
5202
5203 # this way we can check if something was given in the command-line
5203 # this way we can check if something was given in the command-line
5204 if opts.get('port'):
5204 if opts.get('port'):
5205 opts['port'] = util.getport(opts.get('port'))
5205 opts['port'] = util.getport(opts.get('port'))
5206
5206
5207 baseui = repo and repo.baseui or ui
5207 baseui = repo and repo.baseui or ui
5208 optlist = ("name templates style address port prefix ipv6"
5208 optlist = ("name templates style address port prefix ipv6"
5209 " accesslog errorlog certificate encoding")
5209 " accesslog errorlog certificate encoding")
5210 for o in optlist.split():
5210 for o in optlist.split():
5211 val = opts.get(o, '')
5211 val = opts.get(o, '')
5212 if val in (None, ''): # should check against default options instead
5212 if val in (None, ''): # should check against default options instead
5213 continue
5213 continue
5214 baseui.setconfig("web", o, val, 'serve')
5214 baseui.setconfig("web", o, val, 'serve')
5215 if repo and repo.ui != baseui:
5215 if repo and repo.ui != baseui:
5216 repo.ui.setconfig("web", o, val, 'serve')
5216 repo.ui.setconfig("web", o, val, 'serve')
5217
5217
5218 o = opts.get('web_conf') or opts.get('webdir_conf')
5218 o = opts.get('web_conf') or opts.get('webdir_conf')
5219 if not o:
5219 if not o:
5220 if not repo:
5220 if not repo:
5221 raise error.RepoError(_("there is no Mercurial repository"
5221 raise error.RepoError(_("there is no Mercurial repository"
5222 " here (.hg not found)"))
5222 " here (.hg not found)"))
5223 o = repo
5223 o = repo
5224
5224
5225 app = hgweb.hgweb(o, baseui=baseui)
5225 app = hgweb.hgweb(o, baseui=baseui)
5226 service = httpservice(ui, app, opts)
5226 service = httpservice(ui, app, opts)
5227 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5227 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5228
5228
5229 class httpservice(object):
5229 class httpservice(object):
5230 def __init__(self, ui, app, opts):
5230 def __init__(self, ui, app, opts):
5231 self.ui = ui
5231 self.ui = ui
5232 self.app = app
5232 self.app = app
5233 self.opts = opts
5233 self.opts = opts
5234
5234
5235 def init(self):
5235 def init(self):
5236 util.setsignalhandler()
5236 util.setsignalhandler()
5237 self.httpd = hgweb_server.create_server(self.ui, self.app)
5237 self.httpd = hgweb_server.create_server(self.ui, self.app)
5238
5238
5239 if self.opts['port'] and not self.ui.verbose:
5239 if self.opts['port'] and not self.ui.verbose:
5240 return
5240 return
5241
5241
5242 if self.httpd.prefix:
5242 if self.httpd.prefix:
5243 prefix = self.httpd.prefix.strip('/') + '/'
5243 prefix = self.httpd.prefix.strip('/') + '/'
5244 else:
5244 else:
5245 prefix = ''
5245 prefix = ''
5246
5246
5247 port = ':%d' % self.httpd.port
5247 port = ':%d' % self.httpd.port
5248 if port == ':80':
5248 if port == ':80':
5249 port = ''
5249 port = ''
5250
5250
5251 bindaddr = self.httpd.addr
5251 bindaddr = self.httpd.addr
5252 if bindaddr == '0.0.0.0':
5252 if bindaddr == '0.0.0.0':
5253 bindaddr = '*'
5253 bindaddr = '*'
5254 elif ':' in bindaddr: # IPv6
5254 elif ':' in bindaddr: # IPv6
5255 bindaddr = '[%s]' % bindaddr
5255 bindaddr = '[%s]' % bindaddr
5256
5256
5257 fqaddr = self.httpd.fqaddr
5257 fqaddr = self.httpd.fqaddr
5258 if ':' in fqaddr:
5258 if ':' in fqaddr:
5259 fqaddr = '[%s]' % fqaddr
5259 fqaddr = '[%s]' % fqaddr
5260 if self.opts['port']:
5260 if self.opts['port']:
5261 write = self.ui.status
5261 write = self.ui.status
5262 else:
5262 else:
5263 write = self.ui.write
5263 write = self.ui.write
5264 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5264 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5265 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5265 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5266
5266
5267 def run(self):
5267 def run(self):
5268 self.httpd.serve_forever()
5268 self.httpd.serve_forever()
5269
5269
5270
5270
5271 @command('^status|st',
5271 @command('^status|st',
5272 [('A', 'all', None, _('show status of all files')),
5272 [('A', 'all', None, _('show status of all files')),
5273 ('m', 'modified', None, _('show only modified files')),
5273 ('m', 'modified', None, _('show only modified files')),
5274 ('a', 'added', None, _('show only added files')),
5274 ('a', 'added', None, _('show only added files')),
5275 ('r', 'removed', None, _('show only removed files')),
5275 ('r', 'removed', None, _('show only removed files')),
5276 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5276 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5277 ('c', 'clean', None, _('show only files without changes')),
5277 ('c', 'clean', None, _('show only files without changes')),
5278 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5278 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5279 ('i', 'ignored', None, _('show only ignored files')),
5279 ('i', 'ignored', None, _('show only ignored files')),
5280 ('n', 'no-status', None, _('hide status prefix')),
5280 ('n', 'no-status', None, _('hide status prefix')),
5281 ('C', 'copies', None, _('show source of copied files')),
5281 ('C', 'copies', None, _('show source of copied files')),
5282 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5282 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5283 ('', 'rev', [], _('show difference from revision'), _('REV')),
5283 ('', 'rev', [], _('show difference from revision'), _('REV')),
5284 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5284 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5285 ] + walkopts + subrepoopts,
5285 ] + walkopts + subrepoopts,
5286 _('[OPTION]... [FILE]...'))
5286 _('[OPTION]... [FILE]...'))
5287 def status(ui, repo, *pats, **opts):
5287 def status(ui, repo, *pats, **opts):
5288 """show changed files in the working directory
5288 """show changed files in the working directory
5289
5289
5290 Show status of files in the repository. If names are given, only
5290 Show status of files in the repository. If names are given, only
5291 files that match are shown. Files that are clean or ignored or
5291 files that match are shown. Files that are clean or ignored or
5292 the source of a copy/move operation, are not listed unless
5292 the source of a copy/move operation, are not listed unless
5293 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5293 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5294 Unless options described with "show only ..." are given, the
5294 Unless options described with "show only ..." are given, the
5295 options -mardu are used.
5295 options -mardu are used.
5296
5296
5297 Option -q/--quiet hides untracked (unknown and ignored) files
5297 Option -q/--quiet hides untracked (unknown and ignored) files
5298 unless explicitly requested with -u/--unknown or -i/--ignored.
5298 unless explicitly requested with -u/--unknown or -i/--ignored.
5299
5299
5300 .. note::
5300 .. note::
5301
5301
5302 status may appear to disagree with diff if permissions have
5302 status may appear to disagree with diff if permissions have
5303 changed or a merge has occurred. The standard diff format does
5303 changed or a merge has occurred. The standard diff format does
5304 not report permission changes and diff only reports changes
5304 not report permission changes and diff only reports changes
5305 relative to one merge parent.
5305 relative to one merge parent.
5306
5306
5307 If one revision is given, it is used as the base revision.
5307 If one revision is given, it is used as the base revision.
5308 If two revisions are given, the differences between them are
5308 If two revisions are given, the differences between them are
5309 shown. The --change option can also be used as a shortcut to list
5309 shown. The --change option can also be used as a shortcut to list
5310 the changed files of a revision from its first parent.
5310 the changed files of a revision from its first parent.
5311
5311
5312 The codes used to show the status of files are::
5312 The codes used to show the status of files are::
5313
5313
5314 M = modified
5314 M = modified
5315 A = added
5315 A = added
5316 R = removed
5316 R = removed
5317 C = clean
5317 C = clean
5318 ! = missing (deleted by non-hg command, but still tracked)
5318 ! = missing (deleted by non-hg command, but still tracked)
5319 ? = not tracked
5319 ? = not tracked
5320 I = ignored
5320 I = ignored
5321 = origin of the previous file (with --copies)
5321 = origin of the previous file (with --copies)
5322
5322
5323 .. container:: verbose
5323 .. container:: verbose
5324
5324
5325 Examples:
5325 Examples:
5326
5326
5327 - show changes in the working directory relative to a
5327 - show changes in the working directory relative to a
5328 changeset::
5328 changeset::
5329
5329
5330 hg status --rev 9353
5330 hg status --rev 9353
5331
5331
5332 - show all changes including copies in an existing changeset::
5332 - show all changes including copies in an existing changeset::
5333
5333
5334 hg status --copies --change 9353
5334 hg status --copies --change 9353
5335
5335
5336 - get a NUL separated list of added files, suitable for xargs::
5336 - get a NUL separated list of added files, suitable for xargs::
5337
5337
5338 hg status -an0
5338 hg status -an0
5339
5339
5340 Returns 0 on success.
5340 Returns 0 on success.
5341 """
5341 """
5342
5342
5343 revs = opts.get('rev')
5343 revs = opts.get('rev')
5344 change = opts.get('change')
5344 change = opts.get('change')
5345
5345
5346 if revs and change:
5346 if revs and change:
5347 msg = _('cannot specify --rev and --change at the same time')
5347 msg = _('cannot specify --rev and --change at the same time')
5348 raise util.Abort(msg)
5348 raise util.Abort(msg)
5349 elif change:
5349 elif change:
5350 node2 = scmutil.revsingle(repo, change, None).node()
5350 node2 = scmutil.revsingle(repo, change, None).node()
5351 node1 = repo[node2].p1().node()
5351 node1 = repo[node2].p1().node()
5352 else:
5352 else:
5353 node1, node2 = scmutil.revpair(repo, revs)
5353 node1, node2 = scmutil.revpair(repo, revs)
5354
5354
5355 cwd = (pats and repo.getcwd()) or ''
5355 cwd = (pats and repo.getcwd()) or ''
5356 end = opts.get('print0') and '\0' or '\n'
5356 end = opts.get('print0') and '\0' or '\n'
5357 copy = {}
5357 copy = {}
5358 states = 'modified added removed deleted unknown ignored clean'.split()
5358 states = 'modified added removed deleted unknown ignored clean'.split()
5359 show = [k for k in states if opts.get(k)]
5359 show = [k for k in states if opts.get(k)]
5360 if opts.get('all'):
5360 if opts.get('all'):
5361 show += ui.quiet and (states[:4] + ['clean']) or states
5361 show += ui.quiet and (states[:4] + ['clean']) or states
5362 if not show:
5362 if not show:
5363 show = ui.quiet and states[:4] or states[:5]
5363 show = ui.quiet and states[:4] or states[:5]
5364
5364
5365 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5365 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5366 'ignored' in show, 'clean' in show, 'unknown' in show,
5366 'ignored' in show, 'clean' in show, 'unknown' in show,
5367 opts.get('subrepos'))
5367 opts.get('subrepos'))
5368 changestates = zip(states, 'MAR!?IC', stat)
5368 changestates = zip(states, 'MAR!?IC', stat)
5369
5369
5370 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5370 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5371 copy = copies.pathcopies(repo[node1], repo[node2])
5371 copy = copies.pathcopies(repo[node1], repo[node2])
5372
5372
5373 fm = ui.formatter('status', opts)
5373 fm = ui.formatter('status', opts)
5374 fmt = '%s' + end
5374 fmt = '%s' + end
5375 showchar = not opts.get('no_status')
5375 showchar = not opts.get('no_status')
5376
5376
5377 for state, char, files in changestates:
5377 for state, char, files in changestates:
5378 if state in show:
5378 if state in show:
5379 label = 'status.' + state
5379 label = 'status.' + state
5380 for f in files:
5380 for f in files:
5381 fm.startitem()
5381 fm.startitem()
5382 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5382 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5383 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5383 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5384 if f in copy:
5384 if f in copy:
5385 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5385 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5386 label='status.copied')
5386 label='status.copied')
5387 fm.end()
5387 fm.end()
5388
5388
5389 @command('^summary|sum',
5389 @command('^summary|sum',
5390 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5390 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5391 def summary(ui, repo, **opts):
5391 def summary(ui, repo, **opts):
5392 """summarize working directory state
5392 """summarize working directory state
5393
5393
5394 This generates a brief summary of the working directory state,
5394 This generates a brief summary of the working directory state,
5395 including parents, branch, commit status, and available updates.
5395 including parents, branch, commit status, and available updates.
5396
5396
5397 With the --remote option, this will check the default paths for
5397 With the --remote option, this will check the default paths for
5398 incoming and outgoing changes. This can be time-consuming.
5398 incoming and outgoing changes. This can be time-consuming.
5399
5399
5400 Returns 0 on success.
5400 Returns 0 on success.
5401 """
5401 """
5402
5402
5403 ctx = repo[None]
5403 ctx = repo[None]
5404 parents = ctx.parents()
5404 parents = ctx.parents()
5405 pnode = parents[0].node()
5405 pnode = parents[0].node()
5406 marks = []
5406 marks = []
5407
5407
5408 for p in parents:
5408 for p in parents:
5409 # label with log.changeset (instead of log.parent) since this
5409 # label with log.changeset (instead of log.parent) since this
5410 # shows a working directory parent *changeset*:
5410 # shows a working directory parent *changeset*:
5411 # i18n: column positioning for "hg summary"
5411 # i18n: column positioning for "hg summary"
5412 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5412 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5413 label='log.changeset changeset.%s' % p.phasestr())
5413 label='log.changeset changeset.%s' % p.phasestr())
5414 ui.write(' '.join(p.tags()), label='log.tag')
5414 ui.write(' '.join(p.tags()), label='log.tag')
5415 if p.bookmarks():
5415 if p.bookmarks():
5416 marks.extend(p.bookmarks())
5416 marks.extend(p.bookmarks())
5417 if p.rev() == -1:
5417 if p.rev() == -1:
5418 if not len(repo):
5418 if not len(repo):
5419 ui.write(_(' (empty repository)'))
5419 ui.write(_(' (empty repository)'))
5420 else:
5420 else:
5421 ui.write(_(' (no revision checked out)'))
5421 ui.write(_(' (no revision checked out)'))
5422 ui.write('\n')
5422 ui.write('\n')
5423 if p.description():
5423 if p.description():
5424 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5424 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5425 label='log.summary')
5425 label='log.summary')
5426
5426
5427 branch = ctx.branch()
5427 branch = ctx.branch()
5428 bheads = repo.branchheads(branch)
5428 bheads = repo.branchheads(branch)
5429 # i18n: column positioning for "hg summary"
5429 # i18n: column positioning for "hg summary"
5430 m = _('branch: %s\n') % branch
5430 m = _('branch: %s\n') % branch
5431 if branch != 'default':
5431 if branch != 'default':
5432 ui.write(m, label='log.branch')
5432 ui.write(m, label='log.branch')
5433 else:
5433 else:
5434 ui.status(m, label='log.branch')
5434 ui.status(m, label='log.branch')
5435
5435
5436 if marks:
5436 if marks:
5437 current = repo._bookmarkcurrent
5437 current = repo._bookmarkcurrent
5438 # i18n: column positioning for "hg summary"
5438 # i18n: column positioning for "hg summary"
5439 ui.write(_('bookmarks:'), label='log.bookmark')
5439 ui.write(_('bookmarks:'), label='log.bookmark')
5440 if current is not None:
5440 if current is not None:
5441 if current in marks:
5441 if current in marks:
5442 ui.write(' *' + current, label='bookmarks.current')
5442 ui.write(' *' + current, label='bookmarks.current')
5443 marks.remove(current)
5443 marks.remove(current)
5444 else:
5444 else:
5445 ui.write(' [%s]' % current, label='bookmarks.current')
5445 ui.write(' [%s]' % current, label='bookmarks.current')
5446 for m in marks:
5446 for m in marks:
5447 ui.write(' ' + m, label='log.bookmark')
5447 ui.write(' ' + m, label='log.bookmark')
5448 ui.write('\n', label='log.bookmark')
5448 ui.write('\n', label='log.bookmark')
5449
5449
5450 st = list(repo.status(unknown=True))[:6]
5450 st = list(repo.status(unknown=True))[:6]
5451
5451
5452 c = repo.dirstate.copies()
5452 c = repo.dirstate.copies()
5453 copied, renamed = [], []
5453 copied, renamed = [], []
5454 for d, s in c.iteritems():
5454 for d, s in c.iteritems():
5455 if s in st[2]:
5455 if s in st[2]:
5456 st[2].remove(s)
5456 st[2].remove(s)
5457 renamed.append(d)
5457 renamed.append(d)
5458 else:
5458 else:
5459 copied.append(d)
5459 copied.append(d)
5460 if d in st[1]:
5460 if d in st[1]:
5461 st[1].remove(d)
5461 st[1].remove(d)
5462 st.insert(3, renamed)
5462 st.insert(3, renamed)
5463 st.insert(4, copied)
5463 st.insert(4, copied)
5464
5464
5465 ms = mergemod.mergestate(repo)
5465 ms = mergemod.mergestate(repo)
5466 st.append([f for f in ms if ms[f] == 'u'])
5466 st.append([f for f in ms if ms[f] == 'u'])
5467
5467
5468 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5468 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5469 st.append(subs)
5469 st.append(subs)
5470
5470
5471 labels = [ui.label(_('%d modified'), 'status.modified'),
5471 labels = [ui.label(_('%d modified'), 'status.modified'),
5472 ui.label(_('%d added'), 'status.added'),
5472 ui.label(_('%d added'), 'status.added'),
5473 ui.label(_('%d removed'), 'status.removed'),
5473 ui.label(_('%d removed'), 'status.removed'),
5474 ui.label(_('%d renamed'), 'status.copied'),
5474 ui.label(_('%d renamed'), 'status.copied'),
5475 ui.label(_('%d copied'), 'status.copied'),
5475 ui.label(_('%d copied'), 'status.copied'),
5476 ui.label(_('%d deleted'), 'status.deleted'),
5476 ui.label(_('%d deleted'), 'status.deleted'),
5477 ui.label(_('%d unknown'), 'status.unknown'),
5477 ui.label(_('%d unknown'), 'status.unknown'),
5478 ui.label(_('%d ignored'), 'status.ignored'),
5478 ui.label(_('%d ignored'), 'status.ignored'),
5479 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5479 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5480 ui.label(_('%d subrepos'), 'status.modified')]
5480 ui.label(_('%d subrepos'), 'status.modified')]
5481 t = []
5481 t = []
5482 for s, l in zip(st, labels):
5482 for s, l in zip(st, labels):
5483 if s:
5483 if s:
5484 t.append(l % len(s))
5484 t.append(l % len(s))
5485
5485
5486 t = ', '.join(t)
5486 t = ', '.join(t)
5487 cleanworkdir = False
5487 cleanworkdir = False
5488
5488
5489 if repo.vfs.exists('updatestate'):
5489 if repo.vfs.exists('updatestate'):
5490 t += _(' (interrupted update)')
5490 t += _(' (interrupted update)')
5491 elif len(parents) > 1:
5491 elif len(parents) > 1:
5492 t += _(' (merge)')
5492 t += _(' (merge)')
5493 elif branch != parents[0].branch():
5493 elif branch != parents[0].branch():
5494 t += _(' (new branch)')
5494 t += _(' (new branch)')
5495 elif (parents[0].closesbranch() and
5495 elif (parents[0].closesbranch() and
5496 pnode in repo.branchheads(branch, closed=True)):
5496 pnode in repo.branchheads(branch, closed=True)):
5497 t += _(' (head closed)')
5497 t += _(' (head closed)')
5498 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5498 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5499 t += _(' (clean)')
5499 t += _(' (clean)')
5500 cleanworkdir = True
5500 cleanworkdir = True
5501 elif pnode not in bheads:
5501 elif pnode not in bheads:
5502 t += _(' (new branch head)')
5502 t += _(' (new branch head)')
5503
5503
5504 if cleanworkdir:
5504 if cleanworkdir:
5505 # i18n: column positioning for "hg summary"
5505 # i18n: column positioning for "hg summary"
5506 ui.status(_('commit: %s\n') % t.strip())
5506 ui.status(_('commit: %s\n') % t.strip())
5507 else:
5507 else:
5508 # i18n: column positioning for "hg summary"
5508 # i18n: column positioning for "hg summary"
5509 ui.write(_('commit: %s\n') % t.strip())
5509 ui.write(_('commit: %s\n') % t.strip())
5510
5510
5511 # all ancestors of branch heads - all ancestors of parent = new csets
5511 # all ancestors of branch heads - all ancestors of parent = new csets
5512 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5512 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5513 bheads))
5513 bheads))
5514
5514
5515 if new == 0:
5515 if new == 0:
5516 # i18n: column positioning for "hg summary"
5516 # i18n: column positioning for "hg summary"
5517 ui.status(_('update: (current)\n'))
5517 ui.status(_('update: (current)\n'))
5518 elif pnode not in bheads:
5518 elif pnode not in bheads:
5519 # i18n: column positioning for "hg summary"
5519 # i18n: column positioning for "hg summary"
5520 ui.write(_('update: %d new changesets (update)\n') % new)
5520 ui.write(_('update: %d new changesets (update)\n') % new)
5521 else:
5521 else:
5522 # i18n: column positioning for "hg summary"
5522 # i18n: column positioning for "hg summary"
5523 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5523 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5524 (new, len(bheads)))
5524 (new, len(bheads)))
5525
5525
5526 cmdutil.summaryhooks(ui, repo)
5526 cmdutil.summaryhooks(ui, repo)
5527
5527
5528 if opts.get('remote'):
5528 if opts.get('remote'):
5529 t = []
5529 t = []
5530 source, branches = hg.parseurl(ui.expandpath('default'))
5530 source, branches = hg.parseurl(ui.expandpath('default'))
5531 sbranch = branches[0]
5531 sbranch = branches[0]
5532 other = hg.peer(repo, {}, source)
5532 other = hg.peer(repo, {}, source)
5533 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5533 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5534 if revs:
5534 if revs:
5535 revs = [other.lookup(rev) for rev in revs]
5535 revs = [other.lookup(rev) for rev in revs]
5536 ui.debug('comparing with %s\n' % util.hidepassword(source))
5536 ui.debug('comparing with %s\n' % util.hidepassword(source))
5537 repo.ui.pushbuffer()
5537 repo.ui.pushbuffer()
5538 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5538 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5539 _common, incoming, _rheads = commoninc
5539 _common, incoming, _rheads = commoninc
5540 repo.ui.popbuffer()
5540 repo.ui.popbuffer()
5541 if incoming:
5541 if incoming:
5542 t.append(_('1 or more incoming'))
5542 t.append(_('1 or more incoming'))
5543
5543
5544 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5544 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5545 dbranch = branches[0]
5545 dbranch = branches[0]
5546 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5546 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5547 if source != dest:
5547 if source != dest:
5548 other = hg.peer(repo, {}, dest)
5548 other = hg.peer(repo, {}, dest)
5549 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5549 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5550 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5550 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5551 commoninc = None
5551 commoninc = None
5552 if revs:
5552 if revs:
5553 revs = [repo.lookup(rev) for rev in revs]
5553 revs = [repo.lookup(rev) for rev in revs]
5554 repo.ui.pushbuffer()
5554 repo.ui.pushbuffer()
5555 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs,
5555 outgoing = discovery.findcommonoutgoing(repo, other, onlyheads=revs,
5556 commoninc=commoninc)
5556 commoninc=commoninc)
5557 repo.ui.popbuffer()
5557 repo.ui.popbuffer()
5558 o = outgoing.missing
5558 o = outgoing.missing
5559 if o:
5559 if o:
5560 t.append(_('%d outgoing') % len(o))
5560 t.append(_('%d outgoing') % len(o))
5561 if 'bookmarks' in other.listkeys('namespaces'):
5561 if 'bookmarks' in other.listkeys('namespaces'):
5562 lmarks = repo.listkeys('bookmarks')
5562 lmarks = repo.listkeys('bookmarks')
5563 rmarks = other.listkeys('bookmarks')
5563 rmarks = other.listkeys('bookmarks')
5564 diff = set(rmarks) - set(lmarks)
5564 diff = set(rmarks) - set(lmarks)
5565 if len(diff) > 0:
5565 if len(diff) > 0:
5566 t.append(_('%d incoming bookmarks') % len(diff))
5566 t.append(_('%d incoming bookmarks') % len(diff))
5567 diff = set(lmarks) - set(rmarks)
5567 diff = set(lmarks) - set(rmarks)
5568 if len(diff) > 0:
5568 if len(diff) > 0:
5569 t.append(_('%d outgoing bookmarks') % len(diff))
5569 t.append(_('%d outgoing bookmarks') % len(diff))
5570
5570
5571 if t:
5571 if t:
5572 # i18n: column positioning for "hg summary"
5572 # i18n: column positioning for "hg summary"
5573 ui.write(_('remote: %s\n') % (', '.join(t)))
5573 ui.write(_('remote: %s\n') % (', '.join(t)))
5574 else:
5574 else:
5575 # i18n: column positioning for "hg summary"
5575 # i18n: column positioning for "hg summary"
5576 ui.status(_('remote: (synced)\n'))
5576 ui.status(_('remote: (synced)\n'))
5577
5577
5578 @command('tag',
5578 @command('tag',
5579 [('f', 'force', None, _('force tag')),
5579 [('f', 'force', None, _('force tag')),
5580 ('l', 'local', None, _('make the tag local')),
5580 ('l', 'local', None, _('make the tag local')),
5581 ('r', 'rev', '', _('revision to tag'), _('REV')),
5581 ('r', 'rev', '', _('revision to tag'), _('REV')),
5582 ('', 'remove', None, _('remove a tag')),
5582 ('', 'remove', None, _('remove a tag')),
5583 # -l/--local is already there, commitopts cannot be used
5583 # -l/--local is already there, commitopts cannot be used
5584 ('e', 'edit', None, _('edit commit message')),
5584 ('e', 'edit', None, _('edit commit message')),
5585 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5585 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5586 ] + commitopts2,
5586 ] + commitopts2,
5587 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5587 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5588 def tag(ui, repo, name1, *names, **opts):
5588 def tag(ui, repo, name1, *names, **opts):
5589 """add one or more tags for the current or given revision
5589 """add one or more tags for the current or given revision
5590
5590
5591 Name a particular revision using <name>.
5591 Name a particular revision using <name>.
5592
5592
5593 Tags are used to name particular revisions of the repository and are
5593 Tags are used to name particular revisions of the repository and are
5594 very useful to compare different revisions, to go back to significant
5594 very useful to compare different revisions, to go back to significant
5595 earlier versions or to mark branch points as releases, etc. Changing
5595 earlier versions or to mark branch points as releases, etc. Changing
5596 an existing tag is normally disallowed; use -f/--force to override.
5596 an existing tag is normally disallowed; use -f/--force to override.
5597
5597
5598 If no revision is given, the parent of the working directory is
5598 If no revision is given, the parent of the working directory is
5599 used.
5599 used.
5600
5600
5601 To facilitate version control, distribution, and merging of tags,
5601 To facilitate version control, distribution, and merging of tags,
5602 they are stored as a file named ".hgtags" which is managed similarly
5602 they are stored as a file named ".hgtags" which is managed similarly
5603 to other project files and can be hand-edited if necessary. This
5603 to other project files and can be hand-edited if necessary. This
5604 also means that tagging creates a new commit. The file
5604 also means that tagging creates a new commit. The file
5605 ".hg/localtags" is used for local tags (not shared among
5605 ".hg/localtags" is used for local tags (not shared among
5606 repositories).
5606 repositories).
5607
5607
5608 Tag commits are usually made at the head of a branch. If the parent
5608 Tag commits are usually made at the head of a branch. If the parent
5609 of the working directory is not a branch head, :hg:`tag` aborts; use
5609 of the working directory is not a branch head, :hg:`tag` aborts; use
5610 -f/--force to force the tag commit to be based on a non-head
5610 -f/--force to force the tag commit to be based on a non-head
5611 changeset.
5611 changeset.
5612
5612
5613 See :hg:`help dates` for a list of formats valid for -d/--date.
5613 See :hg:`help dates` for a list of formats valid for -d/--date.
5614
5614
5615 Since tag names have priority over branch names during revision
5615 Since tag names have priority over branch names during revision
5616 lookup, using an existing branch name as a tag name is discouraged.
5616 lookup, using an existing branch name as a tag name is discouraged.
5617
5617
5618 Returns 0 on success.
5618 Returns 0 on success.
5619 """
5619 """
5620 wlock = lock = None
5620 wlock = lock = None
5621 try:
5621 try:
5622 wlock = repo.wlock()
5622 wlock = repo.wlock()
5623 lock = repo.lock()
5623 lock = repo.lock()
5624 rev_ = "."
5624 rev_ = "."
5625 names = [t.strip() for t in (name1,) + names]
5625 names = [t.strip() for t in (name1,) + names]
5626 if len(names) != len(set(names)):
5626 if len(names) != len(set(names)):
5627 raise util.Abort(_('tag names must be unique'))
5627 raise util.Abort(_('tag names must be unique'))
5628 for n in names:
5628 for n in names:
5629 scmutil.checknewlabel(repo, n, 'tag')
5629 scmutil.checknewlabel(repo, n, 'tag')
5630 if not n:
5630 if not n:
5631 raise util.Abort(_('tag names cannot consist entirely of '
5631 raise util.Abort(_('tag names cannot consist entirely of '
5632 'whitespace'))
5632 'whitespace'))
5633 if opts.get('rev') and opts.get('remove'):
5633 if opts.get('rev') and opts.get('remove'):
5634 raise util.Abort(_("--rev and --remove are incompatible"))
5634 raise util.Abort(_("--rev and --remove are incompatible"))
5635 if opts.get('rev'):
5635 if opts.get('rev'):
5636 rev_ = opts['rev']
5636 rev_ = opts['rev']
5637 message = opts.get('message')
5637 message = opts.get('message')
5638 if opts.get('remove'):
5638 if opts.get('remove'):
5639 expectedtype = opts.get('local') and 'local' or 'global'
5639 expectedtype = opts.get('local') and 'local' or 'global'
5640 for n in names:
5640 for n in names:
5641 if not repo.tagtype(n):
5641 if not repo.tagtype(n):
5642 raise util.Abort(_("tag '%s' does not exist") % n)
5642 raise util.Abort(_("tag '%s' does not exist") % n)
5643 if repo.tagtype(n) != expectedtype:
5643 if repo.tagtype(n) != expectedtype:
5644 if expectedtype == 'global':
5644 if expectedtype == 'global':
5645 raise util.Abort(_("tag '%s' is not a global tag") % n)
5645 raise util.Abort(_("tag '%s' is not a global tag") % n)
5646 else:
5646 else:
5647 raise util.Abort(_("tag '%s' is not a local tag") % n)
5647 raise util.Abort(_("tag '%s' is not a local tag") % n)
5648 rev_ = nullid
5648 rev_ = nullid
5649 if not message:
5649 if not message:
5650 # we don't translate commit messages
5650 # we don't translate commit messages
5651 message = 'Removed tag %s' % ', '.join(names)
5651 message = 'Removed tag %s' % ', '.join(names)
5652 elif not opts.get('force'):
5652 elif not opts.get('force'):
5653 for n in names:
5653 for n in names:
5654 if n in repo.tags():
5654 if n in repo.tags():
5655 raise util.Abort(_("tag '%s' already exists "
5655 raise util.Abort(_("tag '%s' already exists "
5656 "(use -f to force)") % n)
5656 "(use -f to force)") % n)
5657 if not opts.get('local'):
5657 if not opts.get('local'):
5658 p1, p2 = repo.dirstate.parents()
5658 p1, p2 = repo.dirstate.parents()
5659 if p2 != nullid:
5659 if p2 != nullid:
5660 raise util.Abort(_('uncommitted merge'))
5660 raise util.Abort(_('uncommitted merge'))
5661 bheads = repo.branchheads()
5661 bheads = repo.branchheads()
5662 if not opts.get('force') and bheads and p1 not in bheads:
5662 if not opts.get('force') and bheads and p1 not in bheads:
5663 raise util.Abort(_('not at a branch head (use -f to force)'))
5663 raise util.Abort(_('not at a branch head (use -f to force)'))
5664 r = scmutil.revsingle(repo, rev_).node()
5664 r = scmutil.revsingle(repo, rev_).node()
5665
5665
5666 if not message:
5666 if not message:
5667 # we don't translate commit messages
5667 # we don't translate commit messages
5668 message = ('Added tag %s for changeset %s' %
5668 message = ('Added tag %s for changeset %s' %
5669 (', '.join(names), short(r)))
5669 (', '.join(names), short(r)))
5670
5670
5671 date = opts.get('date')
5671 date = opts.get('date')
5672 if date:
5672 if date:
5673 date = util.parsedate(date)
5673 date = util.parsedate(date)
5674
5674
5675 if opts.get('edit'):
5675 if opts.get('edit'):
5676 message = ui.edit(message, ui.username())
5676 message = ui.edit(message, ui.username())
5677 repo.savecommitmessage(message)
5677 repo.savecommitmessage(message)
5678
5678
5679 # don't allow tagging the null rev
5679 # don't allow tagging the null rev
5680 if (not opts.get('remove') and
5680 if (not opts.get('remove') and
5681 scmutil.revsingle(repo, rev_).rev() == nullrev):
5681 scmutil.revsingle(repo, rev_).rev() == nullrev):
5682 raise util.Abort(_("cannot tag null revision"))
5682 raise util.Abort(_("cannot tag null revision"))
5683
5683
5684 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5684 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
5685 finally:
5685 finally:
5686 release(lock, wlock)
5686 release(lock, wlock)
5687
5687
5688 @command('tags', [], '')
5688 @command('tags', [], '')
5689 def tags(ui, repo, **opts):
5689 def tags(ui, repo, **opts):
5690 """list repository tags
5690 """list repository tags
5691
5691
5692 This lists both regular and local tags. When the -v/--verbose
5692 This lists both regular and local tags. When the -v/--verbose
5693 switch is used, a third column "local" is printed for local tags.
5693 switch is used, a third column "local" is printed for local tags.
5694
5694
5695 Returns 0 on success.
5695 Returns 0 on success.
5696 """
5696 """
5697
5697
5698 fm = ui.formatter('tags', opts)
5698 fm = ui.formatter('tags', opts)
5699 hexfunc = ui.debugflag and hex or short
5699 hexfunc = ui.debugflag and hex or short
5700 tagtype = ""
5700 tagtype = ""
5701
5701
5702 for t, n in reversed(repo.tagslist()):
5702 for t, n in reversed(repo.tagslist()):
5703 hn = hexfunc(n)
5703 hn = hexfunc(n)
5704 label = 'tags.normal'
5704 label = 'tags.normal'
5705 tagtype = ''
5705 tagtype = ''
5706 if repo.tagtype(t) == 'local':
5706 if repo.tagtype(t) == 'local':
5707 label = 'tags.local'
5707 label = 'tags.local'
5708 tagtype = 'local'
5708 tagtype = 'local'
5709
5709
5710 fm.startitem()
5710 fm.startitem()
5711 fm.write('tag', '%s', t, label=label)
5711 fm.write('tag', '%s', t, label=label)
5712 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5712 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5713 fm.condwrite(not ui.quiet, 'rev id', fmt,
5713 fm.condwrite(not ui.quiet, 'rev id', fmt,
5714 repo.changelog.rev(n), hn, label=label)
5714 repo.changelog.rev(n), hn, label=label)
5715 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5715 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5716 tagtype, label=label)
5716 tagtype, label=label)
5717 fm.plain('\n')
5717 fm.plain('\n')
5718 fm.end()
5718 fm.end()
5719
5719
5720 @command('tip',
5720 @command('tip',
5721 [('p', 'patch', None, _('show patch')),
5721 [('p', 'patch', None, _('show patch')),
5722 ('g', 'git', None, _('use git extended diff format')),
5722 ('g', 'git', None, _('use git extended diff format')),
5723 ] + templateopts,
5723 ] + templateopts,
5724 _('[-p] [-g]'))
5724 _('[-p] [-g]'))
5725 def tip(ui, repo, **opts):
5725 def tip(ui, repo, **opts):
5726 """show the tip revision (DEPRECATED)
5726 """show the tip revision (DEPRECATED)
5727
5727
5728 The tip revision (usually just called the tip) is the changeset
5728 The tip revision (usually just called the tip) is the changeset
5729 most recently added to the repository (and therefore the most
5729 most recently added to the repository (and therefore the most
5730 recently changed head).
5730 recently changed head).
5731
5731
5732 If you have just made a commit, that commit will be the tip. If
5732 If you have just made a commit, that commit will be the tip. If
5733 you have just pulled changes from another repository, the tip of
5733 you have just pulled changes from another repository, the tip of
5734 that repository becomes the current tip. The "tip" tag is special
5734 that repository becomes the current tip. The "tip" tag is special
5735 and cannot be renamed or assigned to a different changeset.
5735 and cannot be renamed or assigned to a different changeset.
5736
5736
5737 This command is deprecated, please use :hg:`heads` instead.
5737 This command is deprecated, please use :hg:`heads` instead.
5738
5738
5739 Returns 0 on success.
5739 Returns 0 on success.
5740 """
5740 """
5741 displayer = cmdutil.show_changeset(ui, repo, opts)
5741 displayer = cmdutil.show_changeset(ui, repo, opts)
5742 displayer.show(repo['tip'])
5742 displayer.show(repo['tip'])
5743 displayer.close()
5743 displayer.close()
5744
5744
5745 @command('unbundle',
5745 @command('unbundle',
5746 [('u', 'update', None,
5746 [('u', 'update', None,
5747 _('update to new branch head if changesets were unbundled'))],
5747 _('update to new branch head if changesets were unbundled'))],
5748 _('[-u] FILE...'))
5748 _('[-u] FILE...'))
5749 def unbundle(ui, repo, fname1, *fnames, **opts):
5749 def unbundle(ui, repo, fname1, *fnames, **opts):
5750 """apply one or more changegroup files
5750 """apply one or more changegroup files
5751
5751
5752 Apply one or more compressed changegroup files generated by the
5752 Apply one or more compressed changegroup files generated by the
5753 bundle command.
5753 bundle command.
5754
5754
5755 Returns 0 on success, 1 if an update has unresolved files.
5755 Returns 0 on success, 1 if an update has unresolved files.
5756 """
5756 """
5757 fnames = (fname1,) + fnames
5757 fnames = (fname1,) + fnames
5758
5758
5759 lock = repo.lock()
5759 lock = repo.lock()
5760 wc = repo['.']
5760 wc = repo['.']
5761 try:
5761 try:
5762 for fname in fnames:
5762 for fname in fnames:
5763 f = hg.openpath(ui, fname)
5763 f = hg.openpath(ui, fname)
5764 gen = changegroup.readbundle(f, fname)
5764 gen = changegroup.readbundle(f, fname)
5765 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5765 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
5766 finally:
5766 finally:
5767 lock.release()
5767 lock.release()
5768 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5768 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5769 return postincoming(ui, repo, modheads, opts.get('update'), None)
5769 return postincoming(ui, repo, modheads, opts.get('update'), None)
5770
5770
5771 @command('^update|up|checkout|co',
5771 @command('^update|up|checkout|co',
5772 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5772 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5773 ('c', 'check', None,
5773 ('c', 'check', None,
5774 _('update across branches if no uncommitted changes')),
5774 _('update across branches if no uncommitted changes')),
5775 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5775 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5776 ('r', 'rev', '', _('revision'), _('REV'))],
5776 ('r', 'rev', '', _('revision'), _('REV'))],
5777 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5777 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5778 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5778 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5779 """update working directory (or switch revisions)
5779 """update working directory (or switch revisions)
5780
5780
5781 Update the repository's working directory to the specified
5781 Update the repository's working directory to the specified
5782 changeset. If no changeset is specified, update to the tip of the
5782 changeset. If no changeset is specified, update to the tip of the
5783 current named branch and move the current bookmark (see :hg:`help
5783 current named branch and move the current bookmark (see :hg:`help
5784 bookmarks`).
5784 bookmarks`).
5785
5785
5786 Update sets the working directory's parent revision to the specified
5786 Update sets the working directory's parent revision to the specified
5787 changeset (see :hg:`help parents`).
5787 changeset (see :hg:`help parents`).
5788
5788
5789 If the changeset is not a descendant or ancestor of the working
5789 If the changeset is not a descendant or ancestor of the working
5790 directory's parent, the update is aborted. With the -c/--check
5790 directory's parent, the update is aborted. With the -c/--check
5791 option, the working directory is checked for uncommitted changes; if
5791 option, the working directory is checked for uncommitted changes; if
5792 none are found, the working directory is updated to the specified
5792 none are found, the working directory is updated to the specified
5793 changeset.
5793 changeset.
5794
5794
5795 .. container:: verbose
5795 .. container:: verbose
5796
5796
5797 The following rules apply when the working directory contains
5797 The following rules apply when the working directory contains
5798 uncommitted changes:
5798 uncommitted changes:
5799
5799
5800 1. If neither -c/--check nor -C/--clean is specified, and if
5800 1. If neither -c/--check nor -C/--clean is specified, and if
5801 the requested changeset is an ancestor or descendant of
5801 the requested changeset is an ancestor or descendant of
5802 the working directory's parent, the uncommitted changes
5802 the working directory's parent, the uncommitted changes
5803 are merged into the requested changeset and the merged
5803 are merged into the requested changeset and the merged
5804 result is left uncommitted. If the requested changeset is
5804 result is left uncommitted. If the requested changeset is
5805 not an ancestor or descendant (that is, it is on another
5805 not an ancestor or descendant (that is, it is on another
5806 branch), the update is aborted and the uncommitted changes
5806 branch), the update is aborted and the uncommitted changes
5807 are preserved.
5807 are preserved.
5808
5808
5809 2. With the -c/--check option, the update is aborted and the
5809 2. With the -c/--check option, the update is aborted and the
5810 uncommitted changes are preserved.
5810 uncommitted changes are preserved.
5811
5811
5812 3. With the -C/--clean option, uncommitted changes are discarded and
5812 3. With the -C/--clean option, uncommitted changes are discarded and
5813 the working directory is updated to the requested changeset.
5813 the working directory is updated to the requested changeset.
5814
5814
5815 To cancel an uncommitted merge (and lose your changes), use
5815 To cancel an uncommitted merge (and lose your changes), use
5816 :hg:`update --clean .`.
5816 :hg:`update --clean .`.
5817
5817
5818 Use null as the changeset to remove the working directory (like
5818 Use null as the changeset to remove the working directory (like
5819 :hg:`clone -U`).
5819 :hg:`clone -U`).
5820
5820
5821 If you want to revert just one file to an older revision, use
5821 If you want to revert just one file to an older revision, use
5822 :hg:`revert [-r REV] NAME`.
5822 :hg:`revert [-r REV] NAME`.
5823
5823
5824 See :hg:`help dates` for a list of formats valid for -d/--date.
5824 See :hg:`help dates` for a list of formats valid for -d/--date.
5825
5825
5826 Returns 0 on success, 1 if there are unresolved files.
5826 Returns 0 on success, 1 if there are unresolved files.
5827 """
5827 """
5828 if rev and node:
5828 if rev and node:
5829 raise util.Abort(_("please specify just one revision"))
5829 raise util.Abort(_("please specify just one revision"))
5830
5830
5831 if rev is None or rev == '':
5831 if rev is None or rev == '':
5832 rev = node
5832 rev = node
5833
5833
5834 cmdutil.clearunfinished(repo)
5834 cmdutil.clearunfinished(repo)
5835
5835
5836 # with no argument, we also move the current bookmark, if any
5836 # with no argument, we also move the current bookmark, if any
5837 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5837 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5838
5838
5839 # if we defined a bookmark, we have to remember the original bookmark name
5839 # if we defined a bookmark, we have to remember the original bookmark name
5840 brev = rev
5840 brev = rev
5841 rev = scmutil.revsingle(repo, rev, rev).rev()
5841 rev = scmutil.revsingle(repo, rev, rev).rev()
5842
5842
5843 if check and clean:
5843 if check and clean:
5844 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5844 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5845
5845
5846 if date:
5846 if date:
5847 if rev is not None:
5847 if rev is not None:
5848 raise util.Abort(_("you can't specify a revision and a date"))
5848 raise util.Abort(_("you can't specify a revision and a date"))
5849 rev = cmdutil.finddate(ui, repo, date)
5849 rev = cmdutil.finddate(ui, repo, date)
5850
5850
5851 if check:
5851 if check:
5852 c = repo[None]
5852 c = repo[None]
5853 if c.dirty(merge=False, branch=False, missing=True):
5853 if c.dirty(merge=False, branch=False, missing=True):
5854 raise util.Abort(_("uncommitted changes"))
5854 raise util.Abort(_("uncommitted changes"))
5855 if rev is None:
5855 if rev is None:
5856 rev = repo[repo[None].branch()].rev()
5856 rev = repo[repo[None].branch()].rev()
5857 mergemod._checkunknown(repo, repo[None], repo[rev])
5857 mergemod._checkunknown(repo, repo[None], repo[rev])
5858
5858
5859 if clean:
5859 if clean:
5860 ret = hg.clean(repo, rev)
5860 ret = hg.clean(repo, rev)
5861 else:
5861 else:
5862 ret = hg.update(repo, rev)
5862 ret = hg.update(repo, rev)
5863
5863
5864 if not ret and movemarkfrom:
5864 if not ret and movemarkfrom:
5865 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5865 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5866 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5866 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5867 elif brev in repo._bookmarks:
5867 elif brev in repo._bookmarks:
5868 bookmarks.setcurrent(repo, brev)
5868 bookmarks.setcurrent(repo, brev)
5869 elif brev:
5869 elif brev:
5870 bookmarks.unsetcurrent(repo)
5870 bookmarks.unsetcurrent(repo)
5871
5871
5872 return ret
5872 return ret
5873
5873
5874 @command('verify', [])
5874 @command('verify', [])
5875 def verify(ui, repo):
5875 def verify(ui, repo):
5876 """verify the integrity of the repository
5876 """verify the integrity of the repository
5877
5877
5878 Verify the integrity of the current repository.
5878 Verify the integrity of the current repository.
5879
5879
5880 This will perform an extensive check of the repository's
5880 This will perform an extensive check of the repository's
5881 integrity, validating the hashes and checksums of each entry in
5881 integrity, validating the hashes and checksums of each entry in
5882 the changelog, manifest, and tracked files, as well as the
5882 the changelog, manifest, and tracked files, as well as the
5883 integrity of their crosslinks and indices.
5883 integrity of their crosslinks and indices.
5884
5884
5885 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5885 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5886 for more information about recovery from corruption of the
5886 for more information about recovery from corruption of the
5887 repository.
5887 repository.
5888
5888
5889 Returns 0 on success, 1 if errors are encountered.
5889 Returns 0 on success, 1 if errors are encountered.
5890 """
5890 """
5891 return hg.verify(repo)
5891 return hg.verify(repo)
5892
5892
5893 @command('version', [])
5893 @command('version', [])
5894 def version_(ui):
5894 def version_(ui):
5895 """output version and copyright information"""
5895 """output version and copyright information"""
5896 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5896 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5897 % util.version())
5897 % util.version())
5898 ui.status(_(
5898 ui.status(_(
5899 "(see http://mercurial.selenic.com for more information)\n"
5899 "(see http://mercurial.selenic.com for more information)\n"
5900 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
5900 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
5901 "This is free software; see the source for copying conditions. "
5901 "This is free software; see the source for copying conditions. "
5902 "There is NO\nwarranty; "
5902 "There is NO\nwarranty; "
5903 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5903 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5904 ))
5904 ))
5905
5905
5906 norepo = ("clone init version help debugcommands debugcomplete"
5906 norepo = ("clone init version help debugcommands debugcomplete"
5907 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5907 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5908 " debugknown debuggetbundle debugbundle")
5908 " debugknown debuggetbundle debugbundle")
5909 optionalrepo = ("identify paths serve config showconfig debugancestor debugdag"
5909 optionalrepo = ("identify paths serve config showconfig debugancestor debugdag"
5910 " debugdata debugindex debugindexdot debugrevlog")
5910 " debugdata debugindex debugindexdot debugrevlog")
5911 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5911 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5912 " remove resolve status debugwalk")
5912 " remove resolve status debugwalk")
@@ -1,500 +1,500
1 $ hg init basic
1 $ hg init basic
2 $ cd basic
2 $ cd basic
3
3
4 should complain
4 should complain
5
5
6 $ hg backout
6 $ hg backout
7 abort: please specify a revision to backout
7 abort: please specify a revision to backout
8 [255]
8 [255]
9 $ hg backout -r 0 0
9 $ hg backout -r 0 0
10 abort: please specify just one revision
10 abort: please specify just one revision
11 [255]
11 [255]
12
12
13 basic operation
13 basic operation
14
14
15 $ echo a > a
15 $ echo a > a
16 $ hg commit -d '0 0' -A -m a
16 $ hg commit -d '0 0' -A -m a
17 adding a
17 adding a
18 $ echo b >> a
18 $ echo b >> a
19 $ hg commit -d '1 0' -m b
19 $ hg commit -d '1 0' -m b
20
20
21 $ hg backout -d '2 0' tip --tool=true
21 $ hg backout -d '2 0' tip --tool=true
22 reverting a
22 reverting a
23 changeset 2:2929462c3dff backs out changeset 1:a820f4f40a57
23 changeset 2:2929462c3dff backs out changeset 1:a820f4f40a57
24 $ cat a
24 $ cat a
25 a
25 a
26 $ hg summary
26 $ hg summary
27 parent: 2:2929462c3dff tip
27 parent: 2:2929462c3dff tip
28 Backed out changeset a820f4f40a57
28 Backed out changeset a820f4f40a57
29 branch: default
29 branch: default
30 commit: (clean)
30 commit: (clean)
31 update: (current)
31 update: (current)
32
32
33 file that was removed is recreated
33 file that was removed is recreated
34
34
35 $ cd ..
35 $ cd ..
36 $ hg init remove
36 $ hg init remove
37 $ cd remove
37 $ cd remove
38
38
39 $ echo content > a
39 $ echo content > a
40 $ hg commit -d '0 0' -A -m a
40 $ hg commit -d '0 0' -A -m a
41 adding a
41 adding a
42
42
43 $ hg rm a
43 $ hg rm a
44 $ hg commit -d '1 0' -m b
44 $ hg commit -d '1 0' -m b
45
45
46 $ hg backout -d '2 0' tip --tool=true
46 $ hg backout -d '2 0' tip --tool=true
47 adding a
47 adding a
48 changeset 2:de31bdc76c0d backs out changeset 1:76862dcce372
48 changeset 2:de31bdc76c0d backs out changeset 1:76862dcce372
49 $ cat a
49 $ cat a
50 content
50 content
51 $ hg summary
51 $ hg summary
52 parent: 2:de31bdc76c0d tip
52 parent: 2:de31bdc76c0d tip
53 Backed out changeset 76862dcce372
53 Backed out changeset 76862dcce372
54 branch: default
54 branch: default
55 commit: (clean)
55 commit: (clean)
56 update: (current)
56 update: (current)
57
57
58 backout of backout is as if nothing happened
58 backout of backout is as if nothing happened
59
59
60 $ hg backout -d '3 0' --merge tip --tool=true
60 $ hg backout -d '3 0' --merge tip --tool=true
61 removing a
61 removing a
62 changeset 3:7f6d0f120113 backs out changeset 2:de31bdc76c0d
62 changeset 3:7f6d0f120113 backs out changeset 2:de31bdc76c0d
63 $ test -f a
63 $ test -f a
64 [1]
64 [1]
65 $ hg summary
65 $ hg summary
66 parent: 3:7f6d0f120113 tip
66 parent: 3:7f6d0f120113 tip
67 Backed out changeset de31bdc76c0d
67 Backed out changeset de31bdc76c0d
68 branch: default
68 branch: default
69 commit: (clean)
69 commit: (clean)
70 update: (current)
70 update: (current)
71
71
72 across branch
72 across branch
73
73
74 $ cd ..
74 $ cd ..
75 $ hg init branch
75 $ hg init branch
76 $ cd branch
76 $ cd branch
77 $ echo a > a
77 $ echo a > a
78 $ hg ci -Am0
78 $ hg ci -Am0
79 adding a
79 adding a
80 $ echo b > b
80 $ echo b > b
81 $ hg ci -Am1
81 $ hg ci -Am1
82 adding b
82 adding b
83 $ hg co -C 0
83 $ hg co -C 0
84 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
84 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
85 $ hg summary
85 $ hg summary
86 parent: 0:f7b1eb17ad24
86 parent: 0:f7b1eb17ad24
87 0
87 0
88 branch: default
88 branch: default
89 commit: (clean)
89 commit: (clean)
90 update: 1 new changesets (update)
90 update: 1 new changesets (update)
91
91
92 should fail
92 should fail
93
93
94 $ hg backout 1
94 $ hg backout 1
95 abort: cannot backout change on a different branch
95 abort: cannot backout change that is not an ancestor
96 [255]
96 [255]
97 $ echo c > c
97 $ echo c > c
98 $ hg ci -Am2
98 $ hg ci -Am2
99 adding c
99 adding c
100 created new head
100 created new head
101 $ hg summary
101 $ hg summary
102 parent: 2:db815d6d32e6 tip
102 parent: 2:db815d6d32e6 tip
103 2
103 2
104 branch: default
104 branch: default
105 commit: (clean)
105 commit: (clean)
106 update: 1 new changesets, 2 branch heads (merge)
106 update: 1 new changesets, 2 branch heads (merge)
107
107
108 should fail
108 should fail
109
109
110 $ hg backout 1
110 $ hg backout 1
111 abort: cannot backout change on a different branch
111 abort: cannot backout change that is not an ancestor
112 [255]
112 [255]
113 $ hg summary
113 $ hg summary
114 parent: 2:db815d6d32e6 tip
114 parent: 2:db815d6d32e6 tip
115 2
115 2
116 branch: default
116 branch: default
117 commit: (clean)
117 commit: (clean)
118 update: 1 new changesets, 2 branch heads (merge)
118 update: 1 new changesets, 2 branch heads (merge)
119
119
120 backout with merge
120 backout with merge
121
121
122 $ cd ..
122 $ cd ..
123 $ hg init merge
123 $ hg init merge
124 $ cd merge
124 $ cd merge
125
125
126 $ echo line 1 > a
126 $ echo line 1 > a
127 $ echo line 2 >> a
127 $ echo line 2 >> a
128 $ hg commit -d '0 0' -A -m a
128 $ hg commit -d '0 0' -A -m a
129 adding a
129 adding a
130 $ hg summary
130 $ hg summary
131 parent: 0:59395513a13a tip
131 parent: 0:59395513a13a tip
132 a
132 a
133 branch: default
133 branch: default
134 commit: (clean)
134 commit: (clean)
135 update: (current)
135 update: (current)
136
136
137 remove line 1
137 remove line 1
138
138
139 $ echo line 2 > a
139 $ echo line 2 > a
140 $ hg commit -d '1 0' -m b
140 $ hg commit -d '1 0' -m b
141
141
142 $ echo line 3 >> a
142 $ echo line 3 >> a
143 $ hg commit -d '2 0' -m c
143 $ hg commit -d '2 0' -m c
144
144
145 $ hg backout --merge -d '3 0' 1 --tool=true
145 $ hg backout --merge -d '3 0' 1 --tool=true
146 reverting a
146 reverting a
147 created new head
147 created new head
148 changeset 3:26b8ccb9ad91 backs out changeset 1:5a50a024c182
148 changeset 3:26b8ccb9ad91 backs out changeset 1:5a50a024c182
149 merging with changeset 3:26b8ccb9ad91
149 merging with changeset 3:26b8ccb9ad91
150 merging a
150 merging a
151 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
151 0 files updated, 1 files merged, 0 files removed, 0 files unresolved
152 (branch merge, don't forget to commit)
152 (branch merge, don't forget to commit)
153 $ hg commit -d '4 0' -m d
153 $ hg commit -d '4 0' -m d
154 $ hg summary
154 $ hg summary
155 parent: 4:c7df5e0b9c09 tip
155 parent: 4:c7df5e0b9c09 tip
156 d
156 d
157 branch: default
157 branch: default
158 commit: (clean)
158 commit: (clean)
159 update: (current)
159 update: (current)
160
160
161 check line 1 is back
161 check line 1 is back
162
162
163 $ cat a
163 $ cat a
164 line 1
164 line 1
165 line 2
165 line 2
166 line 3
166 line 3
167
167
168 $ cd ..
168 $ cd ..
169
169
170 backout should not back out subsequent changesets
170 backout should not back out subsequent changesets
171
171
172 $ hg init onecs
172 $ hg init onecs
173 $ cd onecs
173 $ cd onecs
174 $ echo 1 > a
174 $ echo 1 > a
175 $ hg commit -d '0 0' -A -m a
175 $ hg commit -d '0 0' -A -m a
176 adding a
176 adding a
177 $ echo 2 >> a
177 $ echo 2 >> a
178 $ hg commit -d '1 0' -m b
178 $ hg commit -d '1 0' -m b
179 $ echo 1 > b
179 $ echo 1 > b
180 $ hg commit -d '2 0' -A -m c
180 $ hg commit -d '2 0' -A -m c
181 adding b
181 adding b
182 $ hg summary
182 $ hg summary
183 parent: 2:882396649954 tip
183 parent: 2:882396649954 tip
184 c
184 c
185 branch: default
185 branch: default
186 commit: (clean)
186 commit: (clean)
187 update: (current)
187 update: (current)
188
188
189 without --merge
189 without --merge
190 $ hg backout -d '3 0' 1 --tool=true
190 $ hg backout -d '3 0' 1 --tool=true
191 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
191 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
192 changeset 22bca4c721e5 backed out, don't forget to commit.
192 changeset 22bca4c721e5 backed out, don't forget to commit.
193 $ hg locate b
193 $ hg locate b
194 b
194 b
195 $ hg update -C tip
195 $ hg update -C tip
196 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
196 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
197 $ hg locate b
197 $ hg locate b
198 b
198 b
199 $ hg summary
199 $ hg summary
200 parent: 2:882396649954 tip
200 parent: 2:882396649954 tip
201 c
201 c
202 branch: default
202 branch: default
203 commit: (clean)
203 commit: (clean)
204 update: (current)
204 update: (current)
205
205
206 with --merge
206 with --merge
207 $ hg backout --merge -d '3 0' 1 --tool=true
207 $ hg backout --merge -d '3 0' 1 --tool=true
208 reverting a
208 reverting a
209 created new head
209 created new head
210 changeset 3:3202beb76721 backs out changeset 1:22bca4c721e5
210 changeset 3:3202beb76721 backs out changeset 1:22bca4c721e5
211 merging with changeset 3:3202beb76721
211 merging with changeset 3:3202beb76721
212 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
212 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
213 (branch merge, don't forget to commit)
213 (branch merge, don't forget to commit)
214 $ hg locate b
214 $ hg locate b
215 b
215 b
216 $ hg update -C tip
216 $ hg update -C tip
217 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
217 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
218 $ hg locate b
218 $ hg locate b
219 [1]
219 [1]
220
220
221 $ cd ..
221 $ cd ..
222 $ hg init m
222 $ hg init m
223 $ cd m
223 $ cd m
224 $ echo a > a
224 $ echo a > a
225 $ hg commit -d '0 0' -A -m a
225 $ hg commit -d '0 0' -A -m a
226 adding a
226 adding a
227 $ echo b > b
227 $ echo b > b
228 $ hg commit -d '1 0' -A -m b
228 $ hg commit -d '1 0' -A -m b
229 adding b
229 adding b
230 $ echo c > c
230 $ echo c > c
231 $ hg commit -d '2 0' -A -m b
231 $ hg commit -d '2 0' -A -m b
232 adding c
232 adding c
233 $ hg update 1
233 $ hg update 1
234 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
234 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
235 $ echo d > d
235 $ echo d > d
236 $ hg commit -d '3 0' -A -m c
236 $ hg commit -d '3 0' -A -m c
237 adding d
237 adding d
238 created new head
238 created new head
239 $ hg merge 2
239 $ hg merge 2
240 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
240 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
241 (branch merge, don't forget to commit)
241 (branch merge, don't forget to commit)
242 $ hg commit -d '4 0' -A -m d
242 $ hg commit -d '4 0' -A -m d
243 $ hg summary
243 $ hg summary
244 parent: 4:b2f3bb92043e tip
244 parent: 4:b2f3bb92043e tip
245 d
245 d
246 branch: default
246 branch: default
247 commit: (clean)
247 commit: (clean)
248 update: (current)
248 update: (current)
249
249
250 backout of merge should fail
250 backout of merge should fail
251
251
252 $ hg backout 4
252 $ hg backout 4
253 abort: cannot backout a merge changeset
253 abort: cannot backout a merge changeset
254 [255]
254 [255]
255
255
256 backout of merge with bad parent should fail
256 backout of merge with bad parent should fail
257
257
258 $ hg backout --parent 0 4
258 $ hg backout --parent 0 4
259 abort: cb9a9f314b8b is not a parent of b2f3bb92043e
259 abort: cb9a9f314b8b is not a parent of b2f3bb92043e
260 [255]
260 [255]
261
261
262 backout of non-merge with parent should fail
262 backout of non-merge with parent should fail
263
263
264 $ hg backout --parent 0 3
264 $ hg backout --parent 0 3
265 abort: cannot use --parent on non-merge changeset
265 abort: cannot use --parent on non-merge changeset
266 [255]
266 [255]
267
267
268 backout with valid parent should be ok
268 backout with valid parent should be ok
269
269
270 $ hg backout -d '5 0' --parent 2 4 --tool=true
270 $ hg backout -d '5 0' --parent 2 4 --tool=true
271 removing d
271 removing d
272 changeset 5:10e5328c8435 backs out changeset 4:b2f3bb92043e
272 changeset 5:10e5328c8435 backs out changeset 4:b2f3bb92043e
273 $ hg summary
273 $ hg summary
274 parent: 5:10e5328c8435 tip
274 parent: 5:10e5328c8435 tip
275 Backed out changeset b2f3bb92043e
275 Backed out changeset b2f3bb92043e
276 branch: default
276 branch: default
277 commit: (clean)
277 commit: (clean)
278 update: (current)
278 update: (current)
279
279
280 $ hg rollback
280 $ hg rollback
281 repository tip rolled back to revision 4 (undo commit)
281 repository tip rolled back to revision 4 (undo commit)
282 working directory now based on revision 4
282 working directory now based on revision 4
283 $ hg update -C
283 $ hg update -C
284 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
284 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
285 $ hg summary
285 $ hg summary
286 parent: 4:b2f3bb92043e tip
286 parent: 4:b2f3bb92043e tip
287 d
287 d
288 branch: default
288 branch: default
289 commit: (clean)
289 commit: (clean)
290 update: (current)
290 update: (current)
291
291
292 $ hg backout -d '6 0' --parent 3 4 --tool=true
292 $ hg backout -d '6 0' --parent 3 4 --tool=true
293 removing c
293 removing c
294 changeset 5:033590168430 backs out changeset 4:b2f3bb92043e
294 changeset 5:033590168430 backs out changeset 4:b2f3bb92043e
295 $ hg summary
295 $ hg summary
296 parent: 5:033590168430 tip
296 parent: 5:033590168430 tip
297 Backed out changeset b2f3bb92043e
297 Backed out changeset b2f3bb92043e
298 branch: default
298 branch: default
299 commit: (clean)
299 commit: (clean)
300 update: (current)
300 update: (current)
301
301
302 $ cd ..
302 $ cd ..
303
303
304 named branches
304 named branches
305
305
306 $ hg init named_branches
306 $ hg init named_branches
307 $ cd named_branches
307 $ cd named_branches
308
308
309 $ echo default > default
309 $ echo default > default
310 $ hg ci -d '0 0' -Am default
310 $ hg ci -d '0 0' -Am default
311 adding default
311 adding default
312 $ hg branch branch1
312 $ hg branch branch1
313 marked working directory as branch branch1
313 marked working directory as branch branch1
314 (branches are permanent and global, did you want a bookmark?)
314 (branches are permanent and global, did you want a bookmark?)
315 $ echo branch1 > file1
315 $ echo branch1 > file1
316 $ hg ci -d '1 0' -Am file1
316 $ hg ci -d '1 0' -Am file1
317 adding file1
317 adding file1
318 $ hg branch branch2
318 $ hg branch branch2
319 marked working directory as branch branch2
319 marked working directory as branch branch2
320 (branches are permanent and global, did you want a bookmark?)
320 (branches are permanent and global, did you want a bookmark?)
321 $ echo branch2 > file2
321 $ echo branch2 > file2
322 $ hg ci -d '2 0' -Am file2
322 $ hg ci -d '2 0' -Am file2
323 adding file2
323 adding file2
324
324
325 without --merge
325 without --merge
326 $ hg backout -r 1 --tool=true
326 $ hg backout -r 1 --tool=true
327 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
327 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
328 changeset bf1602f437f3 backed out, don't forget to commit.
328 changeset bf1602f437f3 backed out, don't forget to commit.
329 $ hg branch
329 $ hg branch
330 branch2
330 branch2
331 $ hg status -A
331 $ hg status -A
332 R file1
332 R file1
333 C default
333 C default
334 C file2
334 C file2
335 $ hg summary
335 $ hg summary
336 parent: 2:45bbcd363bf0 tip
336 parent: 2:45bbcd363bf0 tip
337 file2
337 file2
338 branch: branch2
338 branch: branch2
339 commit: 1 removed
339 commit: 1 removed
340 update: (current)
340 update: (current)
341
341
342 with --merge
342 with --merge
343 $ hg update -qC
343 $ hg update -qC
344 $ hg backout --merge -d '3 0' -r 1 -m 'backout on branch1' --tool=true
344 $ hg backout --merge -d '3 0' -r 1 -m 'backout on branch1' --tool=true
345 removing file1
345 removing file1
346 created new head
346 created new head
347 changeset 3:d4e8f6db59fb backs out changeset 1:bf1602f437f3
347 changeset 3:d4e8f6db59fb backs out changeset 1:bf1602f437f3
348 merging with changeset 3:d4e8f6db59fb
348 merging with changeset 3:d4e8f6db59fb
349 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
349 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
350 (branch merge, don't forget to commit)
350 (branch merge, don't forget to commit)
351 $ hg summary
351 $ hg summary
352 parent: 2:45bbcd363bf0
352 parent: 2:45bbcd363bf0
353 file2
353 file2
354 parent: 3:d4e8f6db59fb tip
354 parent: 3:d4e8f6db59fb tip
355 backout on branch1
355 backout on branch1
356 branch: branch2
356 branch: branch2
357 commit: 1 removed (merge)
357 commit: 1 removed (merge)
358 update: (current)
358 update: (current)
359 $ hg update -q -C 2
359 $ hg update -q -C 2
360
360
361 on branch2 with branch1 not merged, so file1 should still exist:
361 on branch2 with branch1 not merged, so file1 should still exist:
362
362
363 $ hg id
363 $ hg id
364 45bbcd363bf0 (branch2)
364 45bbcd363bf0 (branch2)
365 $ hg st -A
365 $ hg st -A
366 C default
366 C default
367 C file1
367 C file1
368 C file2
368 C file2
369 $ hg summary
369 $ hg summary
370 parent: 2:45bbcd363bf0
370 parent: 2:45bbcd363bf0
371 file2
371 file2
372 branch: branch2
372 branch: branch2
373 commit: (clean)
373 commit: (clean)
374 update: 1 new changesets, 2 branch heads (merge)
374 update: 1 new changesets, 2 branch heads (merge)
375
375
376 on branch2 with branch1 merged, so file1 should be gone:
376 on branch2 with branch1 merged, so file1 should be gone:
377
377
378 $ hg merge
378 $ hg merge
379 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
379 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
380 (branch merge, don't forget to commit)
380 (branch merge, don't forget to commit)
381 $ hg ci -d '4 0' -m 'merge backout of branch1'
381 $ hg ci -d '4 0' -m 'merge backout of branch1'
382 $ hg id
382 $ hg id
383 22149cdde76d (branch2) tip
383 22149cdde76d (branch2) tip
384 $ hg st -A
384 $ hg st -A
385 C default
385 C default
386 C file2
386 C file2
387 $ hg summary
387 $ hg summary
388 parent: 4:22149cdde76d tip
388 parent: 4:22149cdde76d tip
389 merge backout of branch1
389 merge backout of branch1
390 branch: branch2
390 branch: branch2
391 commit: (clean)
391 commit: (clean)
392 update: (current)
392 update: (current)
393
393
394 on branch1, so no file1 and file2:
394 on branch1, so no file1 and file2:
395
395
396 $ hg co -C branch1
396 $ hg co -C branch1
397 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
397 1 files updated, 0 files merged, 1 files removed, 0 files unresolved
398 $ hg id
398 $ hg id
399 bf1602f437f3 (branch1)
399 bf1602f437f3 (branch1)
400 $ hg st -A
400 $ hg st -A
401 C default
401 C default
402 C file1
402 C file1
403 $ hg summary
403 $ hg summary
404 parent: 1:bf1602f437f3
404 parent: 1:bf1602f437f3
405 file1
405 file1
406 branch: branch1
406 branch: branch1
407 commit: (clean)
407 commit: (clean)
408 update: (current)
408 update: (current)
409
409
410 $ cd ..
410 $ cd ..
411
411
412
412
413 Test usage of `hg resolve` in case of conflict
413 Test usage of `hg resolve` in case of conflict
414 (issue4163)
414 (issue4163)
415
415
416 $ hg init issue4163
416 $ hg init issue4163
417 $ cd issue4163
417 $ cd issue4163
418 $ touch foo
418 $ touch foo
419 $ hg add foo
419 $ hg add foo
420 $ cat > foo << EOF
420 $ cat > foo << EOF
421 > one
421 > one
422 > two
422 > two
423 > three
423 > three
424 > four
424 > four
425 > five
425 > five
426 > six
426 > six
427 > seven
427 > seven
428 > height
428 > height
429 > nine
429 > nine
430 > ten
430 > ten
431 > EOF
431 > EOF
432 $ hg ci -m 'initial'
432 $ hg ci -m 'initial'
433 $ cat > foo << EOF
433 $ cat > foo << EOF
434 > one
434 > one
435 > two
435 > two
436 > THREE
436 > THREE
437 > four
437 > four
438 > five
438 > five
439 > six
439 > six
440 > seven
440 > seven
441 > height
441 > height
442 > nine
442 > nine
443 > ten
443 > ten
444 > EOF
444 > EOF
445 $ hg ci -m 'capital three'
445 $ hg ci -m 'capital three'
446 $ cat > foo << EOF
446 $ cat > foo << EOF
447 > one
447 > one
448 > two
448 > two
449 > THREE
449 > THREE
450 > four
450 > four
451 > five
451 > five
452 > six
452 > six
453 > seven
453 > seven
454 > height
454 > height
455 > nine
455 > nine
456 > TEN
456 > TEN
457 > EOF
457 > EOF
458 $ hg ci -m 'capital ten'
458 $ hg ci -m 'capital ten'
459 $ hg backout -r 'desc("capital three")' --tool internal:fail
459 $ hg backout -r 'desc("capital three")' --tool internal:fail
460 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
460 0 files updated, 0 files merged, 0 files removed, 1 files unresolved
461 use 'hg resolve' to retry unresolved file merges
461 use 'hg resolve' to retry unresolved file merges
462 [1]
462 [1]
463 $ hg status
463 $ hg status
464 $ hg resolve -l # still unresolved
464 $ hg resolve -l # still unresolved
465 U foo
465 U foo
466 $ hg summary
466 $ hg summary
467 parent: 2:b71750c4b0fd tip
467 parent: 2:b71750c4b0fd tip
468 capital ten
468 capital ten
469 branch: default
469 branch: default
470 commit: 1 unresolved (clean)
470 commit: 1 unresolved (clean)
471 update: (current)
471 update: (current)
472 $ hg resolve --all --debug
472 $ hg resolve --all --debug
473 picked tool 'internal:merge' for foo (binary False symlink False)
473 picked tool 'internal:merge' for foo (binary False symlink False)
474 merging foo
474 merging foo
475 my foo@b71750c4b0fd+ other foo@a30dd8addae3 ancestor foo@913609522437
475 my foo@b71750c4b0fd+ other foo@a30dd8addae3 ancestor foo@913609522437
476 premerge successful
476 premerge successful
477 $ hg status
477 $ hg status
478 M foo
478 M foo
479 ? foo.orig
479 ? foo.orig
480 $ hg resolve -l
480 $ hg resolve -l
481 R foo
481 R foo
482 $ hg summary
482 $ hg summary
483 parent: 2:b71750c4b0fd tip
483 parent: 2:b71750c4b0fd tip
484 capital ten
484 capital ten
485 branch: default
485 branch: default
486 commit: 1 modified, 1 unknown
486 commit: 1 modified, 1 unknown
487 update: (current)
487 update: (current)
488 $ cat foo
488 $ cat foo
489 one
489 one
490 two
490 two
491 three
491 three
492 four
492 four
493 five
493 five
494 six
494 six
495 seven
495 seven
496 height
496 height
497 nine
497 nine
498 TEN
498 TEN
499
499
500
500
General Comments 0
You need to be logged in to leave comments. Login now