##// END OF EJS Templates
merge with stable
Matt Mackall -
r21585:652e07de merge default
parent child Browse files
Show More
@@ -1,5965 +1,5966 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, bin, nullid, nullrev, short
8 from node import hex, bin, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _
10 from i18n import _
11 import os, re, difflib, time, tempfile, errno
11 import os, re, difflib, time, tempfile, errno
12 import sys
12 import sys
13 import hg, scmutil, util, revlog, copies, error, bookmarks
13 import hg, scmutil, util, revlog, copies, error, bookmarks
14 import patch, help, encoding, templatekw, discovery
14 import patch, help, encoding, templatekw, discovery
15 import archival, changegroup, cmdutil, hbisect
15 import archival, changegroup, cmdutil, hbisect
16 import sshserver, hgweb, commandserver
16 import sshserver, hgweb, commandserver
17 from hgweb import server as hgweb_server
17 from hgweb import server as hgweb_server
18 import merge as mergemod
18 import merge as mergemod
19 import minirst, revset, fileset
19 import minirst, revset, fileset
20 import dagparser, context, simplemerge, graphmod
20 import dagparser, context, simplemerge, graphmod
21 import random
21 import random
22 import setdiscovery, treediscovery, dagutil, pvec, localrepo
22 import setdiscovery, treediscovery, dagutil, pvec, localrepo
23 import phases, obsolete, exchange
23 import phases, obsolete, exchange
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, 1 if nothing to backout or there are unresolved
420 Returns 0 on success, 1 if nothing to backout or there are unresolved
421 files.
421 files.
422 '''
422 '''
423 if rev and node:
423 if rev and node:
424 raise util.Abort(_("please specify just one revision"))
424 raise util.Abort(_("please specify just one revision"))
425
425
426 if not rev:
426 if not rev:
427 rev = node
427 rev = node
428
428
429 if not rev:
429 if not rev:
430 raise util.Abort(_("please specify a revision to backout"))
430 raise util.Abort(_("please specify a revision to backout"))
431
431
432 date = opts.get('date')
432 date = opts.get('date')
433 if date:
433 if date:
434 opts['date'] = util.parsedate(date)
434 opts['date'] = util.parsedate(date)
435
435
436 cmdutil.checkunfinished(repo)
436 cmdutil.checkunfinished(repo)
437 cmdutil.bailifchanged(repo)
437 cmdutil.bailifchanged(repo)
438 node = scmutil.revsingle(repo, rev).node()
438 node = scmutil.revsingle(repo, rev).node()
439
439
440 op1, op2 = repo.dirstate.parents()
440 op1, op2 = repo.dirstate.parents()
441 if node not in repo.changelog.commonancestorsheads(op1, node):
441 if node not in repo.changelog.commonancestorsheads(op1, node):
442 raise util.Abort(_('cannot backout change that is not an ancestor'))
442 raise util.Abort(_('cannot backout change that is not an ancestor'))
443
443
444 p1, p2 = repo.changelog.parents(node)
444 p1, p2 = repo.changelog.parents(node)
445 if p1 == nullid:
445 if p1 == nullid:
446 raise util.Abort(_('cannot backout a change with no parents'))
446 raise util.Abort(_('cannot backout a change with no parents'))
447 if p2 != nullid:
447 if p2 != nullid:
448 if not opts.get('parent'):
448 if not opts.get('parent'):
449 raise util.Abort(_('cannot backout a merge changeset'))
449 raise util.Abort(_('cannot backout a merge changeset'))
450 p = repo.lookup(opts['parent'])
450 p = repo.lookup(opts['parent'])
451 if p not in (p1, p2):
451 if p not in (p1, p2):
452 raise util.Abort(_('%s is not a parent of %s') %
452 raise util.Abort(_('%s is not a parent of %s') %
453 (short(p), short(node)))
453 (short(p), short(node)))
454 parent = p
454 parent = p
455 else:
455 else:
456 if opts.get('parent'):
456 if opts.get('parent'):
457 raise util.Abort(_('cannot use --parent on non-merge changeset'))
457 raise util.Abort(_('cannot use --parent on non-merge changeset'))
458 parent = p1
458 parent = p1
459
459
460 # the backout should appear on the same branch
460 # the backout should appear on the same branch
461 wlock = repo.wlock()
461 wlock = repo.wlock()
462 try:
462 try:
463 branch = repo.dirstate.branch()
463 branch = repo.dirstate.branch()
464 bheads = repo.branchheads(branch)
464 bheads = repo.branchheads(branch)
465 rctx = scmutil.revsingle(repo, hex(parent))
465 rctx = scmutil.revsingle(repo, hex(parent))
466 if not opts.get('merge') and op1 != node:
466 if not opts.get('merge') and op1 != node:
467 try:
467 try:
468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
468 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
469 'backout')
469 'backout')
470 stats = mergemod.update(repo, parent, True, True, False,
470 stats = mergemod.update(repo, parent, True, True, False,
471 node, False)
471 node, False)
472 repo.setparents(op1, op2)
472 repo.setparents(op1, op2)
473 hg._showstats(repo, stats)
473 hg._showstats(repo, stats)
474 if stats[3]:
474 if stats[3]:
475 repo.ui.status(_("use 'hg resolve' to retry unresolved "
475 repo.ui.status(_("use 'hg resolve' to retry unresolved "
476 "file merges\n"))
476 "file merges\n"))
477 else:
477 else:
478 msg = _("changeset %s backed out, "
478 msg = _("changeset %s backed out, "
479 "don't forget to commit.\n")
479 "don't forget to commit.\n")
480 ui.status(msg % short(node))
480 ui.status(msg % short(node))
481 return stats[3] > 0
481 return stats[3] > 0
482 finally:
482 finally:
483 ui.setconfig('ui', 'forcemerge', '', '')
483 ui.setconfig('ui', 'forcemerge', '', '')
484 else:
484 else:
485 hg.clean(repo, node, show_stats=False)
485 hg.clean(repo, node, show_stats=False)
486 repo.dirstate.setbranch(branch)
486 repo.dirstate.setbranch(branch)
487 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
487 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
488
488
489
489
490 def commitfunc(ui, repo, message, match, opts):
490 def commitfunc(ui, repo, message, match, opts):
491 e = cmdutil.getcommiteditor()
491 e = cmdutil.getcommiteditor()
492 if not message:
492 if not message:
493 # we don't translate commit messages
493 # we don't translate commit messages
494 message = "Backed out changeset %s" % short(node)
494 message = "Backed out changeset %s" % short(node)
495 e = cmdutil.getcommiteditor(edit=True)
495 e = cmdutil.getcommiteditor(edit=True)
496 return repo.commit(message, opts.get('user'), opts.get('date'),
496 return repo.commit(message, opts.get('user'), opts.get('date'),
497 match, editor=e)
497 match, editor=e)
498 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
498 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
499 if not newnode:
499 if not newnode:
500 ui.status(_("nothing changed\n"))
500 ui.status(_("nothing changed\n"))
501 return 1
501 return 1
502 cmdutil.commitstatus(repo, newnode, branch, bheads)
502 cmdutil.commitstatus(repo, newnode, branch, bheads)
503
503
504 def nice(node):
504 def nice(node):
505 return '%d:%s' % (repo.changelog.rev(node), short(node))
505 return '%d:%s' % (repo.changelog.rev(node), short(node))
506 ui.status(_('changeset %s backs out changeset %s\n') %
506 ui.status(_('changeset %s backs out changeset %s\n') %
507 (nice(repo.changelog.tip()), nice(node)))
507 (nice(repo.changelog.tip()), nice(node)))
508 if opts.get('merge') and op1 != node:
508 if opts.get('merge') and op1 != node:
509 hg.clean(repo, op1, show_stats=False)
509 hg.clean(repo, op1, show_stats=False)
510 ui.status(_('merging with changeset %s\n')
510 ui.status(_('merging with changeset %s\n')
511 % nice(repo.changelog.tip()))
511 % nice(repo.changelog.tip()))
512 try:
512 try:
513 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
513 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
514 'backout')
514 'backout')
515 return hg.merge(repo, hex(repo.changelog.tip()))
515 return hg.merge(repo, hex(repo.changelog.tip()))
516 finally:
516 finally:
517 ui.setconfig('ui', 'forcemerge', '', '')
517 ui.setconfig('ui', 'forcemerge', '', '')
518 finally:
518 finally:
519 wlock.release()
519 wlock.release()
520 return 0
520 return 0
521
521
522 @command('bisect',
522 @command('bisect',
523 [('r', 'reset', False, _('reset bisect state')),
523 [('r', 'reset', False, _('reset bisect state')),
524 ('g', 'good', False, _('mark changeset good')),
524 ('g', 'good', False, _('mark changeset good')),
525 ('b', 'bad', False, _('mark changeset bad')),
525 ('b', 'bad', False, _('mark changeset bad')),
526 ('s', 'skip', False, _('skip testing changeset')),
526 ('s', 'skip', False, _('skip testing changeset')),
527 ('e', 'extend', False, _('extend the bisect range')),
527 ('e', 'extend', False, _('extend the bisect range')),
528 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
528 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
529 ('U', 'noupdate', False, _('do not update to target'))],
529 ('U', 'noupdate', False, _('do not update to target'))],
530 _("[-gbsr] [-U] [-c CMD] [REV]"))
530 _("[-gbsr] [-U] [-c CMD] [REV]"))
531 def bisect(ui, repo, rev=None, extra=None, command=None,
531 def bisect(ui, repo, rev=None, extra=None, command=None,
532 reset=None, good=None, bad=None, skip=None, extend=None,
532 reset=None, good=None, bad=None, skip=None, extend=None,
533 noupdate=None):
533 noupdate=None):
534 """subdivision search of changesets
534 """subdivision search of changesets
535
535
536 This command helps to find changesets which introduce problems. To
536 This command helps to find changesets which introduce problems. To
537 use, mark the earliest changeset you know exhibits the problem as
537 use, mark the earliest changeset you know exhibits the problem as
538 bad, then mark the latest changeset which is free from the problem
538 bad, then mark the latest changeset which is free from the problem
539 as good. Bisect will update your working directory to a revision
539 as good. Bisect will update your working directory to a revision
540 for testing (unless the -U/--noupdate option is specified). Once
540 for testing (unless the -U/--noupdate option is specified). Once
541 you have performed tests, mark the working directory as good or
541 you have performed tests, mark the working directory as good or
542 bad, and bisect will either update to another candidate changeset
542 bad, and bisect will either update to another candidate changeset
543 or announce that it has found the bad revision.
543 or announce that it has found the bad revision.
544
544
545 As a shortcut, you can also use the revision argument to mark a
545 As a shortcut, you can also use the revision argument to mark a
546 revision as good or bad without checking it out first.
546 revision as good or bad without checking it out first.
547
547
548 If you supply a command, it will be used for automatic bisection.
548 If you supply a command, it will be used for automatic bisection.
549 The environment variable HG_NODE will contain the ID of the
549 The environment variable HG_NODE will contain the ID of the
550 changeset being tested. The exit status of the command will be
550 changeset being tested. The exit status of the command will be
551 used to mark revisions as good or bad: status 0 means good, 125
551 used to mark revisions as good or bad: status 0 means good, 125
552 means to skip the revision, 127 (command not found) will abort the
552 means to skip the revision, 127 (command not found) will abort the
553 bisection, and any other non-zero exit status means the revision
553 bisection, and any other non-zero exit status means the revision
554 is bad.
554 is bad.
555
555
556 .. container:: verbose
556 .. container:: verbose
557
557
558 Some examples:
558 Some examples:
559
559
560 - start a bisection with known bad revision 34, and good revision 12::
560 - start a bisection with known bad revision 34, and good revision 12::
561
561
562 hg bisect --bad 34
562 hg bisect --bad 34
563 hg bisect --good 12
563 hg bisect --good 12
564
564
565 - advance the current bisection by marking current revision as good or
565 - advance the current bisection by marking current revision as good or
566 bad::
566 bad::
567
567
568 hg bisect --good
568 hg bisect --good
569 hg bisect --bad
569 hg bisect --bad
570
570
571 - mark the current revision, or a known revision, to be skipped (e.g. if
571 - mark the current revision, or a known revision, to be skipped (e.g. if
572 that revision is not usable because of another issue)::
572 that revision is not usable because of another issue)::
573
573
574 hg bisect --skip
574 hg bisect --skip
575 hg bisect --skip 23
575 hg bisect --skip 23
576
576
577 - skip all revisions that do not touch directories ``foo`` or ``bar``::
577 - skip all revisions that do not touch directories ``foo`` or ``bar``::
578
578
579 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
579 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
580
580
581 - forget the current bisection::
581 - forget the current bisection::
582
582
583 hg bisect --reset
583 hg bisect --reset
584
584
585 - use 'make && make tests' to automatically find the first broken
585 - use 'make && make tests' to automatically find the first broken
586 revision::
586 revision::
587
587
588 hg bisect --reset
588 hg bisect --reset
589 hg bisect --bad 34
589 hg bisect --bad 34
590 hg bisect --good 12
590 hg bisect --good 12
591 hg bisect --command "make && make tests"
591 hg bisect --command "make && make tests"
592
592
593 - see all changesets whose states are already known in the current
593 - see all changesets whose states are already known in the current
594 bisection::
594 bisection::
595
595
596 hg log -r "bisect(pruned)"
596 hg log -r "bisect(pruned)"
597
597
598 - see the changeset currently being bisected (especially useful
598 - see the changeset currently being bisected (especially useful
599 if running with -U/--noupdate)::
599 if running with -U/--noupdate)::
600
600
601 hg log -r "bisect(current)"
601 hg log -r "bisect(current)"
602
602
603 - see all changesets that took part in the current bisection::
603 - see all changesets that took part in the current bisection::
604
604
605 hg log -r "bisect(range)"
605 hg log -r "bisect(range)"
606
606
607 - you can even get a nice graph::
607 - you can even get a nice graph::
608
608
609 hg log --graph -r "bisect(range)"
609 hg log --graph -r "bisect(range)"
610
610
611 See :hg:`help revsets` for more about the `bisect()` keyword.
611 See :hg:`help revsets` for more about the `bisect()` keyword.
612
612
613 Returns 0 on success.
613 Returns 0 on success.
614 """
614 """
615 def extendbisectrange(nodes, good):
615 def extendbisectrange(nodes, good):
616 # bisect is incomplete when it ends on a merge node and
616 # bisect is incomplete when it ends on a merge node and
617 # one of the parent was not checked.
617 # one of the parent was not checked.
618 parents = repo[nodes[0]].parents()
618 parents = repo[nodes[0]].parents()
619 if len(parents) > 1:
619 if len(parents) > 1:
620 side = good and state['bad'] or state['good']
620 side = good and state['bad'] or state['good']
621 num = len(set(i.node() for i in parents) & set(side))
621 num = len(set(i.node() for i in parents) & set(side))
622 if num == 1:
622 if num == 1:
623 return parents[0].ancestor(parents[1])
623 return parents[0].ancestor(parents[1])
624 return None
624 return None
625
625
626 def print_result(nodes, good):
626 def print_result(nodes, good):
627 displayer = cmdutil.show_changeset(ui, repo, {})
627 displayer = cmdutil.show_changeset(ui, repo, {})
628 if len(nodes) == 1:
628 if len(nodes) == 1:
629 # narrowed it down to a single revision
629 # narrowed it down to a single revision
630 if good:
630 if good:
631 ui.write(_("The first good revision is:\n"))
631 ui.write(_("The first good revision is:\n"))
632 else:
632 else:
633 ui.write(_("The first bad revision is:\n"))
633 ui.write(_("The first bad revision is:\n"))
634 displayer.show(repo[nodes[0]])
634 displayer.show(repo[nodes[0]])
635 extendnode = extendbisectrange(nodes, good)
635 extendnode = extendbisectrange(nodes, good)
636 if extendnode is not None:
636 if extendnode is not None:
637 ui.write(_('Not all ancestors of this changeset have been'
637 ui.write(_('Not all ancestors of this changeset have been'
638 ' checked.\nUse bisect --extend to continue the '
638 ' checked.\nUse bisect --extend to continue the '
639 'bisection from\nthe common ancestor, %s.\n')
639 'bisection from\nthe common ancestor, %s.\n')
640 % extendnode)
640 % extendnode)
641 else:
641 else:
642 # multiple possible revisions
642 # multiple possible revisions
643 if good:
643 if good:
644 ui.write(_("Due to skipped revisions, the first "
644 ui.write(_("Due to skipped revisions, the first "
645 "good revision could be any of:\n"))
645 "good revision could be any of:\n"))
646 else:
646 else:
647 ui.write(_("Due to skipped revisions, the first "
647 ui.write(_("Due to skipped revisions, the first "
648 "bad revision could be any of:\n"))
648 "bad revision could be any of:\n"))
649 for n in nodes:
649 for n in nodes:
650 displayer.show(repo[n])
650 displayer.show(repo[n])
651 displayer.close()
651 displayer.close()
652
652
653 def check_state(state, interactive=True):
653 def check_state(state, interactive=True):
654 if not state['good'] or not state['bad']:
654 if not state['good'] or not state['bad']:
655 if (good or bad or skip or reset) and interactive:
655 if (good or bad or skip or reset) and interactive:
656 return
656 return
657 if not state['good']:
657 if not state['good']:
658 raise util.Abort(_('cannot bisect (no known good revisions)'))
658 raise util.Abort(_('cannot bisect (no known good revisions)'))
659 else:
659 else:
660 raise util.Abort(_('cannot bisect (no known bad revisions)'))
660 raise util.Abort(_('cannot bisect (no known bad revisions)'))
661 return True
661 return True
662
662
663 # backward compatibility
663 # backward compatibility
664 if rev in "good bad reset init".split():
664 if rev in "good bad reset init".split():
665 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
665 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
666 cmd, rev, extra = rev, extra, None
666 cmd, rev, extra = rev, extra, None
667 if cmd == "good":
667 if cmd == "good":
668 good = True
668 good = True
669 elif cmd == "bad":
669 elif cmd == "bad":
670 bad = True
670 bad = True
671 else:
671 else:
672 reset = True
672 reset = True
673 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
673 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
674 raise util.Abort(_('incompatible arguments'))
674 raise util.Abort(_('incompatible arguments'))
675
675
676 cmdutil.checkunfinished(repo)
676 cmdutil.checkunfinished(repo)
677
677
678 if reset:
678 if reset:
679 p = repo.join("bisect.state")
679 p = repo.join("bisect.state")
680 if os.path.exists(p):
680 if os.path.exists(p):
681 os.unlink(p)
681 os.unlink(p)
682 return
682 return
683
683
684 state = hbisect.load_state(repo)
684 state = hbisect.load_state(repo)
685
685
686 if command:
686 if command:
687 changesets = 1
687 changesets = 1
688 if noupdate:
688 if noupdate:
689 try:
689 try:
690 node = state['current'][0]
690 node = state['current'][0]
691 except LookupError:
691 except LookupError:
692 raise util.Abort(_('current bisect revision is unknown - '
692 raise util.Abort(_('current bisect revision is unknown - '
693 'start a new bisect to fix'))
693 'start a new bisect to fix'))
694 else:
694 else:
695 node, p2 = repo.dirstate.parents()
695 node, p2 = repo.dirstate.parents()
696 if p2 != nullid:
696 if p2 != nullid:
697 raise util.Abort(_('current bisect revision is a merge'))
697 raise util.Abort(_('current bisect revision is a merge'))
698 try:
698 try:
699 while changesets:
699 while changesets:
700 # update state
700 # update state
701 state['current'] = [node]
701 state['current'] = [node]
702 hbisect.save_state(repo, state)
702 hbisect.save_state(repo, state)
703 status = util.system(command,
703 status = util.system(command,
704 environ={'HG_NODE': hex(node)},
704 environ={'HG_NODE': hex(node)},
705 out=ui.fout)
705 out=ui.fout)
706 if status == 125:
706 if status == 125:
707 transition = "skip"
707 transition = "skip"
708 elif status == 0:
708 elif status == 0:
709 transition = "good"
709 transition = "good"
710 # status < 0 means process was killed
710 # status < 0 means process was killed
711 elif status == 127:
711 elif status == 127:
712 raise util.Abort(_("failed to execute %s") % command)
712 raise util.Abort(_("failed to execute %s") % command)
713 elif status < 0:
713 elif status < 0:
714 raise util.Abort(_("%s killed") % command)
714 raise util.Abort(_("%s killed") % command)
715 else:
715 else:
716 transition = "bad"
716 transition = "bad"
717 ctx = scmutil.revsingle(repo, rev, node)
717 ctx = scmutil.revsingle(repo, rev, node)
718 rev = None # clear for future iterations
718 rev = None # clear for future iterations
719 state[transition].append(ctx.node())
719 state[transition].append(ctx.node())
720 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
720 ui.status(_('changeset %d:%s: %s\n') % (ctx, ctx, transition))
721 check_state(state, interactive=False)
721 check_state(state, interactive=False)
722 # bisect
722 # bisect
723 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
723 nodes, changesets, bgood = hbisect.bisect(repo.changelog, state)
724 # update to next check
724 # update to next check
725 node = nodes[0]
725 node = nodes[0]
726 if not noupdate:
726 if not noupdate:
727 cmdutil.bailifchanged(repo)
727 cmdutil.bailifchanged(repo)
728 hg.clean(repo, node, show_stats=False)
728 hg.clean(repo, node, show_stats=False)
729 finally:
729 finally:
730 state['current'] = [node]
730 state['current'] = [node]
731 hbisect.save_state(repo, state)
731 hbisect.save_state(repo, state)
732 print_result(nodes, bgood)
732 print_result(nodes, bgood)
733 return
733 return
734
734
735 # update state
735 # update state
736
736
737 if rev:
737 if rev:
738 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
738 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
739 else:
739 else:
740 nodes = [repo.lookup('.')]
740 nodes = [repo.lookup('.')]
741
741
742 if good or bad or skip:
742 if good or bad or skip:
743 if good:
743 if good:
744 state['good'] += nodes
744 state['good'] += nodes
745 elif bad:
745 elif bad:
746 state['bad'] += nodes
746 state['bad'] += nodes
747 elif skip:
747 elif skip:
748 state['skip'] += nodes
748 state['skip'] += nodes
749 hbisect.save_state(repo, state)
749 hbisect.save_state(repo, state)
750
750
751 if not check_state(state):
751 if not check_state(state):
752 return
752 return
753
753
754 # actually bisect
754 # actually bisect
755 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
755 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
756 if extend:
756 if extend:
757 if not changesets:
757 if not changesets:
758 extendnode = extendbisectrange(nodes, good)
758 extendnode = extendbisectrange(nodes, good)
759 if extendnode is not None:
759 if extendnode is not None:
760 ui.write(_("Extending search to changeset %d:%s\n")
760 ui.write(_("Extending search to changeset %d:%s\n")
761 % (extendnode.rev(), extendnode))
761 % (extendnode.rev(), extendnode))
762 state['current'] = [extendnode.node()]
762 state['current'] = [extendnode.node()]
763 hbisect.save_state(repo, state)
763 hbisect.save_state(repo, state)
764 if noupdate:
764 if noupdate:
765 return
765 return
766 cmdutil.bailifchanged(repo)
766 cmdutil.bailifchanged(repo)
767 return hg.clean(repo, extendnode.node())
767 return hg.clean(repo, extendnode.node())
768 raise util.Abort(_("nothing to extend"))
768 raise util.Abort(_("nothing to extend"))
769
769
770 if changesets == 0:
770 if changesets == 0:
771 print_result(nodes, good)
771 print_result(nodes, good)
772 else:
772 else:
773 assert len(nodes) == 1 # only a single node can be tested next
773 assert len(nodes) == 1 # only a single node can be tested next
774 node = nodes[0]
774 node = nodes[0]
775 # compute the approximate number of remaining tests
775 # compute the approximate number of remaining tests
776 tests, size = 0, 2
776 tests, size = 0, 2
777 while size <= changesets:
777 while size <= changesets:
778 tests, size = tests + 1, size * 2
778 tests, size = tests + 1, size * 2
779 rev = repo.changelog.rev(node)
779 rev = repo.changelog.rev(node)
780 ui.write(_("Testing changeset %d:%s "
780 ui.write(_("Testing changeset %d:%s "
781 "(%d changesets remaining, ~%d tests)\n")
781 "(%d changesets remaining, ~%d tests)\n")
782 % (rev, short(node), changesets, tests))
782 % (rev, short(node), changesets, tests))
783 state['current'] = [node]
783 state['current'] = [node]
784 hbisect.save_state(repo, state)
784 hbisect.save_state(repo, state)
785 if not noupdate:
785 if not noupdate:
786 cmdutil.bailifchanged(repo)
786 cmdutil.bailifchanged(repo)
787 return hg.clean(repo, node)
787 return hg.clean(repo, node)
788
788
789 @command('bookmarks|bookmark',
789 @command('bookmarks|bookmark',
790 [('f', 'force', False, _('force')),
790 [('f', 'force', False, _('force')),
791 ('r', 'rev', '', _('revision'), _('REV')),
791 ('r', 'rev', '', _('revision'), _('REV')),
792 ('d', 'delete', False, _('delete a given bookmark')),
792 ('d', 'delete', False, _('delete a given bookmark')),
793 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
793 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
794 ('i', 'inactive', False, _('mark a bookmark inactive'))],
794 ('i', 'inactive', False, _('mark a bookmark inactive'))],
795 _('hg bookmarks [OPTIONS]... [NAME]...'))
795 _('hg bookmarks [OPTIONS]... [NAME]...'))
796 def bookmark(ui, repo, *names, **opts):
796 def bookmark(ui, repo, *names, **opts):
797 '''track a line of development with movable markers
797 '''track a line of development with movable markers
798
798
799 Bookmarks are pointers to certain commits that move when committing.
799 Bookmarks are pointers to certain commits that move when committing.
800 Bookmarks are local. They can be renamed, copied and deleted. It is
800 Bookmarks are local. They can be renamed, copied and deleted. It is
801 possible to use :hg:`merge NAME` to merge from a given bookmark, and
801 possible to use :hg:`merge NAME` to merge from a given bookmark, and
802 :hg:`update NAME` to update to a given bookmark.
802 :hg:`update NAME` to update to a given bookmark.
803
803
804 You can use :hg:`bookmark NAME` to set a bookmark on the working
804 You can use :hg:`bookmark NAME` to set a bookmark on the working
805 directory's parent revision with the given name. If you specify
805 directory's parent revision with the given name. If you specify
806 a revision using -r REV (where REV may be an existing bookmark),
806 a revision using -r REV (where REV may be an existing bookmark),
807 the bookmark is assigned to that revision.
807 the bookmark is assigned to that revision.
808
808
809 Bookmarks can be pushed and pulled between repositories (see :hg:`help
809 Bookmarks can be pushed and pulled between repositories (see :hg:`help
810 push` and :hg:`help pull`). This requires both the local and remote
810 push` and :hg:`help pull`). This requires both the local and remote
811 repositories to support bookmarks. For versions prior to 1.8, this means
811 repositories to support bookmarks. For versions prior to 1.8, this means
812 the bookmarks extension must be enabled.
812 the bookmarks extension must be enabled.
813
813
814 If you set a bookmark called '@', new clones of the repository will
814 If you set a bookmark called '@', new clones of the repository will
815 have that revision checked out (and the bookmark made active) by
815 have that revision checked out (and the bookmark made active) by
816 default.
816 default.
817
817
818 With -i/--inactive, the new bookmark will not be made the active
818 With -i/--inactive, the new bookmark will not be made the active
819 bookmark. If -r/--rev is given, the new bookmark will not be made
819 bookmark. If -r/--rev is given, the new bookmark will not be made
820 active even if -i/--inactive is not given. If no NAME is given, the
820 active even if -i/--inactive is not given. If no NAME is given, the
821 current active bookmark will be marked inactive.
821 current active bookmark will be marked inactive.
822 '''
822 '''
823 force = opts.get('force')
823 force = opts.get('force')
824 rev = opts.get('rev')
824 rev = opts.get('rev')
825 delete = opts.get('delete')
825 delete = opts.get('delete')
826 rename = opts.get('rename')
826 rename = opts.get('rename')
827 inactive = opts.get('inactive')
827 inactive = opts.get('inactive')
828
828
829 def checkformat(mark):
829 def checkformat(mark):
830 mark = mark.strip()
830 mark = mark.strip()
831 if not mark:
831 if not mark:
832 raise util.Abort(_("bookmark names cannot consist entirely of "
832 raise util.Abort(_("bookmark names cannot consist entirely of "
833 "whitespace"))
833 "whitespace"))
834 scmutil.checknewlabel(repo, mark, 'bookmark')
834 scmutil.checknewlabel(repo, mark, 'bookmark')
835 return mark
835 return mark
836
836
837 def checkconflict(repo, mark, cur, force=False, target=None):
837 def checkconflict(repo, mark, cur, force=False, target=None):
838 if mark in marks and not force:
838 if mark in marks and not force:
839 if target:
839 if target:
840 if marks[mark] == target and target == cur:
840 if marks[mark] == target and target == cur:
841 # re-activating a bookmark
841 # re-activating a bookmark
842 return
842 return
843 anc = repo.changelog.ancestors([repo[target].rev()])
843 anc = repo.changelog.ancestors([repo[target].rev()])
844 bmctx = repo[marks[mark]]
844 bmctx = repo[marks[mark]]
845 divs = [repo[b].node() for b in marks
845 divs = [repo[b].node() for b in marks
846 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
846 if b.split('@', 1)[0] == mark.split('@', 1)[0]]
847
847
848 # allow resolving a single divergent bookmark even if moving
848 # allow resolving a single divergent bookmark even if moving
849 # the bookmark across branches when a revision is specified
849 # the bookmark across branches when a revision is specified
850 # that contains a divergent bookmark
850 # that contains a divergent bookmark
851 if bmctx.rev() not in anc and target in divs:
851 if bmctx.rev() not in anc and target in divs:
852 bookmarks.deletedivergent(repo, [target], mark)
852 bookmarks.deletedivergent(repo, [target], mark)
853 return
853 return
854
854
855 deletefrom = [b for b in divs
855 deletefrom = [b for b in divs
856 if repo[b].rev() in anc or b == target]
856 if repo[b].rev() in anc or b == target]
857 bookmarks.deletedivergent(repo, deletefrom, mark)
857 bookmarks.deletedivergent(repo, deletefrom, mark)
858 if bookmarks.validdest(repo, bmctx, repo[target]):
858 if bookmarks.validdest(repo, bmctx, repo[target]):
859 ui.status(_("moving bookmark '%s' forward from %s\n") %
859 ui.status(_("moving bookmark '%s' forward from %s\n") %
860 (mark, short(bmctx.node())))
860 (mark, short(bmctx.node())))
861 return
861 return
862 raise util.Abort(_("bookmark '%s' already exists "
862 raise util.Abort(_("bookmark '%s' already exists "
863 "(use -f to force)") % mark)
863 "(use -f to force)") % mark)
864 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
864 if ((mark in repo.branchmap() or mark == repo.dirstate.branch())
865 and not force):
865 and not force):
866 raise util.Abort(
866 raise util.Abort(
867 _("a bookmark cannot have the name of an existing branch"))
867 _("a bookmark cannot have the name of an existing branch"))
868
868
869 if delete and rename:
869 if delete and rename:
870 raise util.Abort(_("--delete and --rename are incompatible"))
870 raise util.Abort(_("--delete and --rename are incompatible"))
871 if delete and rev:
871 if delete and rev:
872 raise util.Abort(_("--rev is incompatible with --delete"))
872 raise util.Abort(_("--rev is incompatible with --delete"))
873 if rename and rev:
873 if rename and rev:
874 raise util.Abort(_("--rev is incompatible with --rename"))
874 raise util.Abort(_("--rev is incompatible with --rename"))
875 if not names and (delete or rev):
875 if not names and (delete or rev):
876 raise util.Abort(_("bookmark name required"))
876 raise util.Abort(_("bookmark name required"))
877
877
878 if delete or rename or names or inactive:
878 if delete or rename or names or inactive:
879 wlock = repo.wlock()
879 wlock = repo.wlock()
880 try:
880 try:
881 cur = repo.changectx('.').node()
881 cur = repo.changectx('.').node()
882 marks = repo._bookmarks
882 marks = repo._bookmarks
883 if delete:
883 if delete:
884 for mark in names:
884 for mark in names:
885 if mark not in marks:
885 if mark not in marks:
886 raise util.Abort(_("bookmark '%s' does not exist") %
886 raise util.Abort(_("bookmark '%s' does not exist") %
887 mark)
887 mark)
888 if mark == repo._bookmarkcurrent:
888 if mark == repo._bookmarkcurrent:
889 bookmarks.unsetcurrent(repo)
889 bookmarks.unsetcurrent(repo)
890 del marks[mark]
890 del marks[mark]
891 marks.write()
891 marks.write()
892
892
893 elif rename:
893 elif rename:
894 if not names:
894 if not names:
895 raise util.Abort(_("new bookmark name required"))
895 raise util.Abort(_("new bookmark name required"))
896 elif len(names) > 1:
896 elif len(names) > 1:
897 raise util.Abort(_("only one new bookmark name allowed"))
897 raise util.Abort(_("only one new bookmark name allowed"))
898 mark = checkformat(names[0])
898 mark = checkformat(names[0])
899 if rename not in marks:
899 if rename not in marks:
900 raise util.Abort(_("bookmark '%s' does not exist") % rename)
900 raise util.Abort(_("bookmark '%s' does not exist") % rename)
901 checkconflict(repo, mark, cur, force)
901 checkconflict(repo, mark, cur, force)
902 marks[mark] = marks[rename]
902 marks[mark] = marks[rename]
903 if repo._bookmarkcurrent == rename and not inactive:
903 if repo._bookmarkcurrent == rename and not inactive:
904 bookmarks.setcurrent(repo, mark)
904 bookmarks.setcurrent(repo, mark)
905 del marks[rename]
905 del marks[rename]
906 marks.write()
906 marks.write()
907
907
908 elif names:
908 elif names:
909 newact = None
909 newact = None
910 for mark in names:
910 for mark in names:
911 mark = checkformat(mark)
911 mark = checkformat(mark)
912 if newact is None:
912 if newact is None:
913 newact = mark
913 newact = mark
914 if inactive and mark == repo._bookmarkcurrent:
914 if inactive and mark == repo._bookmarkcurrent:
915 bookmarks.unsetcurrent(repo)
915 bookmarks.unsetcurrent(repo)
916 return
916 return
917 tgt = cur
917 tgt = cur
918 if rev:
918 if rev:
919 tgt = scmutil.revsingle(repo, rev).node()
919 tgt = scmutil.revsingle(repo, rev).node()
920 checkconflict(repo, mark, cur, force, tgt)
920 checkconflict(repo, mark, cur, force, tgt)
921 marks[mark] = tgt
921 marks[mark] = tgt
922 if not inactive and cur == marks[newact] and not rev:
922 if not inactive and cur == marks[newact] and not rev:
923 bookmarks.setcurrent(repo, newact)
923 bookmarks.setcurrent(repo, newact)
924 elif cur != tgt and newact == repo._bookmarkcurrent:
924 elif cur != tgt and newact == repo._bookmarkcurrent:
925 bookmarks.unsetcurrent(repo)
925 bookmarks.unsetcurrent(repo)
926 marks.write()
926 marks.write()
927
927
928 elif inactive:
928 elif inactive:
929 if len(marks) == 0:
929 if len(marks) == 0:
930 ui.status(_("no bookmarks set\n"))
930 ui.status(_("no bookmarks set\n"))
931 elif not repo._bookmarkcurrent:
931 elif not repo._bookmarkcurrent:
932 ui.status(_("no active bookmark\n"))
932 ui.status(_("no active bookmark\n"))
933 else:
933 else:
934 bookmarks.unsetcurrent(repo)
934 bookmarks.unsetcurrent(repo)
935 finally:
935 finally:
936 wlock.release()
936 wlock.release()
937 else: # show bookmarks
937 else: # show bookmarks
938 hexfn = ui.debugflag and hex or short
938 hexfn = ui.debugflag and hex or short
939 marks = repo._bookmarks
939 marks = repo._bookmarks
940 if len(marks) == 0:
940 if len(marks) == 0:
941 ui.status(_("no bookmarks set\n"))
941 ui.status(_("no bookmarks set\n"))
942 else:
942 else:
943 for bmark, n in sorted(marks.iteritems()):
943 for bmark, n in sorted(marks.iteritems()):
944 current = repo._bookmarkcurrent
944 current = repo._bookmarkcurrent
945 if bmark == current:
945 if bmark == current:
946 prefix, label = '*', 'bookmarks.current'
946 prefix, label = '*', 'bookmarks.current'
947 else:
947 else:
948 prefix, label = ' ', ''
948 prefix, label = ' ', ''
949
949
950 if ui.quiet:
950 if ui.quiet:
951 ui.write("%s\n" % bmark, label=label)
951 ui.write("%s\n" % bmark, label=label)
952 else:
952 else:
953 ui.write(" %s %-25s %d:%s\n" % (
953 pad = " " * (25 - encoding.colwidth(bmark))
954 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
954 ui.write(" %s %s%s %d:%s\n" % (
955 prefix, bmark, pad, repo.changelog.rev(n), hexfn(n)),
955 label=label)
956 label=label)
956
957
957 @command('branch',
958 @command('branch',
958 [('f', 'force', None,
959 [('f', 'force', None,
959 _('set branch name even if it shadows an existing branch')),
960 _('set branch name even if it shadows an existing branch')),
960 ('C', 'clean', None, _('reset branch name to parent branch name'))],
961 ('C', 'clean', None, _('reset branch name to parent branch name'))],
961 _('[-fC] [NAME]'))
962 _('[-fC] [NAME]'))
962 def branch(ui, repo, label=None, **opts):
963 def branch(ui, repo, label=None, **opts):
963 """set or show the current branch name
964 """set or show the current branch name
964
965
965 .. note::
966 .. note::
966
967
967 Branch names are permanent and global. Use :hg:`bookmark` to create a
968 Branch names are permanent and global. Use :hg:`bookmark` to create a
968 light-weight bookmark instead. See :hg:`help glossary` for more
969 light-weight bookmark instead. See :hg:`help glossary` for more
969 information about named branches and bookmarks.
970 information about named branches and bookmarks.
970
971
971 With no argument, show the current branch name. With one argument,
972 With no argument, show the current branch name. With one argument,
972 set the working directory branch name (the branch will not exist
973 set the working directory branch name (the branch will not exist
973 in the repository until the next commit). Standard practice
974 in the repository until the next commit). Standard practice
974 recommends that primary development take place on the 'default'
975 recommends that primary development take place on the 'default'
975 branch.
976 branch.
976
977
977 Unless -f/--force is specified, branch will not let you set a
978 Unless -f/--force is specified, branch will not let you set a
978 branch name that already exists, even if it's inactive.
979 branch name that already exists, even if it's inactive.
979
980
980 Use -C/--clean to reset the working directory branch to that of
981 Use -C/--clean to reset the working directory branch to that of
981 the parent of the working directory, negating a previous branch
982 the parent of the working directory, negating a previous branch
982 change.
983 change.
983
984
984 Use the command :hg:`update` to switch to an existing branch. Use
985 Use the command :hg:`update` to switch to an existing branch. Use
985 :hg:`commit --close-branch` to mark this branch as closed.
986 :hg:`commit --close-branch` to mark this branch as closed.
986
987
987 Returns 0 on success.
988 Returns 0 on success.
988 """
989 """
989 if label:
990 if label:
990 label = label.strip()
991 label = label.strip()
991
992
992 if not opts.get('clean') and not label:
993 if not opts.get('clean') and not label:
993 ui.write("%s\n" % repo.dirstate.branch())
994 ui.write("%s\n" % repo.dirstate.branch())
994 return
995 return
995
996
996 wlock = repo.wlock()
997 wlock = repo.wlock()
997 try:
998 try:
998 if opts.get('clean'):
999 if opts.get('clean'):
999 label = repo[None].p1().branch()
1000 label = repo[None].p1().branch()
1000 repo.dirstate.setbranch(label)
1001 repo.dirstate.setbranch(label)
1001 ui.status(_('reset working directory to branch %s\n') % label)
1002 ui.status(_('reset working directory to branch %s\n') % label)
1002 elif label:
1003 elif label:
1003 if not opts.get('force') and label in repo.branchmap():
1004 if not opts.get('force') and label in repo.branchmap():
1004 if label not in [p.branch() for p in repo.parents()]:
1005 if label not in [p.branch() for p in repo.parents()]:
1005 raise util.Abort(_('a branch of the same name already'
1006 raise util.Abort(_('a branch of the same name already'
1006 ' exists'),
1007 ' exists'),
1007 # i18n: "it" refers to an existing branch
1008 # i18n: "it" refers to an existing branch
1008 hint=_("use 'hg update' to switch to it"))
1009 hint=_("use 'hg update' to switch to it"))
1009 scmutil.checknewlabel(repo, label, 'branch')
1010 scmutil.checknewlabel(repo, label, 'branch')
1010 repo.dirstate.setbranch(label)
1011 repo.dirstate.setbranch(label)
1011 ui.status(_('marked working directory as branch %s\n') % label)
1012 ui.status(_('marked working directory as branch %s\n') % label)
1012 ui.status(_('(branches are permanent and global, '
1013 ui.status(_('(branches are permanent and global, '
1013 'did you want a bookmark?)\n'))
1014 'did you want a bookmark?)\n'))
1014 finally:
1015 finally:
1015 wlock.release()
1016 wlock.release()
1016
1017
1017 @command('branches',
1018 @command('branches',
1018 [('a', 'active', False, _('show only branches that have unmerged heads')),
1019 [('a', 'active', False, _('show only branches that have unmerged heads')),
1019 ('c', 'closed', False, _('show normal and closed branches'))],
1020 ('c', 'closed', False, _('show normal and closed branches'))],
1020 _('[-ac]'))
1021 _('[-ac]'))
1021 def branches(ui, repo, active=False, closed=False):
1022 def branches(ui, repo, active=False, closed=False):
1022 """list repository named branches
1023 """list repository named branches
1023
1024
1024 List the repository's named branches, indicating which ones are
1025 List the repository's named branches, indicating which ones are
1025 inactive. If -c/--closed is specified, also list branches which have
1026 inactive. If -c/--closed is specified, also list branches which have
1026 been marked closed (see :hg:`commit --close-branch`).
1027 been marked closed (see :hg:`commit --close-branch`).
1027
1028
1028 If -a/--active is specified, only show active branches. A branch
1029 If -a/--active is specified, only show active branches. A branch
1029 is considered active if it contains repository heads.
1030 is considered active if it contains repository heads.
1030
1031
1031 Use the command :hg:`update` to switch to an existing branch.
1032 Use the command :hg:`update` to switch to an existing branch.
1032
1033
1033 Returns 0.
1034 Returns 0.
1034 """
1035 """
1035
1036
1036 hexfunc = ui.debugflag and hex or short
1037 hexfunc = ui.debugflag and hex or short
1037
1038
1038 allheads = set(repo.heads())
1039 allheads = set(repo.heads())
1039 branches = []
1040 branches = []
1040 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1041 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1041 isactive = not isclosed and bool(set(heads) & allheads)
1042 isactive = not isclosed and bool(set(heads) & allheads)
1042 branches.append((tag, repo[tip], isactive, not isclosed))
1043 branches.append((tag, repo[tip], isactive, not isclosed))
1043 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1044 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1044 reverse=True)
1045 reverse=True)
1045
1046
1046 for tag, ctx, isactive, isopen in branches:
1047 for tag, ctx, isactive, isopen in branches:
1047 if (not active) or isactive:
1048 if (not active) or isactive:
1048 if isactive:
1049 if isactive:
1049 label = 'branches.active'
1050 label = 'branches.active'
1050 notice = ''
1051 notice = ''
1051 elif not isopen:
1052 elif not isopen:
1052 if not closed:
1053 if not closed:
1053 continue
1054 continue
1054 label = 'branches.closed'
1055 label = 'branches.closed'
1055 notice = _(' (closed)')
1056 notice = _(' (closed)')
1056 else:
1057 else:
1057 label = 'branches.inactive'
1058 label = 'branches.inactive'
1058 notice = _(' (inactive)')
1059 notice = _(' (inactive)')
1059 if tag == repo.dirstate.branch():
1060 if tag == repo.dirstate.branch():
1060 label = 'branches.current'
1061 label = 'branches.current'
1061 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1062 rev = str(ctx.rev()).rjust(31 - encoding.colwidth(tag))
1062 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1063 rev = ui.label('%s:%s' % (rev, hexfunc(ctx.node())),
1063 'log.changeset changeset.%s' % ctx.phasestr())
1064 'log.changeset changeset.%s' % ctx.phasestr())
1064 labeledtag = ui.label(tag, label)
1065 labeledtag = ui.label(tag, label)
1065 if ui.quiet:
1066 if ui.quiet:
1066 ui.write("%s\n" % labeledtag)
1067 ui.write("%s\n" % labeledtag)
1067 else:
1068 else:
1068 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1069 ui.write("%s %s%s\n" % (labeledtag, rev, notice))
1069
1070
1070 @command('bundle',
1071 @command('bundle',
1071 [('f', 'force', None, _('run even when the destination is unrelated')),
1072 [('f', 'force', None, _('run even when the destination is unrelated')),
1072 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1073 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1073 _('REV')),
1074 _('REV')),
1074 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1075 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1075 _('BRANCH')),
1076 _('BRANCH')),
1076 ('', 'base', [],
1077 ('', 'base', [],
1077 _('a base changeset assumed to be available at the destination'),
1078 _('a base changeset assumed to be available at the destination'),
1078 _('REV')),
1079 _('REV')),
1079 ('a', 'all', None, _('bundle all changesets in the repository')),
1080 ('a', 'all', None, _('bundle all changesets in the repository')),
1080 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1081 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1081 ] + remoteopts,
1082 ] + remoteopts,
1082 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1083 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
1083 def bundle(ui, repo, fname, dest=None, **opts):
1084 def bundle(ui, repo, fname, dest=None, **opts):
1084 """create a changegroup file
1085 """create a changegroup file
1085
1086
1086 Generate a compressed changegroup file collecting changesets not
1087 Generate a compressed changegroup file collecting changesets not
1087 known to be in another repository.
1088 known to be in another repository.
1088
1089
1089 If you omit the destination repository, then hg assumes the
1090 If you omit the destination repository, then hg assumes the
1090 destination will have all the nodes you specify with --base
1091 destination will have all the nodes you specify with --base
1091 parameters. To create a bundle containing all changesets, use
1092 parameters. To create a bundle containing all changesets, use
1092 -a/--all (or --base null).
1093 -a/--all (or --base null).
1093
1094
1094 You can change compression method with the -t/--type option.
1095 You can change compression method with the -t/--type option.
1095 The available compression methods are: none, bzip2, and
1096 The available compression methods are: none, bzip2, and
1096 gzip (by default, bundles are compressed using bzip2).
1097 gzip (by default, bundles are compressed using bzip2).
1097
1098
1098 The bundle file can then be transferred using conventional means
1099 The bundle file can then be transferred using conventional means
1099 and applied to another repository with the unbundle or pull
1100 and applied to another repository with the unbundle or pull
1100 command. This is useful when direct push and pull are not
1101 command. This is useful when direct push and pull are not
1101 available or when exporting an entire repository is undesirable.
1102 available or when exporting an entire repository is undesirable.
1102
1103
1103 Applying bundles preserves all changeset contents including
1104 Applying bundles preserves all changeset contents including
1104 permissions, copy/rename information, and revision history.
1105 permissions, copy/rename information, and revision history.
1105
1106
1106 Returns 0 on success, 1 if no changes found.
1107 Returns 0 on success, 1 if no changes found.
1107 """
1108 """
1108 revs = None
1109 revs = None
1109 if 'rev' in opts:
1110 if 'rev' in opts:
1110 revs = scmutil.revrange(repo, opts['rev'])
1111 revs = scmutil.revrange(repo, opts['rev'])
1111
1112
1112 bundletype = opts.get('type', 'bzip2').lower()
1113 bundletype = opts.get('type', 'bzip2').lower()
1113 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1114 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1114 bundletype = btypes.get(bundletype)
1115 bundletype = btypes.get(bundletype)
1115 if bundletype not in changegroup.bundletypes:
1116 if bundletype not in changegroup.bundletypes:
1116 raise util.Abort(_('unknown bundle type specified with --type'))
1117 raise util.Abort(_('unknown bundle type specified with --type'))
1117
1118
1118 if opts.get('all'):
1119 if opts.get('all'):
1119 base = ['null']
1120 base = ['null']
1120 else:
1121 else:
1121 base = scmutil.revrange(repo, opts.get('base'))
1122 base = scmutil.revrange(repo, opts.get('base'))
1122 # TODO: get desired bundlecaps from command line.
1123 # TODO: get desired bundlecaps from command line.
1123 bundlecaps = None
1124 bundlecaps = None
1124 if base:
1125 if base:
1125 if dest:
1126 if dest:
1126 raise util.Abort(_("--base is incompatible with specifying "
1127 raise util.Abort(_("--base is incompatible with specifying "
1127 "a destination"))
1128 "a destination"))
1128 common = [repo.lookup(rev) for rev in base]
1129 common = [repo.lookup(rev) for rev in base]
1129 heads = revs and map(repo.lookup, revs) or revs
1130 heads = revs and map(repo.lookup, revs) or revs
1130 cg = changegroup.getbundle(repo, 'bundle', heads=heads, common=common,
1131 cg = changegroup.getbundle(repo, 'bundle', heads=heads, common=common,
1131 bundlecaps=bundlecaps)
1132 bundlecaps=bundlecaps)
1132 outgoing = None
1133 outgoing = None
1133 else:
1134 else:
1134 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1135 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1135 dest, branches = hg.parseurl(dest, opts.get('branch'))
1136 dest, branches = hg.parseurl(dest, opts.get('branch'))
1136 other = hg.peer(repo, opts, dest)
1137 other = hg.peer(repo, opts, dest)
1137 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1138 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1138 heads = revs and map(repo.lookup, revs) or revs
1139 heads = revs and map(repo.lookup, revs) or revs
1139 outgoing = discovery.findcommonoutgoing(repo, other,
1140 outgoing = discovery.findcommonoutgoing(repo, other,
1140 onlyheads=heads,
1141 onlyheads=heads,
1141 force=opts.get('force'),
1142 force=opts.get('force'),
1142 portable=True)
1143 portable=True)
1143 cg = changegroup.getlocalbundle(repo, 'bundle', outgoing, bundlecaps)
1144 cg = changegroup.getlocalbundle(repo, 'bundle', outgoing, bundlecaps)
1144 if not cg:
1145 if not cg:
1145 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1146 scmutil.nochangesfound(ui, repo, outgoing and outgoing.excluded)
1146 return 1
1147 return 1
1147
1148
1148 changegroup.writebundle(cg, fname, bundletype)
1149 changegroup.writebundle(cg, fname, bundletype)
1149
1150
1150 @command('cat',
1151 @command('cat',
1151 [('o', 'output', '',
1152 [('o', 'output', '',
1152 _('print output to file with formatted name'), _('FORMAT')),
1153 _('print output to file with formatted name'), _('FORMAT')),
1153 ('r', 'rev', '', _('print the given revision'), _('REV')),
1154 ('r', 'rev', '', _('print the given revision'), _('REV')),
1154 ('', 'decode', None, _('apply any matching decode filter')),
1155 ('', 'decode', None, _('apply any matching decode filter')),
1155 ] + walkopts,
1156 ] + walkopts,
1156 _('[OPTION]... FILE...'))
1157 _('[OPTION]... FILE...'))
1157 def cat(ui, repo, file1, *pats, **opts):
1158 def cat(ui, repo, file1, *pats, **opts):
1158 """output the current or given revision of files
1159 """output the current or given revision of files
1159
1160
1160 Print the specified files as they were at the given revision. If
1161 Print the specified files as they were at the given revision. If
1161 no revision is given, the parent of the working directory is used.
1162 no revision is given, the parent of the working directory is used.
1162
1163
1163 Output may be to a file, in which case the name of the file is
1164 Output may be to a file, in which case the name of the file is
1164 given using a format string. The formatting rules as follows:
1165 given using a format string. The formatting rules as follows:
1165
1166
1166 :``%%``: literal "%" character
1167 :``%%``: literal "%" character
1167 :``%s``: basename of file being printed
1168 :``%s``: basename of file being printed
1168 :``%d``: dirname of file being printed, or '.' if in repository root
1169 :``%d``: dirname of file being printed, or '.' if in repository root
1169 :``%p``: root-relative path name of file being printed
1170 :``%p``: root-relative path name of file being printed
1170 :``%H``: changeset hash (40 hexadecimal digits)
1171 :``%H``: changeset hash (40 hexadecimal digits)
1171 :``%R``: changeset revision number
1172 :``%R``: changeset revision number
1172 :``%h``: short-form changeset hash (12 hexadecimal digits)
1173 :``%h``: short-form changeset hash (12 hexadecimal digits)
1173 :``%r``: zero-padded changeset revision number
1174 :``%r``: zero-padded changeset revision number
1174 :``%b``: basename of the exporting repository
1175 :``%b``: basename of the exporting repository
1175
1176
1176 Returns 0 on success.
1177 Returns 0 on success.
1177 """
1178 """
1178 ctx = scmutil.revsingle(repo, opts.get('rev'))
1179 ctx = scmutil.revsingle(repo, opts.get('rev'))
1179 m = scmutil.match(ctx, (file1,) + pats, opts)
1180 m = scmutil.match(ctx, (file1,) + pats, opts)
1180
1181
1181 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1182 return cmdutil.cat(ui, repo, ctx, m, '', **opts)
1182
1183
1183 @command('^clone',
1184 @command('^clone',
1184 [('U', 'noupdate', None,
1185 [('U', 'noupdate', None,
1185 _('the clone will include an empty working copy (only a repository)')),
1186 _('the clone will include an empty working copy (only a repository)')),
1186 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1187 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
1187 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1188 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
1188 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1189 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
1189 ('', 'pull', None, _('use pull protocol to copy metadata')),
1190 ('', 'pull', None, _('use pull protocol to copy metadata')),
1190 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1191 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
1191 ] + remoteopts,
1192 ] + remoteopts,
1192 _('[OPTION]... SOURCE [DEST]'))
1193 _('[OPTION]... SOURCE [DEST]'))
1193 def clone(ui, source, dest=None, **opts):
1194 def clone(ui, source, dest=None, **opts):
1194 """make a copy of an existing repository
1195 """make a copy of an existing repository
1195
1196
1196 Create a copy of an existing repository in a new directory.
1197 Create a copy of an existing repository in a new directory.
1197
1198
1198 If no destination directory name is specified, it defaults to the
1199 If no destination directory name is specified, it defaults to the
1199 basename of the source.
1200 basename of the source.
1200
1201
1201 The location of the source is added to the new repository's
1202 The location of the source is added to the new repository's
1202 ``.hg/hgrc`` file, as the default to be used for future pulls.
1203 ``.hg/hgrc`` file, as the default to be used for future pulls.
1203
1204
1204 Only local paths and ``ssh://`` URLs are supported as
1205 Only local paths and ``ssh://`` URLs are supported as
1205 destinations. For ``ssh://`` destinations, no working directory or
1206 destinations. For ``ssh://`` destinations, no working directory or
1206 ``.hg/hgrc`` will be created on the remote side.
1207 ``.hg/hgrc`` will be created on the remote side.
1207
1208
1208 To pull only a subset of changesets, specify one or more revisions
1209 To pull only a subset of changesets, specify one or more revisions
1209 identifiers with -r/--rev or branches with -b/--branch. The
1210 identifiers with -r/--rev or branches with -b/--branch. The
1210 resulting clone will contain only the specified changesets and
1211 resulting clone will contain only the specified changesets and
1211 their ancestors. These options (or 'clone src#rev dest') imply
1212 their ancestors. These options (or 'clone src#rev dest') imply
1212 --pull, even for local source repositories. Note that specifying a
1213 --pull, even for local source repositories. Note that specifying a
1213 tag will include the tagged changeset but not the changeset
1214 tag will include the tagged changeset but not the changeset
1214 containing the tag.
1215 containing the tag.
1215
1216
1216 If the source repository has a bookmark called '@' set, that
1217 If the source repository has a bookmark called '@' set, that
1217 revision will be checked out in the new repository by default.
1218 revision will be checked out in the new repository by default.
1218
1219
1219 To check out a particular version, use -u/--update, or
1220 To check out a particular version, use -u/--update, or
1220 -U/--noupdate to create a clone with no working directory.
1221 -U/--noupdate to create a clone with no working directory.
1221
1222
1222 .. container:: verbose
1223 .. container:: verbose
1223
1224
1224 For efficiency, hardlinks are used for cloning whenever the
1225 For efficiency, hardlinks are used for cloning whenever the
1225 source and destination are on the same filesystem (note this
1226 source and destination are on the same filesystem (note this
1226 applies only to the repository data, not to the working
1227 applies only to the repository data, not to the working
1227 directory). Some filesystems, such as AFS, implement hardlinking
1228 directory). Some filesystems, such as AFS, implement hardlinking
1228 incorrectly, but do not report errors. In these cases, use the
1229 incorrectly, but do not report errors. In these cases, use the
1229 --pull option to avoid hardlinking.
1230 --pull option to avoid hardlinking.
1230
1231
1231 In some cases, you can clone repositories and the working
1232 In some cases, you can clone repositories and the working
1232 directory using full hardlinks with ::
1233 directory using full hardlinks with ::
1233
1234
1234 $ cp -al REPO REPOCLONE
1235 $ cp -al REPO REPOCLONE
1235
1236
1236 This is the fastest way to clone, but it is not always safe. The
1237 This is the fastest way to clone, but it is not always safe. The
1237 operation is not atomic (making sure REPO is not modified during
1238 operation is not atomic (making sure REPO is not modified during
1238 the operation is up to you) and you have to make sure your
1239 the operation is up to you) and you have to make sure your
1239 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1240 editor breaks hardlinks (Emacs and most Linux Kernel tools do
1240 so). Also, this is not compatible with certain extensions that
1241 so). Also, this is not compatible with certain extensions that
1241 place their metadata under the .hg directory, such as mq.
1242 place their metadata under the .hg directory, such as mq.
1242
1243
1243 Mercurial will update the working directory to the first applicable
1244 Mercurial will update the working directory to the first applicable
1244 revision from this list:
1245 revision from this list:
1245
1246
1246 a) null if -U or the source repository has no changesets
1247 a) null if -U or the source repository has no changesets
1247 b) if -u . and the source repository is local, the first parent of
1248 b) if -u . and the source repository is local, the first parent of
1248 the source repository's working directory
1249 the source repository's working directory
1249 c) the changeset specified with -u (if a branch name, this means the
1250 c) the changeset specified with -u (if a branch name, this means the
1250 latest head of that branch)
1251 latest head of that branch)
1251 d) the changeset specified with -r
1252 d) the changeset specified with -r
1252 e) the tipmost head specified with -b
1253 e) the tipmost head specified with -b
1253 f) the tipmost head specified with the url#branch source syntax
1254 f) the tipmost head specified with the url#branch source syntax
1254 g) the revision marked with the '@' bookmark, if present
1255 g) the revision marked with the '@' bookmark, if present
1255 h) the tipmost head of the default branch
1256 h) the tipmost head of the default branch
1256 i) tip
1257 i) tip
1257
1258
1258 Examples:
1259 Examples:
1259
1260
1260 - clone a remote repository to a new directory named hg/::
1261 - clone a remote repository to a new directory named hg/::
1261
1262
1262 hg clone http://selenic.com/hg
1263 hg clone http://selenic.com/hg
1263
1264
1264 - create a lightweight local clone::
1265 - create a lightweight local clone::
1265
1266
1266 hg clone project/ project-feature/
1267 hg clone project/ project-feature/
1267
1268
1268 - clone from an absolute path on an ssh server (note double-slash)::
1269 - clone from an absolute path on an ssh server (note double-slash)::
1269
1270
1270 hg clone ssh://user@server//home/projects/alpha/
1271 hg clone ssh://user@server//home/projects/alpha/
1271
1272
1272 - do a high-speed clone over a LAN while checking out a
1273 - do a high-speed clone over a LAN while checking out a
1273 specified version::
1274 specified version::
1274
1275
1275 hg clone --uncompressed http://server/repo -u 1.5
1276 hg clone --uncompressed http://server/repo -u 1.5
1276
1277
1277 - create a repository without changesets after a particular revision::
1278 - create a repository without changesets after a particular revision::
1278
1279
1279 hg clone -r 04e544 experimental/ good/
1280 hg clone -r 04e544 experimental/ good/
1280
1281
1281 - clone (and track) a particular named branch::
1282 - clone (and track) a particular named branch::
1282
1283
1283 hg clone http://selenic.com/hg#stable
1284 hg clone http://selenic.com/hg#stable
1284
1285
1285 See :hg:`help urls` for details on specifying URLs.
1286 See :hg:`help urls` for details on specifying URLs.
1286
1287
1287 Returns 0 on success.
1288 Returns 0 on success.
1288 """
1289 """
1289 if opts.get('noupdate') and opts.get('updaterev'):
1290 if opts.get('noupdate') and opts.get('updaterev'):
1290 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1291 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1291
1292
1292 r = hg.clone(ui, opts, source, dest,
1293 r = hg.clone(ui, opts, source, dest,
1293 pull=opts.get('pull'),
1294 pull=opts.get('pull'),
1294 stream=opts.get('uncompressed'),
1295 stream=opts.get('uncompressed'),
1295 rev=opts.get('rev'),
1296 rev=opts.get('rev'),
1296 update=opts.get('updaterev') or not opts.get('noupdate'),
1297 update=opts.get('updaterev') or not opts.get('noupdate'),
1297 branch=opts.get('branch'))
1298 branch=opts.get('branch'))
1298
1299
1299 return r is None
1300 return r is None
1300
1301
1301 @command('^commit|ci',
1302 @command('^commit|ci',
1302 [('A', 'addremove', None,
1303 [('A', 'addremove', None,
1303 _('mark new/missing files as added/removed before committing')),
1304 _('mark new/missing files as added/removed before committing')),
1304 ('', 'close-branch', None,
1305 ('', 'close-branch', None,
1305 _('mark a branch as closed, hiding it from the branch list')),
1306 _('mark a branch as closed, hiding it from the branch list')),
1306 ('', 'amend', None, _('amend the parent of the working dir')),
1307 ('', 'amend', None, _('amend the parent of the working dir')),
1307 ('s', 'secret', None, _('use the secret phase for committing')),
1308 ('s', 'secret', None, _('use the secret phase for committing')),
1308 ('e', 'edit', None,
1309 ('e', 'edit', None,
1309 _('further edit commit message already specified')),
1310 _('further edit commit message already specified')),
1310 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1311 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1311 _('[OPTION]... [FILE]...'))
1312 _('[OPTION]... [FILE]...'))
1312 def commit(ui, repo, *pats, **opts):
1313 def commit(ui, repo, *pats, **opts):
1313 """commit the specified files or all outstanding changes
1314 """commit the specified files or all outstanding changes
1314
1315
1315 Commit changes to the given files into the repository. Unlike a
1316 Commit changes to the given files into the repository. Unlike a
1316 centralized SCM, this operation is a local operation. See
1317 centralized SCM, this operation is a local operation. See
1317 :hg:`push` for a way to actively distribute your changes.
1318 :hg:`push` for a way to actively distribute your changes.
1318
1319
1319 If a list of files is omitted, all changes reported by :hg:`status`
1320 If a list of files is omitted, all changes reported by :hg:`status`
1320 will be committed.
1321 will be committed.
1321
1322
1322 If you are committing the result of a merge, do not provide any
1323 If you are committing the result of a merge, do not provide any
1323 filenames or -I/-X filters.
1324 filenames or -I/-X filters.
1324
1325
1325 If no commit message is specified, Mercurial starts your
1326 If no commit message is specified, Mercurial starts your
1326 configured editor where you can enter a message. In case your
1327 configured editor where you can enter a message. In case your
1327 commit fails, you will find a backup of your message in
1328 commit fails, you will find a backup of your message in
1328 ``.hg/last-message.txt``.
1329 ``.hg/last-message.txt``.
1329
1330
1330 The --amend flag can be used to amend the parent of the
1331 The --amend flag can be used to amend the parent of the
1331 working directory with a new commit that contains the changes
1332 working directory with a new commit that contains the changes
1332 in the parent in addition to those currently reported by :hg:`status`,
1333 in the parent in addition to those currently reported by :hg:`status`,
1333 if there are any. The old commit is stored in a backup bundle in
1334 if there are any. The old commit is stored in a backup bundle in
1334 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1335 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1335 on how to restore it).
1336 on how to restore it).
1336
1337
1337 Message, user and date are taken from the amended commit unless
1338 Message, user and date are taken from the amended commit unless
1338 specified. When a message isn't specified on the command line,
1339 specified. When a message isn't specified on the command line,
1339 the editor will open with the message of the amended commit.
1340 the editor will open with the message of the amended commit.
1340
1341
1341 It is not possible to amend public changesets (see :hg:`help phases`)
1342 It is not possible to amend public changesets (see :hg:`help phases`)
1342 or changesets that have children.
1343 or changesets that have children.
1343
1344
1344 See :hg:`help dates` for a list of formats valid for -d/--date.
1345 See :hg:`help dates` for a list of formats valid for -d/--date.
1345
1346
1346 Returns 0 on success, 1 if nothing changed.
1347 Returns 0 on success, 1 if nothing changed.
1347 """
1348 """
1348 if opts.get('subrepos'):
1349 if opts.get('subrepos'):
1349 if opts.get('amend'):
1350 if opts.get('amend'):
1350 raise util.Abort(_('cannot amend with --subrepos'))
1351 raise util.Abort(_('cannot amend with --subrepos'))
1351 # Let --subrepos on the command line override config setting.
1352 # Let --subrepos on the command line override config setting.
1352 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1353 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1353
1354
1354 # Save this for restoring it later
1355 # Save this for restoring it later
1355 oldcommitphase = ui.config('phases', 'new-commit')
1356 oldcommitphase = ui.config('phases', 'new-commit')
1356
1357
1357 cmdutil.checkunfinished(repo, commit=True)
1358 cmdutil.checkunfinished(repo, commit=True)
1358
1359
1359 branch = repo[None].branch()
1360 branch = repo[None].branch()
1360 bheads = repo.branchheads(branch)
1361 bheads = repo.branchheads(branch)
1361
1362
1362 extra = {}
1363 extra = {}
1363 if opts.get('close_branch'):
1364 if opts.get('close_branch'):
1364 extra['close'] = 1
1365 extra['close'] = 1
1365
1366
1366 if not bheads:
1367 if not bheads:
1367 raise util.Abort(_('can only close branch heads'))
1368 raise util.Abort(_('can only close branch heads'))
1368 elif opts.get('amend'):
1369 elif opts.get('amend'):
1369 if repo.parents()[0].p1().branch() != branch and \
1370 if repo.parents()[0].p1().branch() != branch and \
1370 repo.parents()[0].p2().branch() != branch:
1371 repo.parents()[0].p2().branch() != branch:
1371 raise util.Abort(_('can only close branch heads'))
1372 raise util.Abort(_('can only close branch heads'))
1372
1373
1373 if opts.get('amend'):
1374 if opts.get('amend'):
1374 if ui.configbool('ui', 'commitsubrepos'):
1375 if ui.configbool('ui', 'commitsubrepos'):
1375 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1376 raise util.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1376
1377
1377 old = repo['.']
1378 old = repo['.']
1378 if old.phase() == phases.public:
1379 if old.phase() == phases.public:
1379 raise util.Abort(_('cannot amend public changesets'))
1380 raise util.Abort(_('cannot amend public changesets'))
1380 if len(repo[None].parents()) > 1:
1381 if len(repo[None].parents()) > 1:
1381 raise util.Abort(_('cannot amend while merging'))
1382 raise util.Abort(_('cannot amend while merging'))
1382 if (not obsolete._enabled) and old.children():
1383 if (not obsolete._enabled) and old.children():
1383 raise util.Abort(_('cannot amend changeset with children'))
1384 raise util.Abort(_('cannot amend changeset with children'))
1384
1385
1385 # commitfunc is used only for temporary amend commit by cmdutil.amend
1386 # commitfunc is used only for temporary amend commit by cmdutil.amend
1386 def commitfunc(ui, repo, message, match, opts):
1387 def commitfunc(ui, repo, message, match, opts):
1387 return repo.commit(message,
1388 return repo.commit(message,
1388 opts.get('user') or old.user(),
1389 opts.get('user') or old.user(),
1389 opts.get('date') or old.date(),
1390 opts.get('date') or old.date(),
1390 match,
1391 match,
1391 extra=extra)
1392 extra=extra)
1392
1393
1393 current = repo._bookmarkcurrent
1394 current = repo._bookmarkcurrent
1394 marks = old.bookmarks()
1395 marks = old.bookmarks()
1395 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1396 node = cmdutil.amend(ui, repo, commitfunc, old, extra, pats, opts)
1396 if node == old.node():
1397 if node == old.node():
1397 ui.status(_("nothing changed\n"))
1398 ui.status(_("nothing changed\n"))
1398 return 1
1399 return 1
1399 elif marks:
1400 elif marks:
1400 ui.debug('moving bookmarks %r from %s to %s\n' %
1401 ui.debug('moving bookmarks %r from %s to %s\n' %
1401 (marks, old.hex(), hex(node)))
1402 (marks, old.hex(), hex(node)))
1402 newmarks = repo._bookmarks
1403 newmarks = repo._bookmarks
1403 for bm in marks:
1404 for bm in marks:
1404 newmarks[bm] = node
1405 newmarks[bm] = node
1405 if bm == current:
1406 if bm == current:
1406 bookmarks.setcurrent(repo, bm)
1407 bookmarks.setcurrent(repo, bm)
1407 newmarks.write()
1408 newmarks.write()
1408 else:
1409 else:
1409 def commitfunc(ui, repo, message, match, opts):
1410 def commitfunc(ui, repo, message, match, opts):
1410 try:
1411 try:
1411 if opts.get('secret'):
1412 if opts.get('secret'):
1412 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1413 ui.setconfig('phases', 'new-commit', 'secret', 'commit')
1413 # Propagate to subrepos
1414 # Propagate to subrepos
1414 repo.baseui.setconfig('phases', 'new-commit', 'secret',
1415 repo.baseui.setconfig('phases', 'new-commit', 'secret',
1415 'commit')
1416 'commit')
1416
1417
1417 return repo.commit(message, opts.get('user'), opts.get('date'),
1418 return repo.commit(message, opts.get('user'), opts.get('date'),
1418 match,
1419 match,
1419 editor=cmdutil.getcommiteditor(**opts),
1420 editor=cmdutil.getcommiteditor(**opts),
1420 extra=extra)
1421 extra=extra)
1421 finally:
1422 finally:
1422 ui.setconfig('phases', 'new-commit', oldcommitphase, 'commit')
1423 ui.setconfig('phases', 'new-commit', oldcommitphase, 'commit')
1423 repo.baseui.setconfig('phases', 'new-commit', oldcommitphase,
1424 repo.baseui.setconfig('phases', 'new-commit', oldcommitphase,
1424 'commit')
1425 'commit')
1425
1426
1426
1427
1427 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1428 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1428
1429
1429 if not node:
1430 if not node:
1430 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1431 stat = repo.status(match=scmutil.match(repo[None], pats, opts))
1431 if stat[3]:
1432 if stat[3]:
1432 ui.status(_("nothing changed (%d missing files, see "
1433 ui.status(_("nothing changed (%d missing files, see "
1433 "'hg status')\n") % len(stat[3]))
1434 "'hg status')\n") % len(stat[3]))
1434 else:
1435 else:
1435 ui.status(_("nothing changed\n"))
1436 ui.status(_("nothing changed\n"))
1436 return 1
1437 return 1
1437
1438
1438 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1439 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1439
1440
1440 @command('config|showconfig|debugconfig',
1441 @command('config|showconfig|debugconfig',
1441 [('u', 'untrusted', None, _('show untrusted configuration options')),
1442 [('u', 'untrusted', None, _('show untrusted configuration options')),
1442 ('e', 'edit', None, _('edit user config')),
1443 ('e', 'edit', None, _('edit user config')),
1443 ('l', 'local', None, _('edit repository config')),
1444 ('l', 'local', None, _('edit repository config')),
1444 ('g', 'global', None, _('edit global config'))],
1445 ('g', 'global', None, _('edit global config'))],
1445 _('[-u] [NAME]...'))
1446 _('[-u] [NAME]...'))
1446 def config(ui, repo, *values, **opts):
1447 def config(ui, repo, *values, **opts):
1447 """show combined config settings from all hgrc files
1448 """show combined config settings from all hgrc files
1448
1449
1449 With no arguments, print names and values of all config items.
1450 With no arguments, print names and values of all config items.
1450
1451
1451 With one argument of the form section.name, print just the value
1452 With one argument of the form section.name, print just the value
1452 of that config item.
1453 of that config item.
1453
1454
1454 With multiple arguments, print names and values of all config
1455 With multiple arguments, print names and values of all config
1455 items with matching section names.
1456 items with matching section names.
1456
1457
1457 With --edit, start an editor on the user-level config file. With
1458 With --edit, start an editor on the user-level config file. With
1458 --global, edit the system-wide config file. With --local, edit the
1459 --global, edit the system-wide config file. With --local, edit the
1459 repository-level config file.
1460 repository-level config file.
1460
1461
1461 With --debug, the source (filename and line number) is printed
1462 With --debug, the source (filename and line number) is printed
1462 for each config item.
1463 for each config item.
1463
1464
1464 See :hg:`help config` for more information about config files.
1465 See :hg:`help config` for more information about config files.
1465
1466
1466 Returns 0 on success.
1467 Returns 0 on success.
1467
1468
1468 """
1469 """
1469
1470
1470 if opts.get('edit') or opts.get('local') or opts.get('global'):
1471 if opts.get('edit') or opts.get('local') or opts.get('global'):
1471 if opts.get('local') and opts.get('global'):
1472 if opts.get('local') and opts.get('global'):
1472 raise util.Abort(_("can't use --local and --global together"))
1473 raise util.Abort(_("can't use --local and --global together"))
1473
1474
1474 if opts.get('local'):
1475 if opts.get('local'):
1475 if not repo:
1476 if not repo:
1476 raise util.Abort(_("can't use --local outside a repository"))
1477 raise util.Abort(_("can't use --local outside a repository"))
1477 paths = [repo.join('hgrc')]
1478 paths = [repo.join('hgrc')]
1478 elif opts.get('global'):
1479 elif opts.get('global'):
1479 paths = scmutil.systemrcpath()
1480 paths = scmutil.systemrcpath()
1480 else:
1481 else:
1481 paths = scmutil.userrcpath()
1482 paths = scmutil.userrcpath()
1482
1483
1483 for f in paths:
1484 for f in paths:
1484 if os.path.exists(f):
1485 if os.path.exists(f):
1485 break
1486 break
1486 else:
1487 else:
1487 f = paths[0]
1488 f = paths[0]
1488 fp = open(f, "w")
1489 fp = open(f, "w")
1489 fp.write(
1490 fp.write(
1490 '# example config (see "hg help config" for more info)\n'
1491 '# example config (see "hg help config" for more info)\n'
1491 '\n'
1492 '\n'
1492 '[ui]\n'
1493 '[ui]\n'
1493 '# name and email, e.g.\n'
1494 '# name and email, e.g.\n'
1494 '# username = Jane Doe <jdoe@example.com>\n'
1495 '# username = Jane Doe <jdoe@example.com>\n'
1495 'username =\n'
1496 'username =\n'
1496 '\n'
1497 '\n'
1497 '[extensions]\n'
1498 '[extensions]\n'
1498 '# uncomment these lines to enable some popular extensions\n'
1499 '# uncomment these lines to enable some popular extensions\n'
1499 '# (see "hg help extensions" for more info)\n'
1500 '# (see "hg help extensions" for more info)\n'
1500 '# pager =\n'
1501 '# pager =\n'
1501 '# progress =\n'
1502 '# progress =\n'
1502 '# color =\n')
1503 '# color =\n')
1503 fp.close()
1504 fp.close()
1504
1505
1505 editor = ui.geteditor()
1506 editor = ui.geteditor()
1506 util.system("%s \"%s\"" % (editor, f),
1507 util.system("%s \"%s\"" % (editor, f),
1507 onerr=util.Abort, errprefix=_("edit failed"),
1508 onerr=util.Abort, errprefix=_("edit failed"),
1508 out=ui.fout)
1509 out=ui.fout)
1509 return
1510 return
1510
1511
1511 for f in scmutil.rcpath():
1512 for f in scmutil.rcpath():
1512 ui.debug('read config from: %s\n' % f)
1513 ui.debug('read config from: %s\n' % f)
1513 untrusted = bool(opts.get('untrusted'))
1514 untrusted = bool(opts.get('untrusted'))
1514 if values:
1515 if values:
1515 sections = [v for v in values if '.' not in v]
1516 sections = [v for v in values if '.' not in v]
1516 items = [v for v in values if '.' in v]
1517 items = [v for v in values if '.' in v]
1517 if len(items) > 1 or items and sections:
1518 if len(items) > 1 or items and sections:
1518 raise util.Abort(_('only one config item permitted'))
1519 raise util.Abort(_('only one config item permitted'))
1519 for section, name, value in ui.walkconfig(untrusted=untrusted):
1520 for section, name, value in ui.walkconfig(untrusted=untrusted):
1520 value = str(value).replace('\n', '\\n')
1521 value = str(value).replace('\n', '\\n')
1521 sectname = section + '.' + name
1522 sectname = section + '.' + name
1522 if values:
1523 if values:
1523 for v in values:
1524 for v in values:
1524 if v == section:
1525 if v == section:
1525 ui.debug('%s: ' %
1526 ui.debug('%s: ' %
1526 ui.configsource(section, name, untrusted))
1527 ui.configsource(section, name, untrusted))
1527 ui.write('%s=%s\n' % (sectname, value))
1528 ui.write('%s=%s\n' % (sectname, value))
1528 elif v == sectname:
1529 elif v == sectname:
1529 ui.debug('%s: ' %
1530 ui.debug('%s: ' %
1530 ui.configsource(section, name, untrusted))
1531 ui.configsource(section, name, untrusted))
1531 ui.write(value, '\n')
1532 ui.write(value, '\n')
1532 else:
1533 else:
1533 ui.debug('%s: ' %
1534 ui.debug('%s: ' %
1534 ui.configsource(section, name, untrusted))
1535 ui.configsource(section, name, untrusted))
1535 ui.write('%s=%s\n' % (sectname, value))
1536 ui.write('%s=%s\n' % (sectname, value))
1536
1537
1537 @command('copy|cp',
1538 @command('copy|cp',
1538 [('A', 'after', None, _('record a copy that has already occurred')),
1539 [('A', 'after', None, _('record a copy that has already occurred')),
1539 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1540 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1540 ] + walkopts + dryrunopts,
1541 ] + walkopts + dryrunopts,
1541 _('[OPTION]... [SOURCE]... DEST'))
1542 _('[OPTION]... [SOURCE]... DEST'))
1542 def copy(ui, repo, *pats, **opts):
1543 def copy(ui, repo, *pats, **opts):
1543 """mark files as copied for the next commit
1544 """mark files as copied for the next commit
1544
1545
1545 Mark dest as having copies of source files. If dest is a
1546 Mark dest as having copies of source files. If dest is a
1546 directory, copies are put in that directory. If dest is a file,
1547 directory, copies are put in that directory. If dest is a file,
1547 the source must be a single file.
1548 the source must be a single file.
1548
1549
1549 By default, this command copies the contents of files as they
1550 By default, this command copies the contents of files as they
1550 exist in the working directory. If invoked with -A/--after, the
1551 exist in the working directory. If invoked with -A/--after, the
1551 operation is recorded, but no copying is performed.
1552 operation is recorded, but no copying is performed.
1552
1553
1553 This command takes effect with the next commit. To undo a copy
1554 This command takes effect with the next commit. To undo a copy
1554 before that, see :hg:`revert`.
1555 before that, see :hg:`revert`.
1555
1556
1556 Returns 0 on success, 1 if errors are encountered.
1557 Returns 0 on success, 1 if errors are encountered.
1557 """
1558 """
1558 wlock = repo.wlock(False)
1559 wlock = repo.wlock(False)
1559 try:
1560 try:
1560 return cmdutil.copy(ui, repo, pats, opts)
1561 return cmdutil.copy(ui, repo, pats, opts)
1561 finally:
1562 finally:
1562 wlock.release()
1563 wlock.release()
1563
1564
1564 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1565 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1565 def debugancestor(ui, repo, *args):
1566 def debugancestor(ui, repo, *args):
1566 """find the ancestor revision of two revisions in a given index"""
1567 """find the ancestor revision of two revisions in a given index"""
1567 if len(args) == 3:
1568 if len(args) == 3:
1568 index, rev1, rev2 = args
1569 index, rev1, rev2 = args
1569 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1570 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1570 lookup = r.lookup
1571 lookup = r.lookup
1571 elif len(args) == 2:
1572 elif len(args) == 2:
1572 if not repo:
1573 if not repo:
1573 raise util.Abort(_("there is no Mercurial repository here "
1574 raise util.Abort(_("there is no Mercurial repository here "
1574 "(.hg not found)"))
1575 "(.hg not found)"))
1575 rev1, rev2 = args
1576 rev1, rev2 = args
1576 r = repo.changelog
1577 r = repo.changelog
1577 lookup = repo.lookup
1578 lookup = repo.lookup
1578 else:
1579 else:
1579 raise util.Abort(_('either two or three arguments required'))
1580 raise util.Abort(_('either two or three arguments required'))
1580 a = r.ancestor(lookup(rev1), lookup(rev2))
1581 a = r.ancestor(lookup(rev1), lookup(rev2))
1581 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1582 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1582
1583
1583 @command('debugbuilddag',
1584 @command('debugbuilddag',
1584 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1585 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1585 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1586 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1586 ('n', 'new-file', None, _('add new file at each rev'))],
1587 ('n', 'new-file', None, _('add new file at each rev'))],
1587 _('[OPTION]... [TEXT]'))
1588 _('[OPTION]... [TEXT]'))
1588 def debugbuilddag(ui, repo, text=None,
1589 def debugbuilddag(ui, repo, text=None,
1589 mergeable_file=False,
1590 mergeable_file=False,
1590 overwritten_file=False,
1591 overwritten_file=False,
1591 new_file=False):
1592 new_file=False):
1592 """builds a repo with a given DAG from scratch in the current empty repo
1593 """builds a repo with a given DAG from scratch in the current empty repo
1593
1594
1594 The description of the DAG is read from stdin if not given on the
1595 The description of the DAG is read from stdin if not given on the
1595 command line.
1596 command line.
1596
1597
1597 Elements:
1598 Elements:
1598
1599
1599 - "+n" is a linear run of n nodes based on the current default parent
1600 - "+n" is a linear run of n nodes based on the current default parent
1600 - "." is a single node based on the current default parent
1601 - "." is a single node based on the current default parent
1601 - "$" resets the default parent to null (implied at the start);
1602 - "$" resets the default parent to null (implied at the start);
1602 otherwise the default parent is always the last node created
1603 otherwise the default parent is always the last node created
1603 - "<p" sets the default parent to the backref p
1604 - "<p" sets the default parent to the backref p
1604 - "*p" is a fork at parent p, which is a backref
1605 - "*p" is a fork at parent p, which is a backref
1605 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1606 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1606 - "/p2" is a merge of the preceding node and p2
1607 - "/p2" is a merge of the preceding node and p2
1607 - ":tag" defines a local tag for the preceding node
1608 - ":tag" defines a local tag for the preceding node
1608 - "@branch" sets the named branch for subsequent nodes
1609 - "@branch" sets the named branch for subsequent nodes
1609 - "#...\\n" is a comment up to the end of the line
1610 - "#...\\n" is a comment up to the end of the line
1610
1611
1611 Whitespace between the above elements is ignored.
1612 Whitespace between the above elements is ignored.
1612
1613
1613 A backref is either
1614 A backref is either
1614
1615
1615 - a number n, which references the node curr-n, where curr is the current
1616 - a number n, which references the node curr-n, where curr is the current
1616 node, or
1617 node, or
1617 - the name of a local tag you placed earlier using ":tag", or
1618 - the name of a local tag you placed earlier using ":tag", or
1618 - empty to denote the default parent.
1619 - empty to denote the default parent.
1619
1620
1620 All string valued-elements are either strictly alphanumeric, or must
1621 All string valued-elements are either strictly alphanumeric, or must
1621 be enclosed in double quotes ("..."), with "\\" as escape character.
1622 be enclosed in double quotes ("..."), with "\\" as escape character.
1622 """
1623 """
1623
1624
1624 if text is None:
1625 if text is None:
1625 ui.status(_("reading DAG from stdin\n"))
1626 ui.status(_("reading DAG from stdin\n"))
1626 text = ui.fin.read()
1627 text = ui.fin.read()
1627
1628
1628 cl = repo.changelog
1629 cl = repo.changelog
1629 if len(cl) > 0:
1630 if len(cl) > 0:
1630 raise util.Abort(_('repository is not empty'))
1631 raise util.Abort(_('repository is not empty'))
1631
1632
1632 # determine number of revs in DAG
1633 # determine number of revs in DAG
1633 total = 0
1634 total = 0
1634 for type, data in dagparser.parsedag(text):
1635 for type, data in dagparser.parsedag(text):
1635 if type == 'n':
1636 if type == 'n':
1636 total += 1
1637 total += 1
1637
1638
1638 if mergeable_file:
1639 if mergeable_file:
1639 linesperrev = 2
1640 linesperrev = 2
1640 # make a file with k lines per rev
1641 # make a file with k lines per rev
1641 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1642 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1642 initialmergedlines.append("")
1643 initialmergedlines.append("")
1643
1644
1644 tags = []
1645 tags = []
1645
1646
1646 lock = tr = None
1647 lock = tr = None
1647 try:
1648 try:
1648 lock = repo.lock()
1649 lock = repo.lock()
1649 tr = repo.transaction("builddag")
1650 tr = repo.transaction("builddag")
1650
1651
1651 at = -1
1652 at = -1
1652 atbranch = 'default'
1653 atbranch = 'default'
1653 nodeids = []
1654 nodeids = []
1654 id = 0
1655 id = 0
1655 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1656 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1656 for type, data in dagparser.parsedag(text):
1657 for type, data in dagparser.parsedag(text):
1657 if type == 'n':
1658 if type == 'n':
1658 ui.note(('node %s\n' % str(data)))
1659 ui.note(('node %s\n' % str(data)))
1659 id, ps = data
1660 id, ps = data
1660
1661
1661 files = []
1662 files = []
1662 fctxs = {}
1663 fctxs = {}
1663
1664
1664 p2 = None
1665 p2 = None
1665 if mergeable_file:
1666 if mergeable_file:
1666 fn = "mf"
1667 fn = "mf"
1667 p1 = repo[ps[0]]
1668 p1 = repo[ps[0]]
1668 if len(ps) > 1:
1669 if len(ps) > 1:
1669 p2 = repo[ps[1]]
1670 p2 = repo[ps[1]]
1670 pa = p1.ancestor(p2)
1671 pa = p1.ancestor(p2)
1671 base, local, other = [x[fn].data() for x in (pa, p1,
1672 base, local, other = [x[fn].data() for x in (pa, p1,
1672 p2)]
1673 p2)]
1673 m3 = simplemerge.Merge3Text(base, local, other)
1674 m3 = simplemerge.Merge3Text(base, local, other)
1674 ml = [l.strip() for l in m3.merge_lines()]
1675 ml = [l.strip() for l in m3.merge_lines()]
1675 ml.append("")
1676 ml.append("")
1676 elif at > 0:
1677 elif at > 0:
1677 ml = p1[fn].data().split("\n")
1678 ml = p1[fn].data().split("\n")
1678 else:
1679 else:
1679 ml = initialmergedlines
1680 ml = initialmergedlines
1680 ml[id * linesperrev] += " r%i" % id
1681 ml[id * linesperrev] += " r%i" % id
1681 mergedtext = "\n".join(ml)
1682 mergedtext = "\n".join(ml)
1682 files.append(fn)
1683 files.append(fn)
1683 fctxs[fn] = context.memfilectx(fn, mergedtext)
1684 fctxs[fn] = context.memfilectx(fn, mergedtext)
1684
1685
1685 if overwritten_file:
1686 if overwritten_file:
1686 fn = "of"
1687 fn = "of"
1687 files.append(fn)
1688 files.append(fn)
1688 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1689 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1689
1690
1690 if new_file:
1691 if new_file:
1691 fn = "nf%i" % id
1692 fn = "nf%i" % id
1692 files.append(fn)
1693 files.append(fn)
1693 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1694 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1694 if len(ps) > 1:
1695 if len(ps) > 1:
1695 if not p2:
1696 if not p2:
1696 p2 = repo[ps[1]]
1697 p2 = repo[ps[1]]
1697 for fn in p2:
1698 for fn in p2:
1698 if fn.startswith("nf"):
1699 if fn.startswith("nf"):
1699 files.append(fn)
1700 files.append(fn)
1700 fctxs[fn] = p2[fn]
1701 fctxs[fn] = p2[fn]
1701
1702
1702 def fctxfn(repo, cx, path):
1703 def fctxfn(repo, cx, path):
1703 return fctxs.get(path)
1704 return fctxs.get(path)
1704
1705
1705 if len(ps) == 0 or ps[0] < 0:
1706 if len(ps) == 0 or ps[0] < 0:
1706 pars = [None, None]
1707 pars = [None, None]
1707 elif len(ps) == 1:
1708 elif len(ps) == 1:
1708 pars = [nodeids[ps[0]], None]
1709 pars = [nodeids[ps[0]], None]
1709 else:
1710 else:
1710 pars = [nodeids[p] for p in ps]
1711 pars = [nodeids[p] for p in ps]
1711 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1712 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1712 date=(id, 0),
1713 date=(id, 0),
1713 user="debugbuilddag",
1714 user="debugbuilddag",
1714 extra={'branch': atbranch})
1715 extra={'branch': atbranch})
1715 nodeid = repo.commitctx(cx)
1716 nodeid = repo.commitctx(cx)
1716 nodeids.append(nodeid)
1717 nodeids.append(nodeid)
1717 at = id
1718 at = id
1718 elif type == 'l':
1719 elif type == 'l':
1719 id, name = data
1720 id, name = data
1720 ui.note(('tag %s\n' % name))
1721 ui.note(('tag %s\n' % name))
1721 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1722 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1722 elif type == 'a':
1723 elif type == 'a':
1723 ui.note(('branch %s\n' % data))
1724 ui.note(('branch %s\n' % data))
1724 atbranch = data
1725 atbranch = data
1725 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1726 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1726 tr.close()
1727 tr.close()
1727
1728
1728 if tags:
1729 if tags:
1729 repo.opener.write("localtags", "".join(tags))
1730 repo.opener.write("localtags", "".join(tags))
1730 finally:
1731 finally:
1731 ui.progress(_('building'), None)
1732 ui.progress(_('building'), None)
1732 release(tr, lock)
1733 release(tr, lock)
1733
1734
1734 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1735 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1735 def debugbundle(ui, bundlepath, all=None, **opts):
1736 def debugbundle(ui, bundlepath, all=None, **opts):
1736 """lists the contents of a bundle"""
1737 """lists the contents of a bundle"""
1737 f = hg.openpath(ui, bundlepath)
1738 f = hg.openpath(ui, bundlepath)
1738 try:
1739 try:
1739 gen = exchange.readbundle(ui, f, bundlepath)
1740 gen = exchange.readbundle(ui, f, bundlepath)
1740 if all:
1741 if all:
1741 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1742 ui.write(("format: id, p1, p2, cset, delta base, len(delta)\n"))
1742
1743
1743 def showchunks(named):
1744 def showchunks(named):
1744 ui.write("\n%s\n" % named)
1745 ui.write("\n%s\n" % named)
1745 chain = None
1746 chain = None
1746 while True:
1747 while True:
1747 chunkdata = gen.deltachunk(chain)
1748 chunkdata = gen.deltachunk(chain)
1748 if not chunkdata:
1749 if not chunkdata:
1749 break
1750 break
1750 node = chunkdata['node']
1751 node = chunkdata['node']
1751 p1 = chunkdata['p1']
1752 p1 = chunkdata['p1']
1752 p2 = chunkdata['p2']
1753 p2 = chunkdata['p2']
1753 cs = chunkdata['cs']
1754 cs = chunkdata['cs']
1754 deltabase = chunkdata['deltabase']
1755 deltabase = chunkdata['deltabase']
1755 delta = chunkdata['delta']
1756 delta = chunkdata['delta']
1756 ui.write("%s %s %s %s %s %s\n" %
1757 ui.write("%s %s %s %s %s %s\n" %
1757 (hex(node), hex(p1), hex(p2),
1758 (hex(node), hex(p1), hex(p2),
1758 hex(cs), hex(deltabase), len(delta)))
1759 hex(cs), hex(deltabase), len(delta)))
1759 chain = node
1760 chain = node
1760
1761
1761 chunkdata = gen.changelogheader()
1762 chunkdata = gen.changelogheader()
1762 showchunks("changelog")
1763 showchunks("changelog")
1763 chunkdata = gen.manifestheader()
1764 chunkdata = gen.manifestheader()
1764 showchunks("manifest")
1765 showchunks("manifest")
1765 while True:
1766 while True:
1766 chunkdata = gen.filelogheader()
1767 chunkdata = gen.filelogheader()
1767 if not chunkdata:
1768 if not chunkdata:
1768 break
1769 break
1769 fname = chunkdata['filename']
1770 fname = chunkdata['filename']
1770 showchunks(fname)
1771 showchunks(fname)
1771 else:
1772 else:
1772 chunkdata = gen.changelogheader()
1773 chunkdata = gen.changelogheader()
1773 chain = None
1774 chain = None
1774 while True:
1775 while True:
1775 chunkdata = gen.deltachunk(chain)
1776 chunkdata = gen.deltachunk(chain)
1776 if not chunkdata:
1777 if not chunkdata:
1777 break
1778 break
1778 node = chunkdata['node']
1779 node = chunkdata['node']
1779 ui.write("%s\n" % hex(node))
1780 ui.write("%s\n" % hex(node))
1780 chain = node
1781 chain = node
1781 finally:
1782 finally:
1782 f.close()
1783 f.close()
1783
1784
1784 @command('debugcheckstate', [], '')
1785 @command('debugcheckstate', [], '')
1785 def debugcheckstate(ui, repo):
1786 def debugcheckstate(ui, repo):
1786 """validate the correctness of the current dirstate"""
1787 """validate the correctness of the current dirstate"""
1787 parent1, parent2 = repo.dirstate.parents()
1788 parent1, parent2 = repo.dirstate.parents()
1788 m1 = repo[parent1].manifest()
1789 m1 = repo[parent1].manifest()
1789 m2 = repo[parent2].manifest()
1790 m2 = repo[parent2].manifest()
1790 errors = 0
1791 errors = 0
1791 for f in repo.dirstate:
1792 for f in repo.dirstate:
1792 state = repo.dirstate[f]
1793 state = repo.dirstate[f]
1793 if state in "nr" and f not in m1:
1794 if state in "nr" and f not in m1:
1794 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1795 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1795 errors += 1
1796 errors += 1
1796 if state in "a" and f in m1:
1797 if state in "a" and f in m1:
1797 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1798 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1798 errors += 1
1799 errors += 1
1799 if state in "m" and f not in m1 and f not in m2:
1800 if state in "m" and f not in m1 and f not in m2:
1800 ui.warn(_("%s in state %s, but not in either manifest\n") %
1801 ui.warn(_("%s in state %s, but not in either manifest\n") %
1801 (f, state))
1802 (f, state))
1802 errors += 1
1803 errors += 1
1803 for f in m1:
1804 for f in m1:
1804 state = repo.dirstate[f]
1805 state = repo.dirstate[f]
1805 if state not in "nrm":
1806 if state not in "nrm":
1806 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1807 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1807 errors += 1
1808 errors += 1
1808 if errors:
1809 if errors:
1809 error = _(".hg/dirstate inconsistent with current parent's manifest")
1810 error = _(".hg/dirstate inconsistent with current parent's manifest")
1810 raise util.Abort(error)
1811 raise util.Abort(error)
1811
1812
1812 @command('debugcommands', [], _('[COMMAND]'))
1813 @command('debugcommands', [], _('[COMMAND]'))
1813 def debugcommands(ui, cmd='', *args):
1814 def debugcommands(ui, cmd='', *args):
1814 """list all available commands and options"""
1815 """list all available commands and options"""
1815 for cmd, vals in sorted(table.iteritems()):
1816 for cmd, vals in sorted(table.iteritems()):
1816 cmd = cmd.split('|')[0].strip('^')
1817 cmd = cmd.split('|')[0].strip('^')
1817 opts = ', '.join([i[1] for i in vals[1]])
1818 opts = ', '.join([i[1] for i in vals[1]])
1818 ui.write('%s: %s\n' % (cmd, opts))
1819 ui.write('%s: %s\n' % (cmd, opts))
1819
1820
1820 @command('debugcomplete',
1821 @command('debugcomplete',
1821 [('o', 'options', None, _('show the command options'))],
1822 [('o', 'options', None, _('show the command options'))],
1822 _('[-o] CMD'))
1823 _('[-o] CMD'))
1823 def debugcomplete(ui, cmd='', **opts):
1824 def debugcomplete(ui, cmd='', **opts):
1824 """returns the completion list associated with the given command"""
1825 """returns the completion list associated with the given command"""
1825
1826
1826 if opts.get('options'):
1827 if opts.get('options'):
1827 options = []
1828 options = []
1828 otables = [globalopts]
1829 otables = [globalopts]
1829 if cmd:
1830 if cmd:
1830 aliases, entry = cmdutil.findcmd(cmd, table, False)
1831 aliases, entry = cmdutil.findcmd(cmd, table, False)
1831 otables.append(entry[1])
1832 otables.append(entry[1])
1832 for t in otables:
1833 for t in otables:
1833 for o in t:
1834 for o in t:
1834 if "(DEPRECATED)" in o[3]:
1835 if "(DEPRECATED)" in o[3]:
1835 continue
1836 continue
1836 if o[0]:
1837 if o[0]:
1837 options.append('-%s' % o[0])
1838 options.append('-%s' % o[0])
1838 options.append('--%s' % o[1])
1839 options.append('--%s' % o[1])
1839 ui.write("%s\n" % "\n".join(options))
1840 ui.write("%s\n" % "\n".join(options))
1840 return
1841 return
1841
1842
1842 cmdlist = cmdutil.findpossible(cmd, table)
1843 cmdlist = cmdutil.findpossible(cmd, table)
1843 if ui.verbose:
1844 if ui.verbose:
1844 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1845 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1845 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1846 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1846
1847
1847 @command('debugdag',
1848 @command('debugdag',
1848 [('t', 'tags', None, _('use tags as labels')),
1849 [('t', 'tags', None, _('use tags as labels')),
1849 ('b', 'branches', None, _('annotate with branch names')),
1850 ('b', 'branches', None, _('annotate with branch names')),
1850 ('', 'dots', None, _('use dots for runs')),
1851 ('', 'dots', None, _('use dots for runs')),
1851 ('s', 'spaces', None, _('separate elements by spaces'))],
1852 ('s', 'spaces', None, _('separate elements by spaces'))],
1852 _('[OPTION]... [FILE [REV]...]'))
1853 _('[OPTION]... [FILE [REV]...]'))
1853 def debugdag(ui, repo, file_=None, *revs, **opts):
1854 def debugdag(ui, repo, file_=None, *revs, **opts):
1854 """format the changelog or an index DAG as a concise textual description
1855 """format the changelog or an index DAG as a concise textual description
1855
1856
1856 If you pass a revlog index, the revlog's DAG is emitted. If you list
1857 If you pass a revlog index, the revlog's DAG is emitted. If you list
1857 revision numbers, they get labeled in the output as rN.
1858 revision numbers, they get labeled in the output as rN.
1858
1859
1859 Otherwise, the changelog DAG of the current repo is emitted.
1860 Otherwise, the changelog DAG of the current repo is emitted.
1860 """
1861 """
1861 spaces = opts.get('spaces')
1862 spaces = opts.get('spaces')
1862 dots = opts.get('dots')
1863 dots = opts.get('dots')
1863 if file_:
1864 if file_:
1864 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1865 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1865 revs = set((int(r) for r in revs))
1866 revs = set((int(r) for r in revs))
1866 def events():
1867 def events():
1867 for r in rlog:
1868 for r in rlog:
1868 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1869 yield 'n', (r, list(set(p for p in rlog.parentrevs(r)
1869 if p != -1)))
1870 if p != -1)))
1870 if r in revs:
1871 if r in revs:
1871 yield 'l', (r, "r%i" % r)
1872 yield 'l', (r, "r%i" % r)
1872 elif repo:
1873 elif repo:
1873 cl = repo.changelog
1874 cl = repo.changelog
1874 tags = opts.get('tags')
1875 tags = opts.get('tags')
1875 branches = opts.get('branches')
1876 branches = opts.get('branches')
1876 if tags:
1877 if tags:
1877 labels = {}
1878 labels = {}
1878 for l, n in repo.tags().items():
1879 for l, n in repo.tags().items():
1879 labels.setdefault(cl.rev(n), []).append(l)
1880 labels.setdefault(cl.rev(n), []).append(l)
1880 def events():
1881 def events():
1881 b = "default"
1882 b = "default"
1882 for r in cl:
1883 for r in cl:
1883 if branches:
1884 if branches:
1884 newb = cl.read(cl.node(r))[5]['branch']
1885 newb = cl.read(cl.node(r))[5]['branch']
1885 if newb != b:
1886 if newb != b:
1886 yield 'a', newb
1887 yield 'a', newb
1887 b = newb
1888 b = newb
1888 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1889 yield 'n', (r, list(set(p for p in cl.parentrevs(r)
1889 if p != -1)))
1890 if p != -1)))
1890 if tags:
1891 if tags:
1891 ls = labels.get(r)
1892 ls = labels.get(r)
1892 if ls:
1893 if ls:
1893 for l in ls:
1894 for l in ls:
1894 yield 'l', (r, l)
1895 yield 'l', (r, l)
1895 else:
1896 else:
1896 raise util.Abort(_('need repo for changelog dag'))
1897 raise util.Abort(_('need repo for changelog dag'))
1897
1898
1898 for line in dagparser.dagtextlines(events(),
1899 for line in dagparser.dagtextlines(events(),
1899 addspaces=spaces,
1900 addspaces=spaces,
1900 wraplabels=True,
1901 wraplabels=True,
1901 wrapannotations=True,
1902 wrapannotations=True,
1902 wrapnonlinear=dots,
1903 wrapnonlinear=dots,
1903 usedots=dots,
1904 usedots=dots,
1904 maxlinewidth=70):
1905 maxlinewidth=70):
1905 ui.write(line)
1906 ui.write(line)
1906 ui.write("\n")
1907 ui.write("\n")
1907
1908
1908 @command('debugdata',
1909 @command('debugdata',
1909 [('c', 'changelog', False, _('open changelog')),
1910 [('c', 'changelog', False, _('open changelog')),
1910 ('m', 'manifest', False, _('open manifest'))],
1911 ('m', 'manifest', False, _('open manifest'))],
1911 _('-c|-m|FILE REV'))
1912 _('-c|-m|FILE REV'))
1912 def debugdata(ui, repo, file_, rev=None, **opts):
1913 def debugdata(ui, repo, file_, rev=None, **opts):
1913 """dump the contents of a data file revision"""
1914 """dump the contents of a data file revision"""
1914 if opts.get('changelog') or opts.get('manifest'):
1915 if opts.get('changelog') or opts.get('manifest'):
1915 file_, rev = None, file_
1916 file_, rev = None, file_
1916 elif rev is None:
1917 elif rev is None:
1917 raise error.CommandError('debugdata', _('invalid arguments'))
1918 raise error.CommandError('debugdata', _('invalid arguments'))
1918 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1919 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1919 try:
1920 try:
1920 ui.write(r.revision(r.lookup(rev)))
1921 ui.write(r.revision(r.lookup(rev)))
1921 except KeyError:
1922 except KeyError:
1922 raise util.Abort(_('invalid revision identifier %s') % rev)
1923 raise util.Abort(_('invalid revision identifier %s') % rev)
1923
1924
1924 @command('debugdate',
1925 @command('debugdate',
1925 [('e', 'extended', None, _('try extended date formats'))],
1926 [('e', 'extended', None, _('try extended date formats'))],
1926 _('[-e] DATE [RANGE]'))
1927 _('[-e] DATE [RANGE]'))
1927 def debugdate(ui, date, range=None, **opts):
1928 def debugdate(ui, date, range=None, **opts):
1928 """parse and display a date"""
1929 """parse and display a date"""
1929 if opts["extended"]:
1930 if opts["extended"]:
1930 d = util.parsedate(date, util.extendeddateformats)
1931 d = util.parsedate(date, util.extendeddateformats)
1931 else:
1932 else:
1932 d = util.parsedate(date)
1933 d = util.parsedate(date)
1933 ui.write(("internal: %s %s\n") % d)
1934 ui.write(("internal: %s %s\n") % d)
1934 ui.write(("standard: %s\n") % util.datestr(d))
1935 ui.write(("standard: %s\n") % util.datestr(d))
1935 if range:
1936 if range:
1936 m = util.matchdate(range)
1937 m = util.matchdate(range)
1937 ui.write(("match: %s\n") % m(d[0]))
1938 ui.write(("match: %s\n") % m(d[0]))
1938
1939
1939 @command('debugdiscovery',
1940 @command('debugdiscovery',
1940 [('', 'old', None, _('use old-style discovery')),
1941 [('', 'old', None, _('use old-style discovery')),
1941 ('', 'nonheads', None,
1942 ('', 'nonheads', None,
1942 _('use old-style discovery with non-heads included')),
1943 _('use old-style discovery with non-heads included')),
1943 ] + remoteopts,
1944 ] + remoteopts,
1944 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1945 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1945 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1946 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1946 """runs the changeset discovery protocol in isolation"""
1947 """runs the changeset discovery protocol in isolation"""
1947 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1948 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl),
1948 opts.get('branch'))
1949 opts.get('branch'))
1949 remote = hg.peer(repo, opts, remoteurl)
1950 remote = hg.peer(repo, opts, remoteurl)
1950 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1951 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1951
1952
1952 # make sure tests are repeatable
1953 # make sure tests are repeatable
1953 random.seed(12323)
1954 random.seed(12323)
1954
1955
1955 def doit(localheads, remoteheads, remote=remote):
1956 def doit(localheads, remoteheads, remote=remote):
1956 if opts.get('old'):
1957 if opts.get('old'):
1957 if localheads:
1958 if localheads:
1958 raise util.Abort('cannot use localheads with old style '
1959 raise util.Abort('cannot use localheads with old style '
1959 'discovery')
1960 'discovery')
1960 if not util.safehasattr(remote, 'branches'):
1961 if not util.safehasattr(remote, 'branches'):
1961 # enable in-client legacy support
1962 # enable in-client legacy support
1962 remote = localrepo.locallegacypeer(remote.local())
1963 remote = localrepo.locallegacypeer(remote.local())
1963 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1964 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1964 force=True)
1965 force=True)
1965 common = set(common)
1966 common = set(common)
1966 if not opts.get('nonheads'):
1967 if not opts.get('nonheads'):
1967 ui.write(("unpruned common: %s\n") %
1968 ui.write(("unpruned common: %s\n") %
1968 " ".join(sorted(short(n) for n in common)))
1969 " ".join(sorted(short(n) for n in common)))
1969 dag = dagutil.revlogdag(repo.changelog)
1970 dag = dagutil.revlogdag(repo.changelog)
1970 all = dag.ancestorset(dag.internalizeall(common))
1971 all = dag.ancestorset(dag.internalizeall(common))
1971 common = dag.externalizeall(dag.headsetofconnecteds(all))
1972 common = dag.externalizeall(dag.headsetofconnecteds(all))
1972 else:
1973 else:
1973 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1974 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1974 common = set(common)
1975 common = set(common)
1975 rheads = set(hds)
1976 rheads = set(hds)
1976 lheads = set(repo.heads())
1977 lheads = set(repo.heads())
1977 ui.write(("common heads: %s\n") %
1978 ui.write(("common heads: %s\n") %
1978 " ".join(sorted(short(n) for n in common)))
1979 " ".join(sorted(short(n) for n in common)))
1979 if lheads <= common:
1980 if lheads <= common:
1980 ui.write(("local is subset\n"))
1981 ui.write(("local is subset\n"))
1981 elif rheads <= common:
1982 elif rheads <= common:
1982 ui.write(("remote is subset\n"))
1983 ui.write(("remote is subset\n"))
1983
1984
1984 serverlogs = opts.get('serverlog')
1985 serverlogs = opts.get('serverlog')
1985 if serverlogs:
1986 if serverlogs:
1986 for filename in serverlogs:
1987 for filename in serverlogs:
1987 logfile = open(filename, 'r')
1988 logfile = open(filename, 'r')
1988 try:
1989 try:
1989 line = logfile.readline()
1990 line = logfile.readline()
1990 while line:
1991 while line:
1991 parts = line.strip().split(';')
1992 parts = line.strip().split(';')
1992 op = parts[1]
1993 op = parts[1]
1993 if op == 'cg':
1994 if op == 'cg':
1994 pass
1995 pass
1995 elif op == 'cgss':
1996 elif op == 'cgss':
1996 doit(parts[2].split(' '), parts[3].split(' '))
1997 doit(parts[2].split(' '), parts[3].split(' '))
1997 elif op == 'unb':
1998 elif op == 'unb':
1998 doit(parts[3].split(' '), parts[2].split(' '))
1999 doit(parts[3].split(' '), parts[2].split(' '))
1999 line = logfile.readline()
2000 line = logfile.readline()
2000 finally:
2001 finally:
2001 logfile.close()
2002 logfile.close()
2002
2003
2003 else:
2004 else:
2004 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2005 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
2005 opts.get('remote_head'))
2006 opts.get('remote_head'))
2006 localrevs = opts.get('local_head')
2007 localrevs = opts.get('local_head')
2007 doit(localrevs, remoterevs)
2008 doit(localrevs, remoterevs)
2008
2009
2009 @command('debugfileset',
2010 @command('debugfileset',
2010 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2011 [('r', 'rev', '', _('apply the filespec on this revision'), _('REV'))],
2011 _('[-r REV] FILESPEC'))
2012 _('[-r REV] FILESPEC'))
2012 def debugfileset(ui, repo, expr, **opts):
2013 def debugfileset(ui, repo, expr, **opts):
2013 '''parse and apply a fileset specification'''
2014 '''parse and apply a fileset specification'''
2014 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2015 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
2015 if ui.verbose:
2016 if ui.verbose:
2016 tree = fileset.parse(expr)[0]
2017 tree = fileset.parse(expr)[0]
2017 ui.note(tree, "\n")
2018 ui.note(tree, "\n")
2018
2019
2019 for f in ctx.getfileset(expr):
2020 for f in ctx.getfileset(expr):
2020 ui.write("%s\n" % f)
2021 ui.write("%s\n" % f)
2021
2022
2022 @command('debugfsinfo', [], _('[PATH]'))
2023 @command('debugfsinfo', [], _('[PATH]'))
2023 def debugfsinfo(ui, path="."):
2024 def debugfsinfo(ui, path="."):
2024 """show information detected about current filesystem"""
2025 """show information detected about current filesystem"""
2025 util.writefile('.debugfsinfo', '')
2026 util.writefile('.debugfsinfo', '')
2026 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2027 ui.write(('exec: %s\n') % (util.checkexec(path) and 'yes' or 'no'))
2027 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2028 ui.write(('symlink: %s\n') % (util.checklink(path) and 'yes' or 'no'))
2028 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2029 ui.write(('hardlink: %s\n') % (util.checknlink(path) and 'yes' or 'no'))
2029 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2030 ui.write(('case-sensitive: %s\n') % (util.checkcase('.debugfsinfo')
2030 and 'yes' or 'no'))
2031 and 'yes' or 'no'))
2031 os.unlink('.debugfsinfo')
2032 os.unlink('.debugfsinfo')
2032
2033
2033 @command('debuggetbundle',
2034 @command('debuggetbundle',
2034 [('H', 'head', [], _('id of head node'), _('ID')),
2035 [('H', 'head', [], _('id of head node'), _('ID')),
2035 ('C', 'common', [], _('id of common node'), _('ID')),
2036 ('C', 'common', [], _('id of common node'), _('ID')),
2036 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2037 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
2037 _('REPO FILE [-H|-C ID]...'))
2038 _('REPO FILE [-H|-C ID]...'))
2038 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2039 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
2039 """retrieves a bundle from a repo
2040 """retrieves a bundle from a repo
2040
2041
2041 Every ID must be a full-length hex node id string. Saves the bundle to the
2042 Every ID must be a full-length hex node id string. Saves the bundle to the
2042 given file.
2043 given file.
2043 """
2044 """
2044 repo = hg.peer(ui, opts, repopath)
2045 repo = hg.peer(ui, opts, repopath)
2045 if not repo.capable('getbundle'):
2046 if not repo.capable('getbundle'):
2046 raise util.Abort("getbundle() not supported by target repository")
2047 raise util.Abort("getbundle() not supported by target repository")
2047 args = {}
2048 args = {}
2048 if common:
2049 if common:
2049 args['common'] = [bin(s) for s in common]
2050 args['common'] = [bin(s) for s in common]
2050 if head:
2051 if head:
2051 args['heads'] = [bin(s) for s in head]
2052 args['heads'] = [bin(s) for s in head]
2052 # TODO: get desired bundlecaps from command line.
2053 # TODO: get desired bundlecaps from command line.
2053 args['bundlecaps'] = None
2054 args['bundlecaps'] = None
2054 bundle = repo.getbundle('debug', **args)
2055 bundle = repo.getbundle('debug', **args)
2055
2056
2056 bundletype = opts.get('type', 'bzip2').lower()
2057 bundletype = opts.get('type', 'bzip2').lower()
2057 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2058 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
2058 bundletype = btypes.get(bundletype)
2059 bundletype = btypes.get(bundletype)
2059 if bundletype not in changegroup.bundletypes:
2060 if bundletype not in changegroup.bundletypes:
2060 raise util.Abort(_('unknown bundle type specified with --type'))
2061 raise util.Abort(_('unknown bundle type specified with --type'))
2061 changegroup.writebundle(bundle, bundlepath, bundletype)
2062 changegroup.writebundle(bundle, bundlepath, bundletype)
2062
2063
2063 @command('debugignore', [], '')
2064 @command('debugignore', [], '')
2064 def debugignore(ui, repo, *values, **opts):
2065 def debugignore(ui, repo, *values, **opts):
2065 """display the combined ignore pattern"""
2066 """display the combined ignore pattern"""
2066 ignore = repo.dirstate._ignore
2067 ignore = repo.dirstate._ignore
2067 includepat = getattr(ignore, 'includepat', None)
2068 includepat = getattr(ignore, 'includepat', None)
2068 if includepat is not None:
2069 if includepat is not None:
2069 ui.write("%s\n" % includepat)
2070 ui.write("%s\n" % includepat)
2070 else:
2071 else:
2071 raise util.Abort(_("no ignore patterns found"))
2072 raise util.Abort(_("no ignore patterns found"))
2072
2073
2073 @command('debugindex',
2074 @command('debugindex',
2074 [('c', 'changelog', False, _('open changelog')),
2075 [('c', 'changelog', False, _('open changelog')),
2075 ('m', 'manifest', False, _('open manifest')),
2076 ('m', 'manifest', False, _('open manifest')),
2076 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2077 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
2077 _('[-f FORMAT] -c|-m|FILE'))
2078 _('[-f FORMAT] -c|-m|FILE'))
2078 def debugindex(ui, repo, file_=None, **opts):
2079 def debugindex(ui, repo, file_=None, **opts):
2079 """dump the contents of an index file"""
2080 """dump the contents of an index file"""
2080 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2081 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
2081 format = opts.get('format', 0)
2082 format = opts.get('format', 0)
2082 if format not in (0, 1):
2083 if format not in (0, 1):
2083 raise util.Abort(_("unknown format %d") % format)
2084 raise util.Abort(_("unknown format %d") % format)
2084
2085
2085 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2086 generaldelta = r.version & revlog.REVLOGGENERALDELTA
2086 if generaldelta:
2087 if generaldelta:
2087 basehdr = ' delta'
2088 basehdr = ' delta'
2088 else:
2089 else:
2089 basehdr = ' base'
2090 basehdr = ' base'
2090
2091
2091 if format == 0:
2092 if format == 0:
2092 ui.write(" rev offset length " + basehdr + " linkrev"
2093 ui.write(" rev offset length " + basehdr + " linkrev"
2093 " nodeid p1 p2\n")
2094 " nodeid p1 p2\n")
2094 elif format == 1:
2095 elif format == 1:
2095 ui.write(" rev flag offset length"
2096 ui.write(" rev flag offset length"
2096 " size " + basehdr + " link p1 p2"
2097 " size " + basehdr + " link p1 p2"
2097 " nodeid\n")
2098 " nodeid\n")
2098
2099
2099 for i in r:
2100 for i in r:
2100 node = r.node(i)
2101 node = r.node(i)
2101 if generaldelta:
2102 if generaldelta:
2102 base = r.deltaparent(i)
2103 base = r.deltaparent(i)
2103 else:
2104 else:
2104 base = r.chainbase(i)
2105 base = r.chainbase(i)
2105 if format == 0:
2106 if format == 0:
2106 try:
2107 try:
2107 pp = r.parents(node)
2108 pp = r.parents(node)
2108 except Exception:
2109 except Exception:
2109 pp = [nullid, nullid]
2110 pp = [nullid, nullid]
2110 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2111 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
2111 i, r.start(i), r.length(i), base, r.linkrev(i),
2112 i, r.start(i), r.length(i), base, r.linkrev(i),
2112 short(node), short(pp[0]), short(pp[1])))
2113 short(node), short(pp[0]), short(pp[1])))
2113 elif format == 1:
2114 elif format == 1:
2114 pr = r.parentrevs(i)
2115 pr = r.parentrevs(i)
2115 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2116 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
2116 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2117 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
2117 base, r.linkrev(i), pr[0], pr[1], short(node)))
2118 base, r.linkrev(i), pr[0], pr[1], short(node)))
2118
2119
2119 @command('debugindexdot', [], _('FILE'))
2120 @command('debugindexdot', [], _('FILE'))
2120 def debugindexdot(ui, repo, file_):
2121 def debugindexdot(ui, repo, file_):
2121 """dump an index DAG as a graphviz dot file"""
2122 """dump an index DAG as a graphviz dot file"""
2122 r = None
2123 r = None
2123 if repo:
2124 if repo:
2124 filelog = repo.file(file_)
2125 filelog = repo.file(file_)
2125 if len(filelog):
2126 if len(filelog):
2126 r = filelog
2127 r = filelog
2127 if not r:
2128 if not r:
2128 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2129 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
2129 ui.write(("digraph G {\n"))
2130 ui.write(("digraph G {\n"))
2130 for i in r:
2131 for i in r:
2131 node = r.node(i)
2132 node = r.node(i)
2132 pp = r.parents(node)
2133 pp = r.parents(node)
2133 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2134 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
2134 if pp[1] != nullid:
2135 if pp[1] != nullid:
2135 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2136 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
2136 ui.write("}\n")
2137 ui.write("}\n")
2137
2138
2138 @command('debuginstall', [], '')
2139 @command('debuginstall', [], '')
2139 def debuginstall(ui):
2140 def debuginstall(ui):
2140 '''test Mercurial installation
2141 '''test Mercurial installation
2141
2142
2142 Returns 0 on success.
2143 Returns 0 on success.
2143 '''
2144 '''
2144
2145
2145 def writetemp(contents):
2146 def writetemp(contents):
2146 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2147 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
2147 f = os.fdopen(fd, "wb")
2148 f = os.fdopen(fd, "wb")
2148 f.write(contents)
2149 f.write(contents)
2149 f.close()
2150 f.close()
2150 return name
2151 return name
2151
2152
2152 problems = 0
2153 problems = 0
2153
2154
2154 # encoding
2155 # encoding
2155 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2156 ui.status(_("checking encoding (%s)...\n") % encoding.encoding)
2156 try:
2157 try:
2157 encoding.fromlocal("test")
2158 encoding.fromlocal("test")
2158 except util.Abort, inst:
2159 except util.Abort, inst:
2159 ui.write(" %s\n" % inst)
2160 ui.write(" %s\n" % inst)
2160 ui.write(_(" (check that your locale is properly set)\n"))
2161 ui.write(_(" (check that your locale is properly set)\n"))
2161 problems += 1
2162 problems += 1
2162
2163
2163 # Python
2164 # Python
2164 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2165 ui.status(_("checking Python executable (%s)\n") % sys.executable)
2165 ui.status(_("checking Python version (%s)\n")
2166 ui.status(_("checking Python version (%s)\n")
2166 % ("%s.%s.%s" % sys.version_info[:3]))
2167 % ("%s.%s.%s" % sys.version_info[:3]))
2167 ui.status(_("checking Python lib (%s)...\n")
2168 ui.status(_("checking Python lib (%s)...\n")
2168 % os.path.dirname(os.__file__))
2169 % os.path.dirname(os.__file__))
2169
2170
2170 # compiled modules
2171 # compiled modules
2171 ui.status(_("checking installed modules (%s)...\n")
2172 ui.status(_("checking installed modules (%s)...\n")
2172 % os.path.dirname(__file__))
2173 % os.path.dirname(__file__))
2173 try:
2174 try:
2174 import bdiff, mpatch, base85, osutil
2175 import bdiff, mpatch, base85, osutil
2175 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2176 dir(bdiff), dir(mpatch), dir(base85), dir(osutil) # quiet pyflakes
2176 except Exception, inst:
2177 except Exception, inst:
2177 ui.write(" %s\n" % inst)
2178 ui.write(" %s\n" % inst)
2178 ui.write(_(" One or more extensions could not be found"))
2179 ui.write(_(" One or more extensions could not be found"))
2179 ui.write(_(" (check that you compiled the extensions)\n"))
2180 ui.write(_(" (check that you compiled the extensions)\n"))
2180 problems += 1
2181 problems += 1
2181
2182
2182 # templates
2183 # templates
2183 import templater
2184 import templater
2184 p = templater.templatepath()
2185 p = templater.templatepath()
2185 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2186 ui.status(_("checking templates (%s)...\n") % ' '.join(p))
2186 if p:
2187 if p:
2187 m = templater.templatepath("map-cmdline.default")
2188 m = templater.templatepath("map-cmdline.default")
2188 if m:
2189 if m:
2189 # template found, check if it is working
2190 # template found, check if it is working
2190 try:
2191 try:
2191 templater.templater(m)
2192 templater.templater(m)
2192 except Exception, inst:
2193 except Exception, inst:
2193 ui.write(" %s\n" % inst)
2194 ui.write(" %s\n" % inst)
2194 p = None
2195 p = None
2195 else:
2196 else:
2196 ui.write(_(" template 'default' not found\n"))
2197 ui.write(_(" template 'default' not found\n"))
2197 p = None
2198 p = None
2198 else:
2199 else:
2199 ui.write(_(" no template directories found\n"))
2200 ui.write(_(" no template directories found\n"))
2200 if not p:
2201 if not p:
2201 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2202 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
2202 problems += 1
2203 problems += 1
2203
2204
2204 # editor
2205 # editor
2205 ui.status(_("checking commit editor...\n"))
2206 ui.status(_("checking commit editor...\n"))
2206 editor = ui.geteditor()
2207 editor = ui.geteditor()
2207 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2208 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
2208 if not cmdpath:
2209 if not cmdpath:
2209 if editor == 'vi':
2210 if editor == 'vi':
2210 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2211 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
2211 ui.write(_(" (specify a commit editor in your configuration"
2212 ui.write(_(" (specify a commit editor in your configuration"
2212 " file)\n"))
2213 " file)\n"))
2213 else:
2214 else:
2214 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2215 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
2215 ui.write(_(" (specify a commit editor in your configuration"
2216 ui.write(_(" (specify a commit editor in your configuration"
2216 " file)\n"))
2217 " file)\n"))
2217 problems += 1
2218 problems += 1
2218
2219
2219 # check username
2220 # check username
2220 ui.status(_("checking username...\n"))
2221 ui.status(_("checking username...\n"))
2221 try:
2222 try:
2222 ui.username()
2223 ui.username()
2223 except util.Abort, e:
2224 except util.Abort, e:
2224 ui.write(" %s\n" % e)
2225 ui.write(" %s\n" % e)
2225 ui.write(_(" (specify a username in your configuration file)\n"))
2226 ui.write(_(" (specify a username in your configuration file)\n"))
2226 problems += 1
2227 problems += 1
2227
2228
2228 if not problems:
2229 if not problems:
2229 ui.status(_("no problems detected\n"))
2230 ui.status(_("no problems detected\n"))
2230 else:
2231 else:
2231 ui.write(_("%s problems detected,"
2232 ui.write(_("%s problems detected,"
2232 " please check your install!\n") % problems)
2233 " please check your install!\n") % problems)
2233
2234
2234 return problems
2235 return problems
2235
2236
2236 @command('debugknown', [], _('REPO ID...'))
2237 @command('debugknown', [], _('REPO ID...'))
2237 def debugknown(ui, repopath, *ids, **opts):
2238 def debugknown(ui, repopath, *ids, **opts):
2238 """test whether node ids are known to a repo
2239 """test whether node ids are known to a repo
2239
2240
2240 Every ID must be a full-length hex node id string. Returns a list of 0s
2241 Every ID must be a full-length hex node id string. Returns a list of 0s
2241 and 1s indicating unknown/known.
2242 and 1s indicating unknown/known.
2242 """
2243 """
2243 repo = hg.peer(ui, opts, repopath)
2244 repo = hg.peer(ui, opts, repopath)
2244 if not repo.capable('known'):
2245 if not repo.capable('known'):
2245 raise util.Abort("known() not supported by target repository")
2246 raise util.Abort("known() not supported by target repository")
2246 flags = repo.known([bin(s) for s in ids])
2247 flags = repo.known([bin(s) for s in ids])
2247 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2248 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
2248
2249
2249 @command('debuglabelcomplete', [], _('LABEL...'))
2250 @command('debuglabelcomplete', [], _('LABEL...'))
2250 def debuglabelcomplete(ui, repo, *args):
2251 def debuglabelcomplete(ui, repo, *args):
2251 '''complete "labels" - tags, open branch names, bookmark names'''
2252 '''complete "labels" - tags, open branch names, bookmark names'''
2252
2253
2253 labels = set()
2254 labels = set()
2254 labels.update(t[0] for t in repo.tagslist())
2255 labels.update(t[0] for t in repo.tagslist())
2255 labels.update(repo._bookmarks.keys())
2256 labels.update(repo._bookmarks.keys())
2256 labels.update(tag for (tag, heads, tip, closed)
2257 labels.update(tag for (tag, heads, tip, closed)
2257 in repo.branchmap().iterbranches() if not closed)
2258 in repo.branchmap().iterbranches() if not closed)
2258 completions = set()
2259 completions = set()
2259 if not args:
2260 if not args:
2260 args = ['']
2261 args = ['']
2261 for a in args:
2262 for a in args:
2262 completions.update(l for l in labels if l.startswith(a))
2263 completions.update(l for l in labels if l.startswith(a))
2263 ui.write('\n'.join(sorted(completions)))
2264 ui.write('\n'.join(sorted(completions)))
2264 ui.write('\n')
2265 ui.write('\n')
2265
2266
2266 @command('debugobsolete',
2267 @command('debugobsolete',
2267 [('', 'flags', 0, _('markers flag')),
2268 [('', 'flags', 0, _('markers flag')),
2268 ] + commitopts2,
2269 ] + commitopts2,
2269 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2270 _('[OBSOLETED [REPLACEMENT] [REPL... ]'))
2270 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2271 def debugobsolete(ui, repo, precursor=None, *successors, **opts):
2271 """create arbitrary obsolete marker
2272 """create arbitrary obsolete marker
2272
2273
2273 With no arguments, displays the list of obsolescence markers."""
2274 With no arguments, displays the list of obsolescence markers."""
2274 def parsenodeid(s):
2275 def parsenodeid(s):
2275 try:
2276 try:
2276 # We do not use revsingle/revrange functions here to accept
2277 # We do not use revsingle/revrange functions here to accept
2277 # arbitrary node identifiers, possibly not present in the
2278 # arbitrary node identifiers, possibly not present in the
2278 # local repository.
2279 # local repository.
2279 n = bin(s)
2280 n = bin(s)
2280 if len(n) != len(nullid):
2281 if len(n) != len(nullid):
2281 raise TypeError()
2282 raise TypeError()
2282 return n
2283 return n
2283 except TypeError:
2284 except TypeError:
2284 raise util.Abort('changeset references must be full hexadecimal '
2285 raise util.Abort('changeset references must be full hexadecimal '
2285 'node identifiers')
2286 'node identifiers')
2286
2287
2287 if precursor is not None:
2288 if precursor is not None:
2288 metadata = {}
2289 metadata = {}
2289 if 'date' in opts:
2290 if 'date' in opts:
2290 metadata['date'] = opts['date']
2291 metadata['date'] = opts['date']
2291 metadata['user'] = opts['user'] or ui.username()
2292 metadata['user'] = opts['user'] or ui.username()
2292 succs = tuple(parsenodeid(succ) for succ in successors)
2293 succs = tuple(parsenodeid(succ) for succ in successors)
2293 l = repo.lock()
2294 l = repo.lock()
2294 try:
2295 try:
2295 tr = repo.transaction('debugobsolete')
2296 tr = repo.transaction('debugobsolete')
2296 try:
2297 try:
2297 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2298 repo.obsstore.create(tr, parsenodeid(precursor), succs,
2298 opts['flags'], metadata)
2299 opts['flags'], metadata)
2299 tr.close()
2300 tr.close()
2300 finally:
2301 finally:
2301 tr.release()
2302 tr.release()
2302 finally:
2303 finally:
2303 l.release()
2304 l.release()
2304 else:
2305 else:
2305 for m in obsolete.allmarkers(repo):
2306 for m in obsolete.allmarkers(repo):
2306 cmdutil.showmarker(ui, m)
2307 cmdutil.showmarker(ui, m)
2307
2308
2308 @command('debugpathcomplete',
2309 @command('debugpathcomplete',
2309 [('f', 'full', None, _('complete an entire path')),
2310 [('f', 'full', None, _('complete an entire path')),
2310 ('n', 'normal', None, _('show only normal files')),
2311 ('n', 'normal', None, _('show only normal files')),
2311 ('a', 'added', None, _('show only added files')),
2312 ('a', 'added', None, _('show only added files')),
2312 ('r', 'removed', None, _('show only removed files'))],
2313 ('r', 'removed', None, _('show only removed files'))],
2313 _('FILESPEC...'))
2314 _('FILESPEC...'))
2314 def debugpathcomplete(ui, repo, *specs, **opts):
2315 def debugpathcomplete(ui, repo, *specs, **opts):
2315 '''complete part or all of a tracked path
2316 '''complete part or all of a tracked path
2316
2317
2317 This command supports shells that offer path name completion. It
2318 This command supports shells that offer path name completion. It
2318 currently completes only files already known to the dirstate.
2319 currently completes only files already known to the dirstate.
2319
2320
2320 Completion extends only to the next path segment unless
2321 Completion extends only to the next path segment unless
2321 --full is specified, in which case entire paths are used.'''
2322 --full is specified, in which case entire paths are used.'''
2322
2323
2323 def complete(path, acceptable):
2324 def complete(path, acceptable):
2324 dirstate = repo.dirstate
2325 dirstate = repo.dirstate
2325 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2326 spec = os.path.normpath(os.path.join(os.getcwd(), path))
2326 rootdir = repo.root + os.sep
2327 rootdir = repo.root + os.sep
2327 if spec != repo.root and not spec.startswith(rootdir):
2328 if spec != repo.root and not spec.startswith(rootdir):
2328 return [], []
2329 return [], []
2329 if os.path.isdir(spec):
2330 if os.path.isdir(spec):
2330 spec += '/'
2331 spec += '/'
2331 spec = spec[len(rootdir):]
2332 spec = spec[len(rootdir):]
2332 fixpaths = os.sep != '/'
2333 fixpaths = os.sep != '/'
2333 if fixpaths:
2334 if fixpaths:
2334 spec = spec.replace(os.sep, '/')
2335 spec = spec.replace(os.sep, '/')
2335 speclen = len(spec)
2336 speclen = len(spec)
2336 fullpaths = opts['full']
2337 fullpaths = opts['full']
2337 files, dirs = set(), set()
2338 files, dirs = set(), set()
2338 adddir, addfile = dirs.add, files.add
2339 adddir, addfile = dirs.add, files.add
2339 for f, st in dirstate.iteritems():
2340 for f, st in dirstate.iteritems():
2340 if f.startswith(spec) and st[0] in acceptable:
2341 if f.startswith(spec) and st[0] in acceptable:
2341 if fixpaths:
2342 if fixpaths:
2342 f = f.replace('/', os.sep)
2343 f = f.replace('/', os.sep)
2343 if fullpaths:
2344 if fullpaths:
2344 addfile(f)
2345 addfile(f)
2345 continue
2346 continue
2346 s = f.find(os.sep, speclen)
2347 s = f.find(os.sep, speclen)
2347 if s >= 0:
2348 if s >= 0:
2348 adddir(f[:s])
2349 adddir(f[:s])
2349 else:
2350 else:
2350 addfile(f)
2351 addfile(f)
2351 return files, dirs
2352 return files, dirs
2352
2353
2353 acceptable = ''
2354 acceptable = ''
2354 if opts['normal']:
2355 if opts['normal']:
2355 acceptable += 'nm'
2356 acceptable += 'nm'
2356 if opts['added']:
2357 if opts['added']:
2357 acceptable += 'a'
2358 acceptable += 'a'
2358 if opts['removed']:
2359 if opts['removed']:
2359 acceptable += 'r'
2360 acceptable += 'r'
2360 cwd = repo.getcwd()
2361 cwd = repo.getcwd()
2361 if not specs:
2362 if not specs:
2362 specs = ['.']
2363 specs = ['.']
2363
2364
2364 files, dirs = set(), set()
2365 files, dirs = set(), set()
2365 for spec in specs:
2366 for spec in specs:
2366 f, d = complete(spec, acceptable or 'nmar')
2367 f, d = complete(spec, acceptable or 'nmar')
2367 files.update(f)
2368 files.update(f)
2368 dirs.update(d)
2369 dirs.update(d)
2369 files.update(dirs)
2370 files.update(dirs)
2370 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2371 ui.write('\n'.join(repo.pathto(p, cwd) for p in sorted(files)))
2371 ui.write('\n')
2372 ui.write('\n')
2372
2373
2373 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2374 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
2374 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2375 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
2375 '''access the pushkey key/value protocol
2376 '''access the pushkey key/value protocol
2376
2377
2377 With two args, list the keys in the given namespace.
2378 With two args, list the keys in the given namespace.
2378
2379
2379 With five args, set a key to new if it currently is set to old.
2380 With five args, set a key to new if it currently is set to old.
2380 Reports success or failure.
2381 Reports success or failure.
2381 '''
2382 '''
2382
2383
2383 target = hg.peer(ui, {}, repopath)
2384 target = hg.peer(ui, {}, repopath)
2384 if keyinfo:
2385 if keyinfo:
2385 key, old, new = keyinfo
2386 key, old, new = keyinfo
2386 r = target.pushkey(namespace, key, old, new)
2387 r = target.pushkey(namespace, key, old, new)
2387 ui.status(str(r) + '\n')
2388 ui.status(str(r) + '\n')
2388 return not r
2389 return not r
2389 else:
2390 else:
2390 for k, v in sorted(target.listkeys(namespace).iteritems()):
2391 for k, v in sorted(target.listkeys(namespace).iteritems()):
2391 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2392 ui.write("%s\t%s\n" % (k.encode('string-escape'),
2392 v.encode('string-escape')))
2393 v.encode('string-escape')))
2393
2394
2394 @command('debugpvec', [], _('A B'))
2395 @command('debugpvec', [], _('A B'))
2395 def debugpvec(ui, repo, a, b=None):
2396 def debugpvec(ui, repo, a, b=None):
2396 ca = scmutil.revsingle(repo, a)
2397 ca = scmutil.revsingle(repo, a)
2397 cb = scmutil.revsingle(repo, b)
2398 cb = scmutil.revsingle(repo, b)
2398 pa = pvec.ctxpvec(ca)
2399 pa = pvec.ctxpvec(ca)
2399 pb = pvec.ctxpvec(cb)
2400 pb = pvec.ctxpvec(cb)
2400 if pa == pb:
2401 if pa == pb:
2401 rel = "="
2402 rel = "="
2402 elif pa > pb:
2403 elif pa > pb:
2403 rel = ">"
2404 rel = ">"
2404 elif pa < pb:
2405 elif pa < pb:
2405 rel = "<"
2406 rel = "<"
2406 elif pa | pb:
2407 elif pa | pb:
2407 rel = "|"
2408 rel = "|"
2408 ui.write(_("a: %s\n") % pa)
2409 ui.write(_("a: %s\n") % pa)
2409 ui.write(_("b: %s\n") % pb)
2410 ui.write(_("b: %s\n") % pb)
2410 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2411 ui.write(_("depth(a): %d depth(b): %d\n") % (pa._depth, pb._depth))
2411 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2412 ui.write(_("delta: %d hdist: %d distance: %d relation: %s\n") %
2412 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2413 (abs(pa._depth - pb._depth), pvec._hamming(pa._vec, pb._vec),
2413 pa.distance(pb), rel))
2414 pa.distance(pb), rel))
2414
2415
2415 @command('debugrebuilddirstate|debugrebuildstate',
2416 @command('debugrebuilddirstate|debugrebuildstate',
2416 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2417 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
2417 _('[-r REV]'))
2418 _('[-r REV]'))
2418 def debugrebuilddirstate(ui, repo, rev):
2419 def debugrebuilddirstate(ui, repo, rev):
2419 """rebuild the dirstate as it would look like for the given revision
2420 """rebuild the dirstate as it would look like for the given revision
2420
2421
2421 If no revision is specified the first current parent will be used.
2422 If no revision is specified the first current parent will be used.
2422
2423
2423 The dirstate will be set to the files of the given revision.
2424 The dirstate will be set to the files of the given revision.
2424 The actual working directory content or existing dirstate
2425 The actual working directory content or existing dirstate
2425 information such as adds or removes is not considered.
2426 information such as adds or removes is not considered.
2426
2427
2427 One use of this command is to make the next :hg:`status` invocation
2428 One use of this command is to make the next :hg:`status` invocation
2428 check the actual file content.
2429 check the actual file content.
2429 """
2430 """
2430 ctx = scmutil.revsingle(repo, rev)
2431 ctx = scmutil.revsingle(repo, rev)
2431 wlock = repo.wlock()
2432 wlock = repo.wlock()
2432 try:
2433 try:
2433 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2434 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2434 finally:
2435 finally:
2435 wlock.release()
2436 wlock.release()
2436
2437
2437 @command('debugrename',
2438 @command('debugrename',
2438 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2439 [('r', 'rev', '', _('revision to debug'), _('REV'))],
2439 _('[-r REV] FILE'))
2440 _('[-r REV] FILE'))
2440 def debugrename(ui, repo, file1, *pats, **opts):
2441 def debugrename(ui, repo, file1, *pats, **opts):
2441 """dump rename information"""
2442 """dump rename information"""
2442
2443
2443 ctx = scmutil.revsingle(repo, opts.get('rev'))
2444 ctx = scmutil.revsingle(repo, opts.get('rev'))
2444 m = scmutil.match(ctx, (file1,) + pats, opts)
2445 m = scmutil.match(ctx, (file1,) + pats, opts)
2445 for abs in ctx.walk(m):
2446 for abs in ctx.walk(m):
2446 fctx = ctx[abs]
2447 fctx = ctx[abs]
2447 o = fctx.filelog().renamed(fctx.filenode())
2448 o = fctx.filelog().renamed(fctx.filenode())
2448 rel = m.rel(abs)
2449 rel = m.rel(abs)
2449 if o:
2450 if o:
2450 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2451 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
2451 else:
2452 else:
2452 ui.write(_("%s not renamed\n") % rel)
2453 ui.write(_("%s not renamed\n") % rel)
2453
2454
2454 @command('debugrevlog',
2455 @command('debugrevlog',
2455 [('c', 'changelog', False, _('open changelog')),
2456 [('c', 'changelog', False, _('open changelog')),
2456 ('m', 'manifest', False, _('open manifest')),
2457 ('m', 'manifest', False, _('open manifest')),
2457 ('d', 'dump', False, _('dump index data'))],
2458 ('d', 'dump', False, _('dump index data'))],
2458 _('-c|-m|FILE'))
2459 _('-c|-m|FILE'))
2459 def debugrevlog(ui, repo, file_=None, **opts):
2460 def debugrevlog(ui, repo, file_=None, **opts):
2460 """show data and statistics about a revlog"""
2461 """show data and statistics about a revlog"""
2461 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2462 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
2462
2463
2463 if opts.get("dump"):
2464 if opts.get("dump"):
2464 numrevs = len(r)
2465 numrevs = len(r)
2465 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2466 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
2466 " rawsize totalsize compression heads\n")
2467 " rawsize totalsize compression heads\n")
2467 ts = 0
2468 ts = 0
2468 heads = set()
2469 heads = set()
2469 for rev in xrange(numrevs):
2470 for rev in xrange(numrevs):
2470 dbase = r.deltaparent(rev)
2471 dbase = r.deltaparent(rev)
2471 if dbase == -1:
2472 if dbase == -1:
2472 dbase = rev
2473 dbase = rev
2473 cbase = r.chainbase(rev)
2474 cbase = r.chainbase(rev)
2474 p1, p2 = r.parentrevs(rev)
2475 p1, p2 = r.parentrevs(rev)
2475 rs = r.rawsize(rev)
2476 rs = r.rawsize(rev)
2476 ts = ts + rs
2477 ts = ts + rs
2477 heads -= set(r.parentrevs(rev))
2478 heads -= set(r.parentrevs(rev))
2478 heads.add(rev)
2479 heads.add(rev)
2479 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d %11d %5d\n" %
2480 ui.write("%5d %5d %5d %5d %5d %10d %4d %4d %4d %7d %9d %11d %5d\n" %
2480 (rev, p1, p2, r.start(rev), r.end(rev),
2481 (rev, p1, p2, r.start(rev), r.end(rev),
2481 r.start(dbase), r.start(cbase),
2482 r.start(dbase), r.start(cbase),
2482 r.start(p1), r.start(p2),
2483 r.start(p1), r.start(p2),
2483 rs, ts, ts / r.end(rev), len(heads)))
2484 rs, ts, ts / r.end(rev), len(heads)))
2484 return 0
2485 return 0
2485
2486
2486 v = r.version
2487 v = r.version
2487 format = v & 0xFFFF
2488 format = v & 0xFFFF
2488 flags = []
2489 flags = []
2489 gdelta = False
2490 gdelta = False
2490 if v & revlog.REVLOGNGINLINEDATA:
2491 if v & revlog.REVLOGNGINLINEDATA:
2491 flags.append('inline')
2492 flags.append('inline')
2492 if v & revlog.REVLOGGENERALDELTA:
2493 if v & revlog.REVLOGGENERALDELTA:
2493 gdelta = True
2494 gdelta = True
2494 flags.append('generaldelta')
2495 flags.append('generaldelta')
2495 if not flags:
2496 if not flags:
2496 flags = ['(none)']
2497 flags = ['(none)']
2497
2498
2498 nummerges = 0
2499 nummerges = 0
2499 numfull = 0
2500 numfull = 0
2500 numprev = 0
2501 numprev = 0
2501 nump1 = 0
2502 nump1 = 0
2502 nump2 = 0
2503 nump2 = 0
2503 numother = 0
2504 numother = 0
2504 nump1prev = 0
2505 nump1prev = 0
2505 nump2prev = 0
2506 nump2prev = 0
2506 chainlengths = []
2507 chainlengths = []
2507
2508
2508 datasize = [None, 0, 0L]
2509 datasize = [None, 0, 0L]
2509 fullsize = [None, 0, 0L]
2510 fullsize = [None, 0, 0L]
2510 deltasize = [None, 0, 0L]
2511 deltasize = [None, 0, 0L]
2511
2512
2512 def addsize(size, l):
2513 def addsize(size, l):
2513 if l[0] is None or size < l[0]:
2514 if l[0] is None or size < l[0]:
2514 l[0] = size
2515 l[0] = size
2515 if size > l[1]:
2516 if size > l[1]:
2516 l[1] = size
2517 l[1] = size
2517 l[2] += size
2518 l[2] += size
2518
2519
2519 numrevs = len(r)
2520 numrevs = len(r)
2520 for rev in xrange(numrevs):
2521 for rev in xrange(numrevs):
2521 p1, p2 = r.parentrevs(rev)
2522 p1, p2 = r.parentrevs(rev)
2522 delta = r.deltaparent(rev)
2523 delta = r.deltaparent(rev)
2523 if format > 0:
2524 if format > 0:
2524 addsize(r.rawsize(rev), datasize)
2525 addsize(r.rawsize(rev), datasize)
2525 if p2 != nullrev:
2526 if p2 != nullrev:
2526 nummerges += 1
2527 nummerges += 1
2527 size = r.length(rev)
2528 size = r.length(rev)
2528 if delta == nullrev:
2529 if delta == nullrev:
2529 chainlengths.append(0)
2530 chainlengths.append(0)
2530 numfull += 1
2531 numfull += 1
2531 addsize(size, fullsize)
2532 addsize(size, fullsize)
2532 else:
2533 else:
2533 chainlengths.append(chainlengths[delta] + 1)
2534 chainlengths.append(chainlengths[delta] + 1)
2534 addsize(size, deltasize)
2535 addsize(size, deltasize)
2535 if delta == rev - 1:
2536 if delta == rev - 1:
2536 numprev += 1
2537 numprev += 1
2537 if delta == p1:
2538 if delta == p1:
2538 nump1prev += 1
2539 nump1prev += 1
2539 elif delta == p2:
2540 elif delta == p2:
2540 nump2prev += 1
2541 nump2prev += 1
2541 elif delta == p1:
2542 elif delta == p1:
2542 nump1 += 1
2543 nump1 += 1
2543 elif delta == p2:
2544 elif delta == p2:
2544 nump2 += 1
2545 nump2 += 1
2545 elif delta != nullrev:
2546 elif delta != nullrev:
2546 numother += 1
2547 numother += 1
2547
2548
2548 # Adjust size min value for empty cases
2549 # Adjust size min value for empty cases
2549 for size in (datasize, fullsize, deltasize):
2550 for size in (datasize, fullsize, deltasize):
2550 if size[0] is None:
2551 if size[0] is None:
2551 size[0] = 0
2552 size[0] = 0
2552
2553
2553 numdeltas = numrevs - numfull
2554 numdeltas = numrevs - numfull
2554 numoprev = numprev - nump1prev - nump2prev
2555 numoprev = numprev - nump1prev - nump2prev
2555 totalrawsize = datasize[2]
2556 totalrawsize = datasize[2]
2556 datasize[2] /= numrevs
2557 datasize[2] /= numrevs
2557 fulltotal = fullsize[2]
2558 fulltotal = fullsize[2]
2558 fullsize[2] /= numfull
2559 fullsize[2] /= numfull
2559 deltatotal = deltasize[2]
2560 deltatotal = deltasize[2]
2560 if numrevs - numfull > 0:
2561 if numrevs - numfull > 0:
2561 deltasize[2] /= numrevs - numfull
2562 deltasize[2] /= numrevs - numfull
2562 totalsize = fulltotal + deltatotal
2563 totalsize = fulltotal + deltatotal
2563 avgchainlen = sum(chainlengths) / numrevs
2564 avgchainlen = sum(chainlengths) / numrevs
2564 compratio = totalrawsize / totalsize
2565 compratio = totalrawsize / totalsize
2565
2566
2566 basedfmtstr = '%%%dd\n'
2567 basedfmtstr = '%%%dd\n'
2567 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2568 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
2568
2569
2569 def dfmtstr(max):
2570 def dfmtstr(max):
2570 return basedfmtstr % len(str(max))
2571 return basedfmtstr % len(str(max))
2571 def pcfmtstr(max, padding=0):
2572 def pcfmtstr(max, padding=0):
2572 return basepcfmtstr % (len(str(max)), ' ' * padding)
2573 return basepcfmtstr % (len(str(max)), ' ' * padding)
2573
2574
2574 def pcfmt(value, total):
2575 def pcfmt(value, total):
2575 return (value, 100 * float(value) / total)
2576 return (value, 100 * float(value) / total)
2576
2577
2577 ui.write(('format : %d\n') % format)
2578 ui.write(('format : %d\n') % format)
2578 ui.write(('flags : %s\n') % ', '.join(flags))
2579 ui.write(('flags : %s\n') % ', '.join(flags))
2579
2580
2580 ui.write('\n')
2581 ui.write('\n')
2581 fmt = pcfmtstr(totalsize)
2582 fmt = pcfmtstr(totalsize)
2582 fmt2 = dfmtstr(totalsize)
2583 fmt2 = dfmtstr(totalsize)
2583 ui.write(('revisions : ') + fmt2 % numrevs)
2584 ui.write(('revisions : ') + fmt2 % numrevs)
2584 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2585 ui.write((' merges : ') + fmt % pcfmt(nummerges, numrevs))
2585 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2586 ui.write((' normal : ') + fmt % pcfmt(numrevs - nummerges, numrevs))
2586 ui.write(('revisions : ') + fmt2 % numrevs)
2587 ui.write(('revisions : ') + fmt2 % numrevs)
2587 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2588 ui.write((' full : ') + fmt % pcfmt(numfull, numrevs))
2588 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2589 ui.write((' deltas : ') + fmt % pcfmt(numdeltas, numrevs))
2589 ui.write(('revision size : ') + fmt2 % totalsize)
2590 ui.write(('revision size : ') + fmt2 % totalsize)
2590 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2591 ui.write((' full : ') + fmt % pcfmt(fulltotal, totalsize))
2591 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2592 ui.write((' deltas : ') + fmt % pcfmt(deltatotal, totalsize))
2592
2593
2593 ui.write('\n')
2594 ui.write('\n')
2594 fmt = dfmtstr(max(avgchainlen, compratio))
2595 fmt = dfmtstr(max(avgchainlen, compratio))
2595 ui.write(('avg chain length : ') + fmt % avgchainlen)
2596 ui.write(('avg chain length : ') + fmt % avgchainlen)
2596 ui.write(('compression ratio : ') + fmt % compratio)
2597 ui.write(('compression ratio : ') + fmt % compratio)
2597
2598
2598 if format > 0:
2599 if format > 0:
2599 ui.write('\n')
2600 ui.write('\n')
2600 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2601 ui.write(('uncompressed data size (min/max/avg) : %d / %d / %d\n')
2601 % tuple(datasize))
2602 % tuple(datasize))
2602 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2603 ui.write(('full revision size (min/max/avg) : %d / %d / %d\n')
2603 % tuple(fullsize))
2604 % tuple(fullsize))
2604 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2605 ui.write(('delta size (min/max/avg) : %d / %d / %d\n')
2605 % tuple(deltasize))
2606 % tuple(deltasize))
2606
2607
2607 if numdeltas > 0:
2608 if numdeltas > 0:
2608 ui.write('\n')
2609 ui.write('\n')
2609 fmt = pcfmtstr(numdeltas)
2610 fmt = pcfmtstr(numdeltas)
2610 fmt2 = pcfmtstr(numdeltas, 4)
2611 fmt2 = pcfmtstr(numdeltas, 4)
2611 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2612 ui.write(('deltas against prev : ') + fmt % pcfmt(numprev, numdeltas))
2612 if numprev > 0:
2613 if numprev > 0:
2613 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2614 ui.write((' where prev = p1 : ') + fmt2 % pcfmt(nump1prev,
2614 numprev))
2615 numprev))
2615 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2616 ui.write((' where prev = p2 : ') + fmt2 % pcfmt(nump2prev,
2616 numprev))
2617 numprev))
2617 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2618 ui.write((' other : ') + fmt2 % pcfmt(numoprev,
2618 numprev))
2619 numprev))
2619 if gdelta:
2620 if gdelta:
2620 ui.write(('deltas against p1 : ')
2621 ui.write(('deltas against p1 : ')
2621 + fmt % pcfmt(nump1, numdeltas))
2622 + fmt % pcfmt(nump1, numdeltas))
2622 ui.write(('deltas against p2 : ')
2623 ui.write(('deltas against p2 : ')
2623 + fmt % pcfmt(nump2, numdeltas))
2624 + fmt % pcfmt(nump2, numdeltas))
2624 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2625 ui.write(('deltas against other : ') + fmt % pcfmt(numother,
2625 numdeltas))
2626 numdeltas))
2626
2627
2627 @command('debugrevspec',
2628 @command('debugrevspec',
2628 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2629 [('', 'optimize', None, _('print parsed tree after optimizing'))],
2629 ('REVSPEC'))
2630 ('REVSPEC'))
2630 def debugrevspec(ui, repo, expr, **opts):
2631 def debugrevspec(ui, repo, expr, **opts):
2631 """parse and apply a revision specification
2632 """parse and apply a revision specification
2632
2633
2633 Use --verbose to print the parsed tree before and after aliases
2634 Use --verbose to print the parsed tree before and after aliases
2634 expansion.
2635 expansion.
2635 """
2636 """
2636 if ui.verbose:
2637 if ui.verbose:
2637 tree = revset.parse(expr)[0]
2638 tree = revset.parse(expr)[0]
2638 ui.note(revset.prettyformat(tree), "\n")
2639 ui.note(revset.prettyformat(tree), "\n")
2639 newtree = revset.findaliases(ui, tree)
2640 newtree = revset.findaliases(ui, tree)
2640 if newtree != tree:
2641 if newtree != tree:
2641 ui.note(revset.prettyformat(newtree), "\n")
2642 ui.note(revset.prettyformat(newtree), "\n")
2642 if opts["optimize"]:
2643 if opts["optimize"]:
2643 weight, optimizedtree = revset.optimize(newtree, True)
2644 weight, optimizedtree = revset.optimize(newtree, True)
2644 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2645 ui.note("* optimized:\n", revset.prettyformat(optimizedtree), "\n")
2645 func = revset.match(ui, expr)
2646 func = revset.match(ui, expr)
2646 for c in func(repo, revset.spanset(repo)):
2647 for c in func(repo, revset.spanset(repo)):
2647 ui.write("%s\n" % c)
2648 ui.write("%s\n" % c)
2648
2649
2649 @command('debugsetparents', [], _('REV1 [REV2]'))
2650 @command('debugsetparents', [], _('REV1 [REV2]'))
2650 def debugsetparents(ui, repo, rev1, rev2=None):
2651 def debugsetparents(ui, repo, rev1, rev2=None):
2651 """manually set the parents of the current working directory
2652 """manually set the parents of the current working directory
2652
2653
2653 This is useful for writing repository conversion tools, but should
2654 This is useful for writing repository conversion tools, but should
2654 be used with care.
2655 be used with care.
2655
2656
2656 Returns 0 on success.
2657 Returns 0 on success.
2657 """
2658 """
2658
2659
2659 r1 = scmutil.revsingle(repo, rev1).node()
2660 r1 = scmutil.revsingle(repo, rev1).node()
2660 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2661 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2661
2662
2662 wlock = repo.wlock()
2663 wlock = repo.wlock()
2663 try:
2664 try:
2664 repo.setparents(r1, r2)
2665 repo.setparents(r1, r2)
2665 finally:
2666 finally:
2666 wlock.release()
2667 wlock.release()
2667
2668
2668 @command('debugdirstate|debugstate',
2669 @command('debugdirstate|debugstate',
2669 [('', 'nodates', None, _('do not display the saved mtime')),
2670 [('', 'nodates', None, _('do not display the saved mtime')),
2670 ('', 'datesort', None, _('sort by saved mtime'))],
2671 ('', 'datesort', None, _('sort by saved mtime'))],
2671 _('[OPTION]...'))
2672 _('[OPTION]...'))
2672 def debugstate(ui, repo, nodates=None, datesort=None):
2673 def debugstate(ui, repo, nodates=None, datesort=None):
2673 """show the contents of the current dirstate"""
2674 """show the contents of the current dirstate"""
2674 timestr = ""
2675 timestr = ""
2675 showdate = not nodates
2676 showdate = not nodates
2676 if datesort:
2677 if datesort:
2677 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2678 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2678 else:
2679 else:
2679 keyfunc = None # sort by filename
2680 keyfunc = None # sort by filename
2680 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2681 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2681 if showdate:
2682 if showdate:
2682 if ent[3] == -1:
2683 if ent[3] == -1:
2683 # Pad or slice to locale representation
2684 # Pad or slice to locale representation
2684 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2685 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2685 time.localtime(0)))
2686 time.localtime(0)))
2686 timestr = 'unset'
2687 timestr = 'unset'
2687 timestr = (timestr[:locale_len] +
2688 timestr = (timestr[:locale_len] +
2688 ' ' * (locale_len - len(timestr)))
2689 ' ' * (locale_len - len(timestr)))
2689 else:
2690 else:
2690 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2691 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2691 time.localtime(ent[3]))
2692 time.localtime(ent[3]))
2692 if ent[1] & 020000:
2693 if ent[1] & 020000:
2693 mode = 'lnk'
2694 mode = 'lnk'
2694 else:
2695 else:
2695 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2696 mode = '%3o' % (ent[1] & 0777 & ~util.umask)
2696 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2697 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2697 for f in repo.dirstate.copies():
2698 for f in repo.dirstate.copies():
2698 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2699 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2699
2700
2700 @command('debugsub',
2701 @command('debugsub',
2701 [('r', 'rev', '',
2702 [('r', 'rev', '',
2702 _('revision to check'), _('REV'))],
2703 _('revision to check'), _('REV'))],
2703 _('[-r REV] [REV]'))
2704 _('[-r REV] [REV]'))
2704 def debugsub(ui, repo, rev=None):
2705 def debugsub(ui, repo, rev=None):
2705 ctx = scmutil.revsingle(repo, rev, None)
2706 ctx = scmutil.revsingle(repo, rev, None)
2706 for k, v in sorted(ctx.substate.items()):
2707 for k, v in sorted(ctx.substate.items()):
2707 ui.write(('path %s\n') % k)
2708 ui.write(('path %s\n') % k)
2708 ui.write((' source %s\n') % v[0])
2709 ui.write((' source %s\n') % v[0])
2709 ui.write((' revision %s\n') % v[1])
2710 ui.write((' revision %s\n') % v[1])
2710
2711
2711 @command('debugsuccessorssets',
2712 @command('debugsuccessorssets',
2712 [],
2713 [],
2713 _('[REV]'))
2714 _('[REV]'))
2714 def debugsuccessorssets(ui, repo, *revs):
2715 def debugsuccessorssets(ui, repo, *revs):
2715 """show set of successors for revision
2716 """show set of successors for revision
2716
2717
2717 A successors set of changeset A is a consistent group of revisions that
2718 A successors set of changeset A is a consistent group of revisions that
2718 succeed A. It contains non-obsolete changesets only.
2719 succeed A. It contains non-obsolete changesets only.
2719
2720
2720 In most cases a changeset A has a single successors set containing a single
2721 In most cases a changeset A has a single successors set containing a single
2721 successor (changeset A replaced by A').
2722 successor (changeset A replaced by A').
2722
2723
2723 A changeset that is made obsolete with no successors are called "pruned".
2724 A changeset that is made obsolete with no successors are called "pruned".
2724 Such changesets have no successors sets at all.
2725 Such changesets have no successors sets at all.
2725
2726
2726 A changeset that has been "split" will have a successors set containing
2727 A changeset that has been "split" will have a successors set containing
2727 more than one successor.
2728 more than one successor.
2728
2729
2729 A changeset that has been rewritten in multiple different ways is called
2730 A changeset that has been rewritten in multiple different ways is called
2730 "divergent". Such changesets have multiple successor sets (each of which
2731 "divergent". Such changesets have multiple successor sets (each of which
2731 may also be split, i.e. have multiple successors).
2732 may also be split, i.e. have multiple successors).
2732
2733
2733 Results are displayed as follows::
2734 Results are displayed as follows::
2734
2735
2735 <rev1>
2736 <rev1>
2736 <successors-1A>
2737 <successors-1A>
2737 <rev2>
2738 <rev2>
2738 <successors-2A>
2739 <successors-2A>
2739 <successors-2B1> <successors-2B2> <successors-2B3>
2740 <successors-2B1> <successors-2B2> <successors-2B3>
2740
2741
2741 Here rev2 has two possible (i.e. divergent) successors sets. The first
2742 Here rev2 has two possible (i.e. divergent) successors sets. The first
2742 holds one element, whereas the second holds three (i.e. the changeset has
2743 holds one element, whereas the second holds three (i.e. the changeset has
2743 been split).
2744 been split).
2744 """
2745 """
2745 # passed to successorssets caching computation from one call to another
2746 # passed to successorssets caching computation from one call to another
2746 cache = {}
2747 cache = {}
2747 ctx2str = str
2748 ctx2str = str
2748 node2str = short
2749 node2str = short
2749 if ui.debug():
2750 if ui.debug():
2750 def ctx2str(ctx):
2751 def ctx2str(ctx):
2751 return ctx.hex()
2752 return ctx.hex()
2752 node2str = hex
2753 node2str = hex
2753 for rev in scmutil.revrange(repo, revs):
2754 for rev in scmutil.revrange(repo, revs):
2754 ctx = repo[rev]
2755 ctx = repo[rev]
2755 ui.write('%s\n'% ctx2str(ctx))
2756 ui.write('%s\n'% ctx2str(ctx))
2756 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2757 for succsset in obsolete.successorssets(repo, ctx.node(), cache):
2757 if succsset:
2758 if succsset:
2758 ui.write(' ')
2759 ui.write(' ')
2759 ui.write(node2str(succsset[0]))
2760 ui.write(node2str(succsset[0]))
2760 for node in succsset[1:]:
2761 for node in succsset[1:]:
2761 ui.write(' ')
2762 ui.write(' ')
2762 ui.write(node2str(node))
2763 ui.write(node2str(node))
2763 ui.write('\n')
2764 ui.write('\n')
2764
2765
2765 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2766 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2766 def debugwalk(ui, repo, *pats, **opts):
2767 def debugwalk(ui, repo, *pats, **opts):
2767 """show how files match on given patterns"""
2768 """show how files match on given patterns"""
2768 m = scmutil.match(repo[None], pats, opts)
2769 m = scmutil.match(repo[None], pats, opts)
2769 items = list(repo.walk(m))
2770 items = list(repo.walk(m))
2770 if not items:
2771 if not items:
2771 return
2772 return
2772 f = lambda fn: fn
2773 f = lambda fn: fn
2773 if ui.configbool('ui', 'slash') and os.sep != '/':
2774 if ui.configbool('ui', 'slash') and os.sep != '/':
2774 f = lambda fn: util.normpath(fn)
2775 f = lambda fn: util.normpath(fn)
2775 fmt = 'f %%-%ds %%-%ds %%s' % (
2776 fmt = 'f %%-%ds %%-%ds %%s' % (
2776 max([len(abs) for abs in items]),
2777 max([len(abs) for abs in items]),
2777 max([len(m.rel(abs)) for abs in items]))
2778 max([len(m.rel(abs)) for abs in items]))
2778 for abs in items:
2779 for abs in items:
2779 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2780 line = fmt % (abs, f(m.rel(abs)), m.exact(abs) and 'exact' or '')
2780 ui.write("%s\n" % line.rstrip())
2781 ui.write("%s\n" % line.rstrip())
2781
2782
2782 @command('debugwireargs',
2783 @command('debugwireargs',
2783 [('', 'three', '', 'three'),
2784 [('', 'three', '', 'three'),
2784 ('', 'four', '', 'four'),
2785 ('', 'four', '', 'four'),
2785 ('', 'five', '', 'five'),
2786 ('', 'five', '', 'five'),
2786 ] + remoteopts,
2787 ] + remoteopts,
2787 _('REPO [OPTIONS]... [ONE [TWO]]'))
2788 _('REPO [OPTIONS]... [ONE [TWO]]'))
2788 def debugwireargs(ui, repopath, *vals, **opts):
2789 def debugwireargs(ui, repopath, *vals, **opts):
2789 repo = hg.peer(ui, opts, repopath)
2790 repo = hg.peer(ui, opts, repopath)
2790 for opt in remoteopts:
2791 for opt in remoteopts:
2791 del opts[opt[1]]
2792 del opts[opt[1]]
2792 args = {}
2793 args = {}
2793 for k, v in opts.iteritems():
2794 for k, v in opts.iteritems():
2794 if v:
2795 if v:
2795 args[k] = v
2796 args[k] = v
2796 # run twice to check that we don't mess up the stream for the next command
2797 # run twice to check that we don't mess up the stream for the next command
2797 res1 = repo.debugwireargs(*vals, **args)
2798 res1 = repo.debugwireargs(*vals, **args)
2798 res2 = repo.debugwireargs(*vals, **args)
2799 res2 = repo.debugwireargs(*vals, **args)
2799 ui.write("%s\n" % res1)
2800 ui.write("%s\n" % res1)
2800 if res1 != res2:
2801 if res1 != res2:
2801 ui.warn("%s\n" % res2)
2802 ui.warn("%s\n" % res2)
2802
2803
2803 @command('^diff',
2804 @command('^diff',
2804 [('r', 'rev', [], _('revision'), _('REV')),
2805 [('r', 'rev', [], _('revision'), _('REV')),
2805 ('c', 'change', '', _('change made by revision'), _('REV'))
2806 ('c', 'change', '', _('change made by revision'), _('REV'))
2806 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2807 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2807 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2808 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2808 def diff(ui, repo, *pats, **opts):
2809 def diff(ui, repo, *pats, **opts):
2809 """diff repository (or selected files)
2810 """diff repository (or selected files)
2810
2811
2811 Show differences between revisions for the specified files.
2812 Show differences between revisions for the specified files.
2812
2813
2813 Differences between files are shown using the unified diff format.
2814 Differences between files are shown using the unified diff format.
2814
2815
2815 .. note::
2816 .. note::
2816
2817
2817 diff may generate unexpected results for merges, as it will
2818 diff may generate unexpected results for merges, as it will
2818 default to comparing against the working directory's first
2819 default to comparing against the working directory's first
2819 parent changeset if no revisions are specified.
2820 parent changeset if no revisions are specified.
2820
2821
2821 When two revision arguments are given, then changes are shown
2822 When two revision arguments are given, then changes are shown
2822 between those revisions. If only one revision is specified then
2823 between those revisions. If only one revision is specified then
2823 that revision is compared to the working directory, and, when no
2824 that revision is compared to the working directory, and, when no
2824 revisions are specified, the working directory files are compared
2825 revisions are specified, the working directory files are compared
2825 to its parent.
2826 to its parent.
2826
2827
2827 Alternatively you can specify -c/--change with a revision to see
2828 Alternatively you can specify -c/--change with a revision to see
2828 the changes in that changeset relative to its first parent.
2829 the changes in that changeset relative to its first parent.
2829
2830
2830 Without the -a/--text option, diff will avoid generating diffs of
2831 Without the -a/--text option, diff will avoid generating diffs of
2831 files it detects as binary. With -a, diff will generate a diff
2832 files it detects as binary. With -a, diff will generate a diff
2832 anyway, probably with undesirable results.
2833 anyway, probably with undesirable results.
2833
2834
2834 Use the -g/--git option to generate diffs in the git extended diff
2835 Use the -g/--git option to generate diffs in the git extended diff
2835 format. For more information, read :hg:`help diffs`.
2836 format. For more information, read :hg:`help diffs`.
2836
2837
2837 .. container:: verbose
2838 .. container:: verbose
2838
2839
2839 Examples:
2840 Examples:
2840
2841
2841 - compare a file in the current working directory to its parent::
2842 - compare a file in the current working directory to its parent::
2842
2843
2843 hg diff foo.c
2844 hg diff foo.c
2844
2845
2845 - compare two historical versions of a directory, with rename info::
2846 - compare two historical versions of a directory, with rename info::
2846
2847
2847 hg diff --git -r 1.0:1.2 lib/
2848 hg diff --git -r 1.0:1.2 lib/
2848
2849
2849 - get change stats relative to the last change on some date::
2850 - get change stats relative to the last change on some date::
2850
2851
2851 hg diff --stat -r "date('may 2')"
2852 hg diff --stat -r "date('may 2')"
2852
2853
2853 - diff all newly-added files that contain a keyword::
2854 - diff all newly-added files that contain a keyword::
2854
2855
2855 hg diff "set:added() and grep(GNU)"
2856 hg diff "set:added() and grep(GNU)"
2856
2857
2857 - compare a revision and its parents::
2858 - compare a revision and its parents::
2858
2859
2859 hg diff -c 9353 # compare against first parent
2860 hg diff -c 9353 # compare against first parent
2860 hg diff -r 9353^:9353 # same using revset syntax
2861 hg diff -r 9353^:9353 # same using revset syntax
2861 hg diff -r 9353^2:9353 # compare against the second parent
2862 hg diff -r 9353^2:9353 # compare against the second parent
2862
2863
2863 Returns 0 on success.
2864 Returns 0 on success.
2864 """
2865 """
2865
2866
2866 revs = opts.get('rev')
2867 revs = opts.get('rev')
2867 change = opts.get('change')
2868 change = opts.get('change')
2868 stat = opts.get('stat')
2869 stat = opts.get('stat')
2869 reverse = opts.get('reverse')
2870 reverse = opts.get('reverse')
2870
2871
2871 if revs and change:
2872 if revs and change:
2872 msg = _('cannot specify --rev and --change at the same time')
2873 msg = _('cannot specify --rev and --change at the same time')
2873 raise util.Abort(msg)
2874 raise util.Abort(msg)
2874 elif change:
2875 elif change:
2875 node2 = scmutil.revsingle(repo, change, None).node()
2876 node2 = scmutil.revsingle(repo, change, None).node()
2876 node1 = repo[node2].p1().node()
2877 node1 = repo[node2].p1().node()
2877 else:
2878 else:
2878 node1, node2 = scmutil.revpair(repo, revs)
2879 node1, node2 = scmutil.revpair(repo, revs)
2879
2880
2880 if reverse:
2881 if reverse:
2881 node1, node2 = node2, node1
2882 node1, node2 = node2, node1
2882
2883
2883 diffopts = patch.diffopts(ui, opts)
2884 diffopts = patch.diffopts(ui, opts)
2884 m = scmutil.match(repo[node2], pats, opts)
2885 m = scmutil.match(repo[node2], pats, opts)
2885 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2886 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2886 listsubrepos=opts.get('subrepos'))
2887 listsubrepos=opts.get('subrepos'))
2887
2888
2888 @command('^export',
2889 @command('^export',
2889 [('o', 'output', '',
2890 [('o', 'output', '',
2890 _('print output to file with formatted name'), _('FORMAT')),
2891 _('print output to file with formatted name'), _('FORMAT')),
2891 ('', 'switch-parent', None, _('diff against the second parent')),
2892 ('', 'switch-parent', None, _('diff against the second parent')),
2892 ('r', 'rev', [], _('revisions to export'), _('REV')),
2893 ('r', 'rev', [], _('revisions to export'), _('REV')),
2893 ] + diffopts,
2894 ] + diffopts,
2894 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
2895 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'))
2895 def export(ui, repo, *changesets, **opts):
2896 def export(ui, repo, *changesets, **opts):
2896 """dump the header and diffs for one or more changesets
2897 """dump the header and diffs for one or more changesets
2897
2898
2898 Print the changeset header and diffs for one or more revisions.
2899 Print the changeset header and diffs for one or more revisions.
2899 If no revision is given, the parent of the working directory is used.
2900 If no revision is given, the parent of the working directory is used.
2900
2901
2901 The information shown in the changeset header is: author, date,
2902 The information shown in the changeset header is: author, date,
2902 branch name (if non-default), changeset hash, parent(s) and commit
2903 branch name (if non-default), changeset hash, parent(s) and commit
2903 comment.
2904 comment.
2904
2905
2905 .. note::
2906 .. note::
2906
2907
2907 export may generate unexpected diff output for merge
2908 export may generate unexpected diff output for merge
2908 changesets, as it will compare the merge changeset against its
2909 changesets, as it will compare the merge changeset against its
2909 first parent only.
2910 first parent only.
2910
2911
2911 Output may be to a file, in which case the name of the file is
2912 Output may be to a file, in which case the name of the file is
2912 given using a format string. The formatting rules are as follows:
2913 given using a format string. The formatting rules are as follows:
2913
2914
2914 :``%%``: literal "%" character
2915 :``%%``: literal "%" character
2915 :``%H``: changeset hash (40 hexadecimal digits)
2916 :``%H``: changeset hash (40 hexadecimal digits)
2916 :``%N``: number of patches being generated
2917 :``%N``: number of patches being generated
2917 :``%R``: changeset revision number
2918 :``%R``: changeset revision number
2918 :``%b``: basename of the exporting repository
2919 :``%b``: basename of the exporting repository
2919 :``%h``: short-form changeset hash (12 hexadecimal digits)
2920 :``%h``: short-form changeset hash (12 hexadecimal digits)
2920 :``%m``: first line of the commit message (only alphanumeric characters)
2921 :``%m``: first line of the commit message (only alphanumeric characters)
2921 :``%n``: zero-padded sequence number, starting at 1
2922 :``%n``: zero-padded sequence number, starting at 1
2922 :``%r``: zero-padded changeset revision number
2923 :``%r``: zero-padded changeset revision number
2923
2924
2924 Without the -a/--text option, export will avoid generating diffs
2925 Without the -a/--text option, export will avoid generating diffs
2925 of files it detects as binary. With -a, export will generate a
2926 of files it detects as binary. With -a, export will generate a
2926 diff anyway, probably with undesirable results.
2927 diff anyway, probably with undesirable results.
2927
2928
2928 Use the -g/--git option to generate diffs in the git extended diff
2929 Use the -g/--git option to generate diffs in the git extended diff
2929 format. See :hg:`help diffs` for more information.
2930 format. See :hg:`help diffs` for more information.
2930
2931
2931 With the --switch-parent option, the diff will be against the
2932 With the --switch-parent option, the diff will be against the
2932 second parent. It can be useful to review a merge.
2933 second parent. It can be useful to review a merge.
2933
2934
2934 .. container:: verbose
2935 .. container:: verbose
2935
2936
2936 Examples:
2937 Examples:
2937
2938
2938 - use export and import to transplant a bugfix to the current
2939 - use export and import to transplant a bugfix to the current
2939 branch::
2940 branch::
2940
2941
2941 hg export -r 9353 | hg import -
2942 hg export -r 9353 | hg import -
2942
2943
2943 - export all the changesets between two revisions to a file with
2944 - export all the changesets between two revisions to a file with
2944 rename information::
2945 rename information::
2945
2946
2946 hg export --git -r 123:150 > changes.txt
2947 hg export --git -r 123:150 > changes.txt
2947
2948
2948 - split outgoing changes into a series of patches with
2949 - split outgoing changes into a series of patches with
2949 descriptive names::
2950 descriptive names::
2950
2951
2951 hg export -r "outgoing()" -o "%n-%m.patch"
2952 hg export -r "outgoing()" -o "%n-%m.patch"
2952
2953
2953 Returns 0 on success.
2954 Returns 0 on success.
2954 """
2955 """
2955 changesets += tuple(opts.get('rev', []))
2956 changesets += tuple(opts.get('rev', []))
2956 if not changesets:
2957 if not changesets:
2957 changesets = ['.']
2958 changesets = ['.']
2958 revs = scmutil.revrange(repo, changesets)
2959 revs = scmutil.revrange(repo, changesets)
2959 if not revs:
2960 if not revs:
2960 raise util.Abort(_("export requires at least one changeset"))
2961 raise util.Abort(_("export requires at least one changeset"))
2961 if len(revs) > 1:
2962 if len(revs) > 1:
2962 ui.note(_('exporting patches:\n'))
2963 ui.note(_('exporting patches:\n'))
2963 else:
2964 else:
2964 ui.note(_('exporting patch:\n'))
2965 ui.note(_('exporting patch:\n'))
2965 cmdutil.export(repo, revs, template=opts.get('output'),
2966 cmdutil.export(repo, revs, template=opts.get('output'),
2966 switch_parent=opts.get('switch_parent'),
2967 switch_parent=opts.get('switch_parent'),
2967 opts=patch.diffopts(ui, opts))
2968 opts=patch.diffopts(ui, opts))
2968
2969
2969 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2970 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2970 def forget(ui, repo, *pats, **opts):
2971 def forget(ui, repo, *pats, **opts):
2971 """forget the specified files on the next commit
2972 """forget the specified files on the next commit
2972
2973
2973 Mark the specified files so they will no longer be tracked
2974 Mark the specified files so they will no longer be tracked
2974 after the next commit.
2975 after the next commit.
2975
2976
2976 This only removes files from the current branch, not from the
2977 This only removes files from the current branch, not from the
2977 entire project history, and it does not delete them from the
2978 entire project history, and it does not delete them from the
2978 working directory.
2979 working directory.
2979
2980
2980 To undo a forget before the next commit, see :hg:`add`.
2981 To undo a forget before the next commit, see :hg:`add`.
2981
2982
2982 .. container:: verbose
2983 .. container:: verbose
2983
2984
2984 Examples:
2985 Examples:
2985
2986
2986 - forget newly-added binary files::
2987 - forget newly-added binary files::
2987
2988
2988 hg forget "set:added() and binary()"
2989 hg forget "set:added() and binary()"
2989
2990
2990 - forget files that would be excluded by .hgignore::
2991 - forget files that would be excluded by .hgignore::
2991
2992
2992 hg forget "set:hgignore()"
2993 hg forget "set:hgignore()"
2993
2994
2994 Returns 0 on success.
2995 Returns 0 on success.
2995 """
2996 """
2996
2997
2997 if not pats:
2998 if not pats:
2998 raise util.Abort(_('no files specified'))
2999 raise util.Abort(_('no files specified'))
2999
3000
3000 m = scmutil.match(repo[None], pats, opts)
3001 m = scmutil.match(repo[None], pats, opts)
3001 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3002 rejected = cmdutil.forget(ui, repo, m, prefix="", explicitonly=False)[0]
3002 return rejected and 1 or 0
3003 return rejected and 1 or 0
3003
3004
3004 @command(
3005 @command(
3005 'graft',
3006 'graft',
3006 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3007 [('r', 'rev', [], _('revisions to graft'), _('REV')),
3007 ('c', 'continue', False, _('resume interrupted graft')),
3008 ('c', 'continue', False, _('resume interrupted graft')),
3008 ('e', 'edit', False, _('invoke editor on commit messages')),
3009 ('e', 'edit', False, _('invoke editor on commit messages')),
3009 ('', 'log', None, _('append graft info to log message')),
3010 ('', 'log', None, _('append graft info to log message')),
3010 ('D', 'currentdate', False,
3011 ('D', 'currentdate', False,
3011 _('record the current date as commit date')),
3012 _('record the current date as commit date')),
3012 ('U', 'currentuser', False,
3013 ('U', 'currentuser', False,
3013 _('record the current user as committer'), _('DATE'))]
3014 _('record the current user as committer'), _('DATE'))]
3014 + commitopts2 + mergetoolopts + dryrunopts,
3015 + commitopts2 + mergetoolopts + dryrunopts,
3015 _('[OPTION]... [-r] REV...'))
3016 _('[OPTION]... [-r] REV...'))
3016 def graft(ui, repo, *revs, **opts):
3017 def graft(ui, repo, *revs, **opts):
3017 '''copy changes from other branches onto the current branch
3018 '''copy changes from other branches onto the current branch
3018
3019
3019 This command uses Mercurial's merge logic to copy individual
3020 This command uses Mercurial's merge logic to copy individual
3020 changes from other branches without merging branches in the
3021 changes from other branches without merging branches in the
3021 history graph. This is sometimes known as 'backporting' or
3022 history graph. This is sometimes known as 'backporting' or
3022 'cherry-picking'. By default, graft will copy user, date, and
3023 'cherry-picking'. By default, graft will copy user, date, and
3023 description from the source changesets.
3024 description from the source changesets.
3024
3025
3025 Changesets that are ancestors of the current revision, that have
3026 Changesets that are ancestors of the current revision, that have
3026 already been grafted, or that are merges will be skipped.
3027 already been grafted, or that are merges will be skipped.
3027
3028
3028 If --log is specified, log messages will have a comment appended
3029 If --log is specified, log messages will have a comment appended
3029 of the form::
3030 of the form::
3030
3031
3031 (grafted from CHANGESETHASH)
3032 (grafted from CHANGESETHASH)
3032
3033
3033 If a graft merge results in conflicts, the graft process is
3034 If a graft merge results in conflicts, the graft process is
3034 interrupted so that the current merge can be manually resolved.
3035 interrupted so that the current merge can be manually resolved.
3035 Once all conflicts are addressed, the graft process can be
3036 Once all conflicts are addressed, the graft process can be
3036 continued with the -c/--continue option.
3037 continued with the -c/--continue option.
3037
3038
3038 .. note::
3039 .. note::
3039
3040
3040 The -c/--continue option does not reapply earlier options.
3041 The -c/--continue option does not reapply earlier options.
3041
3042
3042 .. container:: verbose
3043 .. container:: verbose
3043
3044
3044 Examples:
3045 Examples:
3045
3046
3046 - copy a single change to the stable branch and edit its description::
3047 - copy a single change to the stable branch and edit its description::
3047
3048
3048 hg update stable
3049 hg update stable
3049 hg graft --edit 9393
3050 hg graft --edit 9393
3050
3051
3051 - graft a range of changesets with one exception, updating dates::
3052 - graft a range of changesets with one exception, updating dates::
3052
3053
3053 hg graft -D "2085::2093 and not 2091"
3054 hg graft -D "2085::2093 and not 2091"
3054
3055
3055 - continue a graft after resolving conflicts::
3056 - continue a graft after resolving conflicts::
3056
3057
3057 hg graft -c
3058 hg graft -c
3058
3059
3059 - show the source of a grafted changeset::
3060 - show the source of a grafted changeset::
3060
3061
3061 hg log --debug -r .
3062 hg log --debug -r .
3062
3063
3063 Returns 0 on successful completion.
3064 Returns 0 on successful completion.
3064 '''
3065 '''
3065
3066
3066 revs = list(revs)
3067 revs = list(revs)
3067 revs.extend(opts['rev'])
3068 revs.extend(opts['rev'])
3068
3069
3069 if not opts.get('user') and opts.get('currentuser'):
3070 if not opts.get('user') and opts.get('currentuser'):
3070 opts['user'] = ui.username()
3071 opts['user'] = ui.username()
3071 if not opts.get('date') and opts.get('currentdate'):
3072 if not opts.get('date') and opts.get('currentdate'):
3072 opts['date'] = "%d %d" % util.makedate()
3073 opts['date'] = "%d %d" % util.makedate()
3073
3074
3074 editor = cmdutil.getcommiteditor(**opts)
3075 editor = cmdutil.getcommiteditor(**opts)
3075
3076
3076 cont = False
3077 cont = False
3077 if opts['continue']:
3078 if opts['continue']:
3078 cont = True
3079 cont = True
3079 if revs:
3080 if revs:
3080 raise util.Abort(_("can't specify --continue and revisions"))
3081 raise util.Abort(_("can't specify --continue and revisions"))
3081 # read in unfinished revisions
3082 # read in unfinished revisions
3082 try:
3083 try:
3083 nodes = repo.opener.read('graftstate').splitlines()
3084 nodes = repo.opener.read('graftstate').splitlines()
3084 revs = [repo[node].rev() for node in nodes]
3085 revs = [repo[node].rev() for node in nodes]
3085 except IOError, inst:
3086 except IOError, inst:
3086 if inst.errno != errno.ENOENT:
3087 if inst.errno != errno.ENOENT:
3087 raise
3088 raise
3088 raise util.Abort(_("no graft state found, can't continue"))
3089 raise util.Abort(_("no graft state found, can't continue"))
3089 else:
3090 else:
3090 cmdutil.checkunfinished(repo)
3091 cmdutil.checkunfinished(repo)
3091 cmdutil.bailifchanged(repo)
3092 cmdutil.bailifchanged(repo)
3092 if not revs:
3093 if not revs:
3093 raise util.Abort(_('no revisions specified'))
3094 raise util.Abort(_('no revisions specified'))
3094 revs = scmutil.revrange(repo, revs)
3095 revs = scmutil.revrange(repo, revs)
3095
3096
3096 # check for merges
3097 # check for merges
3097 for rev in repo.revs('%ld and merge()', revs):
3098 for rev in repo.revs('%ld and merge()', revs):
3098 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3099 ui.warn(_('skipping ungraftable merge revision %s\n') % rev)
3099 revs.remove(rev)
3100 revs.remove(rev)
3100 if not revs:
3101 if not revs:
3101 return -1
3102 return -1
3102
3103
3103 # check for ancestors of dest branch
3104 # check for ancestors of dest branch
3104 crev = repo['.'].rev()
3105 crev = repo['.'].rev()
3105 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3106 ancestors = repo.changelog.ancestors([crev], inclusive=True)
3106 # Cannot use x.remove(y) on smart set, this has to be a list.
3107 # Cannot use x.remove(y) on smart set, this has to be a list.
3107 # XXX make this lazy in the future
3108 # XXX make this lazy in the future
3108 revs = list(revs)
3109 revs = list(revs)
3109 # don't mutate while iterating, create a copy
3110 # don't mutate while iterating, create a copy
3110 for rev in list(revs):
3111 for rev in list(revs):
3111 if rev in ancestors:
3112 if rev in ancestors:
3112 ui.warn(_('skipping ancestor revision %s\n') % rev)
3113 ui.warn(_('skipping ancestor revision %s\n') % rev)
3113 # XXX remove on list is slow
3114 # XXX remove on list is slow
3114 revs.remove(rev)
3115 revs.remove(rev)
3115 if not revs:
3116 if not revs:
3116 return -1
3117 return -1
3117
3118
3118 # analyze revs for earlier grafts
3119 # analyze revs for earlier grafts
3119 ids = {}
3120 ids = {}
3120 for ctx in repo.set("%ld", revs):
3121 for ctx in repo.set("%ld", revs):
3121 ids[ctx.hex()] = ctx.rev()
3122 ids[ctx.hex()] = ctx.rev()
3122 n = ctx.extra().get('source')
3123 n = ctx.extra().get('source')
3123 if n:
3124 if n:
3124 ids[n] = ctx.rev()
3125 ids[n] = ctx.rev()
3125
3126
3126 # check ancestors for earlier grafts
3127 # check ancestors for earlier grafts
3127 ui.debug('scanning for duplicate grafts\n')
3128 ui.debug('scanning for duplicate grafts\n')
3128
3129
3129 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3130 for rev in repo.changelog.findmissingrevs(revs, [crev]):
3130 ctx = repo[rev]
3131 ctx = repo[rev]
3131 n = ctx.extra().get('source')
3132 n = ctx.extra().get('source')
3132 if n in ids:
3133 if n in ids:
3133 r = repo[n].rev()
3134 r = repo[n].rev()
3134 if r in revs:
3135 if r in revs:
3135 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3136 ui.warn(_('skipping revision %s (already grafted to %s)\n')
3136 % (r, rev))
3137 % (r, rev))
3137 revs.remove(r)
3138 revs.remove(r)
3138 elif ids[n] in revs:
3139 elif ids[n] in revs:
3139 ui.warn(_('skipping already grafted revision %s '
3140 ui.warn(_('skipping already grafted revision %s '
3140 '(%s also has origin %d)\n') % (ids[n], rev, r))
3141 '(%s also has origin %d)\n') % (ids[n], rev, r))
3141 revs.remove(ids[n])
3142 revs.remove(ids[n])
3142 elif ctx.hex() in ids:
3143 elif ctx.hex() in ids:
3143 r = ids[ctx.hex()]
3144 r = ids[ctx.hex()]
3144 ui.warn(_('skipping already grafted revision %s '
3145 ui.warn(_('skipping already grafted revision %s '
3145 '(was grafted from %d)\n') % (r, rev))
3146 '(was grafted from %d)\n') % (r, rev))
3146 revs.remove(r)
3147 revs.remove(r)
3147 if not revs:
3148 if not revs:
3148 return -1
3149 return -1
3149
3150
3150 wlock = repo.wlock()
3151 wlock = repo.wlock()
3151 try:
3152 try:
3152 current = repo['.']
3153 current = repo['.']
3153 for pos, ctx in enumerate(repo.set("%ld", revs)):
3154 for pos, ctx in enumerate(repo.set("%ld", revs)):
3154
3155
3155 ui.status(_('grafting revision %s\n') % ctx.rev())
3156 ui.status(_('grafting revision %s\n') % ctx.rev())
3156 if opts.get('dry_run'):
3157 if opts.get('dry_run'):
3157 continue
3158 continue
3158
3159
3159 source = ctx.extra().get('source')
3160 source = ctx.extra().get('source')
3160 if not source:
3161 if not source:
3161 source = ctx.hex()
3162 source = ctx.hex()
3162 extra = {'source': source}
3163 extra = {'source': source}
3163 user = ctx.user()
3164 user = ctx.user()
3164 if opts.get('user'):
3165 if opts.get('user'):
3165 user = opts['user']
3166 user = opts['user']
3166 date = ctx.date()
3167 date = ctx.date()
3167 if opts.get('date'):
3168 if opts.get('date'):
3168 date = opts['date']
3169 date = opts['date']
3169 message = ctx.description()
3170 message = ctx.description()
3170 if opts.get('log'):
3171 if opts.get('log'):
3171 message += '\n(grafted from %s)' % ctx.hex()
3172 message += '\n(grafted from %s)' % ctx.hex()
3172
3173
3173 # we don't merge the first commit when continuing
3174 # we don't merge the first commit when continuing
3174 if not cont:
3175 if not cont:
3175 # perform the graft merge with p1(rev) as 'ancestor'
3176 # perform the graft merge with p1(rev) as 'ancestor'
3176 try:
3177 try:
3177 # ui.forcemerge is an internal variable, do not document
3178 # ui.forcemerge is an internal variable, do not document
3178 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3179 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
3179 'graft')
3180 'graft')
3180 stats = mergemod.update(repo, ctx.node(), True, True, False,
3181 stats = mergemod.update(repo, ctx.node(), True, True, False,
3181 ctx.p1().node(),
3182 ctx.p1().node(),
3182 labels=['local', 'graft'])
3183 labels=['local', 'graft'])
3183 finally:
3184 finally:
3184 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3185 repo.ui.setconfig('ui', 'forcemerge', '', 'graft')
3185 # report any conflicts
3186 # report any conflicts
3186 if stats and stats[3] > 0:
3187 if stats and stats[3] > 0:
3187 # write out state for --continue
3188 # write out state for --continue
3188 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3189 nodelines = [repo[rev].hex() + "\n" for rev in revs[pos:]]
3189 repo.opener.write('graftstate', ''.join(nodelines))
3190 repo.opener.write('graftstate', ''.join(nodelines))
3190 raise util.Abort(
3191 raise util.Abort(
3191 _("unresolved conflicts, can't continue"),
3192 _("unresolved conflicts, can't continue"),
3192 hint=_('use hg resolve and hg graft --continue'))
3193 hint=_('use hg resolve and hg graft --continue'))
3193 else:
3194 else:
3194 cont = False
3195 cont = False
3195
3196
3196 # drop the second merge parent
3197 # drop the second merge parent
3197 repo.setparents(current.node(), nullid)
3198 repo.setparents(current.node(), nullid)
3198 repo.dirstate.write()
3199 repo.dirstate.write()
3199 # fix up dirstate for copies and renames
3200 # fix up dirstate for copies and renames
3200 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3201 cmdutil.duplicatecopies(repo, ctx.rev(), ctx.p1().rev())
3201
3202
3202 # commit
3203 # commit
3203 node = repo.commit(text=message, user=user,
3204 node = repo.commit(text=message, user=user,
3204 date=date, extra=extra, editor=editor)
3205 date=date, extra=extra, editor=editor)
3205 if node is None:
3206 if node is None:
3206 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3207 ui.status(_('graft for revision %s is empty\n') % ctx.rev())
3207 else:
3208 else:
3208 current = repo[node]
3209 current = repo[node]
3209 finally:
3210 finally:
3210 wlock.release()
3211 wlock.release()
3211
3212
3212 # remove state when we complete successfully
3213 # remove state when we complete successfully
3213 if not opts.get('dry_run'):
3214 if not opts.get('dry_run'):
3214 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3215 util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
3215
3216
3216 return 0
3217 return 0
3217
3218
3218 @command('grep',
3219 @command('grep',
3219 [('0', 'print0', None, _('end fields with NUL')),
3220 [('0', 'print0', None, _('end fields with NUL')),
3220 ('', 'all', None, _('print all revisions that match')),
3221 ('', 'all', None, _('print all revisions that match')),
3221 ('a', 'text', None, _('treat all files as text')),
3222 ('a', 'text', None, _('treat all files as text')),
3222 ('f', 'follow', None,
3223 ('f', 'follow', None,
3223 _('follow changeset history,'
3224 _('follow changeset history,'
3224 ' or file history across copies and renames')),
3225 ' or file history across copies and renames')),
3225 ('i', 'ignore-case', None, _('ignore case when matching')),
3226 ('i', 'ignore-case', None, _('ignore case when matching')),
3226 ('l', 'files-with-matches', None,
3227 ('l', 'files-with-matches', None,
3227 _('print only filenames and revisions that match')),
3228 _('print only filenames and revisions that match')),
3228 ('n', 'line-number', None, _('print matching line numbers')),
3229 ('n', 'line-number', None, _('print matching line numbers')),
3229 ('r', 'rev', [],
3230 ('r', 'rev', [],
3230 _('only search files changed within revision range'), _('REV')),
3231 _('only search files changed within revision range'), _('REV')),
3231 ('u', 'user', None, _('list the author (long with -v)')),
3232 ('u', 'user', None, _('list the author (long with -v)')),
3232 ('d', 'date', None, _('list the date (short with -q)')),
3233 ('d', 'date', None, _('list the date (short with -q)')),
3233 ] + walkopts,
3234 ] + walkopts,
3234 _('[OPTION]... PATTERN [FILE]...'))
3235 _('[OPTION]... PATTERN [FILE]...'))
3235 def grep(ui, repo, pattern, *pats, **opts):
3236 def grep(ui, repo, pattern, *pats, **opts):
3236 """search for a pattern in specified files and revisions
3237 """search for a pattern in specified files and revisions
3237
3238
3238 Search revisions of files for a regular expression.
3239 Search revisions of files for a regular expression.
3239
3240
3240 This command behaves differently than Unix grep. It only accepts
3241 This command behaves differently than Unix grep. It only accepts
3241 Python/Perl regexps. It searches repository history, not the
3242 Python/Perl regexps. It searches repository history, not the
3242 working directory. It always prints the revision number in which a
3243 working directory. It always prints the revision number in which a
3243 match appears.
3244 match appears.
3244
3245
3245 By default, grep only prints output for the first revision of a
3246 By default, grep only prints output for the first revision of a
3246 file in which it finds a match. To get it to print every revision
3247 file in which it finds a match. To get it to print every revision
3247 that contains a change in match status ("-" for a match that
3248 that contains a change in match status ("-" for a match that
3248 becomes a non-match, or "+" for a non-match that becomes a match),
3249 becomes a non-match, or "+" for a non-match that becomes a match),
3249 use the --all flag.
3250 use the --all flag.
3250
3251
3251 Returns 0 if a match is found, 1 otherwise.
3252 Returns 0 if a match is found, 1 otherwise.
3252 """
3253 """
3253 reflags = re.M
3254 reflags = re.M
3254 if opts.get('ignore_case'):
3255 if opts.get('ignore_case'):
3255 reflags |= re.I
3256 reflags |= re.I
3256 try:
3257 try:
3257 regexp = util.compilere(pattern, reflags)
3258 regexp = util.compilere(pattern, reflags)
3258 except re.error, inst:
3259 except re.error, inst:
3259 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3260 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
3260 return 1
3261 return 1
3261 sep, eol = ':', '\n'
3262 sep, eol = ':', '\n'
3262 if opts.get('print0'):
3263 if opts.get('print0'):
3263 sep = eol = '\0'
3264 sep = eol = '\0'
3264
3265
3265 getfile = util.lrucachefunc(repo.file)
3266 getfile = util.lrucachefunc(repo.file)
3266
3267
3267 def matchlines(body):
3268 def matchlines(body):
3268 begin = 0
3269 begin = 0
3269 linenum = 0
3270 linenum = 0
3270 while begin < len(body):
3271 while begin < len(body):
3271 match = regexp.search(body, begin)
3272 match = regexp.search(body, begin)
3272 if not match:
3273 if not match:
3273 break
3274 break
3274 mstart, mend = match.span()
3275 mstart, mend = match.span()
3275 linenum += body.count('\n', begin, mstart) + 1
3276 linenum += body.count('\n', begin, mstart) + 1
3276 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3277 lstart = body.rfind('\n', begin, mstart) + 1 or begin
3277 begin = body.find('\n', mend) + 1 or len(body) + 1
3278 begin = body.find('\n', mend) + 1 or len(body) + 1
3278 lend = begin - 1
3279 lend = begin - 1
3279 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3280 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
3280
3281
3281 class linestate(object):
3282 class linestate(object):
3282 def __init__(self, line, linenum, colstart, colend):
3283 def __init__(self, line, linenum, colstart, colend):
3283 self.line = line
3284 self.line = line
3284 self.linenum = linenum
3285 self.linenum = linenum
3285 self.colstart = colstart
3286 self.colstart = colstart
3286 self.colend = colend
3287 self.colend = colend
3287
3288
3288 def __hash__(self):
3289 def __hash__(self):
3289 return hash((self.linenum, self.line))
3290 return hash((self.linenum, self.line))
3290
3291
3291 def __eq__(self, other):
3292 def __eq__(self, other):
3292 return self.line == other.line
3293 return self.line == other.line
3293
3294
3294 def __iter__(self):
3295 def __iter__(self):
3295 yield (self.line[:self.colstart], '')
3296 yield (self.line[:self.colstart], '')
3296 yield (self.line[self.colstart:self.colend], 'grep.match')
3297 yield (self.line[self.colstart:self.colend], 'grep.match')
3297 rest = self.line[self.colend:]
3298 rest = self.line[self.colend:]
3298 while rest != '':
3299 while rest != '':
3299 match = regexp.search(rest)
3300 match = regexp.search(rest)
3300 if not match:
3301 if not match:
3301 yield (rest, '')
3302 yield (rest, '')
3302 break
3303 break
3303 mstart, mend = match.span()
3304 mstart, mend = match.span()
3304 yield (rest[:mstart], '')
3305 yield (rest[:mstart], '')
3305 yield (rest[mstart:mend], 'grep.match')
3306 yield (rest[mstart:mend], 'grep.match')
3306 rest = rest[mend:]
3307 rest = rest[mend:]
3307
3308
3308 matches = {}
3309 matches = {}
3309 copies = {}
3310 copies = {}
3310 def grepbody(fn, rev, body):
3311 def grepbody(fn, rev, body):
3311 matches[rev].setdefault(fn, [])
3312 matches[rev].setdefault(fn, [])
3312 m = matches[rev][fn]
3313 m = matches[rev][fn]
3313 for lnum, cstart, cend, line in matchlines(body):
3314 for lnum, cstart, cend, line in matchlines(body):
3314 s = linestate(line, lnum, cstart, cend)
3315 s = linestate(line, lnum, cstart, cend)
3315 m.append(s)
3316 m.append(s)
3316
3317
3317 def difflinestates(a, b):
3318 def difflinestates(a, b):
3318 sm = difflib.SequenceMatcher(None, a, b)
3319 sm = difflib.SequenceMatcher(None, a, b)
3319 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3320 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
3320 if tag == 'insert':
3321 if tag == 'insert':
3321 for i in xrange(blo, bhi):
3322 for i in xrange(blo, bhi):
3322 yield ('+', b[i])
3323 yield ('+', b[i])
3323 elif tag == 'delete':
3324 elif tag == 'delete':
3324 for i in xrange(alo, ahi):
3325 for i in xrange(alo, ahi):
3325 yield ('-', a[i])
3326 yield ('-', a[i])
3326 elif tag == 'replace':
3327 elif tag == 'replace':
3327 for i in xrange(alo, ahi):
3328 for i in xrange(alo, ahi):
3328 yield ('-', a[i])
3329 yield ('-', a[i])
3329 for i in xrange(blo, bhi):
3330 for i in xrange(blo, bhi):
3330 yield ('+', b[i])
3331 yield ('+', b[i])
3331
3332
3332 def display(fn, ctx, pstates, states):
3333 def display(fn, ctx, pstates, states):
3333 rev = ctx.rev()
3334 rev = ctx.rev()
3334 datefunc = ui.quiet and util.shortdate or util.datestr
3335 datefunc = ui.quiet and util.shortdate or util.datestr
3335 found = False
3336 found = False
3336 @util.cachefunc
3337 @util.cachefunc
3337 def binary():
3338 def binary():
3338 flog = getfile(fn)
3339 flog = getfile(fn)
3339 return util.binary(flog.read(ctx.filenode(fn)))
3340 return util.binary(flog.read(ctx.filenode(fn)))
3340
3341
3341 if opts.get('all'):
3342 if opts.get('all'):
3342 iter = difflinestates(pstates, states)
3343 iter = difflinestates(pstates, states)
3343 else:
3344 else:
3344 iter = [('', l) for l in states]
3345 iter = [('', l) for l in states]
3345 for change, l in iter:
3346 for change, l in iter:
3346 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3347 cols = [(fn, 'grep.filename'), (str(rev), 'grep.rev')]
3347
3348
3348 if opts.get('line_number'):
3349 if opts.get('line_number'):
3349 cols.append((str(l.linenum), 'grep.linenumber'))
3350 cols.append((str(l.linenum), 'grep.linenumber'))
3350 if opts.get('all'):
3351 if opts.get('all'):
3351 cols.append((change, 'grep.change'))
3352 cols.append((change, 'grep.change'))
3352 if opts.get('user'):
3353 if opts.get('user'):
3353 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3354 cols.append((ui.shortuser(ctx.user()), 'grep.user'))
3354 if opts.get('date'):
3355 if opts.get('date'):
3355 cols.append((datefunc(ctx.date()), 'grep.date'))
3356 cols.append((datefunc(ctx.date()), 'grep.date'))
3356 for col, label in cols[:-1]:
3357 for col, label in cols[:-1]:
3357 ui.write(col, label=label)
3358 ui.write(col, label=label)
3358 ui.write(sep, label='grep.sep')
3359 ui.write(sep, label='grep.sep')
3359 ui.write(cols[-1][0], label=cols[-1][1])
3360 ui.write(cols[-1][0], label=cols[-1][1])
3360 if not opts.get('files_with_matches'):
3361 if not opts.get('files_with_matches'):
3361 ui.write(sep, label='grep.sep')
3362 ui.write(sep, label='grep.sep')
3362 if not opts.get('text') and binary():
3363 if not opts.get('text') and binary():
3363 ui.write(" Binary file matches")
3364 ui.write(" Binary file matches")
3364 else:
3365 else:
3365 for s, label in l:
3366 for s, label in l:
3366 ui.write(s, label=label)
3367 ui.write(s, label=label)
3367 ui.write(eol)
3368 ui.write(eol)
3368 found = True
3369 found = True
3369 if opts.get('files_with_matches'):
3370 if opts.get('files_with_matches'):
3370 break
3371 break
3371 return found
3372 return found
3372
3373
3373 skip = {}
3374 skip = {}
3374 revfiles = {}
3375 revfiles = {}
3375 matchfn = scmutil.match(repo[None], pats, opts)
3376 matchfn = scmutil.match(repo[None], pats, opts)
3376 found = False
3377 found = False
3377 follow = opts.get('follow')
3378 follow = opts.get('follow')
3378
3379
3379 def prep(ctx, fns):
3380 def prep(ctx, fns):
3380 rev = ctx.rev()
3381 rev = ctx.rev()
3381 pctx = ctx.p1()
3382 pctx = ctx.p1()
3382 parent = pctx.rev()
3383 parent = pctx.rev()
3383 matches.setdefault(rev, {})
3384 matches.setdefault(rev, {})
3384 matches.setdefault(parent, {})
3385 matches.setdefault(parent, {})
3385 files = revfiles.setdefault(rev, [])
3386 files = revfiles.setdefault(rev, [])
3386 for fn in fns:
3387 for fn in fns:
3387 flog = getfile(fn)
3388 flog = getfile(fn)
3388 try:
3389 try:
3389 fnode = ctx.filenode(fn)
3390 fnode = ctx.filenode(fn)
3390 except error.LookupError:
3391 except error.LookupError:
3391 continue
3392 continue
3392
3393
3393 copied = flog.renamed(fnode)
3394 copied = flog.renamed(fnode)
3394 copy = follow and copied and copied[0]
3395 copy = follow and copied and copied[0]
3395 if copy:
3396 if copy:
3396 copies.setdefault(rev, {})[fn] = copy
3397 copies.setdefault(rev, {})[fn] = copy
3397 if fn in skip:
3398 if fn in skip:
3398 if copy:
3399 if copy:
3399 skip[copy] = True
3400 skip[copy] = True
3400 continue
3401 continue
3401 files.append(fn)
3402 files.append(fn)
3402
3403
3403 if fn not in matches[rev]:
3404 if fn not in matches[rev]:
3404 grepbody(fn, rev, flog.read(fnode))
3405 grepbody(fn, rev, flog.read(fnode))
3405
3406
3406 pfn = copy or fn
3407 pfn = copy or fn
3407 if pfn not in matches[parent]:
3408 if pfn not in matches[parent]:
3408 try:
3409 try:
3409 fnode = pctx.filenode(pfn)
3410 fnode = pctx.filenode(pfn)
3410 grepbody(pfn, parent, flog.read(fnode))
3411 grepbody(pfn, parent, flog.read(fnode))
3411 except error.LookupError:
3412 except error.LookupError:
3412 pass
3413 pass
3413
3414
3414 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3415 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3415 rev = ctx.rev()
3416 rev = ctx.rev()
3416 parent = ctx.p1().rev()
3417 parent = ctx.p1().rev()
3417 for fn in sorted(revfiles.get(rev, [])):
3418 for fn in sorted(revfiles.get(rev, [])):
3418 states = matches[rev][fn]
3419 states = matches[rev][fn]
3419 copy = copies.get(rev, {}).get(fn)
3420 copy = copies.get(rev, {}).get(fn)
3420 if fn in skip:
3421 if fn in skip:
3421 if copy:
3422 if copy:
3422 skip[copy] = True
3423 skip[copy] = True
3423 continue
3424 continue
3424 pstates = matches.get(parent, {}).get(copy or fn, [])
3425 pstates = matches.get(parent, {}).get(copy or fn, [])
3425 if pstates or states:
3426 if pstates or states:
3426 r = display(fn, ctx, pstates, states)
3427 r = display(fn, ctx, pstates, states)
3427 found = found or r
3428 found = found or r
3428 if r and not opts.get('all'):
3429 if r and not opts.get('all'):
3429 skip[fn] = True
3430 skip[fn] = True
3430 if copy:
3431 if copy:
3431 skip[copy] = True
3432 skip[copy] = True
3432 del matches[rev]
3433 del matches[rev]
3433 del revfiles[rev]
3434 del revfiles[rev]
3434
3435
3435 return not found
3436 return not found
3436
3437
3437 @command('heads',
3438 @command('heads',
3438 [('r', 'rev', '',
3439 [('r', 'rev', '',
3439 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3440 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3440 ('t', 'topo', False, _('show topological heads only')),
3441 ('t', 'topo', False, _('show topological heads only')),
3441 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3442 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3442 ('c', 'closed', False, _('show normal and closed branch heads')),
3443 ('c', 'closed', False, _('show normal and closed branch heads')),
3443 ] + templateopts,
3444 ] + templateopts,
3444 _('[-ct] [-r STARTREV] [REV]...'))
3445 _('[-ct] [-r STARTREV] [REV]...'))
3445 def heads(ui, repo, *branchrevs, **opts):
3446 def heads(ui, repo, *branchrevs, **opts):
3446 """show branch heads
3447 """show branch heads
3447
3448
3448 With no arguments, show all open branch heads in the repository.
3449 With no arguments, show all open branch heads in the repository.
3449 Branch heads are changesets that have no descendants on the
3450 Branch heads are changesets that have no descendants on the
3450 same branch. They are where development generally takes place and
3451 same branch. They are where development generally takes place and
3451 are the usual targets for update and merge operations.
3452 are the usual targets for update and merge operations.
3452
3453
3453 If one or more REVs are given, only open branch heads on the
3454 If one or more REVs are given, only open branch heads on the
3454 branches associated with the specified changesets are shown. This
3455 branches associated with the specified changesets are shown. This
3455 means that you can use :hg:`heads .` to see the heads on the
3456 means that you can use :hg:`heads .` to see the heads on the
3456 currently checked-out branch.
3457 currently checked-out branch.
3457
3458
3458 If -c/--closed is specified, also show branch heads marked closed
3459 If -c/--closed is specified, also show branch heads marked closed
3459 (see :hg:`commit --close-branch`).
3460 (see :hg:`commit --close-branch`).
3460
3461
3461 If STARTREV is specified, only those heads that are descendants of
3462 If STARTREV is specified, only those heads that are descendants of
3462 STARTREV will be displayed.
3463 STARTREV will be displayed.
3463
3464
3464 If -t/--topo is specified, named branch mechanics will be ignored and only
3465 If -t/--topo is specified, named branch mechanics will be ignored and only
3465 topological heads (changesets with no children) will be shown.
3466 topological heads (changesets with no children) will be shown.
3466
3467
3467 Returns 0 if matching heads are found, 1 if not.
3468 Returns 0 if matching heads are found, 1 if not.
3468 """
3469 """
3469
3470
3470 start = None
3471 start = None
3471 if 'rev' in opts:
3472 if 'rev' in opts:
3472 start = scmutil.revsingle(repo, opts['rev'], None).node()
3473 start = scmutil.revsingle(repo, opts['rev'], None).node()
3473
3474
3474 if opts.get('topo'):
3475 if opts.get('topo'):
3475 heads = [repo[h] for h in repo.heads(start)]
3476 heads = [repo[h] for h in repo.heads(start)]
3476 else:
3477 else:
3477 heads = []
3478 heads = []
3478 for branch in repo.branchmap():
3479 for branch in repo.branchmap():
3479 heads += repo.branchheads(branch, start, opts.get('closed'))
3480 heads += repo.branchheads(branch, start, opts.get('closed'))
3480 heads = [repo[h] for h in heads]
3481 heads = [repo[h] for h in heads]
3481
3482
3482 if branchrevs:
3483 if branchrevs:
3483 branches = set(repo[br].branch() for br in branchrevs)
3484 branches = set(repo[br].branch() for br in branchrevs)
3484 heads = [h for h in heads if h.branch() in branches]
3485 heads = [h for h in heads if h.branch() in branches]
3485
3486
3486 if opts.get('active') and branchrevs:
3487 if opts.get('active') and branchrevs:
3487 dagheads = repo.heads(start)
3488 dagheads = repo.heads(start)
3488 heads = [h for h in heads if h.node() in dagheads]
3489 heads = [h for h in heads if h.node() in dagheads]
3489
3490
3490 if branchrevs:
3491 if branchrevs:
3491 haveheads = set(h.branch() for h in heads)
3492 haveheads = set(h.branch() for h in heads)
3492 if branches - haveheads:
3493 if branches - haveheads:
3493 headless = ', '.join(b for b in branches - haveheads)
3494 headless = ', '.join(b for b in branches - haveheads)
3494 msg = _('no open branch heads found on branches %s')
3495 msg = _('no open branch heads found on branches %s')
3495 if opts.get('rev'):
3496 if opts.get('rev'):
3496 msg += _(' (started at %s)') % opts['rev']
3497 msg += _(' (started at %s)') % opts['rev']
3497 ui.warn((msg + '\n') % headless)
3498 ui.warn((msg + '\n') % headless)
3498
3499
3499 if not heads:
3500 if not heads:
3500 return 1
3501 return 1
3501
3502
3502 heads = sorted(heads, key=lambda x: -x.rev())
3503 heads = sorted(heads, key=lambda x: -x.rev())
3503 displayer = cmdutil.show_changeset(ui, repo, opts)
3504 displayer = cmdutil.show_changeset(ui, repo, opts)
3504 for ctx in heads:
3505 for ctx in heads:
3505 displayer.show(ctx)
3506 displayer.show(ctx)
3506 displayer.close()
3507 displayer.close()
3507
3508
3508 @command('help',
3509 @command('help',
3509 [('e', 'extension', None, _('show only help for extensions')),
3510 [('e', 'extension', None, _('show only help for extensions')),
3510 ('c', 'command', None, _('show only help for commands')),
3511 ('c', 'command', None, _('show only help for commands')),
3511 ('k', 'keyword', '', _('show topics matching keyword')),
3512 ('k', 'keyword', '', _('show topics matching keyword')),
3512 ],
3513 ],
3513 _('[-ec] [TOPIC]'))
3514 _('[-ec] [TOPIC]'))
3514 def help_(ui, name=None, **opts):
3515 def help_(ui, name=None, **opts):
3515 """show help for a given topic or a help overview
3516 """show help for a given topic or a help overview
3516
3517
3517 With no arguments, print a list of commands with short help messages.
3518 With no arguments, print a list of commands with short help messages.
3518
3519
3519 Given a topic, extension, or command name, print help for that
3520 Given a topic, extension, or command name, print help for that
3520 topic.
3521 topic.
3521
3522
3522 Returns 0 if successful.
3523 Returns 0 if successful.
3523 """
3524 """
3524
3525
3525 textwidth = min(ui.termwidth(), 80) - 2
3526 textwidth = min(ui.termwidth(), 80) - 2
3526
3527
3527 keep = ui.verbose and ['verbose'] or []
3528 keep = ui.verbose and ['verbose'] or []
3528 text = help.help_(ui, name, **opts)
3529 text = help.help_(ui, name, **opts)
3529
3530
3530 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3531 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3531 if 'verbose' in pruned:
3532 if 'verbose' in pruned:
3532 keep.append('omitted')
3533 keep.append('omitted')
3533 else:
3534 else:
3534 keep.append('notomitted')
3535 keep.append('notomitted')
3535 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3536 formatted, pruned = minirst.format(text, textwidth, keep=keep)
3536 ui.write(formatted)
3537 ui.write(formatted)
3537
3538
3538
3539
3539 @command('identify|id',
3540 @command('identify|id',
3540 [('r', 'rev', '',
3541 [('r', 'rev', '',
3541 _('identify the specified revision'), _('REV')),
3542 _('identify the specified revision'), _('REV')),
3542 ('n', 'num', None, _('show local revision number')),
3543 ('n', 'num', None, _('show local revision number')),
3543 ('i', 'id', None, _('show global revision id')),
3544 ('i', 'id', None, _('show global revision id')),
3544 ('b', 'branch', None, _('show branch')),
3545 ('b', 'branch', None, _('show branch')),
3545 ('t', 'tags', None, _('show tags')),
3546 ('t', 'tags', None, _('show tags')),
3546 ('B', 'bookmarks', None, _('show bookmarks')),
3547 ('B', 'bookmarks', None, _('show bookmarks')),
3547 ] + remoteopts,
3548 ] + remoteopts,
3548 _('[-nibtB] [-r REV] [SOURCE]'))
3549 _('[-nibtB] [-r REV] [SOURCE]'))
3549 def identify(ui, repo, source=None, rev=None,
3550 def identify(ui, repo, source=None, rev=None,
3550 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3551 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3551 """identify the working copy or specified revision
3552 """identify the working copy or specified revision
3552
3553
3553 Print a summary identifying the repository state at REV using one or
3554 Print a summary identifying the repository state at REV using one or
3554 two parent hash identifiers, followed by a "+" if the working
3555 two parent hash identifiers, followed by a "+" if the working
3555 directory has uncommitted changes, the branch name (if not default),
3556 directory has uncommitted changes, the branch name (if not default),
3556 a list of tags, and a list of bookmarks.
3557 a list of tags, and a list of bookmarks.
3557
3558
3558 When REV is not given, print a summary of the current state of the
3559 When REV is not given, print a summary of the current state of the
3559 repository.
3560 repository.
3560
3561
3561 Specifying a path to a repository root or Mercurial bundle will
3562 Specifying a path to a repository root or Mercurial bundle will
3562 cause lookup to operate on that repository/bundle.
3563 cause lookup to operate on that repository/bundle.
3563
3564
3564 .. container:: verbose
3565 .. container:: verbose
3565
3566
3566 Examples:
3567 Examples:
3567
3568
3568 - generate a build identifier for the working directory::
3569 - generate a build identifier for the working directory::
3569
3570
3570 hg id --id > build-id.dat
3571 hg id --id > build-id.dat
3571
3572
3572 - find the revision corresponding to a tag::
3573 - find the revision corresponding to a tag::
3573
3574
3574 hg id -n -r 1.3
3575 hg id -n -r 1.3
3575
3576
3576 - check the most recent revision of a remote repository::
3577 - check the most recent revision of a remote repository::
3577
3578
3578 hg id -r tip http://selenic.com/hg/
3579 hg id -r tip http://selenic.com/hg/
3579
3580
3580 Returns 0 if successful.
3581 Returns 0 if successful.
3581 """
3582 """
3582
3583
3583 if not repo and not source:
3584 if not repo and not source:
3584 raise util.Abort(_("there is no Mercurial repository here "
3585 raise util.Abort(_("there is no Mercurial repository here "
3585 "(.hg not found)"))
3586 "(.hg not found)"))
3586
3587
3587 hexfunc = ui.debugflag and hex or short
3588 hexfunc = ui.debugflag and hex or short
3588 default = not (num or id or branch or tags or bookmarks)
3589 default = not (num or id or branch or tags or bookmarks)
3589 output = []
3590 output = []
3590 revs = []
3591 revs = []
3591
3592
3592 if source:
3593 if source:
3593 source, branches = hg.parseurl(ui.expandpath(source))
3594 source, branches = hg.parseurl(ui.expandpath(source))
3594 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3595 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3595 repo = peer.local()
3596 repo = peer.local()
3596 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3597 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3597
3598
3598 if not repo:
3599 if not repo:
3599 if num or branch or tags:
3600 if num or branch or tags:
3600 raise util.Abort(
3601 raise util.Abort(
3601 _("can't query remote revision number, branch, or tags"))
3602 _("can't query remote revision number, branch, or tags"))
3602 if not rev and revs:
3603 if not rev and revs:
3603 rev = revs[0]
3604 rev = revs[0]
3604 if not rev:
3605 if not rev:
3605 rev = "tip"
3606 rev = "tip"
3606
3607
3607 remoterev = peer.lookup(rev)
3608 remoterev = peer.lookup(rev)
3608 if default or id:
3609 if default or id:
3609 output = [hexfunc(remoterev)]
3610 output = [hexfunc(remoterev)]
3610
3611
3611 def getbms():
3612 def getbms():
3612 bms = []
3613 bms = []
3613
3614
3614 if 'bookmarks' in peer.listkeys('namespaces'):
3615 if 'bookmarks' in peer.listkeys('namespaces'):
3615 hexremoterev = hex(remoterev)
3616 hexremoterev = hex(remoterev)
3616 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3617 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3617 if bmr == hexremoterev]
3618 if bmr == hexremoterev]
3618
3619
3619 return sorted(bms)
3620 return sorted(bms)
3620
3621
3621 if bookmarks:
3622 if bookmarks:
3622 output.extend(getbms())
3623 output.extend(getbms())
3623 elif default and not ui.quiet:
3624 elif default and not ui.quiet:
3624 # multiple bookmarks for a single parent separated by '/'
3625 # multiple bookmarks for a single parent separated by '/'
3625 bm = '/'.join(getbms())
3626 bm = '/'.join(getbms())
3626 if bm:
3627 if bm:
3627 output.append(bm)
3628 output.append(bm)
3628 else:
3629 else:
3629 if not rev:
3630 if not rev:
3630 ctx = repo[None]
3631 ctx = repo[None]
3631 parents = ctx.parents()
3632 parents = ctx.parents()
3632 changed = ""
3633 changed = ""
3633 if default or id or num:
3634 if default or id or num:
3634 if (util.any(repo.status())
3635 if (util.any(repo.status())
3635 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3636 or util.any(ctx.sub(s).dirty() for s in ctx.substate)):
3636 changed = '+'
3637 changed = '+'
3637 if default or id:
3638 if default or id:
3638 output = ["%s%s" %
3639 output = ["%s%s" %
3639 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3640 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
3640 if num:
3641 if num:
3641 output.append("%s%s" %
3642 output.append("%s%s" %
3642 ('+'.join([str(p.rev()) for p in parents]), changed))
3643 ('+'.join([str(p.rev()) for p in parents]), changed))
3643 else:
3644 else:
3644 ctx = scmutil.revsingle(repo, rev)
3645 ctx = scmutil.revsingle(repo, rev)
3645 if default or id:
3646 if default or id:
3646 output = [hexfunc(ctx.node())]
3647 output = [hexfunc(ctx.node())]
3647 if num:
3648 if num:
3648 output.append(str(ctx.rev()))
3649 output.append(str(ctx.rev()))
3649
3650
3650 if default and not ui.quiet:
3651 if default and not ui.quiet:
3651 b = ctx.branch()
3652 b = ctx.branch()
3652 if b != 'default':
3653 if b != 'default':
3653 output.append("(%s)" % b)
3654 output.append("(%s)" % b)
3654
3655
3655 # multiple tags for a single parent separated by '/'
3656 # multiple tags for a single parent separated by '/'
3656 t = '/'.join(ctx.tags())
3657 t = '/'.join(ctx.tags())
3657 if t:
3658 if t:
3658 output.append(t)
3659 output.append(t)
3659
3660
3660 # multiple bookmarks for a single parent separated by '/'
3661 # multiple bookmarks for a single parent separated by '/'
3661 bm = '/'.join(ctx.bookmarks())
3662 bm = '/'.join(ctx.bookmarks())
3662 if bm:
3663 if bm:
3663 output.append(bm)
3664 output.append(bm)
3664 else:
3665 else:
3665 if branch:
3666 if branch:
3666 output.append(ctx.branch())
3667 output.append(ctx.branch())
3667
3668
3668 if tags:
3669 if tags:
3669 output.extend(ctx.tags())
3670 output.extend(ctx.tags())
3670
3671
3671 if bookmarks:
3672 if bookmarks:
3672 output.extend(ctx.bookmarks())
3673 output.extend(ctx.bookmarks())
3673
3674
3674 ui.write("%s\n" % ' '.join(output))
3675 ui.write("%s\n" % ' '.join(output))
3675
3676
3676 @command('import|patch',
3677 @command('import|patch',
3677 [('p', 'strip', 1,
3678 [('p', 'strip', 1,
3678 _('directory strip option for patch. This has the same '
3679 _('directory strip option for patch. This has the same '
3679 'meaning as the corresponding patch option'), _('NUM')),
3680 'meaning as the corresponding patch option'), _('NUM')),
3680 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3681 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3681 ('e', 'edit', False, _('invoke editor on commit messages')),
3682 ('e', 'edit', False, _('invoke editor on commit messages')),
3682 ('f', 'force', None,
3683 ('f', 'force', None,
3683 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3684 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3684 ('', 'no-commit', None,
3685 ('', 'no-commit', None,
3685 _("don't commit, just update the working directory")),
3686 _("don't commit, just update the working directory")),
3686 ('', 'bypass', None,
3687 ('', 'bypass', None,
3687 _("apply patch without touching the working directory")),
3688 _("apply patch without touching the working directory")),
3688 ('', 'partial', None,
3689 ('', 'partial', None,
3689 _('commit even if some hunks fail')),
3690 _('commit even if some hunks fail')),
3690 ('', 'exact', None,
3691 ('', 'exact', None,
3691 _('apply patch to the nodes from which it was generated')),
3692 _('apply patch to the nodes from which it was generated')),
3692 ('', 'import-branch', None,
3693 ('', 'import-branch', None,
3693 _('use any branch information in patch (implied by --exact)'))] +
3694 _('use any branch information in patch (implied by --exact)'))] +
3694 commitopts + commitopts2 + similarityopts,
3695 commitopts + commitopts2 + similarityopts,
3695 _('[OPTION]... PATCH...'))
3696 _('[OPTION]... PATCH...'))
3696 def import_(ui, repo, patch1=None, *patches, **opts):
3697 def import_(ui, repo, patch1=None, *patches, **opts):
3697 """import an ordered set of patches
3698 """import an ordered set of patches
3698
3699
3699 Import a list of patches and commit them individually (unless
3700 Import a list of patches and commit them individually (unless
3700 --no-commit is specified).
3701 --no-commit is specified).
3701
3702
3702 Because import first applies changes to the working directory,
3703 Because import first applies changes to the working directory,
3703 import will abort if there are outstanding changes.
3704 import will abort if there are outstanding changes.
3704
3705
3705 You can import a patch straight from a mail message. Even patches
3706 You can import a patch straight from a mail message. Even patches
3706 as attachments work (to use the body part, it must have type
3707 as attachments work (to use the body part, it must have type
3707 text/plain or text/x-patch). From and Subject headers of email
3708 text/plain or text/x-patch). From and Subject headers of email
3708 message are used as default committer and commit message. All
3709 message are used as default committer and commit message. All
3709 text/plain body parts before first diff are added to commit
3710 text/plain body parts before first diff are added to commit
3710 message.
3711 message.
3711
3712
3712 If the imported patch was generated by :hg:`export`, user and
3713 If the imported patch was generated by :hg:`export`, user and
3713 description from patch override values from message headers and
3714 description from patch override values from message headers and
3714 body. Values given on command line with -m/--message and -u/--user
3715 body. Values given on command line with -m/--message and -u/--user
3715 override these.
3716 override these.
3716
3717
3717 If --exact is specified, import will set the working directory to
3718 If --exact is specified, import will set the working directory to
3718 the parent of each patch before applying it, and will abort if the
3719 the parent of each patch before applying it, and will abort if the
3719 resulting changeset has a different ID than the one recorded in
3720 resulting changeset has a different ID than the one recorded in
3720 the patch. This may happen due to character set problems or other
3721 the patch. This may happen due to character set problems or other
3721 deficiencies in the text patch format.
3722 deficiencies in the text patch format.
3722
3723
3723 Use --bypass to apply and commit patches directly to the
3724 Use --bypass to apply and commit patches directly to the
3724 repository, not touching the working directory. Without --exact,
3725 repository, not touching the working directory. Without --exact,
3725 patches will be applied on top of the working directory parent
3726 patches will be applied on top of the working directory parent
3726 revision.
3727 revision.
3727
3728
3728 With -s/--similarity, hg will attempt to discover renames and
3729 With -s/--similarity, hg will attempt to discover renames and
3729 copies in the patch in the same way as :hg:`addremove`.
3730 copies in the patch in the same way as :hg:`addremove`.
3730
3731
3731 Use --partial to ensure a changeset will be created from the patch
3732 Use --partial to ensure a changeset will be created from the patch
3732 even if some hunks fail to apply. Hunks that fail to apply will be
3733 even if some hunks fail to apply. Hunks that fail to apply will be
3733 written to a <target-file>.rej file. Conflicts can then be resolved
3734 written to a <target-file>.rej file. Conflicts can then be resolved
3734 by hand before :hg:`commit --amend` is run to update the created
3735 by hand before :hg:`commit --amend` is run to update the created
3735 changeset. This flag exists to let people import patches that
3736 changeset. This flag exists to let people import patches that
3736 partially apply without losing the associated metadata (author,
3737 partially apply without losing the associated metadata (author,
3737 date, description, ...), Note that when none of the hunk applies
3738 date, description, ...), Note that when none of the hunk applies
3738 cleanly, :hg:`import --partial` will create an empty changeset,
3739 cleanly, :hg:`import --partial` will create an empty changeset,
3739 importing only the patch metadata.
3740 importing only the patch metadata.
3740
3741
3741 To read a patch from standard input, use "-" as the patch name. If
3742 To read a patch from standard input, use "-" as the patch name. If
3742 a URL is specified, the patch will be downloaded from it.
3743 a URL is specified, the patch will be downloaded from it.
3743 See :hg:`help dates` for a list of formats valid for -d/--date.
3744 See :hg:`help dates` for a list of formats valid for -d/--date.
3744
3745
3745 .. container:: verbose
3746 .. container:: verbose
3746
3747
3747 Examples:
3748 Examples:
3748
3749
3749 - import a traditional patch from a website and detect renames::
3750 - import a traditional patch from a website and detect renames::
3750
3751
3751 hg import -s 80 http://example.com/bugfix.patch
3752 hg import -s 80 http://example.com/bugfix.patch
3752
3753
3753 - import a changeset from an hgweb server::
3754 - import a changeset from an hgweb server::
3754
3755
3755 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3756 hg import http://www.selenic.com/hg/rev/5ca8c111e9aa
3756
3757
3757 - import all the patches in an Unix-style mbox::
3758 - import all the patches in an Unix-style mbox::
3758
3759
3759 hg import incoming-patches.mbox
3760 hg import incoming-patches.mbox
3760
3761
3761 - attempt to exactly restore an exported changeset (not always
3762 - attempt to exactly restore an exported changeset (not always
3762 possible)::
3763 possible)::
3763
3764
3764 hg import --exact proposed-fix.patch
3765 hg import --exact proposed-fix.patch
3765
3766
3766 Returns 0 on success, 1 on partial success (see --partial).
3767 Returns 0 on success, 1 on partial success (see --partial).
3767 """
3768 """
3768
3769
3769 if not patch1:
3770 if not patch1:
3770 raise util.Abort(_('need at least one patch to import'))
3771 raise util.Abort(_('need at least one patch to import'))
3771
3772
3772 patches = (patch1,) + patches
3773 patches = (patch1,) + patches
3773
3774
3774 date = opts.get('date')
3775 date = opts.get('date')
3775 if date:
3776 if date:
3776 opts['date'] = util.parsedate(date)
3777 opts['date'] = util.parsedate(date)
3777
3778
3778 update = not opts.get('bypass')
3779 update = not opts.get('bypass')
3779 if not update and opts.get('no_commit'):
3780 if not update and opts.get('no_commit'):
3780 raise util.Abort(_('cannot use --no-commit with --bypass'))
3781 raise util.Abort(_('cannot use --no-commit with --bypass'))
3781 try:
3782 try:
3782 sim = float(opts.get('similarity') or 0)
3783 sim = float(opts.get('similarity') or 0)
3783 except ValueError:
3784 except ValueError:
3784 raise util.Abort(_('similarity must be a number'))
3785 raise util.Abort(_('similarity must be a number'))
3785 if sim < 0 or sim > 100:
3786 if sim < 0 or sim > 100:
3786 raise util.Abort(_('similarity must be between 0 and 100'))
3787 raise util.Abort(_('similarity must be between 0 and 100'))
3787 if sim and not update:
3788 if sim and not update:
3788 raise util.Abort(_('cannot use --similarity with --bypass'))
3789 raise util.Abort(_('cannot use --similarity with --bypass'))
3789
3790
3790 if update:
3791 if update:
3791 cmdutil.checkunfinished(repo)
3792 cmdutil.checkunfinished(repo)
3792 if (opts.get('exact') or not opts.get('force')) and update:
3793 if (opts.get('exact') or not opts.get('force')) and update:
3793 cmdutil.bailifchanged(repo)
3794 cmdutil.bailifchanged(repo)
3794
3795
3795 base = opts["base"]
3796 base = opts["base"]
3796 wlock = lock = tr = None
3797 wlock = lock = tr = None
3797 msgs = []
3798 msgs = []
3798 ret = 0
3799 ret = 0
3799
3800
3800
3801
3801 try:
3802 try:
3802 try:
3803 try:
3803 wlock = repo.wlock()
3804 wlock = repo.wlock()
3804 if not opts.get('no_commit'):
3805 if not opts.get('no_commit'):
3805 lock = repo.lock()
3806 lock = repo.lock()
3806 tr = repo.transaction('import')
3807 tr = repo.transaction('import')
3807 parents = repo.parents()
3808 parents = repo.parents()
3808 for patchurl in patches:
3809 for patchurl in patches:
3809 if patchurl == '-':
3810 if patchurl == '-':
3810 ui.status(_('applying patch from stdin\n'))
3811 ui.status(_('applying patch from stdin\n'))
3811 patchfile = ui.fin
3812 patchfile = ui.fin
3812 patchurl = 'stdin' # for error message
3813 patchurl = 'stdin' # for error message
3813 else:
3814 else:
3814 patchurl = os.path.join(base, patchurl)
3815 patchurl = os.path.join(base, patchurl)
3815 ui.status(_('applying %s\n') % patchurl)
3816 ui.status(_('applying %s\n') % patchurl)
3816 patchfile = hg.openpath(ui, patchurl)
3817 patchfile = hg.openpath(ui, patchurl)
3817
3818
3818 haspatch = False
3819 haspatch = False
3819 for hunk in patch.split(patchfile):
3820 for hunk in patch.split(patchfile):
3820 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3821 (msg, node, rej) = cmdutil.tryimportone(ui, repo, hunk,
3821 parents, opts,
3822 parents, opts,
3822 msgs, hg.clean)
3823 msgs, hg.clean)
3823 if msg:
3824 if msg:
3824 haspatch = True
3825 haspatch = True
3825 ui.note(msg + '\n')
3826 ui.note(msg + '\n')
3826 if update or opts.get('exact'):
3827 if update or opts.get('exact'):
3827 parents = repo.parents()
3828 parents = repo.parents()
3828 else:
3829 else:
3829 parents = [repo[node]]
3830 parents = [repo[node]]
3830 if rej:
3831 if rej:
3831 ui.write_err(_("patch applied partially\n"))
3832 ui.write_err(_("patch applied partially\n"))
3832 ui.write_err(("(fix the .rej files and run "
3833 ui.write_err(("(fix the .rej files and run "
3833 "`hg commit --amend`)\n"))
3834 "`hg commit --amend`)\n"))
3834 ret = 1
3835 ret = 1
3835 break
3836 break
3836
3837
3837 if not haspatch:
3838 if not haspatch:
3838 raise util.Abort(_('%s: no diffs found') % patchurl)
3839 raise util.Abort(_('%s: no diffs found') % patchurl)
3839
3840
3840 if tr:
3841 if tr:
3841 tr.close()
3842 tr.close()
3842 if msgs:
3843 if msgs:
3843 repo.savecommitmessage('\n* * *\n'.join(msgs))
3844 repo.savecommitmessage('\n* * *\n'.join(msgs))
3844 return ret
3845 return ret
3845 except: # re-raises
3846 except: # re-raises
3846 # wlock.release() indirectly calls dirstate.write(): since
3847 # wlock.release() indirectly calls dirstate.write(): since
3847 # we're crashing, we do not want to change the working dir
3848 # we're crashing, we do not want to change the working dir
3848 # parent after all, so make sure it writes nothing
3849 # parent after all, so make sure it writes nothing
3849 repo.dirstate.invalidate()
3850 repo.dirstate.invalidate()
3850 raise
3851 raise
3851 finally:
3852 finally:
3852 if tr:
3853 if tr:
3853 tr.release()
3854 tr.release()
3854 release(lock, wlock)
3855 release(lock, wlock)
3855
3856
3856 @command('incoming|in',
3857 @command('incoming|in',
3857 [('f', 'force', None,
3858 [('f', 'force', None,
3858 _('run even if remote repository is unrelated')),
3859 _('run even if remote repository is unrelated')),
3859 ('n', 'newest-first', None, _('show newest record first')),
3860 ('n', 'newest-first', None, _('show newest record first')),
3860 ('', 'bundle', '',
3861 ('', 'bundle', '',
3861 _('file to store the bundles into'), _('FILE')),
3862 _('file to store the bundles into'), _('FILE')),
3862 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3863 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3863 ('B', 'bookmarks', False, _("compare bookmarks")),
3864 ('B', 'bookmarks', False, _("compare bookmarks")),
3864 ('b', 'branch', [],
3865 ('b', 'branch', [],
3865 _('a specific branch you would like to pull'), _('BRANCH')),
3866 _('a specific branch you would like to pull'), _('BRANCH')),
3866 ] + logopts + remoteopts + subrepoopts,
3867 ] + logopts + remoteopts + subrepoopts,
3867 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3868 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3868 def incoming(ui, repo, source="default", **opts):
3869 def incoming(ui, repo, source="default", **opts):
3869 """show new changesets found in source
3870 """show new changesets found in source
3870
3871
3871 Show new changesets found in the specified path/URL or the default
3872 Show new changesets found in the specified path/URL or the default
3872 pull location. These are the changesets that would have been pulled
3873 pull location. These are the changesets that would have been pulled
3873 if a pull at the time you issued this command.
3874 if a pull at the time you issued this command.
3874
3875
3875 For remote repository, using --bundle avoids downloading the
3876 For remote repository, using --bundle avoids downloading the
3876 changesets twice if the incoming is followed by a pull.
3877 changesets twice if the incoming is followed by a pull.
3877
3878
3878 See pull for valid source format details.
3879 See pull for valid source format details.
3879
3880
3880 .. container:: verbose
3881 .. container:: verbose
3881
3882
3882 Examples:
3883 Examples:
3883
3884
3884 - show incoming changes with patches and full description::
3885 - show incoming changes with patches and full description::
3885
3886
3886 hg incoming -vp
3887 hg incoming -vp
3887
3888
3888 - show incoming changes excluding merges, store a bundle::
3889 - show incoming changes excluding merges, store a bundle::
3889
3890
3890 hg in -vpM --bundle incoming.hg
3891 hg in -vpM --bundle incoming.hg
3891 hg pull incoming.hg
3892 hg pull incoming.hg
3892
3893
3893 - briefly list changes inside a bundle::
3894 - briefly list changes inside a bundle::
3894
3895
3895 hg in changes.hg -T "{desc|firstline}\\n"
3896 hg in changes.hg -T "{desc|firstline}\\n"
3896
3897
3897 Returns 0 if there are incoming changes, 1 otherwise.
3898 Returns 0 if there are incoming changes, 1 otherwise.
3898 """
3899 """
3899 if opts.get('graph'):
3900 if opts.get('graph'):
3900 cmdutil.checkunsupportedgraphflags([], opts)
3901 cmdutil.checkunsupportedgraphflags([], opts)
3901 def display(other, chlist, displayer):
3902 def display(other, chlist, displayer):
3902 revdag = cmdutil.graphrevs(other, chlist, opts)
3903 revdag = cmdutil.graphrevs(other, chlist, opts)
3903 showparents = [ctx.node() for ctx in repo[None].parents()]
3904 showparents = [ctx.node() for ctx in repo[None].parents()]
3904 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3905 cmdutil.displaygraph(ui, revdag, displayer, showparents,
3905 graphmod.asciiedges)
3906 graphmod.asciiedges)
3906
3907
3907 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3908 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3908 return 0
3909 return 0
3909
3910
3910 if opts.get('bundle') and opts.get('subrepos'):
3911 if opts.get('bundle') and opts.get('subrepos'):
3911 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3912 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3912
3913
3913 if opts.get('bookmarks'):
3914 if opts.get('bookmarks'):
3914 source, branches = hg.parseurl(ui.expandpath(source),
3915 source, branches = hg.parseurl(ui.expandpath(source),
3915 opts.get('branch'))
3916 opts.get('branch'))
3916 other = hg.peer(repo, opts, source)
3917 other = hg.peer(repo, opts, source)
3917 if 'bookmarks' not in other.listkeys('namespaces'):
3918 if 'bookmarks' not in other.listkeys('namespaces'):
3918 ui.warn(_("remote doesn't support bookmarks\n"))
3919 ui.warn(_("remote doesn't support bookmarks\n"))
3919 return 0
3920 return 0
3920 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3921 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3921 return bookmarks.diff(ui, repo, other)
3922 return bookmarks.diff(ui, repo, other)
3922
3923
3923 repo._subtoppath = ui.expandpath(source)
3924 repo._subtoppath = ui.expandpath(source)
3924 try:
3925 try:
3925 return hg.incoming(ui, repo, source, opts)
3926 return hg.incoming(ui, repo, source, opts)
3926 finally:
3927 finally:
3927 del repo._subtoppath
3928 del repo._subtoppath
3928
3929
3929
3930
3930 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3931 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3931 def init(ui, dest=".", **opts):
3932 def init(ui, dest=".", **opts):
3932 """create a new repository in the given directory
3933 """create a new repository in the given directory
3933
3934
3934 Initialize a new repository in the given directory. If the given
3935 Initialize a new repository in the given directory. If the given
3935 directory does not exist, it will be created.
3936 directory does not exist, it will be created.
3936
3937
3937 If no directory is given, the current directory is used.
3938 If no directory is given, the current directory is used.
3938
3939
3939 It is possible to specify an ``ssh://`` URL as the destination.
3940 It is possible to specify an ``ssh://`` URL as the destination.
3940 See :hg:`help urls` for more information.
3941 See :hg:`help urls` for more information.
3941
3942
3942 Returns 0 on success.
3943 Returns 0 on success.
3943 """
3944 """
3944 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3945 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3945
3946
3946 @command('locate',
3947 @command('locate',
3947 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3948 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3948 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3949 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3949 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3950 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3950 ] + walkopts,
3951 ] + walkopts,
3951 _('[OPTION]... [PATTERN]...'))
3952 _('[OPTION]... [PATTERN]...'))
3952 def locate(ui, repo, *pats, **opts):
3953 def locate(ui, repo, *pats, **opts):
3953 """locate files matching specific patterns
3954 """locate files matching specific patterns
3954
3955
3955 Print files under Mercurial control in the working directory whose
3956 Print files under Mercurial control in the working directory whose
3956 names match the given patterns.
3957 names match the given patterns.
3957
3958
3958 By default, this command searches all directories in the working
3959 By default, this command searches all directories in the working
3959 directory. To search just the current directory and its
3960 directory. To search just the current directory and its
3960 subdirectories, use "--include .".
3961 subdirectories, use "--include .".
3961
3962
3962 If no patterns are given to match, this command prints the names
3963 If no patterns are given to match, this command prints the names
3963 of all files under Mercurial control in the working directory.
3964 of all files under Mercurial control in the working directory.
3964
3965
3965 If you want to feed the output of this command into the "xargs"
3966 If you want to feed the output of this command into the "xargs"
3966 command, use the -0 option to both this command and "xargs". This
3967 command, use the -0 option to both this command and "xargs". This
3967 will avoid the problem of "xargs" treating single filenames that
3968 will avoid the problem of "xargs" treating single filenames that
3968 contain whitespace as multiple filenames.
3969 contain whitespace as multiple filenames.
3969
3970
3970 Returns 0 if a match is found, 1 otherwise.
3971 Returns 0 if a match is found, 1 otherwise.
3971 """
3972 """
3972 end = opts.get('print0') and '\0' or '\n'
3973 end = opts.get('print0') and '\0' or '\n'
3973 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3974 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3974
3975
3975 ret = 1
3976 ret = 1
3976 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3977 m = scmutil.match(repo[rev], pats, opts, default='relglob')
3977 m.bad = lambda x, y: False
3978 m.bad = lambda x, y: False
3978 for abs in repo[rev].walk(m):
3979 for abs in repo[rev].walk(m):
3979 if not rev and abs not in repo.dirstate:
3980 if not rev and abs not in repo.dirstate:
3980 continue
3981 continue
3981 if opts.get('fullpath'):
3982 if opts.get('fullpath'):
3982 ui.write(repo.wjoin(abs), end)
3983 ui.write(repo.wjoin(abs), end)
3983 else:
3984 else:
3984 ui.write(((pats and m.rel(abs)) or abs), end)
3985 ui.write(((pats and m.rel(abs)) or abs), end)
3985 ret = 0
3986 ret = 0
3986
3987
3987 return ret
3988 return ret
3988
3989
3989 @command('^log|history',
3990 @command('^log|history',
3990 [('f', 'follow', None,
3991 [('f', 'follow', None,
3991 _('follow changeset history, or file history across copies and renames')),
3992 _('follow changeset history, or file history across copies and renames')),
3992 ('', 'follow-first', None,
3993 ('', 'follow-first', None,
3993 _('only follow the first parent of merge changesets (DEPRECATED)')),
3994 _('only follow the first parent of merge changesets (DEPRECATED)')),
3994 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3995 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3995 ('C', 'copies', None, _('show copied files')),
3996 ('C', 'copies', None, _('show copied files')),
3996 ('k', 'keyword', [],
3997 ('k', 'keyword', [],
3997 _('do case-insensitive search for a given text'), _('TEXT')),
3998 _('do case-insensitive search for a given text'), _('TEXT')),
3998 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3999 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3999 ('', 'removed', None, _('include revisions where files were removed')),
4000 ('', 'removed', None, _('include revisions where files were removed')),
4000 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4001 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
4001 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4002 ('u', 'user', [], _('revisions committed by user'), _('USER')),
4002 ('', 'only-branch', [],
4003 ('', 'only-branch', [],
4003 _('show only changesets within the given named branch (DEPRECATED)'),
4004 _('show only changesets within the given named branch (DEPRECATED)'),
4004 _('BRANCH')),
4005 _('BRANCH')),
4005 ('b', 'branch', [],
4006 ('b', 'branch', [],
4006 _('show changesets within the given named branch'), _('BRANCH')),
4007 _('show changesets within the given named branch'), _('BRANCH')),
4007 ('P', 'prune', [],
4008 ('P', 'prune', [],
4008 _('do not display revision or any of its ancestors'), _('REV')),
4009 _('do not display revision or any of its ancestors'), _('REV')),
4009 ] + logopts + walkopts,
4010 ] + logopts + walkopts,
4010 _('[OPTION]... [FILE]'))
4011 _('[OPTION]... [FILE]'))
4011 def log(ui, repo, *pats, **opts):
4012 def log(ui, repo, *pats, **opts):
4012 """show revision history of entire repository or files
4013 """show revision history of entire repository or files
4013
4014
4014 Print the revision history of the specified files or the entire
4015 Print the revision history of the specified files or the entire
4015 project.
4016 project.
4016
4017
4017 If no revision range is specified, the default is ``tip:0`` unless
4018 If no revision range is specified, the default is ``tip:0`` unless
4018 --follow is set, in which case the working directory parent is
4019 --follow is set, in which case the working directory parent is
4019 used as the starting revision.
4020 used as the starting revision.
4020
4021
4021 File history is shown without following rename or copy history of
4022 File history is shown without following rename or copy history of
4022 files. Use -f/--follow with a filename to follow history across
4023 files. Use -f/--follow with a filename to follow history across
4023 renames and copies. --follow without a filename will only show
4024 renames and copies. --follow without a filename will only show
4024 ancestors or descendants of the starting revision.
4025 ancestors or descendants of the starting revision.
4025
4026
4026 By default this command prints revision number and changeset id,
4027 By default this command prints revision number and changeset id,
4027 tags, non-trivial parents, user, date and time, and a summary for
4028 tags, non-trivial parents, user, date and time, and a summary for
4028 each commit. When the -v/--verbose switch is used, the list of
4029 each commit. When the -v/--verbose switch is used, the list of
4029 changed files and full commit message are shown.
4030 changed files and full commit message are shown.
4030
4031
4031 With --graph the revisions are shown as an ASCII art DAG with the most
4032 With --graph the revisions are shown as an ASCII art DAG with the most
4032 recent changeset at the top.
4033 recent changeset at the top.
4033 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4034 'o' is a changeset, '@' is a working directory parent, 'x' is obsolete,
4034 and '+' represents a fork where the changeset from the lines below is a
4035 and '+' represents a fork where the changeset from the lines below is a
4035 parent of the 'o' merge on the same line.
4036 parent of the 'o' merge on the same line.
4036
4037
4037 .. note::
4038 .. note::
4038
4039
4039 log -p/--patch may generate unexpected diff output for merge
4040 log -p/--patch may generate unexpected diff output for merge
4040 changesets, as it will only compare the merge changeset against
4041 changesets, as it will only compare the merge changeset against
4041 its first parent. Also, only files different from BOTH parents
4042 its first parent. Also, only files different from BOTH parents
4042 will appear in files:.
4043 will appear in files:.
4043
4044
4044 .. note::
4045 .. note::
4045
4046
4046 for performance reasons, log FILE may omit duplicate changes
4047 for performance reasons, log FILE may omit duplicate changes
4047 made on branches and will not show deletions. To see all
4048 made on branches and will not show deletions. To see all
4048 changes including duplicates and deletions, use the --removed
4049 changes including duplicates and deletions, use the --removed
4049 switch.
4050 switch.
4050
4051
4051 .. container:: verbose
4052 .. container:: verbose
4052
4053
4053 Some examples:
4054 Some examples:
4054
4055
4055 - changesets with full descriptions and file lists::
4056 - changesets with full descriptions and file lists::
4056
4057
4057 hg log -v
4058 hg log -v
4058
4059
4059 - changesets ancestral to the working directory::
4060 - changesets ancestral to the working directory::
4060
4061
4061 hg log -f
4062 hg log -f
4062
4063
4063 - last 10 commits on the current branch::
4064 - last 10 commits on the current branch::
4064
4065
4065 hg log -l 10 -b .
4066 hg log -l 10 -b .
4066
4067
4067 - changesets showing all modifications of a file, including removals::
4068 - changesets showing all modifications of a file, including removals::
4068
4069
4069 hg log --removed file.c
4070 hg log --removed file.c
4070
4071
4071 - all changesets that touch a directory, with diffs, excluding merges::
4072 - all changesets that touch a directory, with diffs, excluding merges::
4072
4073
4073 hg log -Mp lib/
4074 hg log -Mp lib/
4074
4075
4075 - all revision numbers that match a keyword::
4076 - all revision numbers that match a keyword::
4076
4077
4077 hg log -k bug --template "{rev}\\n"
4078 hg log -k bug --template "{rev}\\n"
4078
4079
4079 - check if a given changeset is included is a tagged release::
4080 - check if a given changeset is included is a tagged release::
4080
4081
4081 hg log -r "a21ccf and ancestor(1.9)"
4082 hg log -r "a21ccf and ancestor(1.9)"
4082
4083
4083 - find all changesets by some user in a date range::
4084 - find all changesets by some user in a date range::
4084
4085
4085 hg log -k alice -d "may 2008 to jul 2008"
4086 hg log -k alice -d "may 2008 to jul 2008"
4086
4087
4087 - summary of all changesets after the last tag::
4088 - summary of all changesets after the last tag::
4088
4089
4089 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4090 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
4090
4091
4091 See :hg:`help dates` for a list of formats valid for -d/--date.
4092 See :hg:`help dates` for a list of formats valid for -d/--date.
4092
4093
4093 See :hg:`help revisions` and :hg:`help revsets` for more about
4094 See :hg:`help revisions` and :hg:`help revsets` for more about
4094 specifying revisions.
4095 specifying revisions.
4095
4096
4096 See :hg:`help templates` for more about pre-packaged styles and
4097 See :hg:`help templates` for more about pre-packaged styles and
4097 specifying custom templates.
4098 specifying custom templates.
4098
4099
4099 Returns 0 on success.
4100 Returns 0 on success.
4100 """
4101 """
4101 if opts.get('graph'):
4102 if opts.get('graph'):
4102 return cmdutil.graphlog(ui, repo, *pats, **opts)
4103 return cmdutil.graphlog(ui, repo, *pats, **opts)
4103
4104
4104 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4105 revs, expr, filematcher = cmdutil.getlogrevs(repo, pats, opts)
4105 limit = cmdutil.loglimit(opts)
4106 limit = cmdutil.loglimit(opts)
4106 count = 0
4107 count = 0
4107
4108
4108 getrenamed = None
4109 getrenamed = None
4109 if opts.get('copies'):
4110 if opts.get('copies'):
4110 endrev = None
4111 endrev = None
4111 if opts.get('rev'):
4112 if opts.get('rev'):
4112 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4113 endrev = scmutil.revrange(repo, opts.get('rev')).max() + 1
4113 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4114 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
4114
4115
4115 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4116 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4116 for rev in revs:
4117 for rev in revs:
4117 if count == limit:
4118 if count == limit:
4118 break
4119 break
4119 ctx = repo[rev]
4120 ctx = repo[rev]
4120 copies = None
4121 copies = None
4121 if getrenamed is not None and rev:
4122 if getrenamed is not None and rev:
4122 copies = []
4123 copies = []
4123 for fn in ctx.files():
4124 for fn in ctx.files():
4124 rename = getrenamed(fn, rev)
4125 rename = getrenamed(fn, rev)
4125 if rename:
4126 if rename:
4126 copies.append((fn, rename[0]))
4127 copies.append((fn, rename[0]))
4127 revmatchfn = filematcher and filematcher(ctx.rev()) or None
4128 revmatchfn = filematcher and filematcher(ctx.rev()) or None
4128 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4129 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
4129 if displayer.flush(rev):
4130 if displayer.flush(rev):
4130 count += 1
4131 count += 1
4131
4132
4132 displayer.close()
4133 displayer.close()
4133
4134
4134 @command('manifest',
4135 @command('manifest',
4135 [('r', 'rev', '', _('revision to display'), _('REV')),
4136 [('r', 'rev', '', _('revision to display'), _('REV')),
4136 ('', 'all', False, _("list files from all revisions"))],
4137 ('', 'all', False, _("list files from all revisions"))],
4137 _('[-r REV]'))
4138 _('[-r REV]'))
4138 def manifest(ui, repo, node=None, rev=None, **opts):
4139 def manifest(ui, repo, node=None, rev=None, **opts):
4139 """output the current or given revision of the project manifest
4140 """output the current or given revision of the project manifest
4140
4141
4141 Print a list of version controlled files for the given revision.
4142 Print a list of version controlled files for the given revision.
4142 If no revision is given, the first parent of the working directory
4143 If no revision is given, the first parent of the working directory
4143 is used, or the null revision if no revision is checked out.
4144 is used, or the null revision if no revision is checked out.
4144
4145
4145 With -v, print file permissions, symlink and executable bits.
4146 With -v, print file permissions, symlink and executable bits.
4146 With --debug, print file revision hashes.
4147 With --debug, print file revision hashes.
4147
4148
4148 If option --all is specified, the list of all files from all revisions
4149 If option --all is specified, the list of all files from all revisions
4149 is printed. This includes deleted and renamed files.
4150 is printed. This includes deleted and renamed files.
4150
4151
4151 Returns 0 on success.
4152 Returns 0 on success.
4152 """
4153 """
4153
4154
4154 fm = ui.formatter('manifest', opts)
4155 fm = ui.formatter('manifest', opts)
4155
4156
4156 if opts.get('all'):
4157 if opts.get('all'):
4157 if rev or node:
4158 if rev or node:
4158 raise util.Abort(_("can't specify a revision with --all"))
4159 raise util.Abort(_("can't specify a revision with --all"))
4159
4160
4160 res = []
4161 res = []
4161 prefix = "data/"
4162 prefix = "data/"
4162 suffix = ".i"
4163 suffix = ".i"
4163 plen = len(prefix)
4164 plen = len(prefix)
4164 slen = len(suffix)
4165 slen = len(suffix)
4165 lock = repo.lock()
4166 lock = repo.lock()
4166 try:
4167 try:
4167 for fn, b, size in repo.store.datafiles():
4168 for fn, b, size in repo.store.datafiles():
4168 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4169 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
4169 res.append(fn[plen:-slen])
4170 res.append(fn[plen:-slen])
4170 finally:
4171 finally:
4171 lock.release()
4172 lock.release()
4172 for f in res:
4173 for f in res:
4173 fm.startitem()
4174 fm.startitem()
4174 fm.write("path", '%s\n', f)
4175 fm.write("path", '%s\n', f)
4175 fm.end()
4176 fm.end()
4176 return
4177 return
4177
4178
4178 if rev and node:
4179 if rev and node:
4179 raise util.Abort(_("please specify just one revision"))
4180 raise util.Abort(_("please specify just one revision"))
4180
4181
4181 if not node:
4182 if not node:
4182 node = rev
4183 node = rev
4183
4184
4184 char = {'l': '@', 'x': '*', '': ''}
4185 char = {'l': '@', 'x': '*', '': ''}
4185 mode = {'l': '644', 'x': '755', '': '644'}
4186 mode = {'l': '644', 'x': '755', '': '644'}
4186 ctx = scmutil.revsingle(repo, node)
4187 ctx = scmutil.revsingle(repo, node)
4187 mf = ctx.manifest()
4188 mf = ctx.manifest()
4188 for f in ctx:
4189 for f in ctx:
4189 fm.startitem()
4190 fm.startitem()
4190 fl = ctx[f].flags()
4191 fl = ctx[f].flags()
4191 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4192 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
4192 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4193 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
4193 fm.write('path', '%s\n', f)
4194 fm.write('path', '%s\n', f)
4194 fm.end()
4195 fm.end()
4195
4196
4196 @command('^merge',
4197 @command('^merge',
4197 [('f', 'force', None,
4198 [('f', 'force', None,
4198 _('force a merge including outstanding changes (DEPRECATED)')),
4199 _('force a merge including outstanding changes (DEPRECATED)')),
4199 ('r', 'rev', '', _('revision to merge'), _('REV')),
4200 ('r', 'rev', '', _('revision to merge'), _('REV')),
4200 ('P', 'preview', None,
4201 ('P', 'preview', None,
4201 _('review revisions to merge (no merge is performed)'))
4202 _('review revisions to merge (no merge is performed)'))
4202 ] + mergetoolopts,
4203 ] + mergetoolopts,
4203 _('[-P] [-f] [[-r] REV]'))
4204 _('[-P] [-f] [[-r] REV]'))
4204 def merge(ui, repo, node=None, **opts):
4205 def merge(ui, repo, node=None, **opts):
4205 """merge working directory with another revision
4206 """merge working directory with another revision
4206
4207
4207 The current working directory is updated with all changes made in
4208 The current working directory is updated with all changes made in
4208 the requested revision since the last common predecessor revision.
4209 the requested revision since the last common predecessor revision.
4209
4210
4210 Files that changed between either parent are marked as changed for
4211 Files that changed between either parent are marked as changed for
4211 the next commit and a commit must be performed before any further
4212 the next commit and a commit must be performed before any further
4212 updates to the repository are allowed. The next commit will have
4213 updates to the repository are allowed. The next commit will have
4213 two parents.
4214 two parents.
4214
4215
4215 ``--tool`` can be used to specify the merge tool used for file
4216 ``--tool`` can be used to specify the merge tool used for file
4216 merges. It overrides the HGMERGE environment variable and your
4217 merges. It overrides the HGMERGE environment variable and your
4217 configuration files. See :hg:`help merge-tools` for options.
4218 configuration files. See :hg:`help merge-tools` for options.
4218
4219
4219 If no revision is specified, the working directory's parent is a
4220 If no revision is specified, the working directory's parent is a
4220 head revision, and the current branch contains exactly one other
4221 head revision, and the current branch contains exactly one other
4221 head, the other head is merged with by default. Otherwise, an
4222 head, the other head is merged with by default. Otherwise, an
4222 explicit revision with which to merge with must be provided.
4223 explicit revision with which to merge with must be provided.
4223
4224
4224 :hg:`resolve` must be used to resolve unresolved files.
4225 :hg:`resolve` must be used to resolve unresolved files.
4225
4226
4226 To undo an uncommitted merge, use :hg:`update --clean .` which
4227 To undo an uncommitted merge, use :hg:`update --clean .` which
4227 will check out a clean copy of the original merge parent, losing
4228 will check out a clean copy of the original merge parent, losing
4228 all changes.
4229 all changes.
4229
4230
4230 Returns 0 on success, 1 if there are unresolved files.
4231 Returns 0 on success, 1 if there are unresolved files.
4231 """
4232 """
4232
4233
4233 if opts.get('rev') and node:
4234 if opts.get('rev') and node:
4234 raise util.Abort(_("please specify just one revision"))
4235 raise util.Abort(_("please specify just one revision"))
4235 if not node:
4236 if not node:
4236 node = opts.get('rev')
4237 node = opts.get('rev')
4237
4238
4238 if node:
4239 if node:
4239 node = scmutil.revsingle(repo, node).node()
4240 node = scmutil.revsingle(repo, node).node()
4240
4241
4241 if not node and repo._bookmarkcurrent:
4242 if not node and repo._bookmarkcurrent:
4242 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4243 bmheads = repo.bookmarkheads(repo._bookmarkcurrent)
4243 curhead = repo[repo._bookmarkcurrent].node()
4244 curhead = repo[repo._bookmarkcurrent].node()
4244 if len(bmheads) == 2:
4245 if len(bmheads) == 2:
4245 if curhead == bmheads[0]:
4246 if curhead == bmheads[0]:
4246 node = bmheads[1]
4247 node = bmheads[1]
4247 else:
4248 else:
4248 node = bmheads[0]
4249 node = bmheads[0]
4249 elif len(bmheads) > 2:
4250 elif len(bmheads) > 2:
4250 raise util.Abort(_("multiple matching bookmarks to merge - "
4251 raise util.Abort(_("multiple matching bookmarks to merge - "
4251 "please merge with an explicit rev or bookmark"),
4252 "please merge with an explicit rev or bookmark"),
4252 hint=_("run 'hg heads' to see all heads"))
4253 hint=_("run 'hg heads' to see all heads"))
4253 elif len(bmheads) <= 1:
4254 elif len(bmheads) <= 1:
4254 raise util.Abort(_("no matching bookmark to merge - "
4255 raise util.Abort(_("no matching bookmark to merge - "
4255 "please merge with an explicit rev or bookmark"),
4256 "please merge with an explicit rev or bookmark"),
4256 hint=_("run 'hg heads' to see all heads"))
4257 hint=_("run 'hg heads' to see all heads"))
4257
4258
4258 if not node and not repo._bookmarkcurrent:
4259 if not node and not repo._bookmarkcurrent:
4259 branch = repo[None].branch()
4260 branch = repo[None].branch()
4260 bheads = repo.branchheads(branch)
4261 bheads = repo.branchheads(branch)
4261 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4262 nbhs = [bh for bh in bheads if not repo[bh].bookmarks()]
4262
4263
4263 if len(nbhs) > 2:
4264 if len(nbhs) > 2:
4264 raise util.Abort(_("branch '%s' has %d heads - "
4265 raise util.Abort(_("branch '%s' has %d heads - "
4265 "please merge with an explicit rev")
4266 "please merge with an explicit rev")
4266 % (branch, len(bheads)),
4267 % (branch, len(bheads)),
4267 hint=_("run 'hg heads .' to see heads"))
4268 hint=_("run 'hg heads .' to see heads"))
4268
4269
4269 parent = repo.dirstate.p1()
4270 parent = repo.dirstate.p1()
4270 if len(nbhs) <= 1:
4271 if len(nbhs) <= 1:
4271 if len(bheads) > 1:
4272 if len(bheads) > 1:
4272 raise util.Abort(_("heads are bookmarked - "
4273 raise util.Abort(_("heads are bookmarked - "
4273 "please merge with an explicit rev"),
4274 "please merge with an explicit rev"),
4274 hint=_("run 'hg heads' to see all heads"))
4275 hint=_("run 'hg heads' to see all heads"))
4275 if len(repo.heads()) > 1:
4276 if len(repo.heads()) > 1:
4276 raise util.Abort(_("branch '%s' has one head - "
4277 raise util.Abort(_("branch '%s' has one head - "
4277 "please merge with an explicit rev")
4278 "please merge with an explicit rev")
4278 % branch,
4279 % branch,
4279 hint=_("run 'hg heads' to see all heads"))
4280 hint=_("run 'hg heads' to see all heads"))
4280 msg, hint = _('nothing to merge'), None
4281 msg, hint = _('nothing to merge'), None
4281 if parent != repo.lookup(branch):
4282 if parent != repo.lookup(branch):
4282 hint = _("use 'hg update' instead")
4283 hint = _("use 'hg update' instead")
4283 raise util.Abort(msg, hint=hint)
4284 raise util.Abort(msg, hint=hint)
4284
4285
4285 if parent not in bheads:
4286 if parent not in bheads:
4286 raise util.Abort(_('working directory not at a head revision'),
4287 raise util.Abort(_('working directory not at a head revision'),
4287 hint=_("use 'hg update' or merge with an "
4288 hint=_("use 'hg update' or merge with an "
4288 "explicit revision"))
4289 "explicit revision"))
4289 if parent == nbhs[0]:
4290 if parent == nbhs[0]:
4290 node = nbhs[-1]
4291 node = nbhs[-1]
4291 else:
4292 else:
4292 node = nbhs[0]
4293 node = nbhs[0]
4293
4294
4294 if opts.get('preview'):
4295 if opts.get('preview'):
4295 # find nodes that are ancestors of p2 but not of p1
4296 # find nodes that are ancestors of p2 but not of p1
4296 p1 = repo.lookup('.')
4297 p1 = repo.lookup('.')
4297 p2 = repo.lookup(node)
4298 p2 = repo.lookup(node)
4298 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4299 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4299
4300
4300 displayer = cmdutil.show_changeset(ui, repo, opts)
4301 displayer = cmdutil.show_changeset(ui, repo, opts)
4301 for node in nodes:
4302 for node in nodes:
4302 displayer.show(repo[node])
4303 displayer.show(repo[node])
4303 displayer.close()
4304 displayer.close()
4304 return 0
4305 return 0
4305
4306
4306 try:
4307 try:
4307 # ui.forcemerge is an internal variable, do not document
4308 # ui.forcemerge is an internal variable, do not document
4308 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4309 repo.ui.setconfig('ui', 'forcemerge', opts.get('tool', ''), 'merge')
4309 return hg.merge(repo, node, force=opts.get('force'))
4310 return hg.merge(repo, node, force=opts.get('force'))
4310 finally:
4311 finally:
4311 ui.setconfig('ui', 'forcemerge', '', 'merge')
4312 ui.setconfig('ui', 'forcemerge', '', 'merge')
4312
4313
4313 @command('outgoing|out',
4314 @command('outgoing|out',
4314 [('f', 'force', None, _('run even when the destination is unrelated')),
4315 [('f', 'force', None, _('run even when the destination is unrelated')),
4315 ('r', 'rev', [],
4316 ('r', 'rev', [],
4316 _('a changeset intended to be included in the destination'), _('REV')),
4317 _('a changeset intended to be included in the destination'), _('REV')),
4317 ('n', 'newest-first', None, _('show newest record first')),
4318 ('n', 'newest-first', None, _('show newest record first')),
4318 ('B', 'bookmarks', False, _('compare bookmarks')),
4319 ('B', 'bookmarks', False, _('compare bookmarks')),
4319 ('b', 'branch', [], _('a specific branch you would like to push'),
4320 ('b', 'branch', [], _('a specific branch you would like to push'),
4320 _('BRANCH')),
4321 _('BRANCH')),
4321 ] + logopts + remoteopts + subrepoopts,
4322 ] + logopts + remoteopts + subrepoopts,
4322 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4323 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
4323 def outgoing(ui, repo, dest=None, **opts):
4324 def outgoing(ui, repo, dest=None, **opts):
4324 """show changesets not found in the destination
4325 """show changesets not found in the destination
4325
4326
4326 Show changesets not found in the specified destination repository
4327 Show changesets not found in the specified destination repository
4327 or the default push location. These are the changesets that would
4328 or the default push location. These are the changesets that would
4328 be pushed if a push was requested.
4329 be pushed if a push was requested.
4329
4330
4330 See pull for details of valid destination formats.
4331 See pull for details of valid destination formats.
4331
4332
4332 Returns 0 if there are outgoing changes, 1 otherwise.
4333 Returns 0 if there are outgoing changes, 1 otherwise.
4333 """
4334 """
4334 if opts.get('graph'):
4335 if opts.get('graph'):
4335 cmdutil.checkunsupportedgraphflags([], opts)
4336 cmdutil.checkunsupportedgraphflags([], opts)
4336 o, other = hg._outgoing(ui, repo, dest, opts)
4337 o, other = hg._outgoing(ui, repo, dest, opts)
4337 if not o:
4338 if not o:
4338 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4339 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4339 return
4340 return
4340
4341
4341 revdag = cmdutil.graphrevs(repo, o, opts)
4342 revdag = cmdutil.graphrevs(repo, o, opts)
4342 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4343 displayer = cmdutil.show_changeset(ui, repo, opts, buffered=True)
4343 showparents = [ctx.node() for ctx in repo[None].parents()]
4344 showparents = [ctx.node() for ctx in repo[None].parents()]
4344 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4345 cmdutil.displaygraph(ui, revdag, displayer, showparents,
4345 graphmod.asciiedges)
4346 graphmod.asciiedges)
4346 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4347 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4347 return 0
4348 return 0
4348
4349
4349 if opts.get('bookmarks'):
4350 if opts.get('bookmarks'):
4350 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4351 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4351 dest, branches = hg.parseurl(dest, opts.get('branch'))
4352 dest, branches = hg.parseurl(dest, opts.get('branch'))
4352 other = hg.peer(repo, opts, dest)
4353 other = hg.peer(repo, opts, dest)
4353 if 'bookmarks' not in other.listkeys('namespaces'):
4354 if 'bookmarks' not in other.listkeys('namespaces'):
4354 ui.warn(_("remote doesn't support bookmarks\n"))
4355 ui.warn(_("remote doesn't support bookmarks\n"))
4355 return 0
4356 return 0
4356 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4357 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4357 return bookmarks.diff(ui, other, repo)
4358 return bookmarks.diff(ui, other, repo)
4358
4359
4359 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4360 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
4360 try:
4361 try:
4361 return hg.outgoing(ui, repo, dest, opts)
4362 return hg.outgoing(ui, repo, dest, opts)
4362 finally:
4363 finally:
4363 del repo._subtoppath
4364 del repo._subtoppath
4364
4365
4365 @command('parents',
4366 @command('parents',
4366 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4367 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4367 ] + templateopts,
4368 ] + templateopts,
4368 _('[-r REV] [FILE]'))
4369 _('[-r REV] [FILE]'))
4369 def parents(ui, repo, file_=None, **opts):
4370 def parents(ui, repo, file_=None, **opts):
4370 """show the parents of the working directory or revision
4371 """show the parents of the working directory or revision
4371
4372
4372 Print the working directory's parent revisions. If a revision is
4373 Print the working directory's parent revisions. If a revision is
4373 given via -r/--rev, the parent of that revision will be printed.
4374 given via -r/--rev, the parent of that revision will be printed.
4374 If a file argument is given, the revision in which the file was
4375 If a file argument is given, the revision in which the file was
4375 last changed (before the working directory revision or the
4376 last changed (before the working directory revision or the
4376 argument to --rev if given) is printed.
4377 argument to --rev if given) is printed.
4377
4378
4378 Returns 0 on success.
4379 Returns 0 on success.
4379 """
4380 """
4380
4381
4381 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4382 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
4382
4383
4383 if file_:
4384 if file_:
4384 m = scmutil.match(ctx, (file_,), opts)
4385 m = scmutil.match(ctx, (file_,), opts)
4385 if m.anypats() or len(m.files()) != 1:
4386 if m.anypats() or len(m.files()) != 1:
4386 raise util.Abort(_('can only specify an explicit filename'))
4387 raise util.Abort(_('can only specify an explicit filename'))
4387 file_ = m.files()[0]
4388 file_ = m.files()[0]
4388 filenodes = []
4389 filenodes = []
4389 for cp in ctx.parents():
4390 for cp in ctx.parents():
4390 if not cp:
4391 if not cp:
4391 continue
4392 continue
4392 try:
4393 try:
4393 filenodes.append(cp.filenode(file_))
4394 filenodes.append(cp.filenode(file_))
4394 except error.LookupError:
4395 except error.LookupError:
4395 pass
4396 pass
4396 if not filenodes:
4397 if not filenodes:
4397 raise util.Abort(_("'%s' not found in manifest!") % file_)
4398 raise util.Abort(_("'%s' not found in manifest!") % file_)
4398 p = []
4399 p = []
4399 for fn in filenodes:
4400 for fn in filenodes:
4400 fctx = repo.filectx(file_, fileid=fn)
4401 fctx = repo.filectx(file_, fileid=fn)
4401 p.append(fctx.node())
4402 p.append(fctx.node())
4402 else:
4403 else:
4403 p = [cp.node() for cp in ctx.parents()]
4404 p = [cp.node() for cp in ctx.parents()]
4404
4405
4405 displayer = cmdutil.show_changeset(ui, repo, opts)
4406 displayer = cmdutil.show_changeset(ui, repo, opts)
4406 for n in p:
4407 for n in p:
4407 if n != nullid:
4408 if n != nullid:
4408 displayer.show(repo[n])
4409 displayer.show(repo[n])
4409 displayer.close()
4410 displayer.close()
4410
4411
4411 @command('paths', [], _('[NAME]'))
4412 @command('paths', [], _('[NAME]'))
4412 def paths(ui, repo, search=None):
4413 def paths(ui, repo, search=None):
4413 """show aliases for remote repositories
4414 """show aliases for remote repositories
4414
4415
4415 Show definition of symbolic path name NAME. If no name is given,
4416 Show definition of symbolic path name NAME. If no name is given,
4416 show definition of all available names.
4417 show definition of all available names.
4417
4418
4418 Option -q/--quiet suppresses all output when searching for NAME
4419 Option -q/--quiet suppresses all output when searching for NAME
4419 and shows only the path names when listing all definitions.
4420 and shows only the path names when listing all definitions.
4420
4421
4421 Path names are defined in the [paths] section of your
4422 Path names are defined in the [paths] section of your
4422 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4423 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4423 repository, ``.hg/hgrc`` is used, too.
4424 repository, ``.hg/hgrc`` is used, too.
4424
4425
4425 The path names ``default`` and ``default-push`` have a special
4426 The path names ``default`` and ``default-push`` have a special
4426 meaning. When performing a push or pull operation, they are used
4427 meaning. When performing a push or pull operation, they are used
4427 as fallbacks if no location is specified on the command-line.
4428 as fallbacks if no location is specified on the command-line.
4428 When ``default-push`` is set, it will be used for push and
4429 When ``default-push`` is set, it will be used for push and
4429 ``default`` will be used for pull; otherwise ``default`` is used
4430 ``default`` will be used for pull; otherwise ``default`` is used
4430 as the fallback for both. When cloning a repository, the clone
4431 as the fallback for both. When cloning a repository, the clone
4431 source is written as ``default`` in ``.hg/hgrc``. Note that
4432 source is written as ``default`` in ``.hg/hgrc``. Note that
4432 ``default`` and ``default-push`` apply to all inbound (e.g.
4433 ``default`` and ``default-push`` apply to all inbound (e.g.
4433 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4434 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
4434 :hg:`bundle`) operations.
4435 :hg:`bundle`) operations.
4435
4436
4436 See :hg:`help urls` for more information.
4437 See :hg:`help urls` for more information.
4437
4438
4438 Returns 0 on success.
4439 Returns 0 on success.
4439 """
4440 """
4440 if search:
4441 if search:
4441 for name, path in ui.configitems("paths"):
4442 for name, path in ui.configitems("paths"):
4442 if name == search:
4443 if name == search:
4443 ui.status("%s\n" % util.hidepassword(path))
4444 ui.status("%s\n" % util.hidepassword(path))
4444 return
4445 return
4445 if not ui.quiet:
4446 if not ui.quiet:
4446 ui.warn(_("not found!\n"))
4447 ui.warn(_("not found!\n"))
4447 return 1
4448 return 1
4448 else:
4449 else:
4449 for name, path in ui.configitems("paths"):
4450 for name, path in ui.configitems("paths"):
4450 if ui.quiet:
4451 if ui.quiet:
4451 ui.write("%s\n" % name)
4452 ui.write("%s\n" % name)
4452 else:
4453 else:
4453 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4454 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
4454
4455
4455 @command('phase',
4456 @command('phase',
4456 [('p', 'public', False, _('set changeset phase to public')),
4457 [('p', 'public', False, _('set changeset phase to public')),
4457 ('d', 'draft', False, _('set changeset phase to draft')),
4458 ('d', 'draft', False, _('set changeset phase to draft')),
4458 ('s', 'secret', False, _('set changeset phase to secret')),
4459 ('s', 'secret', False, _('set changeset phase to secret')),
4459 ('f', 'force', False, _('allow to move boundary backward')),
4460 ('f', 'force', False, _('allow to move boundary backward')),
4460 ('r', 'rev', [], _('target revision'), _('REV')),
4461 ('r', 'rev', [], _('target revision'), _('REV')),
4461 ],
4462 ],
4462 _('[-p|-d|-s] [-f] [-r] REV...'))
4463 _('[-p|-d|-s] [-f] [-r] REV...'))
4463 def phase(ui, repo, *revs, **opts):
4464 def phase(ui, repo, *revs, **opts):
4464 """set or show the current phase name
4465 """set or show the current phase name
4465
4466
4466 With no argument, show the phase name of specified revisions.
4467 With no argument, show the phase name of specified revisions.
4467
4468
4468 With one of -p/--public, -d/--draft or -s/--secret, change the
4469 With one of -p/--public, -d/--draft or -s/--secret, change the
4469 phase value of the specified revisions.
4470 phase value of the specified revisions.
4470
4471
4471 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4472 Unless -f/--force is specified, :hg:`phase` won't move changeset from a
4472 lower phase to an higher phase. Phases are ordered as follows::
4473 lower phase to an higher phase. Phases are ordered as follows::
4473
4474
4474 public < draft < secret
4475 public < draft < secret
4475
4476
4476 Returns 0 on success, 1 if no phases were changed or some could not
4477 Returns 0 on success, 1 if no phases were changed or some could not
4477 be changed.
4478 be changed.
4478 """
4479 """
4479 # search for a unique phase argument
4480 # search for a unique phase argument
4480 targetphase = None
4481 targetphase = None
4481 for idx, name in enumerate(phases.phasenames):
4482 for idx, name in enumerate(phases.phasenames):
4482 if opts[name]:
4483 if opts[name]:
4483 if targetphase is not None:
4484 if targetphase is not None:
4484 raise util.Abort(_('only one phase can be specified'))
4485 raise util.Abort(_('only one phase can be specified'))
4485 targetphase = idx
4486 targetphase = idx
4486
4487
4487 # look for specified revision
4488 # look for specified revision
4488 revs = list(revs)
4489 revs = list(revs)
4489 revs.extend(opts['rev'])
4490 revs.extend(opts['rev'])
4490 if not revs:
4491 if not revs:
4491 raise util.Abort(_('no revisions specified'))
4492 raise util.Abort(_('no revisions specified'))
4492
4493
4493 revs = scmutil.revrange(repo, revs)
4494 revs = scmutil.revrange(repo, revs)
4494
4495
4495 lock = None
4496 lock = None
4496 ret = 0
4497 ret = 0
4497 if targetphase is None:
4498 if targetphase is None:
4498 # display
4499 # display
4499 for r in revs:
4500 for r in revs:
4500 ctx = repo[r]
4501 ctx = repo[r]
4501 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4502 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4502 else:
4503 else:
4503 lock = repo.lock()
4504 lock = repo.lock()
4504 try:
4505 try:
4505 # set phase
4506 # set phase
4506 if not revs:
4507 if not revs:
4507 raise util.Abort(_('empty revision set'))
4508 raise util.Abort(_('empty revision set'))
4508 nodes = [repo[r].node() for r in revs]
4509 nodes = [repo[r].node() for r in revs]
4509 olddata = repo._phasecache.getphaserevs(repo)[:]
4510 olddata = repo._phasecache.getphaserevs(repo)[:]
4510 phases.advanceboundary(repo, targetphase, nodes)
4511 phases.advanceboundary(repo, targetphase, nodes)
4511 if opts['force']:
4512 if opts['force']:
4512 phases.retractboundary(repo, targetphase, nodes)
4513 phases.retractboundary(repo, targetphase, nodes)
4513 finally:
4514 finally:
4514 lock.release()
4515 lock.release()
4515 # moving revision from public to draft may hide them
4516 # moving revision from public to draft may hide them
4516 # We have to check result on an unfiltered repository
4517 # We have to check result on an unfiltered repository
4517 unfi = repo.unfiltered()
4518 unfi = repo.unfiltered()
4518 newdata = repo._phasecache.getphaserevs(unfi)
4519 newdata = repo._phasecache.getphaserevs(unfi)
4519 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4520 changes = sum(o != newdata[i] for i, o in enumerate(olddata))
4520 cl = unfi.changelog
4521 cl = unfi.changelog
4521 rejected = [n for n in nodes
4522 rejected = [n for n in nodes
4522 if newdata[cl.rev(n)] < targetphase]
4523 if newdata[cl.rev(n)] < targetphase]
4523 if rejected:
4524 if rejected:
4524 ui.warn(_('cannot move %i changesets to a higher '
4525 ui.warn(_('cannot move %i changesets to a higher '
4525 'phase, use --force\n') % len(rejected))
4526 'phase, use --force\n') % len(rejected))
4526 ret = 1
4527 ret = 1
4527 if changes:
4528 if changes:
4528 msg = _('phase changed for %i changesets\n') % changes
4529 msg = _('phase changed for %i changesets\n') % changes
4529 if ret:
4530 if ret:
4530 ui.status(msg)
4531 ui.status(msg)
4531 else:
4532 else:
4532 ui.note(msg)
4533 ui.note(msg)
4533 else:
4534 else:
4534 ui.warn(_('no phases changed\n'))
4535 ui.warn(_('no phases changed\n'))
4535 ret = 1
4536 ret = 1
4536 return ret
4537 return ret
4537
4538
4538 def postincoming(ui, repo, modheads, optupdate, checkout):
4539 def postincoming(ui, repo, modheads, optupdate, checkout):
4539 if modheads == 0:
4540 if modheads == 0:
4540 return
4541 return
4541 if optupdate:
4542 if optupdate:
4542 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4543 checkout, movemarkfrom = bookmarks.calculateupdate(ui, repo, checkout)
4543 try:
4544 try:
4544 ret = hg.update(repo, checkout)
4545 ret = hg.update(repo, checkout)
4545 except util.Abort, inst:
4546 except util.Abort, inst:
4546 ui.warn(_("not updating: %s\n") % str(inst))
4547 ui.warn(_("not updating: %s\n") % str(inst))
4547 if inst.hint:
4548 if inst.hint:
4548 ui.warn(_("(%s)\n") % inst.hint)
4549 ui.warn(_("(%s)\n") % inst.hint)
4549 return 0
4550 return 0
4550 if not ret and not checkout:
4551 if not ret and not checkout:
4551 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4552 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
4552 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4553 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
4553 return ret
4554 return ret
4554 if modheads > 1:
4555 if modheads > 1:
4555 currentbranchheads = len(repo.branchheads())
4556 currentbranchheads = len(repo.branchheads())
4556 if currentbranchheads == modheads:
4557 if currentbranchheads == modheads:
4557 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4558 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4558 elif currentbranchheads > 1:
4559 elif currentbranchheads > 1:
4559 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4560 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4560 "merge)\n"))
4561 "merge)\n"))
4561 else:
4562 else:
4562 ui.status(_("(run 'hg heads' to see heads)\n"))
4563 ui.status(_("(run 'hg heads' to see heads)\n"))
4563 else:
4564 else:
4564 ui.status(_("(run 'hg update' to get a working copy)\n"))
4565 ui.status(_("(run 'hg update' to get a working copy)\n"))
4565
4566
4566 @command('^pull',
4567 @command('^pull',
4567 [('u', 'update', None,
4568 [('u', 'update', None,
4568 _('update to new branch head if changesets were pulled')),
4569 _('update to new branch head if changesets were pulled')),
4569 ('f', 'force', None, _('run even when remote repository is unrelated')),
4570 ('f', 'force', None, _('run even when remote repository is unrelated')),
4570 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4571 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4571 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4572 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4572 ('b', 'branch', [], _('a specific branch you would like to pull'),
4573 ('b', 'branch', [], _('a specific branch you would like to pull'),
4573 _('BRANCH')),
4574 _('BRANCH')),
4574 ] + remoteopts,
4575 ] + remoteopts,
4575 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4576 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
4576 def pull(ui, repo, source="default", **opts):
4577 def pull(ui, repo, source="default", **opts):
4577 """pull changes from the specified source
4578 """pull changes from the specified source
4578
4579
4579 Pull changes from a remote repository to a local one.
4580 Pull changes from a remote repository to a local one.
4580
4581
4581 This finds all changes from the repository at the specified path
4582 This finds all changes from the repository at the specified path
4582 or URL and adds them to a local repository (the current one unless
4583 or URL and adds them to a local repository (the current one unless
4583 -R is specified). By default, this does not update the copy of the
4584 -R is specified). By default, this does not update the copy of the
4584 project in the working directory.
4585 project in the working directory.
4585
4586
4586 Use :hg:`incoming` if you want to see what would have been added
4587 Use :hg:`incoming` if you want to see what would have been added
4587 by a pull at the time you issued this command. If you then decide
4588 by a pull at the time you issued this command. If you then decide
4588 to add those changes to the repository, you should use :hg:`pull
4589 to add those changes to the repository, you should use :hg:`pull
4589 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4590 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4590
4591
4591 If SOURCE is omitted, the 'default' path will be used.
4592 If SOURCE is omitted, the 'default' path will be used.
4592 See :hg:`help urls` for more information.
4593 See :hg:`help urls` for more information.
4593
4594
4594 Returns 0 on success, 1 if an update had unresolved files.
4595 Returns 0 on success, 1 if an update had unresolved files.
4595 """
4596 """
4596 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4597 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4597 other = hg.peer(repo, opts, source)
4598 other = hg.peer(repo, opts, source)
4598 try:
4599 try:
4599 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4600 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4600 revs, checkout = hg.addbranchrevs(repo, other, branches,
4601 revs, checkout = hg.addbranchrevs(repo, other, branches,
4601 opts.get('rev'))
4602 opts.get('rev'))
4602
4603
4603 remotebookmarks = other.listkeys('bookmarks')
4604 remotebookmarks = other.listkeys('bookmarks')
4604
4605
4605 if opts.get('bookmark'):
4606 if opts.get('bookmark'):
4606 if not revs:
4607 if not revs:
4607 revs = []
4608 revs = []
4608 for b in opts['bookmark']:
4609 for b in opts['bookmark']:
4609 if b not in remotebookmarks:
4610 if b not in remotebookmarks:
4610 raise util.Abort(_('remote bookmark %s not found!') % b)
4611 raise util.Abort(_('remote bookmark %s not found!') % b)
4611 revs.append(remotebookmarks[b])
4612 revs.append(remotebookmarks[b])
4612
4613
4613 if revs:
4614 if revs:
4614 try:
4615 try:
4615 revs = [other.lookup(rev) for rev in revs]
4616 revs = [other.lookup(rev) for rev in revs]
4616 except error.CapabilityError:
4617 except error.CapabilityError:
4617 err = _("other repository doesn't support revision lookup, "
4618 err = _("other repository doesn't support revision lookup, "
4618 "so a rev cannot be specified.")
4619 "so a rev cannot be specified.")
4619 raise util.Abort(err)
4620 raise util.Abort(err)
4620
4621
4621 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4622 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
4622 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4623 bookmarks.updatefromremote(ui, repo, remotebookmarks, source)
4623 if checkout:
4624 if checkout:
4624 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4625 checkout = str(repo.changelog.rev(other.lookup(checkout)))
4625 repo._subtoppath = source
4626 repo._subtoppath = source
4626 try:
4627 try:
4627 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4628 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
4628
4629
4629 finally:
4630 finally:
4630 del repo._subtoppath
4631 del repo._subtoppath
4631
4632
4632 # update specified bookmarks
4633 # update specified bookmarks
4633 if opts.get('bookmark'):
4634 if opts.get('bookmark'):
4634 marks = repo._bookmarks
4635 marks = repo._bookmarks
4635 for b in opts['bookmark']:
4636 for b in opts['bookmark']:
4636 # explicit pull overrides local bookmark if any
4637 # explicit pull overrides local bookmark if any
4637 ui.status(_("importing bookmark %s\n") % b)
4638 ui.status(_("importing bookmark %s\n") % b)
4638 marks[b] = repo[remotebookmarks[b]].node()
4639 marks[b] = repo[remotebookmarks[b]].node()
4639 marks.write()
4640 marks.write()
4640 finally:
4641 finally:
4641 other.close()
4642 other.close()
4642 return ret
4643 return ret
4643
4644
4644 @command('^push',
4645 @command('^push',
4645 [('f', 'force', None, _('force push')),
4646 [('f', 'force', None, _('force push')),
4646 ('r', 'rev', [],
4647 ('r', 'rev', [],
4647 _('a changeset intended to be included in the destination'),
4648 _('a changeset intended to be included in the destination'),
4648 _('REV')),
4649 _('REV')),
4649 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4650 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4650 ('b', 'branch', [],
4651 ('b', 'branch', [],
4651 _('a specific branch you would like to push'), _('BRANCH')),
4652 _('a specific branch you would like to push'), _('BRANCH')),
4652 ('', 'new-branch', False, _('allow pushing a new branch')),
4653 ('', 'new-branch', False, _('allow pushing a new branch')),
4653 ] + remoteopts,
4654 ] + remoteopts,
4654 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4655 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
4655 def push(ui, repo, dest=None, **opts):
4656 def push(ui, repo, dest=None, **opts):
4656 """push changes to the specified destination
4657 """push changes to the specified destination
4657
4658
4658 Push changesets from the local repository to the specified
4659 Push changesets from the local repository to the specified
4659 destination.
4660 destination.
4660
4661
4661 This operation is symmetrical to pull: it is identical to a pull
4662 This operation is symmetrical to pull: it is identical to a pull
4662 in the destination repository from the current one.
4663 in the destination repository from the current one.
4663
4664
4664 By default, push will not allow creation of new heads at the
4665 By default, push will not allow creation of new heads at the
4665 destination, since multiple heads would make it unclear which head
4666 destination, since multiple heads would make it unclear which head
4666 to use. In this situation, it is recommended to pull and merge
4667 to use. In this situation, it is recommended to pull and merge
4667 before pushing.
4668 before pushing.
4668
4669
4669 Use --new-branch if you want to allow push to create a new named
4670 Use --new-branch if you want to allow push to create a new named
4670 branch that is not present at the destination. This allows you to
4671 branch that is not present at the destination. This allows you to
4671 only create a new branch without forcing other changes.
4672 only create a new branch without forcing other changes.
4672
4673
4673 .. note::
4674 .. note::
4674
4675
4675 Extra care should be taken with the -f/--force option,
4676 Extra care should be taken with the -f/--force option,
4676 which will push all new heads on all branches, an action which will
4677 which will push all new heads on all branches, an action which will
4677 almost always cause confusion for collaborators.
4678 almost always cause confusion for collaborators.
4678
4679
4679 If -r/--rev is used, the specified revision and all its ancestors
4680 If -r/--rev is used, the specified revision and all its ancestors
4680 will be pushed to the remote repository.
4681 will be pushed to the remote repository.
4681
4682
4682 If -B/--bookmark is used, the specified bookmarked revision, its
4683 If -B/--bookmark is used, the specified bookmarked revision, its
4683 ancestors, and the bookmark will be pushed to the remote
4684 ancestors, and the bookmark will be pushed to the remote
4684 repository.
4685 repository.
4685
4686
4686 Please see :hg:`help urls` for important details about ``ssh://``
4687 Please see :hg:`help urls` for important details about ``ssh://``
4687 URLs. If DESTINATION is omitted, a default path will be used.
4688 URLs. If DESTINATION is omitted, a default path will be used.
4688
4689
4689 Returns 0 if push was successful, 1 if nothing to push.
4690 Returns 0 if push was successful, 1 if nothing to push.
4690 """
4691 """
4691
4692
4692 if opts.get('bookmark'):
4693 if opts.get('bookmark'):
4693 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4694 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4694 for b in opts['bookmark']:
4695 for b in opts['bookmark']:
4695 # translate -B options to -r so changesets get pushed
4696 # translate -B options to -r so changesets get pushed
4696 if b in repo._bookmarks:
4697 if b in repo._bookmarks:
4697 opts.setdefault('rev', []).append(b)
4698 opts.setdefault('rev', []).append(b)
4698 else:
4699 else:
4699 # if we try to push a deleted bookmark, translate it to null
4700 # if we try to push a deleted bookmark, translate it to null
4700 # this lets simultaneous -r, -b options continue working
4701 # this lets simultaneous -r, -b options continue working
4701 opts.setdefault('rev', []).append("null")
4702 opts.setdefault('rev', []).append("null")
4702
4703
4703 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4704 dest = ui.expandpath(dest or 'default-push', dest or 'default')
4704 dest, branches = hg.parseurl(dest, opts.get('branch'))
4705 dest, branches = hg.parseurl(dest, opts.get('branch'))
4705 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4706 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4706 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4707 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4707 try:
4708 try:
4708 other = hg.peer(repo, opts, dest)
4709 other = hg.peer(repo, opts, dest)
4709 except error.RepoError:
4710 except error.RepoError:
4710 if dest == "default-push":
4711 if dest == "default-push":
4711 raise util.Abort(_("default repository not configured!"),
4712 raise util.Abort(_("default repository not configured!"),
4712 hint=_('see the "path" section in "hg help config"'))
4713 hint=_('see the "path" section in "hg help config"'))
4713 else:
4714 else:
4714 raise
4715 raise
4715
4716
4716 if revs:
4717 if revs:
4717 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4718 revs = [repo.lookup(r) for r in scmutil.revrange(repo, revs)]
4718
4719
4719 repo._subtoppath = dest
4720 repo._subtoppath = dest
4720 try:
4721 try:
4721 # push subrepos depth-first for coherent ordering
4722 # push subrepos depth-first for coherent ordering
4722 c = repo['']
4723 c = repo['']
4723 subs = c.substate # only repos that are committed
4724 subs = c.substate # only repos that are committed
4724 for s in sorted(subs):
4725 for s in sorted(subs):
4725 result = c.sub(s).push(opts)
4726 result = c.sub(s).push(opts)
4726 if result == 0:
4727 if result == 0:
4727 return not result
4728 return not result
4728 finally:
4729 finally:
4729 del repo._subtoppath
4730 del repo._subtoppath
4730 result = repo.push(other, opts.get('force'), revs=revs,
4731 result = repo.push(other, opts.get('force'), revs=revs,
4731 newbranch=opts.get('new_branch'))
4732 newbranch=opts.get('new_branch'))
4732
4733
4733 result = not result
4734 result = not result
4734
4735
4735 if opts.get('bookmark'):
4736 if opts.get('bookmark'):
4736 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4737 bresult = bookmarks.pushtoremote(ui, repo, other, opts['bookmark'])
4737 if bresult == 2:
4738 if bresult == 2:
4738 return 2
4739 return 2
4739 if not result and bresult:
4740 if not result and bresult:
4740 result = 2
4741 result = 2
4741
4742
4742 return result
4743 return result
4743
4744
4744 @command('recover', [])
4745 @command('recover', [])
4745 def recover(ui, repo):
4746 def recover(ui, repo):
4746 """roll back an interrupted transaction
4747 """roll back an interrupted transaction
4747
4748
4748 Recover from an interrupted commit or pull.
4749 Recover from an interrupted commit or pull.
4749
4750
4750 This command tries to fix the repository status after an
4751 This command tries to fix the repository status after an
4751 interrupted operation. It should only be necessary when Mercurial
4752 interrupted operation. It should only be necessary when Mercurial
4752 suggests it.
4753 suggests it.
4753
4754
4754 Returns 0 if successful, 1 if nothing to recover or verify fails.
4755 Returns 0 if successful, 1 if nothing to recover or verify fails.
4755 """
4756 """
4756 if repo.recover():
4757 if repo.recover():
4757 return hg.verify(repo)
4758 return hg.verify(repo)
4758 return 1
4759 return 1
4759
4760
4760 @command('^remove|rm',
4761 @command('^remove|rm',
4761 [('A', 'after', None, _('record delete for missing files')),
4762 [('A', 'after', None, _('record delete for missing files')),
4762 ('f', 'force', None,
4763 ('f', 'force', None,
4763 _('remove (and delete) file even if added or modified')),
4764 _('remove (and delete) file even if added or modified')),
4764 ] + walkopts,
4765 ] + walkopts,
4765 _('[OPTION]... FILE...'))
4766 _('[OPTION]... FILE...'))
4766 def remove(ui, repo, *pats, **opts):
4767 def remove(ui, repo, *pats, **opts):
4767 """remove the specified files on the next commit
4768 """remove the specified files on the next commit
4768
4769
4769 Schedule the indicated files for removal from the current branch.
4770 Schedule the indicated files for removal from the current branch.
4770
4771
4771 This command schedules the files to be removed at the next commit.
4772 This command schedules the files to be removed at the next commit.
4772 To undo a remove before that, see :hg:`revert`. To undo added
4773 To undo a remove before that, see :hg:`revert`. To undo added
4773 files, see :hg:`forget`.
4774 files, see :hg:`forget`.
4774
4775
4775 .. container:: verbose
4776 .. container:: verbose
4776
4777
4777 -A/--after can be used to remove only files that have already
4778 -A/--after can be used to remove only files that have already
4778 been deleted, -f/--force can be used to force deletion, and -Af
4779 been deleted, -f/--force can be used to force deletion, and -Af
4779 can be used to remove files from the next revision without
4780 can be used to remove files from the next revision without
4780 deleting them from the working directory.
4781 deleting them from the working directory.
4781
4782
4782 The following table details the behavior of remove for different
4783 The following table details the behavior of remove for different
4783 file states (columns) and option combinations (rows). The file
4784 file states (columns) and option combinations (rows). The file
4784 states are Added [A], Clean [C], Modified [M] and Missing [!]
4785 states are Added [A], Clean [C], Modified [M] and Missing [!]
4785 (as reported by :hg:`status`). The actions are Warn, Remove
4786 (as reported by :hg:`status`). The actions are Warn, Remove
4786 (from branch) and Delete (from disk):
4787 (from branch) and Delete (from disk):
4787
4788
4788 ========= == == == ==
4789 ========= == == == ==
4789 opt/state A C M !
4790 opt/state A C M !
4790 ========= == == == ==
4791 ========= == == == ==
4791 none W RD W R
4792 none W RD W R
4792 -f R RD RD R
4793 -f R RD RD R
4793 -A W W W R
4794 -A W W W R
4794 -Af R R R R
4795 -Af R R R R
4795 ========= == == == ==
4796 ========= == == == ==
4796
4797
4797 Note that remove never deletes files in Added [A] state from the
4798 Note that remove never deletes files in Added [A] state from the
4798 working directory, not even if option --force is specified.
4799 working directory, not even if option --force is specified.
4799
4800
4800 Returns 0 on success, 1 if any warnings encountered.
4801 Returns 0 on success, 1 if any warnings encountered.
4801 """
4802 """
4802
4803
4803 ret = 0
4804 ret = 0
4804 after, force = opts.get('after'), opts.get('force')
4805 after, force = opts.get('after'), opts.get('force')
4805 if not pats and not after:
4806 if not pats and not after:
4806 raise util.Abort(_('no files specified'))
4807 raise util.Abort(_('no files specified'))
4807
4808
4808 m = scmutil.match(repo[None], pats, opts)
4809 m = scmutil.match(repo[None], pats, opts)
4809 s = repo.status(match=m, clean=True)
4810 s = repo.status(match=m, clean=True)
4810 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4811 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
4811
4812
4812 # warn about failure to delete explicit files/dirs
4813 # warn about failure to delete explicit files/dirs
4813 wctx = repo[None]
4814 wctx = repo[None]
4814 for f in m.files():
4815 for f in m.files():
4815 if f in repo.dirstate or f in wctx.dirs():
4816 if f in repo.dirstate or f in wctx.dirs():
4816 continue
4817 continue
4817 if os.path.exists(m.rel(f)):
4818 if os.path.exists(m.rel(f)):
4818 if os.path.isdir(m.rel(f)):
4819 if os.path.isdir(m.rel(f)):
4819 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4820 ui.warn(_('not removing %s: no tracked files\n') % m.rel(f))
4820 else:
4821 else:
4821 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4822 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
4822 # missing files will generate a warning elsewhere
4823 # missing files will generate a warning elsewhere
4823 ret = 1
4824 ret = 1
4824
4825
4825 if force:
4826 if force:
4826 list = modified + deleted + clean + added
4827 list = modified + deleted + clean + added
4827 elif after:
4828 elif after:
4828 list = deleted
4829 list = deleted
4829 for f in modified + added + clean:
4830 for f in modified + added + clean:
4830 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4831 ui.warn(_('not removing %s: file still exists\n') % m.rel(f))
4831 ret = 1
4832 ret = 1
4832 else:
4833 else:
4833 list = deleted + clean
4834 list = deleted + clean
4834 for f in modified:
4835 for f in modified:
4835 ui.warn(_('not removing %s: file is modified (use -f'
4836 ui.warn(_('not removing %s: file is modified (use -f'
4836 ' to force removal)\n') % m.rel(f))
4837 ' to force removal)\n') % m.rel(f))
4837 ret = 1
4838 ret = 1
4838 for f in added:
4839 for f in added:
4839 ui.warn(_('not removing %s: file has been marked for add'
4840 ui.warn(_('not removing %s: file has been marked for add'
4840 ' (use forget to undo)\n') % m.rel(f))
4841 ' (use forget to undo)\n') % m.rel(f))
4841 ret = 1
4842 ret = 1
4842
4843
4843 for f in sorted(list):
4844 for f in sorted(list):
4844 if ui.verbose or not m.exact(f):
4845 if ui.verbose or not m.exact(f):
4845 ui.status(_('removing %s\n') % m.rel(f))
4846 ui.status(_('removing %s\n') % m.rel(f))
4846
4847
4847 wlock = repo.wlock()
4848 wlock = repo.wlock()
4848 try:
4849 try:
4849 if not after:
4850 if not after:
4850 for f in list:
4851 for f in list:
4851 if f in added:
4852 if f in added:
4852 continue # we never unlink added files on remove
4853 continue # we never unlink added files on remove
4853 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4854 util.unlinkpath(repo.wjoin(f), ignoremissing=True)
4854 repo[None].forget(list)
4855 repo[None].forget(list)
4855 finally:
4856 finally:
4856 wlock.release()
4857 wlock.release()
4857
4858
4858 return ret
4859 return ret
4859
4860
4860 @command('rename|move|mv',
4861 @command('rename|move|mv',
4861 [('A', 'after', None, _('record a rename that has already occurred')),
4862 [('A', 'after', None, _('record a rename that has already occurred')),
4862 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4863 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4863 ] + walkopts + dryrunopts,
4864 ] + walkopts + dryrunopts,
4864 _('[OPTION]... SOURCE... DEST'))
4865 _('[OPTION]... SOURCE... DEST'))
4865 def rename(ui, repo, *pats, **opts):
4866 def rename(ui, repo, *pats, **opts):
4866 """rename files; equivalent of copy + remove
4867 """rename files; equivalent of copy + remove
4867
4868
4868 Mark dest as copies of sources; mark sources for deletion. If dest
4869 Mark dest as copies of sources; mark sources for deletion. If dest
4869 is a directory, copies are put in that directory. If dest is a
4870 is a directory, copies are put in that directory. If dest is a
4870 file, there can only be one source.
4871 file, there can only be one source.
4871
4872
4872 By default, this command copies the contents of files as they
4873 By default, this command copies the contents of files as they
4873 exist in the working directory. If invoked with -A/--after, the
4874 exist in the working directory. If invoked with -A/--after, the
4874 operation is recorded, but no copying is performed.
4875 operation is recorded, but no copying is performed.
4875
4876
4876 This command takes effect at the next commit. To undo a rename
4877 This command takes effect at the next commit. To undo a rename
4877 before that, see :hg:`revert`.
4878 before that, see :hg:`revert`.
4878
4879
4879 Returns 0 on success, 1 if errors are encountered.
4880 Returns 0 on success, 1 if errors are encountered.
4880 """
4881 """
4881 wlock = repo.wlock(False)
4882 wlock = repo.wlock(False)
4882 try:
4883 try:
4883 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4884 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4884 finally:
4885 finally:
4885 wlock.release()
4886 wlock.release()
4886
4887
4887 @command('resolve',
4888 @command('resolve',
4888 [('a', 'all', None, _('select all unresolved files')),
4889 [('a', 'all', None, _('select all unresolved files')),
4889 ('l', 'list', None, _('list state of files needing merge')),
4890 ('l', 'list', None, _('list state of files needing merge')),
4890 ('m', 'mark', None, _('mark files as resolved')),
4891 ('m', 'mark', None, _('mark files as resolved')),
4891 ('u', 'unmark', None, _('mark files as unresolved')),
4892 ('u', 'unmark', None, _('mark files as unresolved')),
4892 ('n', 'no-status', None, _('hide status prefix'))]
4893 ('n', 'no-status', None, _('hide status prefix'))]
4893 + mergetoolopts + walkopts,
4894 + mergetoolopts + walkopts,
4894 _('[OPTION]... [FILE]...'))
4895 _('[OPTION]... [FILE]...'))
4895 def resolve(ui, repo, *pats, **opts):
4896 def resolve(ui, repo, *pats, **opts):
4896 """redo merges or set/view the merge status of files
4897 """redo merges or set/view the merge status of files
4897
4898
4898 Merges with unresolved conflicts are often the result of
4899 Merges with unresolved conflicts are often the result of
4899 non-interactive merging using the ``internal:merge`` configuration
4900 non-interactive merging using the ``internal:merge`` configuration
4900 setting, or a command-line merge tool like ``diff3``. The resolve
4901 setting, or a command-line merge tool like ``diff3``. The resolve
4901 command is used to manage the files involved in a merge, after
4902 command is used to manage the files involved in a merge, after
4902 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4903 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4903 working directory must have two parents). See :hg:`help
4904 working directory must have two parents). See :hg:`help
4904 merge-tools` for information on configuring merge tools.
4905 merge-tools` for information on configuring merge tools.
4905
4906
4906 The resolve command can be used in the following ways:
4907 The resolve command can be used in the following ways:
4907
4908
4908 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4909 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4909 files, discarding any previous merge attempts. Re-merging is not
4910 files, discarding any previous merge attempts. Re-merging is not
4910 performed for files already marked as resolved. Use ``--all/-a``
4911 performed for files already marked as resolved. Use ``--all/-a``
4911 to select all unresolved files. ``--tool`` can be used to specify
4912 to select all unresolved files. ``--tool`` can be used to specify
4912 the merge tool used for the given files. It overrides the HGMERGE
4913 the merge tool used for the given files. It overrides the HGMERGE
4913 environment variable and your configuration files. Previous file
4914 environment variable and your configuration files. Previous file
4914 contents are saved with a ``.orig`` suffix.
4915 contents are saved with a ``.orig`` suffix.
4915
4916
4916 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4917 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4917 (e.g. after having manually fixed-up the files). The default is
4918 (e.g. after having manually fixed-up the files). The default is
4918 to mark all unresolved files.
4919 to mark all unresolved files.
4919
4920
4920 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4921 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4921 default is to mark all resolved files.
4922 default is to mark all resolved files.
4922
4923
4923 - :hg:`resolve -l`: list files which had or still have conflicts.
4924 - :hg:`resolve -l`: list files which had or still have conflicts.
4924 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4925 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4925
4926
4926 Note that Mercurial will not let you commit files with unresolved
4927 Note that Mercurial will not let you commit files with unresolved
4927 merge conflicts. You must use :hg:`resolve -m ...` before you can
4928 merge conflicts. You must use :hg:`resolve -m ...` before you can
4928 commit after a conflicting merge.
4929 commit after a conflicting merge.
4929
4930
4930 Returns 0 on success, 1 if any files fail a resolve attempt.
4931 Returns 0 on success, 1 if any files fail a resolve attempt.
4931 """
4932 """
4932
4933
4933 all, mark, unmark, show, nostatus = \
4934 all, mark, unmark, show, nostatus = \
4934 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4935 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4935
4936
4936 if (show and (mark or unmark)) or (mark and unmark):
4937 if (show and (mark or unmark)) or (mark and unmark):
4937 raise util.Abort(_("too many options specified"))
4938 raise util.Abort(_("too many options specified"))
4938 if pats and all:
4939 if pats and all:
4939 raise util.Abort(_("can't specify --all and patterns"))
4940 raise util.Abort(_("can't specify --all and patterns"))
4940 if not (all or pats or show or mark or unmark):
4941 if not (all or pats or show or mark or unmark):
4941 raise util.Abort(_('no files or directories specified; '
4942 raise util.Abort(_('no files or directories specified; '
4942 'use --all to remerge all files'))
4943 'use --all to remerge all files'))
4943
4944
4944 ms = mergemod.mergestate(repo)
4945 ms = mergemod.mergestate(repo)
4945
4946
4946 if not ms.active() and not show:
4947 if not ms.active() and not show:
4947 raise util.Abort(_('resolve command not applicable when not merging'))
4948 raise util.Abort(_('resolve command not applicable when not merging'))
4948
4949
4949 m = scmutil.match(repo[None], pats, opts)
4950 m = scmutil.match(repo[None], pats, opts)
4950 ret = 0
4951 ret = 0
4951
4952
4952 didwork = False
4953 didwork = False
4953 for f in ms:
4954 for f in ms:
4954 if not m(f):
4955 if not m(f):
4955 continue
4956 continue
4956
4957
4957 didwork = True
4958 didwork = True
4958
4959
4959 if show:
4960 if show:
4960 if nostatus:
4961 if nostatus:
4961 ui.write("%s\n" % f)
4962 ui.write("%s\n" % f)
4962 else:
4963 else:
4963 ui.write("%s %s\n" % (ms[f].upper(), f),
4964 ui.write("%s %s\n" % (ms[f].upper(), f),
4964 label='resolve.' +
4965 label='resolve.' +
4965 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4966 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4966 elif mark:
4967 elif mark:
4967 ms.mark(f, "r")
4968 ms.mark(f, "r")
4968 elif unmark:
4969 elif unmark:
4969 ms.mark(f, "u")
4970 ms.mark(f, "u")
4970 else:
4971 else:
4971 wctx = repo[None]
4972 wctx = repo[None]
4972
4973
4973 # backup pre-resolve (merge uses .orig for its own purposes)
4974 # backup pre-resolve (merge uses .orig for its own purposes)
4974 a = repo.wjoin(f)
4975 a = repo.wjoin(f)
4975 util.copyfile(a, a + ".resolve")
4976 util.copyfile(a, a + ".resolve")
4976
4977
4977 try:
4978 try:
4978 # resolve file
4979 # resolve file
4979 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4980 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''),
4980 'resolve')
4981 'resolve')
4981 if ms.resolve(f, wctx):
4982 if ms.resolve(f, wctx):
4982 ret = 1
4983 ret = 1
4983 finally:
4984 finally:
4984 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4985 ui.setconfig('ui', 'forcemerge', '', 'resolve')
4985 ms.commit()
4986 ms.commit()
4986
4987
4987 # replace filemerge's .orig file with our resolve file
4988 # replace filemerge's .orig file with our resolve file
4988 util.rename(a + ".resolve", a + ".orig")
4989 util.rename(a + ".resolve", a + ".orig")
4989
4990
4990 ms.commit()
4991 ms.commit()
4991
4992
4992 if not didwork and pats:
4993 if not didwork and pats:
4993 ui.warn(_("arguments do not match paths that need resolved\n"))
4994 ui.warn(_("arguments do not match paths that need resolved\n"))
4994
4995
4995 # Nudge users into finishing an unfinished operation. We don't print
4996 # Nudge users into finishing an unfinished operation. We don't print
4996 # this with the list/show operation because we want list/show to remain
4997 # this with the list/show operation because we want list/show to remain
4997 # machine readable.
4998 # machine readable.
4998 if not list(ms.unresolved()) and not show:
4999 if not list(ms.unresolved()) and not show:
4999 ui.status(_('no more unresolved files\n'))
5000 ui.status(_('no more unresolved files\n'))
5000
5001
5001 return ret
5002 return ret
5002
5003
5003 @command('revert',
5004 @command('revert',
5004 [('a', 'all', None, _('revert all changes when no arguments given')),
5005 [('a', 'all', None, _('revert all changes when no arguments given')),
5005 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5006 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5006 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5007 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5007 ('C', 'no-backup', None, _('do not save backup copies of files')),
5008 ('C', 'no-backup', None, _('do not save backup copies of files')),
5008 ] + walkopts + dryrunopts,
5009 ] + walkopts + dryrunopts,
5009 _('[OPTION]... [-r REV] [NAME]...'))
5010 _('[OPTION]... [-r REV] [NAME]...'))
5010 def revert(ui, repo, *pats, **opts):
5011 def revert(ui, repo, *pats, **opts):
5011 """restore files to their checkout state
5012 """restore files to their checkout state
5012
5013
5013 .. note::
5014 .. note::
5014
5015
5015 To check out earlier revisions, you should use :hg:`update REV`.
5016 To check out earlier revisions, you should use :hg:`update REV`.
5016 To cancel an uncommitted merge (and lose your changes),
5017 To cancel an uncommitted merge (and lose your changes),
5017 use :hg:`update --clean .`.
5018 use :hg:`update --clean .`.
5018
5019
5019 With no revision specified, revert the specified files or directories
5020 With no revision specified, revert the specified files or directories
5020 to the contents they had in the parent of the working directory.
5021 to the contents they had in the parent of the working directory.
5021 This restores the contents of files to an unmodified
5022 This restores the contents of files to an unmodified
5022 state and unschedules adds, removes, copies, and renames. If the
5023 state and unschedules adds, removes, copies, and renames. If the
5023 working directory has two parents, you must explicitly specify a
5024 working directory has two parents, you must explicitly specify a
5024 revision.
5025 revision.
5025
5026
5026 Using the -r/--rev or -d/--date options, revert the given files or
5027 Using the -r/--rev or -d/--date options, revert the given files or
5027 directories to their states as of a specific revision. Because
5028 directories to their states as of a specific revision. Because
5028 revert does not change the working directory parents, this will
5029 revert does not change the working directory parents, this will
5029 cause these files to appear modified. This can be helpful to "back
5030 cause these files to appear modified. This can be helpful to "back
5030 out" some or all of an earlier change. See :hg:`backout` for a
5031 out" some or all of an earlier change. See :hg:`backout` for a
5031 related method.
5032 related method.
5032
5033
5033 Modified files are saved with a .orig suffix before reverting.
5034 Modified files are saved with a .orig suffix before reverting.
5034 To disable these backups, use --no-backup.
5035 To disable these backups, use --no-backup.
5035
5036
5036 See :hg:`help dates` for a list of formats valid for -d/--date.
5037 See :hg:`help dates` for a list of formats valid for -d/--date.
5037
5038
5038 Returns 0 on success.
5039 Returns 0 on success.
5039 """
5040 """
5040
5041
5041 if opts.get("date"):
5042 if opts.get("date"):
5042 if opts.get("rev"):
5043 if opts.get("rev"):
5043 raise util.Abort(_("you can't specify a revision and a date"))
5044 raise util.Abort(_("you can't specify a revision and a date"))
5044 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5045 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5045
5046
5046 parent, p2 = repo.dirstate.parents()
5047 parent, p2 = repo.dirstate.parents()
5047 if not opts.get('rev') and p2 != nullid:
5048 if not opts.get('rev') and p2 != nullid:
5048 # revert after merge is a trap for new users (issue2915)
5049 # revert after merge is a trap for new users (issue2915)
5049 raise util.Abort(_('uncommitted merge with no revision specified'),
5050 raise util.Abort(_('uncommitted merge with no revision specified'),
5050 hint=_('use "hg update" or see "hg help revert"'))
5051 hint=_('use "hg update" or see "hg help revert"'))
5051
5052
5052 ctx = scmutil.revsingle(repo, opts.get('rev'))
5053 ctx = scmutil.revsingle(repo, opts.get('rev'))
5053
5054
5054 if not pats and not opts.get('all'):
5055 if not pats and not opts.get('all'):
5055 msg = _("no files or directories specified")
5056 msg = _("no files or directories specified")
5056 if p2 != nullid:
5057 if p2 != nullid:
5057 hint = _("uncommitted merge, use --all to discard all changes,"
5058 hint = _("uncommitted merge, use --all to discard all changes,"
5058 " or 'hg update -C .' to abort the merge")
5059 " or 'hg update -C .' to abort the merge")
5059 raise util.Abort(msg, hint=hint)
5060 raise util.Abort(msg, hint=hint)
5060 dirty = util.any(repo.status())
5061 dirty = util.any(repo.status())
5061 node = ctx.node()
5062 node = ctx.node()
5062 if node != parent:
5063 if node != parent:
5063 if dirty:
5064 if dirty:
5064 hint = _("uncommitted changes, use --all to discard all"
5065 hint = _("uncommitted changes, use --all to discard all"
5065 " changes, or 'hg update %s' to update") % ctx.rev()
5066 " changes, or 'hg update %s' to update") % ctx.rev()
5066 else:
5067 else:
5067 hint = _("use --all to revert all files,"
5068 hint = _("use --all to revert all files,"
5068 " or 'hg update %s' to update") % ctx.rev()
5069 " or 'hg update %s' to update") % ctx.rev()
5069 elif dirty:
5070 elif dirty:
5070 hint = _("uncommitted changes, use --all to discard all changes")
5071 hint = _("uncommitted changes, use --all to discard all changes")
5071 else:
5072 else:
5072 hint = _("use --all to revert all files")
5073 hint = _("use --all to revert all files")
5073 raise util.Abort(msg, hint=hint)
5074 raise util.Abort(msg, hint=hint)
5074
5075
5075 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5076 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats, **opts)
5076
5077
5077 @command('rollback', dryrunopts +
5078 @command('rollback', dryrunopts +
5078 [('f', 'force', False, _('ignore safety measures'))])
5079 [('f', 'force', False, _('ignore safety measures'))])
5079 def rollback(ui, repo, **opts):
5080 def rollback(ui, repo, **opts):
5080 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5081 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5081
5082
5082 Please use :hg:`commit --amend` instead of rollback to correct
5083 Please use :hg:`commit --amend` instead of rollback to correct
5083 mistakes in the last commit.
5084 mistakes in the last commit.
5084
5085
5085 This command should be used with care. There is only one level of
5086 This command should be used with care. There is only one level of
5086 rollback, and there is no way to undo a rollback. It will also
5087 rollback, and there is no way to undo a rollback. It will also
5087 restore the dirstate at the time of the last transaction, losing
5088 restore the dirstate at the time of the last transaction, losing
5088 any dirstate changes since that time. This command does not alter
5089 any dirstate changes since that time. This command does not alter
5089 the working directory.
5090 the working directory.
5090
5091
5091 Transactions are used to encapsulate the effects of all commands
5092 Transactions are used to encapsulate the effects of all commands
5092 that create new changesets or propagate existing changesets into a
5093 that create new changesets or propagate existing changesets into a
5093 repository.
5094 repository.
5094
5095
5095 .. container:: verbose
5096 .. container:: verbose
5096
5097
5097 For example, the following commands are transactional, and their
5098 For example, the following commands are transactional, and their
5098 effects can be rolled back:
5099 effects can be rolled back:
5099
5100
5100 - commit
5101 - commit
5101 - import
5102 - import
5102 - pull
5103 - pull
5103 - push (with this repository as the destination)
5104 - push (with this repository as the destination)
5104 - unbundle
5105 - unbundle
5105
5106
5106 To avoid permanent data loss, rollback will refuse to rollback a
5107 To avoid permanent data loss, rollback will refuse to rollback a
5107 commit transaction if it isn't checked out. Use --force to
5108 commit transaction if it isn't checked out. Use --force to
5108 override this protection.
5109 override this protection.
5109
5110
5110 This command is not intended for use on public repositories. Once
5111 This command is not intended for use on public repositories. Once
5111 changes are visible for pull by other users, rolling a transaction
5112 changes are visible for pull by other users, rolling a transaction
5112 back locally is ineffective (someone else may already have pulled
5113 back locally is ineffective (someone else may already have pulled
5113 the changes). Furthermore, a race is possible with readers of the
5114 the changes). Furthermore, a race is possible with readers of the
5114 repository; for example an in-progress pull from the repository
5115 repository; for example an in-progress pull from the repository
5115 may fail if a rollback is performed.
5116 may fail if a rollback is performed.
5116
5117
5117 Returns 0 on success, 1 if no rollback data is available.
5118 Returns 0 on success, 1 if no rollback data is available.
5118 """
5119 """
5119 return repo.rollback(dryrun=opts.get('dry_run'),
5120 return repo.rollback(dryrun=opts.get('dry_run'),
5120 force=opts.get('force'))
5121 force=opts.get('force'))
5121
5122
5122 @command('root', [])
5123 @command('root', [])
5123 def root(ui, repo):
5124 def root(ui, repo):
5124 """print the root (top) of the current working directory
5125 """print the root (top) of the current working directory
5125
5126
5126 Print the root directory of the current repository.
5127 Print the root directory of the current repository.
5127
5128
5128 Returns 0 on success.
5129 Returns 0 on success.
5129 """
5130 """
5130 ui.write(repo.root + "\n")
5131 ui.write(repo.root + "\n")
5131
5132
5132 @command('^serve',
5133 @command('^serve',
5133 [('A', 'accesslog', '', _('name of access log file to write to'),
5134 [('A', 'accesslog', '', _('name of access log file to write to'),
5134 _('FILE')),
5135 _('FILE')),
5135 ('d', 'daemon', None, _('run server in background')),
5136 ('d', 'daemon', None, _('run server in background')),
5136 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5137 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
5137 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5138 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5138 # use string type, then we can check if something was passed
5139 # use string type, then we can check if something was passed
5139 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5140 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5140 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5141 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5141 _('ADDR')),
5142 _('ADDR')),
5142 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5143 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5143 _('PREFIX')),
5144 _('PREFIX')),
5144 ('n', 'name', '',
5145 ('n', 'name', '',
5145 _('name to show in web pages (default: working directory)'), _('NAME')),
5146 _('name to show in web pages (default: working directory)'), _('NAME')),
5146 ('', 'web-conf', '',
5147 ('', 'web-conf', '',
5147 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5148 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
5148 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5149 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5149 _('FILE')),
5150 _('FILE')),
5150 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5151 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5151 ('', 'stdio', None, _('for remote clients')),
5152 ('', 'stdio', None, _('for remote clients')),
5152 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5153 ('', 'cmdserver', '', _('for remote clients'), _('MODE')),
5153 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5154 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5154 ('', 'style', '', _('template style to use'), _('STYLE')),
5155 ('', 'style', '', _('template style to use'), _('STYLE')),
5155 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5156 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5156 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5157 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
5157 _('[OPTION]...'))
5158 _('[OPTION]...'))
5158 def serve(ui, repo, **opts):
5159 def serve(ui, repo, **opts):
5159 """start stand-alone webserver
5160 """start stand-alone webserver
5160
5161
5161 Start a local HTTP repository browser and pull server. You can use
5162 Start a local HTTP repository browser and pull server. You can use
5162 this for ad-hoc sharing and browsing of repositories. It is
5163 this for ad-hoc sharing and browsing of repositories. It is
5163 recommended to use a real web server to serve a repository for
5164 recommended to use a real web server to serve a repository for
5164 longer periods of time.
5165 longer periods of time.
5165
5166
5166 Please note that the server does not implement access control.
5167 Please note that the server does not implement access control.
5167 This means that, by default, anybody can read from the server and
5168 This means that, by default, anybody can read from the server and
5168 nobody can write to it by default. Set the ``web.allow_push``
5169 nobody can write to it by default. Set the ``web.allow_push``
5169 option to ``*`` to allow everybody to push to the server. You
5170 option to ``*`` to allow everybody to push to the server. You
5170 should use a real web server if you need to authenticate users.
5171 should use a real web server if you need to authenticate users.
5171
5172
5172 By default, the server logs accesses to stdout and errors to
5173 By default, the server logs accesses to stdout and errors to
5173 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5174 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5174 files.
5175 files.
5175
5176
5176 To have the server choose a free port number to listen on, specify
5177 To have the server choose a free port number to listen on, specify
5177 a port number of 0; in this case, the server will print the port
5178 a port number of 0; in this case, the server will print the port
5178 number it uses.
5179 number it uses.
5179
5180
5180 Returns 0 on success.
5181 Returns 0 on success.
5181 """
5182 """
5182
5183
5183 if opts["stdio"] and opts["cmdserver"]:
5184 if opts["stdio"] and opts["cmdserver"]:
5184 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5185 raise util.Abort(_("cannot use --stdio with --cmdserver"))
5185
5186
5186 def checkrepo():
5187 def checkrepo():
5187 if repo is None:
5188 if repo is None:
5188 raise error.RepoError(_("there is no Mercurial repository here"
5189 raise error.RepoError(_("there is no Mercurial repository here"
5189 " (.hg not found)"))
5190 " (.hg not found)"))
5190
5191
5191 if opts["stdio"]:
5192 if opts["stdio"]:
5192 checkrepo()
5193 checkrepo()
5193 s = sshserver.sshserver(ui, repo)
5194 s = sshserver.sshserver(ui, repo)
5194 s.serve_forever()
5195 s.serve_forever()
5195
5196
5196 if opts["cmdserver"]:
5197 if opts["cmdserver"]:
5197 s = commandserver.server(ui, repo, opts["cmdserver"])
5198 s = commandserver.server(ui, repo, opts["cmdserver"])
5198 return s.serve()
5199 return s.serve()
5199
5200
5200 # this way we can check if something was given in the command-line
5201 # this way we can check if something was given in the command-line
5201 if opts.get('port'):
5202 if opts.get('port'):
5202 opts['port'] = util.getport(opts.get('port'))
5203 opts['port'] = util.getport(opts.get('port'))
5203
5204
5204 baseui = repo and repo.baseui or ui
5205 baseui = repo and repo.baseui or ui
5205 optlist = ("name templates style address port prefix ipv6"
5206 optlist = ("name templates style address port prefix ipv6"
5206 " accesslog errorlog certificate encoding")
5207 " accesslog errorlog certificate encoding")
5207 for o in optlist.split():
5208 for o in optlist.split():
5208 val = opts.get(o, '')
5209 val = opts.get(o, '')
5209 if val in (None, ''): # should check against default options instead
5210 if val in (None, ''): # should check against default options instead
5210 continue
5211 continue
5211 baseui.setconfig("web", o, val, 'serve')
5212 baseui.setconfig("web", o, val, 'serve')
5212 if repo and repo.ui != baseui:
5213 if repo and repo.ui != baseui:
5213 repo.ui.setconfig("web", o, val, 'serve')
5214 repo.ui.setconfig("web", o, val, 'serve')
5214
5215
5215 o = opts.get('web_conf') or opts.get('webdir_conf')
5216 o = opts.get('web_conf') or opts.get('webdir_conf')
5216 if not o:
5217 if not o:
5217 if not repo:
5218 if not repo:
5218 raise error.RepoError(_("there is no Mercurial repository"
5219 raise error.RepoError(_("there is no Mercurial repository"
5219 " here (.hg not found)"))
5220 " here (.hg not found)"))
5220 o = repo
5221 o = repo
5221
5222
5222 app = hgweb.hgweb(o, baseui=baseui)
5223 app = hgweb.hgweb(o, baseui=baseui)
5223 service = httpservice(ui, app, opts)
5224 service = httpservice(ui, app, opts)
5224 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5225 cmdutil.service(opts, initfn=service.init, runfn=service.run)
5225
5226
5226 class httpservice(object):
5227 class httpservice(object):
5227 def __init__(self, ui, app, opts):
5228 def __init__(self, ui, app, opts):
5228 self.ui = ui
5229 self.ui = ui
5229 self.app = app
5230 self.app = app
5230 self.opts = opts
5231 self.opts = opts
5231
5232
5232 def init(self):
5233 def init(self):
5233 util.setsignalhandler()
5234 util.setsignalhandler()
5234 self.httpd = hgweb_server.create_server(self.ui, self.app)
5235 self.httpd = hgweb_server.create_server(self.ui, self.app)
5235
5236
5236 if self.opts['port'] and not self.ui.verbose:
5237 if self.opts['port'] and not self.ui.verbose:
5237 return
5238 return
5238
5239
5239 if self.httpd.prefix:
5240 if self.httpd.prefix:
5240 prefix = self.httpd.prefix.strip('/') + '/'
5241 prefix = self.httpd.prefix.strip('/') + '/'
5241 else:
5242 else:
5242 prefix = ''
5243 prefix = ''
5243
5244
5244 port = ':%d' % self.httpd.port
5245 port = ':%d' % self.httpd.port
5245 if port == ':80':
5246 if port == ':80':
5246 port = ''
5247 port = ''
5247
5248
5248 bindaddr = self.httpd.addr
5249 bindaddr = self.httpd.addr
5249 if bindaddr == '0.0.0.0':
5250 if bindaddr == '0.0.0.0':
5250 bindaddr = '*'
5251 bindaddr = '*'
5251 elif ':' in bindaddr: # IPv6
5252 elif ':' in bindaddr: # IPv6
5252 bindaddr = '[%s]' % bindaddr
5253 bindaddr = '[%s]' % bindaddr
5253
5254
5254 fqaddr = self.httpd.fqaddr
5255 fqaddr = self.httpd.fqaddr
5255 if ':' in fqaddr:
5256 if ':' in fqaddr:
5256 fqaddr = '[%s]' % fqaddr
5257 fqaddr = '[%s]' % fqaddr
5257 if self.opts['port']:
5258 if self.opts['port']:
5258 write = self.ui.status
5259 write = self.ui.status
5259 else:
5260 else:
5260 write = self.ui.write
5261 write = self.ui.write
5261 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5262 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
5262 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5263 (fqaddr, port, prefix, bindaddr, self.httpd.port))
5263
5264
5264 def run(self):
5265 def run(self):
5265 self.httpd.serve_forever()
5266 self.httpd.serve_forever()
5266
5267
5267
5268
5268 @command('^status|st',
5269 @command('^status|st',
5269 [('A', 'all', None, _('show status of all files')),
5270 [('A', 'all', None, _('show status of all files')),
5270 ('m', 'modified', None, _('show only modified files')),
5271 ('m', 'modified', None, _('show only modified files')),
5271 ('a', 'added', None, _('show only added files')),
5272 ('a', 'added', None, _('show only added files')),
5272 ('r', 'removed', None, _('show only removed files')),
5273 ('r', 'removed', None, _('show only removed files')),
5273 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5274 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5274 ('c', 'clean', None, _('show only files without changes')),
5275 ('c', 'clean', None, _('show only files without changes')),
5275 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5276 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5276 ('i', 'ignored', None, _('show only ignored files')),
5277 ('i', 'ignored', None, _('show only ignored files')),
5277 ('n', 'no-status', None, _('hide status prefix')),
5278 ('n', 'no-status', None, _('hide status prefix')),
5278 ('C', 'copies', None, _('show source of copied files')),
5279 ('C', 'copies', None, _('show source of copied files')),
5279 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5280 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5280 ('', 'rev', [], _('show difference from revision'), _('REV')),
5281 ('', 'rev', [], _('show difference from revision'), _('REV')),
5281 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5282 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5282 ] + walkopts + subrepoopts,
5283 ] + walkopts + subrepoopts,
5283 _('[OPTION]... [FILE]...'))
5284 _('[OPTION]... [FILE]...'))
5284 def status(ui, repo, *pats, **opts):
5285 def status(ui, repo, *pats, **opts):
5285 """show changed files in the working directory
5286 """show changed files in the working directory
5286
5287
5287 Show status of files in the repository. If names are given, only
5288 Show status of files in the repository. If names are given, only
5288 files that match are shown. Files that are clean or ignored or
5289 files that match are shown. Files that are clean or ignored or
5289 the source of a copy/move operation, are not listed unless
5290 the source of a copy/move operation, are not listed unless
5290 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5291 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5291 Unless options described with "show only ..." are given, the
5292 Unless options described with "show only ..." are given, the
5292 options -mardu are used.
5293 options -mardu are used.
5293
5294
5294 Option -q/--quiet hides untracked (unknown and ignored) files
5295 Option -q/--quiet hides untracked (unknown and ignored) files
5295 unless explicitly requested with -u/--unknown or -i/--ignored.
5296 unless explicitly requested with -u/--unknown or -i/--ignored.
5296
5297
5297 .. note::
5298 .. note::
5298
5299
5299 status may appear to disagree with diff if permissions have
5300 status may appear to disagree with diff if permissions have
5300 changed or a merge has occurred. The standard diff format does
5301 changed or a merge has occurred. The standard diff format does
5301 not report permission changes and diff only reports changes
5302 not report permission changes and diff only reports changes
5302 relative to one merge parent.
5303 relative to one merge parent.
5303
5304
5304 If one revision is given, it is used as the base revision.
5305 If one revision is given, it is used as the base revision.
5305 If two revisions are given, the differences between them are
5306 If two revisions are given, the differences between them are
5306 shown. The --change option can also be used as a shortcut to list
5307 shown. The --change option can also be used as a shortcut to list
5307 the changed files of a revision from its first parent.
5308 the changed files of a revision from its first parent.
5308
5309
5309 The codes used to show the status of files are::
5310 The codes used to show the status of files are::
5310
5311
5311 M = modified
5312 M = modified
5312 A = added
5313 A = added
5313 R = removed
5314 R = removed
5314 C = clean
5315 C = clean
5315 ! = missing (deleted by non-hg command, but still tracked)
5316 ! = missing (deleted by non-hg command, but still tracked)
5316 ? = not tracked
5317 ? = not tracked
5317 I = ignored
5318 I = ignored
5318 = origin of the previous file (with --copies)
5319 = origin of the previous file (with --copies)
5319
5320
5320 .. container:: verbose
5321 .. container:: verbose
5321
5322
5322 Examples:
5323 Examples:
5323
5324
5324 - show changes in the working directory relative to a
5325 - show changes in the working directory relative to a
5325 changeset::
5326 changeset::
5326
5327
5327 hg status --rev 9353
5328 hg status --rev 9353
5328
5329
5329 - show all changes including copies in an existing changeset::
5330 - show all changes including copies in an existing changeset::
5330
5331
5331 hg status --copies --change 9353
5332 hg status --copies --change 9353
5332
5333
5333 - get a NUL separated list of added files, suitable for xargs::
5334 - get a NUL separated list of added files, suitable for xargs::
5334
5335
5335 hg status -an0
5336 hg status -an0
5336
5337
5337 Returns 0 on success.
5338 Returns 0 on success.
5338 """
5339 """
5339
5340
5340 revs = opts.get('rev')
5341 revs = opts.get('rev')
5341 change = opts.get('change')
5342 change = opts.get('change')
5342
5343
5343 if revs and change:
5344 if revs and change:
5344 msg = _('cannot specify --rev and --change at the same time')
5345 msg = _('cannot specify --rev and --change at the same time')
5345 raise util.Abort(msg)
5346 raise util.Abort(msg)
5346 elif change:
5347 elif change:
5347 node2 = scmutil.revsingle(repo, change, None).node()
5348 node2 = scmutil.revsingle(repo, change, None).node()
5348 node1 = repo[node2].p1().node()
5349 node1 = repo[node2].p1().node()
5349 else:
5350 else:
5350 node1, node2 = scmutil.revpair(repo, revs)
5351 node1, node2 = scmutil.revpair(repo, revs)
5351
5352
5352 cwd = (pats and repo.getcwd()) or ''
5353 cwd = (pats and repo.getcwd()) or ''
5353 end = opts.get('print0') and '\0' or '\n'
5354 end = opts.get('print0') and '\0' or '\n'
5354 copy = {}
5355 copy = {}
5355 states = 'modified added removed deleted unknown ignored clean'.split()
5356 states = 'modified added removed deleted unknown ignored clean'.split()
5356 show = [k for k in states if opts.get(k)]
5357 show = [k for k in states if opts.get(k)]
5357 if opts.get('all'):
5358 if opts.get('all'):
5358 show += ui.quiet and (states[:4] + ['clean']) or states
5359 show += ui.quiet and (states[:4] + ['clean']) or states
5359 if not show:
5360 if not show:
5360 show = ui.quiet and states[:4] or states[:5]
5361 show = ui.quiet and states[:4] or states[:5]
5361
5362
5362 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5363 stat = repo.status(node1, node2, scmutil.match(repo[node2], pats, opts),
5363 'ignored' in show, 'clean' in show, 'unknown' in show,
5364 'ignored' in show, 'clean' in show, 'unknown' in show,
5364 opts.get('subrepos'))
5365 opts.get('subrepos'))
5365 changestates = zip(states, 'MAR!?IC', stat)
5366 changestates = zip(states, 'MAR!?IC', stat)
5366
5367
5367 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5368 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
5368 copy = copies.pathcopies(repo[node1], repo[node2])
5369 copy = copies.pathcopies(repo[node1], repo[node2])
5369
5370
5370 fm = ui.formatter('status', opts)
5371 fm = ui.formatter('status', opts)
5371 fmt = '%s' + end
5372 fmt = '%s' + end
5372 showchar = not opts.get('no_status')
5373 showchar = not opts.get('no_status')
5373
5374
5374 for state, char, files in changestates:
5375 for state, char, files in changestates:
5375 if state in show:
5376 if state in show:
5376 label = 'status.' + state
5377 label = 'status.' + state
5377 for f in files:
5378 for f in files:
5378 fm.startitem()
5379 fm.startitem()
5379 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5380 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5380 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5381 fm.write('path', fmt, repo.pathto(f, cwd), label=label)
5381 if f in copy:
5382 if f in copy:
5382 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5383 fm.write("copy", ' %s' + end, repo.pathto(copy[f], cwd),
5383 label='status.copied')
5384 label='status.copied')
5384 fm.end()
5385 fm.end()
5385
5386
5386 @command('^summary|sum',
5387 @command('^summary|sum',
5387 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5388 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
5388 def summary(ui, repo, **opts):
5389 def summary(ui, repo, **opts):
5389 """summarize working directory state
5390 """summarize working directory state
5390
5391
5391 This generates a brief summary of the working directory state,
5392 This generates a brief summary of the working directory state,
5392 including parents, branch, commit status, and available updates.
5393 including parents, branch, commit status, and available updates.
5393
5394
5394 With the --remote option, this will check the default paths for
5395 With the --remote option, this will check the default paths for
5395 incoming and outgoing changes. This can be time-consuming.
5396 incoming and outgoing changes. This can be time-consuming.
5396
5397
5397 Returns 0 on success.
5398 Returns 0 on success.
5398 """
5399 """
5399
5400
5400 ctx = repo[None]
5401 ctx = repo[None]
5401 parents = ctx.parents()
5402 parents = ctx.parents()
5402 pnode = parents[0].node()
5403 pnode = parents[0].node()
5403 marks = []
5404 marks = []
5404
5405
5405 for p in parents:
5406 for p in parents:
5406 # label with log.changeset (instead of log.parent) since this
5407 # label with log.changeset (instead of log.parent) since this
5407 # shows a working directory parent *changeset*:
5408 # shows a working directory parent *changeset*:
5408 # i18n: column positioning for "hg summary"
5409 # i18n: column positioning for "hg summary"
5409 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5410 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
5410 label='log.changeset changeset.%s' % p.phasestr())
5411 label='log.changeset changeset.%s' % p.phasestr())
5411 ui.write(' '.join(p.tags()), label='log.tag')
5412 ui.write(' '.join(p.tags()), label='log.tag')
5412 if p.bookmarks():
5413 if p.bookmarks():
5413 marks.extend(p.bookmarks())
5414 marks.extend(p.bookmarks())
5414 if p.rev() == -1:
5415 if p.rev() == -1:
5415 if not len(repo):
5416 if not len(repo):
5416 ui.write(_(' (empty repository)'))
5417 ui.write(_(' (empty repository)'))
5417 else:
5418 else:
5418 ui.write(_(' (no revision checked out)'))
5419 ui.write(_(' (no revision checked out)'))
5419 ui.write('\n')
5420 ui.write('\n')
5420 if p.description():
5421 if p.description():
5421 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5422 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5422 label='log.summary')
5423 label='log.summary')
5423
5424
5424 branch = ctx.branch()
5425 branch = ctx.branch()
5425 bheads = repo.branchheads(branch)
5426 bheads = repo.branchheads(branch)
5426 # i18n: column positioning for "hg summary"
5427 # i18n: column positioning for "hg summary"
5427 m = _('branch: %s\n') % branch
5428 m = _('branch: %s\n') % branch
5428 if branch != 'default':
5429 if branch != 'default':
5429 ui.write(m, label='log.branch')
5430 ui.write(m, label='log.branch')
5430 else:
5431 else:
5431 ui.status(m, label='log.branch')
5432 ui.status(m, label='log.branch')
5432
5433
5433 if marks:
5434 if marks:
5434 current = repo._bookmarkcurrent
5435 current = repo._bookmarkcurrent
5435 # i18n: column positioning for "hg summary"
5436 # i18n: column positioning for "hg summary"
5436 ui.write(_('bookmarks:'), label='log.bookmark')
5437 ui.write(_('bookmarks:'), label='log.bookmark')
5437 if current is not None:
5438 if current is not None:
5438 if current in marks:
5439 if current in marks:
5439 ui.write(' *' + current, label='bookmarks.current')
5440 ui.write(' *' + current, label='bookmarks.current')
5440 marks.remove(current)
5441 marks.remove(current)
5441 else:
5442 else:
5442 ui.write(' [%s]' % current, label='bookmarks.current')
5443 ui.write(' [%s]' % current, label='bookmarks.current')
5443 for m in marks:
5444 for m in marks:
5444 ui.write(' ' + m, label='log.bookmark')
5445 ui.write(' ' + m, label='log.bookmark')
5445 ui.write('\n', label='log.bookmark')
5446 ui.write('\n', label='log.bookmark')
5446
5447
5447 st = list(repo.status(unknown=True))[:6]
5448 st = list(repo.status(unknown=True))[:6]
5448
5449
5449 c = repo.dirstate.copies()
5450 c = repo.dirstate.copies()
5450 copied, renamed = [], []
5451 copied, renamed = [], []
5451 for d, s in c.iteritems():
5452 for d, s in c.iteritems():
5452 if s in st[2]:
5453 if s in st[2]:
5453 st[2].remove(s)
5454 st[2].remove(s)
5454 renamed.append(d)
5455 renamed.append(d)
5455 else:
5456 else:
5456 copied.append(d)
5457 copied.append(d)
5457 if d in st[1]:
5458 if d in st[1]:
5458 st[1].remove(d)
5459 st[1].remove(d)
5459 st.insert(3, renamed)
5460 st.insert(3, renamed)
5460 st.insert(4, copied)
5461 st.insert(4, copied)
5461
5462
5462 ms = mergemod.mergestate(repo)
5463 ms = mergemod.mergestate(repo)
5463 st.append([f for f in ms if ms[f] == 'u'])
5464 st.append([f for f in ms if ms[f] == 'u'])
5464
5465
5465 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5466 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5466 st.append(subs)
5467 st.append(subs)
5467
5468
5468 labels = [ui.label(_('%d modified'), 'status.modified'),
5469 labels = [ui.label(_('%d modified'), 'status.modified'),
5469 ui.label(_('%d added'), 'status.added'),
5470 ui.label(_('%d added'), 'status.added'),
5470 ui.label(_('%d removed'), 'status.removed'),
5471 ui.label(_('%d removed'), 'status.removed'),
5471 ui.label(_('%d renamed'), 'status.copied'),
5472 ui.label(_('%d renamed'), 'status.copied'),
5472 ui.label(_('%d copied'), 'status.copied'),
5473 ui.label(_('%d copied'), 'status.copied'),
5473 ui.label(_('%d deleted'), 'status.deleted'),
5474 ui.label(_('%d deleted'), 'status.deleted'),
5474 ui.label(_('%d unknown'), 'status.unknown'),
5475 ui.label(_('%d unknown'), 'status.unknown'),
5475 ui.label(_('%d ignored'), 'status.ignored'),
5476 ui.label(_('%d ignored'), 'status.ignored'),
5476 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5477 ui.label(_('%d unresolved'), 'resolve.unresolved'),
5477 ui.label(_('%d subrepos'), 'status.modified')]
5478 ui.label(_('%d subrepos'), 'status.modified')]
5478 t = []
5479 t = []
5479 for s, l in zip(st, labels):
5480 for s, l in zip(st, labels):
5480 if s:
5481 if s:
5481 t.append(l % len(s))
5482 t.append(l % len(s))
5482
5483
5483 t = ', '.join(t)
5484 t = ', '.join(t)
5484 cleanworkdir = False
5485 cleanworkdir = False
5485
5486
5486 if repo.vfs.exists('updatestate'):
5487 if repo.vfs.exists('updatestate'):
5487 t += _(' (interrupted update)')
5488 t += _(' (interrupted update)')
5488 elif len(parents) > 1:
5489 elif len(parents) > 1:
5489 t += _(' (merge)')
5490 t += _(' (merge)')
5490 elif branch != parents[0].branch():
5491 elif branch != parents[0].branch():
5491 t += _(' (new branch)')
5492 t += _(' (new branch)')
5492 elif (parents[0].closesbranch() and
5493 elif (parents[0].closesbranch() and
5493 pnode in repo.branchheads(branch, closed=True)):
5494 pnode in repo.branchheads(branch, closed=True)):
5494 t += _(' (head closed)')
5495 t += _(' (head closed)')
5495 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5496 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
5496 t += _(' (clean)')
5497 t += _(' (clean)')
5497 cleanworkdir = True
5498 cleanworkdir = True
5498 elif pnode not in bheads:
5499 elif pnode not in bheads:
5499 t += _(' (new branch head)')
5500 t += _(' (new branch head)')
5500
5501
5501 if cleanworkdir:
5502 if cleanworkdir:
5502 # i18n: column positioning for "hg summary"
5503 # i18n: column positioning for "hg summary"
5503 ui.status(_('commit: %s\n') % t.strip())
5504 ui.status(_('commit: %s\n') % t.strip())
5504 else:
5505 else:
5505 # i18n: column positioning for "hg summary"
5506 # i18n: column positioning for "hg summary"
5506 ui.write(_('commit: %s\n') % t.strip())
5507 ui.write(_('commit: %s\n') % t.strip())
5507
5508
5508 # all ancestors of branch heads - all ancestors of parent = new csets
5509 # all ancestors of branch heads - all ancestors of parent = new csets
5509 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5510 new = len(repo.changelog.findmissing([ctx.node() for ctx in parents],
5510 bheads))
5511 bheads))
5511
5512
5512 if new == 0:
5513 if new == 0:
5513 # i18n: column positioning for "hg summary"
5514 # i18n: column positioning for "hg summary"
5514 ui.status(_('update: (current)\n'))
5515 ui.status(_('update: (current)\n'))
5515 elif pnode not in bheads:
5516 elif pnode not in bheads:
5516 # i18n: column positioning for "hg summary"
5517 # i18n: column positioning for "hg summary"
5517 ui.write(_('update: %d new changesets (update)\n') % new)
5518 ui.write(_('update: %d new changesets (update)\n') % new)
5518 else:
5519 else:
5519 # i18n: column positioning for "hg summary"
5520 # i18n: column positioning for "hg summary"
5520 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5521 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5521 (new, len(bheads)))
5522 (new, len(bheads)))
5522
5523
5523 cmdutil.summaryhooks(ui, repo)
5524 cmdutil.summaryhooks(ui, repo)
5524
5525
5525 if opts.get('remote'):
5526 if opts.get('remote'):
5526 needsincoming, needsoutgoing = True, True
5527 needsincoming, needsoutgoing = True, True
5527 else:
5528 else:
5528 needsincoming, needsoutgoing = False, False
5529 needsincoming, needsoutgoing = False, False
5529 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5530 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5530 if i:
5531 if i:
5531 needsincoming = True
5532 needsincoming = True
5532 if o:
5533 if o:
5533 needsoutgoing = True
5534 needsoutgoing = True
5534 if not needsincoming and not needsoutgoing:
5535 if not needsincoming and not needsoutgoing:
5535 return
5536 return
5536
5537
5537 def getincoming():
5538 def getincoming():
5538 source, branches = hg.parseurl(ui.expandpath('default'))
5539 source, branches = hg.parseurl(ui.expandpath('default'))
5539 sbranch = branches[0]
5540 sbranch = branches[0]
5540 try:
5541 try:
5541 other = hg.peer(repo, {}, source)
5542 other = hg.peer(repo, {}, source)
5542 except error.RepoError:
5543 except error.RepoError:
5543 if opts.get('remote'):
5544 if opts.get('remote'):
5544 raise
5545 raise
5545 return source, sbranch, None, None, None
5546 return source, sbranch, None, None, None
5546 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5547 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5547 if revs:
5548 if revs:
5548 revs = [other.lookup(rev) for rev in revs]
5549 revs = [other.lookup(rev) for rev in revs]
5549 ui.debug('comparing with %s\n' % util.hidepassword(source))
5550 ui.debug('comparing with %s\n' % util.hidepassword(source))
5550 repo.ui.pushbuffer()
5551 repo.ui.pushbuffer()
5551 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5552 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5552 repo.ui.popbuffer()
5553 repo.ui.popbuffer()
5553 return source, sbranch, other, commoninc, commoninc[1]
5554 return source, sbranch, other, commoninc, commoninc[1]
5554
5555
5555 if needsincoming:
5556 if needsincoming:
5556 source, sbranch, sother, commoninc, incoming = getincoming()
5557 source, sbranch, sother, commoninc, incoming = getincoming()
5557 else:
5558 else:
5558 source = sbranch = sother = commoninc = incoming = None
5559 source = sbranch = sother = commoninc = incoming = None
5559
5560
5560 def getoutgoing():
5561 def getoutgoing():
5561 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5562 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5562 dbranch = branches[0]
5563 dbranch = branches[0]
5563 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5564 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5564 if source != dest:
5565 if source != dest:
5565 try:
5566 try:
5566 dother = hg.peer(repo, {}, dest)
5567 dother = hg.peer(repo, {}, dest)
5567 except error.RepoError:
5568 except error.RepoError:
5568 if opts.get('remote'):
5569 if opts.get('remote'):
5569 raise
5570 raise
5570 return dest, dbranch, None, None
5571 return dest, dbranch, None, None
5571 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5572 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5572 elif sother is None:
5573 elif sother is None:
5573 # there is no explicit destination peer, but source one is invalid
5574 # there is no explicit destination peer, but source one is invalid
5574 return dest, dbranch, None, None
5575 return dest, dbranch, None, None
5575 else:
5576 else:
5576 dother = sother
5577 dother = sother
5577 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5578 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5578 common = None
5579 common = None
5579 else:
5580 else:
5580 common = commoninc
5581 common = commoninc
5581 if revs:
5582 if revs:
5582 revs = [repo.lookup(rev) for rev in revs]
5583 revs = [repo.lookup(rev) for rev in revs]
5583 repo.ui.pushbuffer()
5584 repo.ui.pushbuffer()
5584 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5585 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5585 commoninc=common)
5586 commoninc=common)
5586 repo.ui.popbuffer()
5587 repo.ui.popbuffer()
5587 return dest, dbranch, dother, outgoing
5588 return dest, dbranch, dother, outgoing
5588
5589
5589 if needsoutgoing:
5590 if needsoutgoing:
5590 dest, dbranch, dother, outgoing = getoutgoing()
5591 dest, dbranch, dother, outgoing = getoutgoing()
5591 else:
5592 else:
5592 dest = dbranch = dother = outgoing = None
5593 dest = dbranch = dother = outgoing = None
5593
5594
5594 if opts.get('remote'):
5595 if opts.get('remote'):
5595 t = []
5596 t = []
5596 if incoming:
5597 if incoming:
5597 t.append(_('1 or more incoming'))
5598 t.append(_('1 or more incoming'))
5598 o = outgoing.missing
5599 o = outgoing.missing
5599 if o:
5600 if o:
5600 t.append(_('%d outgoing') % len(o))
5601 t.append(_('%d outgoing') % len(o))
5601 other = dother or sother
5602 other = dother or sother
5602 if 'bookmarks' in other.listkeys('namespaces'):
5603 if 'bookmarks' in other.listkeys('namespaces'):
5603 lmarks = repo.listkeys('bookmarks')
5604 lmarks = repo.listkeys('bookmarks')
5604 rmarks = other.listkeys('bookmarks')
5605 rmarks = other.listkeys('bookmarks')
5605 diff = set(rmarks) - set(lmarks)
5606 diff = set(rmarks) - set(lmarks)
5606 if len(diff) > 0:
5607 if len(diff) > 0:
5607 t.append(_('%d incoming bookmarks') % len(diff))
5608 t.append(_('%d incoming bookmarks') % len(diff))
5608 diff = set(lmarks) - set(rmarks)
5609 diff = set(lmarks) - set(rmarks)
5609 if len(diff) > 0:
5610 if len(diff) > 0:
5610 t.append(_('%d outgoing bookmarks') % len(diff))
5611 t.append(_('%d outgoing bookmarks') % len(diff))
5611
5612
5612 if t:
5613 if t:
5613 # i18n: column positioning for "hg summary"
5614 # i18n: column positioning for "hg summary"
5614 ui.write(_('remote: %s\n') % (', '.join(t)))
5615 ui.write(_('remote: %s\n') % (', '.join(t)))
5615 else:
5616 else:
5616 # i18n: column positioning for "hg summary"
5617 # i18n: column positioning for "hg summary"
5617 ui.status(_('remote: (synced)\n'))
5618 ui.status(_('remote: (synced)\n'))
5618
5619
5619 cmdutil.summaryremotehooks(ui, repo, opts,
5620 cmdutil.summaryremotehooks(ui, repo, opts,
5620 ((source, sbranch, sother, commoninc),
5621 ((source, sbranch, sother, commoninc),
5621 (dest, dbranch, dother, outgoing)))
5622 (dest, dbranch, dother, outgoing)))
5622
5623
5623 @command('tag',
5624 @command('tag',
5624 [('f', 'force', None, _('force tag')),
5625 [('f', 'force', None, _('force tag')),
5625 ('l', 'local', None, _('make the tag local')),
5626 ('l', 'local', None, _('make the tag local')),
5626 ('r', 'rev', '', _('revision to tag'), _('REV')),
5627 ('r', 'rev', '', _('revision to tag'), _('REV')),
5627 ('', 'remove', None, _('remove a tag')),
5628 ('', 'remove', None, _('remove a tag')),
5628 # -l/--local is already there, commitopts cannot be used
5629 # -l/--local is already there, commitopts cannot be used
5629 ('e', 'edit', None, _('edit commit message')),
5630 ('e', 'edit', None, _('edit commit message')),
5630 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5631 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
5631 ] + commitopts2,
5632 ] + commitopts2,
5632 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5633 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
5633 def tag(ui, repo, name1, *names, **opts):
5634 def tag(ui, repo, name1, *names, **opts):
5634 """add one or more tags for the current or given revision
5635 """add one or more tags for the current or given revision
5635
5636
5636 Name a particular revision using <name>.
5637 Name a particular revision using <name>.
5637
5638
5638 Tags are used to name particular revisions of the repository and are
5639 Tags are used to name particular revisions of the repository and are
5639 very useful to compare different revisions, to go back to significant
5640 very useful to compare different revisions, to go back to significant
5640 earlier versions or to mark branch points as releases, etc. Changing
5641 earlier versions or to mark branch points as releases, etc. Changing
5641 an existing tag is normally disallowed; use -f/--force to override.
5642 an existing tag is normally disallowed; use -f/--force to override.
5642
5643
5643 If no revision is given, the parent of the working directory is
5644 If no revision is given, the parent of the working directory is
5644 used.
5645 used.
5645
5646
5646 To facilitate version control, distribution, and merging of tags,
5647 To facilitate version control, distribution, and merging of tags,
5647 they are stored as a file named ".hgtags" which is managed similarly
5648 they are stored as a file named ".hgtags" which is managed similarly
5648 to other project files and can be hand-edited if necessary. This
5649 to other project files and can be hand-edited if necessary. This
5649 also means that tagging creates a new commit. The file
5650 also means that tagging creates a new commit. The file
5650 ".hg/localtags" is used for local tags (not shared among
5651 ".hg/localtags" is used for local tags (not shared among
5651 repositories).
5652 repositories).
5652
5653
5653 Tag commits are usually made at the head of a branch. If the parent
5654 Tag commits are usually made at the head of a branch. If the parent
5654 of the working directory is not a branch head, :hg:`tag` aborts; use
5655 of the working directory is not a branch head, :hg:`tag` aborts; use
5655 -f/--force to force the tag commit to be based on a non-head
5656 -f/--force to force the tag commit to be based on a non-head
5656 changeset.
5657 changeset.
5657
5658
5658 See :hg:`help dates` for a list of formats valid for -d/--date.
5659 See :hg:`help dates` for a list of formats valid for -d/--date.
5659
5660
5660 Since tag names have priority over branch names during revision
5661 Since tag names have priority over branch names during revision
5661 lookup, using an existing branch name as a tag name is discouraged.
5662 lookup, using an existing branch name as a tag name is discouraged.
5662
5663
5663 Returns 0 on success.
5664 Returns 0 on success.
5664 """
5665 """
5665 wlock = lock = None
5666 wlock = lock = None
5666 try:
5667 try:
5667 wlock = repo.wlock()
5668 wlock = repo.wlock()
5668 lock = repo.lock()
5669 lock = repo.lock()
5669 rev_ = "."
5670 rev_ = "."
5670 names = [t.strip() for t in (name1,) + names]
5671 names = [t.strip() for t in (name1,) + names]
5671 if len(names) != len(set(names)):
5672 if len(names) != len(set(names)):
5672 raise util.Abort(_('tag names must be unique'))
5673 raise util.Abort(_('tag names must be unique'))
5673 for n in names:
5674 for n in names:
5674 scmutil.checknewlabel(repo, n, 'tag')
5675 scmutil.checknewlabel(repo, n, 'tag')
5675 if not n:
5676 if not n:
5676 raise util.Abort(_('tag names cannot consist entirely of '
5677 raise util.Abort(_('tag names cannot consist entirely of '
5677 'whitespace'))
5678 'whitespace'))
5678 if opts.get('rev') and opts.get('remove'):
5679 if opts.get('rev') and opts.get('remove'):
5679 raise util.Abort(_("--rev and --remove are incompatible"))
5680 raise util.Abort(_("--rev and --remove are incompatible"))
5680 if opts.get('rev'):
5681 if opts.get('rev'):
5681 rev_ = opts['rev']
5682 rev_ = opts['rev']
5682 message = opts.get('message')
5683 message = opts.get('message')
5683 if opts.get('remove'):
5684 if opts.get('remove'):
5684 expectedtype = opts.get('local') and 'local' or 'global'
5685 expectedtype = opts.get('local') and 'local' or 'global'
5685 for n in names:
5686 for n in names:
5686 if not repo.tagtype(n):
5687 if not repo.tagtype(n):
5687 raise util.Abort(_("tag '%s' does not exist") % n)
5688 raise util.Abort(_("tag '%s' does not exist") % n)
5688 if repo.tagtype(n) != expectedtype:
5689 if repo.tagtype(n) != expectedtype:
5689 if expectedtype == 'global':
5690 if expectedtype == 'global':
5690 raise util.Abort(_("tag '%s' is not a global tag") % n)
5691 raise util.Abort(_("tag '%s' is not a global tag") % n)
5691 else:
5692 else:
5692 raise util.Abort(_("tag '%s' is not a local tag") % n)
5693 raise util.Abort(_("tag '%s' is not a local tag") % n)
5693 rev_ = nullid
5694 rev_ = nullid
5694 if not message:
5695 if not message:
5695 # we don't translate commit messages
5696 # we don't translate commit messages
5696 message = 'Removed tag %s' % ', '.join(names)
5697 message = 'Removed tag %s' % ', '.join(names)
5697 elif not opts.get('force'):
5698 elif not opts.get('force'):
5698 for n in names:
5699 for n in names:
5699 if n in repo.tags():
5700 if n in repo.tags():
5700 raise util.Abort(_("tag '%s' already exists "
5701 raise util.Abort(_("tag '%s' already exists "
5701 "(use -f to force)") % n)
5702 "(use -f to force)") % n)
5702 if not opts.get('local'):
5703 if not opts.get('local'):
5703 p1, p2 = repo.dirstate.parents()
5704 p1, p2 = repo.dirstate.parents()
5704 if p2 != nullid:
5705 if p2 != nullid:
5705 raise util.Abort(_('uncommitted merge'))
5706 raise util.Abort(_('uncommitted merge'))
5706 bheads = repo.branchheads()
5707 bheads = repo.branchheads()
5707 if not opts.get('force') and bheads and p1 not in bheads:
5708 if not opts.get('force') and bheads and p1 not in bheads:
5708 raise util.Abort(_('not at a branch head (use -f to force)'))
5709 raise util.Abort(_('not at a branch head (use -f to force)'))
5709 r = scmutil.revsingle(repo, rev_).node()
5710 r = scmutil.revsingle(repo, rev_).node()
5710
5711
5711 if not message:
5712 if not message:
5712 # we don't translate commit messages
5713 # we don't translate commit messages
5713 message = ('Added tag %s for changeset %s' %
5714 message = ('Added tag %s for changeset %s' %
5714 (', '.join(names), short(r)))
5715 (', '.join(names), short(r)))
5715
5716
5716 date = opts.get('date')
5717 date = opts.get('date')
5717 if date:
5718 if date:
5718 date = util.parsedate(date)
5719 date = util.parsedate(date)
5719
5720
5720 editor = cmdutil.getcommiteditor(**opts)
5721 editor = cmdutil.getcommiteditor(**opts)
5721
5722
5722 # don't allow tagging the null rev
5723 # don't allow tagging the null rev
5723 if (not opts.get('remove') and
5724 if (not opts.get('remove') and
5724 scmutil.revsingle(repo, rev_).rev() == nullrev):
5725 scmutil.revsingle(repo, rev_).rev() == nullrev):
5725 raise util.Abort(_("cannot tag null revision"))
5726 raise util.Abort(_("cannot tag null revision"))
5726
5727
5727 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
5728 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date,
5728 editor=editor)
5729 editor=editor)
5729 finally:
5730 finally:
5730 release(lock, wlock)
5731 release(lock, wlock)
5731
5732
5732 @command('tags', [], '')
5733 @command('tags', [], '')
5733 def tags(ui, repo, **opts):
5734 def tags(ui, repo, **opts):
5734 """list repository tags
5735 """list repository tags
5735
5736
5736 This lists both regular and local tags. When the -v/--verbose
5737 This lists both regular and local tags. When the -v/--verbose
5737 switch is used, a third column "local" is printed for local tags.
5738 switch is used, a third column "local" is printed for local tags.
5738
5739
5739 Returns 0 on success.
5740 Returns 0 on success.
5740 """
5741 """
5741
5742
5742 fm = ui.formatter('tags', opts)
5743 fm = ui.formatter('tags', opts)
5743 hexfunc = ui.debugflag and hex or short
5744 hexfunc = ui.debugflag and hex or short
5744 tagtype = ""
5745 tagtype = ""
5745
5746
5746 for t, n in reversed(repo.tagslist()):
5747 for t, n in reversed(repo.tagslist()):
5747 hn = hexfunc(n)
5748 hn = hexfunc(n)
5748 label = 'tags.normal'
5749 label = 'tags.normal'
5749 tagtype = ''
5750 tagtype = ''
5750 if repo.tagtype(t) == 'local':
5751 if repo.tagtype(t) == 'local':
5751 label = 'tags.local'
5752 label = 'tags.local'
5752 tagtype = 'local'
5753 tagtype = 'local'
5753
5754
5754 fm.startitem()
5755 fm.startitem()
5755 fm.write('tag', '%s', t, label=label)
5756 fm.write('tag', '%s', t, label=label)
5756 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5757 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5757 fm.condwrite(not ui.quiet, 'rev id', fmt,
5758 fm.condwrite(not ui.quiet, 'rev id', fmt,
5758 repo.changelog.rev(n), hn, label=label)
5759 repo.changelog.rev(n), hn, label=label)
5759 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5760 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5760 tagtype, label=label)
5761 tagtype, label=label)
5761 fm.plain('\n')
5762 fm.plain('\n')
5762 fm.end()
5763 fm.end()
5763
5764
5764 @command('tip',
5765 @command('tip',
5765 [('p', 'patch', None, _('show patch')),
5766 [('p', 'patch', None, _('show patch')),
5766 ('g', 'git', None, _('use git extended diff format')),
5767 ('g', 'git', None, _('use git extended diff format')),
5767 ] + templateopts,
5768 ] + templateopts,
5768 _('[-p] [-g]'))
5769 _('[-p] [-g]'))
5769 def tip(ui, repo, **opts):
5770 def tip(ui, repo, **opts):
5770 """show the tip revision (DEPRECATED)
5771 """show the tip revision (DEPRECATED)
5771
5772
5772 The tip revision (usually just called the tip) is the changeset
5773 The tip revision (usually just called the tip) is the changeset
5773 most recently added to the repository (and therefore the most
5774 most recently added to the repository (and therefore the most
5774 recently changed head).
5775 recently changed head).
5775
5776
5776 If you have just made a commit, that commit will be the tip. If
5777 If you have just made a commit, that commit will be the tip. If
5777 you have just pulled changes from another repository, the tip of
5778 you have just pulled changes from another repository, the tip of
5778 that repository becomes the current tip. The "tip" tag is special
5779 that repository becomes the current tip. The "tip" tag is special
5779 and cannot be renamed or assigned to a different changeset.
5780 and cannot be renamed or assigned to a different changeset.
5780
5781
5781 This command is deprecated, please use :hg:`heads` instead.
5782 This command is deprecated, please use :hg:`heads` instead.
5782
5783
5783 Returns 0 on success.
5784 Returns 0 on success.
5784 """
5785 """
5785 displayer = cmdutil.show_changeset(ui, repo, opts)
5786 displayer = cmdutil.show_changeset(ui, repo, opts)
5786 displayer.show(repo['tip'])
5787 displayer.show(repo['tip'])
5787 displayer.close()
5788 displayer.close()
5788
5789
5789 @command('unbundle',
5790 @command('unbundle',
5790 [('u', 'update', None,
5791 [('u', 'update', None,
5791 _('update to new branch head if changesets were unbundled'))],
5792 _('update to new branch head if changesets were unbundled'))],
5792 _('[-u] FILE...'))
5793 _('[-u] FILE...'))
5793 def unbundle(ui, repo, fname1, *fnames, **opts):
5794 def unbundle(ui, repo, fname1, *fnames, **opts):
5794 """apply one or more changegroup files
5795 """apply one or more changegroup files
5795
5796
5796 Apply one or more compressed changegroup files generated by the
5797 Apply one or more compressed changegroup files generated by the
5797 bundle command.
5798 bundle command.
5798
5799
5799 Returns 0 on success, 1 if an update has unresolved files.
5800 Returns 0 on success, 1 if an update has unresolved files.
5800 """
5801 """
5801 fnames = (fname1,) + fnames
5802 fnames = (fname1,) + fnames
5802
5803
5803 lock = repo.lock()
5804 lock = repo.lock()
5804 wc = repo['.']
5805 wc = repo['.']
5805 try:
5806 try:
5806 for fname in fnames:
5807 for fname in fnames:
5807 f = hg.openpath(ui, fname)
5808 f = hg.openpath(ui, fname)
5808 gen = exchange.readbundle(ui, f, fname)
5809 gen = exchange.readbundle(ui, f, fname)
5809 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
5810 modheads = changegroup.addchangegroup(repo, gen, 'unbundle',
5810 'bundle:' + fname)
5811 'bundle:' + fname)
5811 finally:
5812 finally:
5812 lock.release()
5813 lock.release()
5813 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5814 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5814 return postincoming(ui, repo, modheads, opts.get('update'), None)
5815 return postincoming(ui, repo, modheads, opts.get('update'), None)
5815
5816
5816 @command('^update|up|checkout|co',
5817 @command('^update|up|checkout|co',
5817 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5818 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5818 ('c', 'check', None,
5819 ('c', 'check', None,
5819 _('update across branches if no uncommitted changes')),
5820 _('update across branches if no uncommitted changes')),
5820 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5821 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5821 ('r', 'rev', '', _('revision'), _('REV'))
5822 ('r', 'rev', '', _('revision'), _('REV'))
5822 ] + mergetoolopts,
5823 ] + mergetoolopts,
5823 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5824 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5824 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5825 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False,
5825 tool=None):
5826 tool=None):
5826 """update working directory (or switch revisions)
5827 """update working directory (or switch revisions)
5827
5828
5828 Update the repository's working directory to the specified
5829 Update the repository's working directory to the specified
5829 changeset. If no changeset is specified, update to the tip of the
5830 changeset. If no changeset is specified, update to the tip of the
5830 current named branch and move the current bookmark (see :hg:`help
5831 current named branch and move the current bookmark (see :hg:`help
5831 bookmarks`).
5832 bookmarks`).
5832
5833
5833 Update sets the working directory's parent revision to the specified
5834 Update sets the working directory's parent revision to the specified
5834 changeset (see :hg:`help parents`).
5835 changeset (see :hg:`help parents`).
5835
5836
5836 If the changeset is not a descendant or ancestor of the working
5837 If the changeset is not a descendant or ancestor of the working
5837 directory's parent, the update is aborted. With the -c/--check
5838 directory's parent, the update is aborted. With the -c/--check
5838 option, the working directory is checked for uncommitted changes; if
5839 option, the working directory is checked for uncommitted changes; if
5839 none are found, the working directory is updated to the specified
5840 none are found, the working directory is updated to the specified
5840 changeset.
5841 changeset.
5841
5842
5842 .. container:: verbose
5843 .. container:: verbose
5843
5844
5844 The following rules apply when the working directory contains
5845 The following rules apply when the working directory contains
5845 uncommitted changes:
5846 uncommitted changes:
5846
5847
5847 1. If neither -c/--check nor -C/--clean is specified, and if
5848 1. If neither -c/--check nor -C/--clean is specified, and if
5848 the requested changeset is an ancestor or descendant of
5849 the requested changeset is an ancestor or descendant of
5849 the working directory's parent, the uncommitted changes
5850 the working directory's parent, the uncommitted changes
5850 are merged into the requested changeset and the merged
5851 are merged into the requested changeset and the merged
5851 result is left uncommitted. If the requested changeset is
5852 result is left uncommitted. If the requested changeset is
5852 not an ancestor or descendant (that is, it is on another
5853 not an ancestor or descendant (that is, it is on another
5853 branch), the update is aborted and the uncommitted changes
5854 branch), the update is aborted and the uncommitted changes
5854 are preserved.
5855 are preserved.
5855
5856
5856 2. With the -c/--check option, the update is aborted and the
5857 2. With the -c/--check option, the update is aborted and the
5857 uncommitted changes are preserved.
5858 uncommitted changes are preserved.
5858
5859
5859 3. With the -C/--clean option, uncommitted changes are discarded and
5860 3. With the -C/--clean option, uncommitted changes are discarded and
5860 the working directory is updated to the requested changeset.
5861 the working directory is updated to the requested changeset.
5861
5862
5862 To cancel an uncommitted merge (and lose your changes), use
5863 To cancel an uncommitted merge (and lose your changes), use
5863 :hg:`update --clean .`.
5864 :hg:`update --clean .`.
5864
5865
5865 Use null as the changeset to remove the working directory (like
5866 Use null as the changeset to remove the working directory (like
5866 :hg:`clone -U`).
5867 :hg:`clone -U`).
5867
5868
5868 If you want to revert just one file to an older revision, use
5869 If you want to revert just one file to an older revision, use
5869 :hg:`revert [-r REV] NAME`.
5870 :hg:`revert [-r REV] NAME`.
5870
5871
5871 See :hg:`help dates` for a list of formats valid for -d/--date.
5872 See :hg:`help dates` for a list of formats valid for -d/--date.
5872
5873
5873 Returns 0 on success, 1 if there are unresolved files.
5874 Returns 0 on success, 1 if there are unresolved files.
5874 """
5875 """
5875 if rev and node:
5876 if rev and node:
5876 raise util.Abort(_("please specify just one revision"))
5877 raise util.Abort(_("please specify just one revision"))
5877
5878
5878 if rev is None or rev == '':
5879 if rev is None or rev == '':
5879 rev = node
5880 rev = node
5880
5881
5881 cmdutil.clearunfinished(repo)
5882 cmdutil.clearunfinished(repo)
5882
5883
5883 # with no argument, we also move the current bookmark, if any
5884 # with no argument, we also move the current bookmark, if any
5884 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5885 rev, movemarkfrom = bookmarks.calculateupdate(ui, repo, rev)
5885
5886
5886 # if we defined a bookmark, we have to remember the original bookmark name
5887 # if we defined a bookmark, we have to remember the original bookmark name
5887 brev = rev
5888 brev = rev
5888 rev = scmutil.revsingle(repo, rev, rev).rev()
5889 rev = scmutil.revsingle(repo, rev, rev).rev()
5889
5890
5890 if check and clean:
5891 if check and clean:
5891 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5892 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5892
5893
5893 if date:
5894 if date:
5894 if rev is not None:
5895 if rev is not None:
5895 raise util.Abort(_("you can't specify a revision and a date"))
5896 raise util.Abort(_("you can't specify a revision and a date"))
5896 rev = cmdutil.finddate(ui, repo, date)
5897 rev = cmdutil.finddate(ui, repo, date)
5897
5898
5898 if check:
5899 if check:
5899 c = repo[None]
5900 c = repo[None]
5900 if c.dirty(merge=False, branch=False, missing=True):
5901 if c.dirty(merge=False, branch=False, missing=True):
5901 raise util.Abort(_("uncommitted changes"))
5902 raise util.Abort(_("uncommitted changes"))
5902 if rev is None:
5903 if rev is None:
5903 rev = repo[repo[None].branch()].rev()
5904 rev = repo[repo[None].branch()].rev()
5904 mergemod._checkunknown(repo, repo[None], repo[rev])
5905 mergemod._checkunknown(repo, repo[None], repo[rev])
5905
5906
5906 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5907 repo.ui.setconfig('ui', 'forcemerge', tool, 'update')
5907
5908
5908 if clean:
5909 if clean:
5909 ret = hg.clean(repo, rev)
5910 ret = hg.clean(repo, rev)
5910 else:
5911 else:
5911 ret = hg.update(repo, rev)
5912 ret = hg.update(repo, rev)
5912
5913
5913 if not ret and movemarkfrom:
5914 if not ret and movemarkfrom:
5914 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5915 if bookmarks.update(repo, [movemarkfrom], repo['.'].node()):
5915 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5916 ui.status(_("updating bookmark %s\n") % repo._bookmarkcurrent)
5916 elif brev in repo._bookmarks:
5917 elif brev in repo._bookmarks:
5917 bookmarks.setcurrent(repo, brev)
5918 bookmarks.setcurrent(repo, brev)
5918 ui.status(_("(activating bookmark %s)\n") % brev)
5919 ui.status(_("(activating bookmark %s)\n") % brev)
5919 elif brev:
5920 elif brev:
5920 if repo._bookmarkcurrent:
5921 if repo._bookmarkcurrent:
5921 ui.status(_("(leaving bookmark %s)\n") %
5922 ui.status(_("(leaving bookmark %s)\n") %
5922 repo._bookmarkcurrent)
5923 repo._bookmarkcurrent)
5923 bookmarks.unsetcurrent(repo)
5924 bookmarks.unsetcurrent(repo)
5924
5925
5925 return ret
5926 return ret
5926
5927
5927 @command('verify', [])
5928 @command('verify', [])
5928 def verify(ui, repo):
5929 def verify(ui, repo):
5929 """verify the integrity of the repository
5930 """verify the integrity of the repository
5930
5931
5931 Verify the integrity of the current repository.
5932 Verify the integrity of the current repository.
5932
5933
5933 This will perform an extensive check of the repository's
5934 This will perform an extensive check of the repository's
5934 integrity, validating the hashes and checksums of each entry in
5935 integrity, validating the hashes and checksums of each entry in
5935 the changelog, manifest, and tracked files, as well as the
5936 the changelog, manifest, and tracked files, as well as the
5936 integrity of their crosslinks and indices.
5937 integrity of their crosslinks and indices.
5937
5938
5938 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5939 Please see http://mercurial.selenic.com/wiki/RepositoryCorruption
5939 for more information about recovery from corruption of the
5940 for more information about recovery from corruption of the
5940 repository.
5941 repository.
5941
5942
5942 Returns 0 on success, 1 if errors are encountered.
5943 Returns 0 on success, 1 if errors are encountered.
5943 """
5944 """
5944 return hg.verify(repo)
5945 return hg.verify(repo)
5945
5946
5946 @command('version', [])
5947 @command('version', [])
5947 def version_(ui):
5948 def version_(ui):
5948 """output version and copyright information"""
5949 """output version and copyright information"""
5949 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5950 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5950 % util.version())
5951 % util.version())
5951 ui.status(_(
5952 ui.status(_(
5952 "(see http://mercurial.selenic.com for more information)\n"
5953 "(see http://mercurial.selenic.com for more information)\n"
5953 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
5954 "\nCopyright (C) 2005-2014 Matt Mackall and others\n"
5954 "This is free software; see the source for copying conditions. "
5955 "This is free software; see the source for copying conditions. "
5955 "There is NO\nwarranty; "
5956 "There is NO\nwarranty; "
5956 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5957 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5957 ))
5958 ))
5958
5959
5959 norepo = ("clone init version help debugcommands debugcomplete"
5960 norepo = ("clone init version help debugcommands debugcomplete"
5960 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5961 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5961 " debugknown debuggetbundle debugbundle")
5962 " debugknown debuggetbundle debugbundle")
5962 optionalrepo = ("identify paths serve config showconfig debugancestor debugdag"
5963 optionalrepo = ("identify paths serve config showconfig debugancestor debugdag"
5963 " debugdata debugindex debugindexdot debugrevlog")
5964 " debugdata debugindex debugindexdot debugrevlog")
5964 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5965 inferrepo = ("add addremove annotate cat commit diff grep forget log parents"
5965 " remove resolve status debugwalk")
5966 " remove resolve status debugwalk")
@@ -1,901 +1,910 b''
1 # dispatch.py - command dispatching for mercurial
1 # dispatch.py - command dispatching 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 i18n import _
8 from i18n import _
9 import os, sys, atexit, signal, pdb, socket, errno, shlex, time, traceback, re
9 import os, sys, atexit, signal, pdb, socket, errno, shlex, time, traceback, re
10 import util, commands, hg, fancyopts, extensions, hook, error
10 import util, commands, hg, fancyopts, extensions, hook, error
11 import cmdutil, encoding
11 import cmdutil, encoding
12 import ui as uimod
12 import ui as uimod
13
13
14 class request(object):
14 class request(object):
15 def __init__(self, args, ui=None, repo=None, fin=None, fout=None,
15 def __init__(self, args, ui=None, repo=None, fin=None, fout=None,
16 ferr=None):
16 ferr=None):
17 self.args = args
17 self.args = args
18 self.ui = ui
18 self.ui = ui
19 self.repo = repo
19 self.repo = repo
20
20
21 # input/output/error streams
21 # input/output/error streams
22 self.fin = fin
22 self.fin = fin
23 self.fout = fout
23 self.fout = fout
24 self.ferr = ferr
24 self.ferr = ferr
25
25
26 def run():
26 def run():
27 "run the command in sys.argv"
27 "run the command in sys.argv"
28 sys.exit((dispatch(request(sys.argv[1:])) or 0) & 255)
28 sys.exit((dispatch(request(sys.argv[1:])) or 0) & 255)
29
29
30 def dispatch(req):
30 def dispatch(req):
31 "run the command specified in req.args"
31 "run the command specified in req.args"
32 if req.ferr:
32 if req.ferr:
33 ferr = req.ferr
33 ferr = req.ferr
34 elif req.ui:
34 elif req.ui:
35 ferr = req.ui.ferr
35 ferr = req.ui.ferr
36 else:
36 else:
37 ferr = sys.stderr
37 ferr = sys.stderr
38
38
39 try:
39 try:
40 if not req.ui:
40 if not req.ui:
41 req.ui = uimod.ui()
41 req.ui = uimod.ui()
42 if '--traceback' in req.args:
42 if '--traceback' in req.args:
43 req.ui.setconfig('ui', 'traceback', 'on', '--traceback')
43 req.ui.setconfig('ui', 'traceback', 'on', '--traceback')
44
44
45 # set ui streams from the request
45 # set ui streams from the request
46 if req.fin:
46 if req.fin:
47 req.ui.fin = req.fin
47 req.ui.fin = req.fin
48 if req.fout:
48 if req.fout:
49 req.ui.fout = req.fout
49 req.ui.fout = req.fout
50 if req.ferr:
50 if req.ferr:
51 req.ui.ferr = req.ferr
51 req.ui.ferr = req.ferr
52 except util.Abort, inst:
52 except util.Abort, inst:
53 ferr.write(_("abort: %s\n") % inst)
53 ferr.write(_("abort: %s\n") % inst)
54 if inst.hint:
54 if inst.hint:
55 ferr.write(_("(%s)\n") % inst.hint)
55 ferr.write(_("(%s)\n") % inst.hint)
56 return -1
56 return -1
57 except error.ParseError, inst:
57 except error.ParseError, inst:
58 if len(inst.args) > 1:
58 if len(inst.args) > 1:
59 ferr.write(_("hg: parse error at %s: %s\n") %
59 ferr.write(_("hg: parse error at %s: %s\n") %
60 (inst.args[1], inst.args[0]))
60 (inst.args[1], inst.args[0]))
61 else:
61 else:
62 ferr.write(_("hg: parse error: %s\n") % inst.args[0])
62 ferr.write(_("hg: parse error: %s\n") % inst.args[0])
63 return -1
63 return -1
64
64
65 msg = ' '.join(' ' in a and repr(a) or a for a in req.args)
65 msg = ' '.join(' ' in a and repr(a) or a for a in req.args)
66 starttime = time.time()
66 starttime = time.time()
67 ret = None
67 ret = None
68 try:
68 try:
69 ret = _runcatch(req)
69 ret = _runcatch(req)
70 return ret
70 return ret
71 finally:
71 finally:
72 duration = time.time() - starttime
72 duration = time.time() - starttime
73 req.ui.log("commandfinish", "%s exited %s after %0.2f seconds\n",
73 req.ui.log("commandfinish", "%s exited %s after %0.2f seconds\n",
74 msg, ret or 0, duration)
74 msg, ret or 0, duration)
75
75
76 def _runcatch(req):
76 def _runcatch(req):
77 def catchterm(*args):
77 def catchterm(*args):
78 raise error.SignalInterrupt
78 raise error.SignalInterrupt
79
79
80 ui = req.ui
80 ui = req.ui
81 try:
81 try:
82 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
82 for name in 'SIGBREAK', 'SIGHUP', 'SIGTERM':
83 num = getattr(signal, name, None)
83 num = getattr(signal, name, None)
84 if num:
84 if num:
85 signal.signal(num, catchterm)
85 signal.signal(num, catchterm)
86 except ValueError:
86 except ValueError:
87 pass # happens if called in a thread
87 pass # happens if called in a thread
88
88
89 try:
89 try:
90 try:
90 try:
91 debugger = 'pdb'
91 debugger = 'pdb'
92 debugtrace = {
92 debugtrace = {
93 'pdb' : pdb.set_trace
93 'pdb' : pdb.set_trace
94 }
94 }
95 debugmortem = {
95 debugmortem = {
96 'pdb' : pdb.post_mortem
96 'pdb' : pdb.post_mortem
97 }
97 }
98
98
99 # read --config before doing anything else
99 # read --config before doing anything else
100 # (e.g. to change trust settings for reading .hg/hgrc)
100 # (e.g. to change trust settings for reading .hg/hgrc)
101 cfgs = _parseconfig(req.ui, _earlygetopt(['--config'], req.args))
101 cfgs = _parseconfig(req.ui, _earlygetopt(['--config'], req.args))
102
102
103 if req.repo:
103 if req.repo:
104 # copy configs that were passed on the cmdline (--config) to
104 # copy configs that were passed on the cmdline (--config) to
105 # the repo ui
105 # the repo ui
106 for sec, name, val in cfgs:
106 for sec, name, val in cfgs:
107 req.repo.ui.setconfig(sec, name, val, source='--config')
107 req.repo.ui.setconfig(sec, name, val, source='--config')
108
108
109 # if we are in HGPLAIN mode, then disable custom debugging
109 # if we are in HGPLAIN mode, then disable custom debugging
110 debugger = ui.config("ui", "debugger")
110 debugger = ui.config("ui", "debugger")
111 debugmod = pdb
111 debugmod = pdb
112 if not debugger or ui.plain():
112 if not debugger or ui.plain():
113 debugger = 'pdb'
113 debugger = 'pdb'
114 elif '--debugger' in req.args:
114 elif '--debugger' in req.args:
115 # This import can be slow for fancy debuggers, so only
115 # This import can be slow for fancy debuggers, so only
116 # do it when absolutely necessary, i.e. when actual
116 # do it when absolutely necessary, i.e. when actual
117 # debugging has been requested
117 # debugging has been requested
118 try:
118 try:
119 debugmod = __import__(debugger)
119 debugmod = __import__(debugger)
120 except ImportError:
120 except ImportError:
121 pass # Leave debugmod = pdb
121 pass # Leave debugmod = pdb
122
122
123 debugtrace[debugger] = debugmod.set_trace
123 debugtrace[debugger] = debugmod.set_trace
124 debugmortem[debugger] = debugmod.post_mortem
124 debugmortem[debugger] = debugmod.post_mortem
125
125
126 # enter the debugger before command execution
126 # enter the debugger before command execution
127 if '--debugger' in req.args:
127 if '--debugger' in req.args:
128 ui.warn(_("entering debugger - "
128 ui.warn(_("entering debugger - "
129 "type c to continue starting hg or h for help\n"))
129 "type c to continue starting hg or h for help\n"))
130
130
131 if (debugger != 'pdb' and
131 if (debugger != 'pdb' and
132 debugtrace[debugger] == debugtrace['pdb']):
132 debugtrace[debugger] == debugtrace['pdb']):
133 ui.warn(_("%s debugger specified "
133 ui.warn(_("%s debugger specified "
134 "but its module was not found\n") % debugger)
134 "but its module was not found\n") % debugger)
135
135
136 debugtrace[debugger]()
136 debugtrace[debugger]()
137 try:
137 try:
138 return _dispatch(req)
138 return _dispatch(req)
139 finally:
139 finally:
140 ui.flush()
140 ui.flush()
141 except: # re-raises
141 except: # re-raises
142 # enter the debugger when we hit an exception
142 # enter the debugger when we hit an exception
143 if '--debugger' in req.args:
143 if '--debugger' in req.args:
144 traceback.print_exc()
144 traceback.print_exc()
145 debugmortem[debugger](sys.exc_info()[2])
145 debugmortem[debugger](sys.exc_info()[2])
146 ui.traceback()
146 ui.traceback()
147 raise
147 raise
148
148
149 # Global exception handling, alphabetically
149 # Global exception handling, alphabetically
150 # Mercurial-specific first, followed by built-in and library exceptions
150 # Mercurial-specific first, followed by built-in and library exceptions
151 except error.AmbiguousCommand, inst:
151 except error.AmbiguousCommand, inst:
152 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
152 ui.warn(_("hg: command '%s' is ambiguous:\n %s\n") %
153 (inst.args[0], " ".join(inst.args[1])))
153 (inst.args[0], " ".join(inst.args[1])))
154 except error.ParseError, inst:
154 except error.ParseError, inst:
155 if len(inst.args) > 1:
155 if len(inst.args) > 1:
156 ui.warn(_("hg: parse error at %s: %s\n") %
156 ui.warn(_("hg: parse error at %s: %s\n") %
157 (inst.args[1], inst.args[0]))
157 (inst.args[1], inst.args[0]))
158 else:
158 else:
159 ui.warn(_("hg: parse error: %s\n") % inst.args[0])
159 ui.warn(_("hg: parse error: %s\n") % inst.args[0])
160 return -1
160 return -1
161 except error.LockHeld, inst:
161 except error.LockHeld, inst:
162 if inst.errno == errno.ETIMEDOUT:
162 if inst.errno == errno.ETIMEDOUT:
163 reason = _('timed out waiting for lock held by %s') % inst.locker
163 reason = _('timed out waiting for lock held by %s') % inst.locker
164 else:
164 else:
165 reason = _('lock held by %s') % inst.locker
165 reason = _('lock held by %s') % inst.locker
166 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
166 ui.warn(_("abort: %s: %s\n") % (inst.desc or inst.filename, reason))
167 except error.LockUnavailable, inst:
167 except error.LockUnavailable, inst:
168 ui.warn(_("abort: could not lock %s: %s\n") %
168 ui.warn(_("abort: could not lock %s: %s\n") %
169 (inst.desc or inst.filename, inst.strerror))
169 (inst.desc or inst.filename, inst.strerror))
170 except error.CommandError, inst:
170 except error.CommandError, inst:
171 if inst.args[0]:
171 if inst.args[0]:
172 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
172 ui.warn(_("hg %s: %s\n") % (inst.args[0], inst.args[1]))
173 commands.help_(ui, inst.args[0], full=False, command=True)
173 commands.help_(ui, inst.args[0], full=False, command=True)
174 else:
174 else:
175 ui.warn(_("hg: %s\n") % inst.args[1])
175 ui.warn(_("hg: %s\n") % inst.args[1])
176 commands.help_(ui, 'shortlist')
176 commands.help_(ui, 'shortlist')
177 except error.OutOfBandError, inst:
177 except error.OutOfBandError, inst:
178 ui.warn(_("abort: remote error:\n"))
178 ui.warn(_("abort: remote error:\n"))
179 ui.warn(''.join(inst.args))
179 ui.warn(''.join(inst.args))
180 except error.RepoError, inst:
180 except error.RepoError, inst:
181 ui.warn(_("abort: %s!\n") % inst)
181 ui.warn(_("abort: %s!\n") % inst)
182 if inst.hint:
182 if inst.hint:
183 ui.warn(_("(%s)\n") % inst.hint)
183 ui.warn(_("(%s)\n") % inst.hint)
184 except error.ResponseError, inst:
184 except error.ResponseError, inst:
185 ui.warn(_("abort: %s") % inst.args[0])
185 ui.warn(_("abort: %s") % inst.args[0])
186 if not isinstance(inst.args[1], basestring):
186 if not isinstance(inst.args[1], basestring):
187 ui.warn(" %r\n" % (inst.args[1],))
187 ui.warn(" %r\n" % (inst.args[1],))
188 elif not inst.args[1]:
188 elif not inst.args[1]:
189 ui.warn(_(" empty string\n"))
189 ui.warn(_(" empty string\n"))
190 else:
190 else:
191 ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
191 ui.warn("\n%r\n" % util.ellipsis(inst.args[1]))
192 except error.RevlogError, inst:
192 except error.RevlogError, inst:
193 ui.warn(_("abort: %s!\n") % inst)
193 ui.warn(_("abort: %s!\n") % inst)
194 except error.SignalInterrupt:
194 except error.SignalInterrupt:
195 ui.warn(_("killed!\n"))
195 ui.warn(_("killed!\n"))
196 except error.UnknownCommand, inst:
196 except error.UnknownCommand, inst:
197 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
197 ui.warn(_("hg: unknown command '%s'\n") % inst.args[0])
198 try:
198 try:
199 # check if the command is in a disabled extension
199 # check if the command is in a disabled extension
200 # (but don't check for extensions themselves)
200 # (but don't check for extensions themselves)
201 commands.help_(ui, inst.args[0], unknowncmd=True)
201 commands.help_(ui, inst.args[0], unknowncmd=True)
202 except error.UnknownCommand:
202 except error.UnknownCommand:
203 commands.help_(ui, 'shortlist')
203 commands.help_(ui, 'shortlist')
204 except error.InterventionRequired, inst:
204 except error.InterventionRequired, inst:
205 ui.warn("%s\n" % inst)
205 ui.warn("%s\n" % inst)
206 return 1
206 return 1
207 except util.Abort, inst:
207 except util.Abort, inst:
208 ui.warn(_("abort: %s\n") % inst)
208 ui.warn(_("abort: %s\n") % inst)
209 if inst.hint:
209 if inst.hint:
210 ui.warn(_("(%s)\n") % inst.hint)
210 ui.warn(_("(%s)\n") % inst.hint)
211 except ImportError, inst:
211 except ImportError, inst:
212 ui.warn(_("abort: %s!\n") % inst)
212 ui.warn(_("abort: %s!\n") % inst)
213 m = str(inst).split()[-1]
213 m = str(inst).split()[-1]
214 if m in "mpatch bdiff".split():
214 if m in "mpatch bdiff".split():
215 ui.warn(_("(did you forget to compile extensions?)\n"))
215 ui.warn(_("(did you forget to compile extensions?)\n"))
216 elif m in "zlib".split():
216 elif m in "zlib".split():
217 ui.warn(_("(is your Python install correct?)\n"))
217 ui.warn(_("(is your Python install correct?)\n"))
218 except IOError, inst:
218 except IOError, inst:
219 if util.safehasattr(inst, "code"):
219 if util.safehasattr(inst, "code"):
220 ui.warn(_("abort: %s\n") % inst)
220 ui.warn(_("abort: %s\n") % inst)
221 elif util.safehasattr(inst, "reason"):
221 elif util.safehasattr(inst, "reason"):
222 try: # usually it is in the form (errno, strerror)
222 try: # usually it is in the form (errno, strerror)
223 reason = inst.reason.args[1]
223 reason = inst.reason.args[1]
224 except (AttributeError, IndexError):
224 except (AttributeError, IndexError):
225 # it might be anything, for example a string
225 # it might be anything, for example a string
226 reason = inst.reason
226 reason = inst.reason
227 ui.warn(_("abort: error: %s\n") % reason)
227 ui.warn(_("abort: error: %s\n") % reason)
228 elif util.safehasattr(inst, "args") and inst.args[0] == errno.EPIPE:
228 elif util.safehasattr(inst, "args") and inst.args[0] == errno.EPIPE:
229 if ui.debugflag:
229 if ui.debugflag:
230 ui.warn(_("broken pipe\n"))
230 ui.warn(_("broken pipe\n"))
231 elif getattr(inst, "strerror", None):
231 elif getattr(inst, "strerror", None):
232 if getattr(inst, "filename", None):
232 if getattr(inst, "filename", None):
233 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
233 ui.warn(_("abort: %s: %s\n") % (inst.strerror, inst.filename))
234 else:
234 else:
235 ui.warn(_("abort: %s\n") % inst.strerror)
235 ui.warn(_("abort: %s\n") % inst.strerror)
236 else:
236 else:
237 raise
237 raise
238 except OSError, inst:
238 except OSError, inst:
239 if getattr(inst, "filename", None) is not None:
239 if getattr(inst, "filename", None) is not None:
240 ui.warn(_("abort: %s: '%s'\n") % (inst.strerror, inst.filename))
240 ui.warn(_("abort: %s: '%s'\n") % (inst.strerror, inst.filename))
241 else:
241 else:
242 ui.warn(_("abort: %s\n") % inst.strerror)
242 ui.warn(_("abort: %s\n") % inst.strerror)
243 except KeyboardInterrupt:
243 except KeyboardInterrupt:
244 try:
244 try:
245 ui.warn(_("interrupted!\n"))
245 ui.warn(_("interrupted!\n"))
246 except IOError, inst:
246 except IOError, inst:
247 if inst.errno == errno.EPIPE:
247 if inst.errno == errno.EPIPE:
248 if ui.debugflag:
248 if ui.debugflag:
249 ui.warn(_("\nbroken pipe\n"))
249 ui.warn(_("\nbroken pipe\n"))
250 else:
250 else:
251 raise
251 raise
252 except MemoryError:
252 except MemoryError:
253 ui.warn(_("abort: out of memory\n"))
253 ui.warn(_("abort: out of memory\n"))
254 except SystemExit, inst:
254 except SystemExit, inst:
255 # Commands shouldn't sys.exit directly, but give a return code.
255 # Commands shouldn't sys.exit directly, but give a return code.
256 # Just in case catch this and and pass exit code to caller.
256 # Just in case catch this and and pass exit code to caller.
257 return inst.code
257 return inst.code
258 except socket.error, inst:
258 except socket.error, inst:
259 ui.warn(_("abort: %s\n") % inst.args[-1])
259 ui.warn(_("abort: %s\n") % inst.args[-1])
260 except: # re-raises
260 except: # re-raises
261 myver = util.version()
261 myver = util.version()
262 # For compatibility checking, we discard the portion of the hg
262 # For compatibility checking, we discard the portion of the hg
263 # version after the + on the assumption that if a "normal
263 # version after the + on the assumption that if a "normal
264 # user" is running a build with a + in it the packager
264 # user" is running a build with a + in it the packager
265 # probably built from fairly close to a tag and anyone with a
265 # probably built from fairly close to a tag and anyone with a
266 # 'make local' copy of hg (where the version number can be out
266 # 'make local' copy of hg (where the version number can be out
267 # of date) will be clueful enough to notice the implausible
267 # of date) will be clueful enough to notice the implausible
268 # version number and try updating.
268 # version number and try updating.
269 compare = myver.split('+')[0]
269 compare = myver.split('+')[0]
270 ct = tuplever(compare)
270 ct = tuplever(compare)
271 worst = None, ct, ''
271 worst = None, ct, ''
272 for name, mod in extensions.extensions():
272 for name, mod in extensions.extensions():
273 testedwith = getattr(mod, 'testedwith', '')
273 testedwith = getattr(mod, 'testedwith', '')
274 report = getattr(mod, 'buglink', _('the extension author.'))
274 report = getattr(mod, 'buglink', _('the extension author.'))
275 if not testedwith.strip():
275 if not testedwith.strip():
276 # We found an untested extension. It's likely the culprit.
276 # We found an untested extension. It's likely the culprit.
277 worst = name, 'unknown', report
277 worst = name, 'unknown', report
278 break
278 break
279 if compare not in testedwith.split() and testedwith != 'internal':
279 if compare not in testedwith.split() and testedwith != 'internal':
280 tested = [tuplever(v) for v in testedwith.split()]
280 tested = [tuplever(v) for v in testedwith.split()]
281 lower = [t for t in tested if t < ct]
281 lower = [t for t in tested if t < ct]
282 nearest = max(lower or tested)
282 nearest = max(lower or tested)
283 if worst[0] is None or nearest < worst[1]:
283 if worst[0] is None or nearest < worst[1]:
284 worst = name, nearest, report
284 worst = name, nearest, report
285 if worst[0] is not None:
285 if worst[0] is not None:
286 name, testedwith, report = worst
286 name, testedwith, report = worst
287 if not isinstance(testedwith, str):
287 if not isinstance(testedwith, str):
288 testedwith = '.'.join([str(c) for c in testedwith])
288 testedwith = '.'.join([str(c) for c in testedwith])
289 warning = (_('** Unknown exception encountered with '
289 warning = (_('** Unknown exception encountered with '
290 'possibly-broken third-party extension %s\n'
290 'possibly-broken third-party extension %s\n'
291 '** which supports versions %s of Mercurial.\n'
291 '** which supports versions %s of Mercurial.\n'
292 '** Please disable %s and try your action again.\n'
292 '** Please disable %s and try your action again.\n'
293 '** If that fixes the bug please report it to %s\n')
293 '** If that fixes the bug please report it to %s\n')
294 % (name, testedwith, name, report))
294 % (name, testedwith, name, report))
295 else:
295 else:
296 warning = (_("** unknown exception encountered, "
296 warning = (_("** unknown exception encountered, "
297 "please report by visiting\n") +
297 "please report by visiting\n") +
298 _("** http://mercurial.selenic.com/wiki/BugTracker\n"))
298 _("** http://mercurial.selenic.com/wiki/BugTracker\n"))
299 warning += ((_("** Python %s\n") % sys.version.replace('\n', '')) +
299 warning += ((_("** Python %s\n") % sys.version.replace('\n', '')) +
300 (_("** Mercurial Distributed SCM (version %s)\n") % myver) +
300 (_("** Mercurial Distributed SCM (version %s)\n") % myver) +
301 (_("** Extensions loaded: %s\n") %
301 (_("** Extensions loaded: %s\n") %
302 ", ".join([x[0] for x in extensions.extensions()])))
302 ", ".join([x[0] for x in extensions.extensions()])))
303 ui.log("commandexception", "%s\n%s\n", warning, traceback.format_exc())
303 ui.log("commandexception", "%s\n%s\n", warning, traceback.format_exc())
304 ui.warn(warning)
304 ui.warn(warning)
305 raise
305 raise
306
306
307 return -1
307 return -1
308
308
309 def tuplever(v):
309 def tuplever(v):
310 try:
310 try:
311 return tuple([int(i) for i in v.split('.')])
311 return tuple([int(i) for i in v.split('.')])
312 except ValueError:
312 except ValueError:
313 return tuple()
313 return tuple()
314
314
315 def aliasargs(fn, givenargs):
315 def aliasargs(fn, givenargs):
316 args = getattr(fn, 'args', [])
316 args = getattr(fn, 'args', [])
317 if args:
317 if args:
318 cmd = ' '.join(map(util.shellquote, args))
318 cmd = ' '.join(map(util.shellquote, args))
319
319
320 nums = []
320 nums = []
321 def replacer(m):
321 def replacer(m):
322 num = int(m.group(1)) - 1
322 num = int(m.group(1)) - 1
323 nums.append(num)
323 nums.append(num)
324 if num < len(givenargs):
324 if num < len(givenargs):
325 return givenargs[num]
325 return givenargs[num]
326 raise util.Abort(_('too few arguments for command alias'))
326 raise util.Abort(_('too few arguments for command alias'))
327 cmd = re.sub(r'\$(\d+|\$)', replacer, cmd)
327 cmd = re.sub(r'\$(\d+|\$)', replacer, cmd)
328 givenargs = [x for i, x in enumerate(givenargs)
328 givenargs = [x for i, x in enumerate(givenargs)
329 if i not in nums]
329 if i not in nums]
330 args = shlex.split(cmd)
330 args = shlex.split(cmd)
331 return args + givenargs
331 return args + givenargs
332
332
333 class cmdalias(object):
333 class cmdalias(object):
334 def __init__(self, name, definition, cmdtable):
334 def __init__(self, name, definition, cmdtable):
335 self.name = self.cmd = name
335 self.name = self.cmd = name
336 self.cmdname = ''
336 self.cmdname = ''
337 self.definition = definition
337 self.definition = definition
338 self.args = []
338 self.args = []
339 self.opts = []
339 self.opts = []
340 self.help = ''
340 self.help = ''
341 self.norepo = True
341 self.norepo = True
342 self.optionalrepo = False
342 self.optionalrepo = False
343 self.badalias = False
343 self.badalias = False
344
344
345 try:
345 try:
346 aliases, entry = cmdutil.findcmd(self.name, cmdtable)
346 aliases, entry = cmdutil.findcmd(self.name, cmdtable)
347 for alias, e in cmdtable.iteritems():
347 for alias, e in cmdtable.iteritems():
348 if e is entry:
348 if e is entry:
349 self.cmd = alias
349 self.cmd = alias
350 break
350 break
351 self.shadows = True
351 self.shadows = True
352 except error.UnknownCommand:
352 except error.UnknownCommand:
353 self.shadows = False
353 self.shadows = False
354
354
355 if not self.definition:
355 if not self.definition:
356 def fn(ui, *args):
356 def fn(ui, *args):
357 ui.warn(_("no definition for alias '%s'\n") % self.name)
357 ui.warn(_("no definition for alias '%s'\n") % self.name)
358 return 1
358 return -1
359 self.fn = fn
359 self.fn = fn
360 self.badalias = True
360 self.badalias = True
361 return
361 return
362
362
363 if self.definition.startswith('!'):
363 if self.definition.startswith('!'):
364 self.shell = True
364 self.shell = True
365 def fn(ui, *args):
365 def fn(ui, *args):
366 env = {'HG_ARGS': ' '.join((self.name,) + args)}
366 env = {'HG_ARGS': ' '.join((self.name,) + args)}
367 def _checkvar(m):
367 def _checkvar(m):
368 if m.groups()[0] == '$':
368 if m.groups()[0] == '$':
369 return m.group()
369 return m.group()
370 elif int(m.groups()[0]) <= len(args):
370 elif int(m.groups()[0]) <= len(args):
371 return m.group()
371 return m.group()
372 else:
372 else:
373 ui.debug("No argument found for substitution "
373 ui.debug("No argument found for substitution "
374 "of %i variable in alias '%s' definition."
374 "of %i variable in alias '%s' definition."
375 % (int(m.groups()[0]), self.name))
375 % (int(m.groups()[0]), self.name))
376 return ''
376 return ''
377 cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
377 cmd = re.sub(r'\$(\d+|\$)', _checkvar, self.definition[1:])
378 replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
378 replace = dict((str(i + 1), arg) for i, arg in enumerate(args))
379 replace['0'] = self.name
379 replace['0'] = self.name
380 replace['@'] = ' '.join(args)
380 replace['@'] = ' '.join(args)
381 cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
381 cmd = util.interpolate(r'\$', replace, cmd, escape_prefix=True)
382 return util.system(cmd, environ=env, out=ui.fout)
382 return util.system(cmd, environ=env, out=ui.fout)
383 self.fn = fn
383 self.fn = fn
384 return
384 return
385
385
386 args = shlex.split(self.definition)
386 try:
387 args = shlex.split(self.definition)
388 except ValueError, inst:
389 def fn(ui, *args):
390 ui.warn(_("error in definition for alias '%s': %s\n")
391 % (self.name, inst))
392 return -1
393 self.fn = fn
394 self.badalias = True
395 return
387 self.cmdname = cmd = args.pop(0)
396 self.cmdname = cmd = args.pop(0)
388 args = map(util.expandpath, args)
397 args = map(util.expandpath, args)
389
398
390 for invalidarg in ("--cwd", "-R", "--repository", "--repo", "--config"):
399 for invalidarg in ("--cwd", "-R", "--repository", "--repo", "--config"):
391 if _earlygetopt([invalidarg], args):
400 if _earlygetopt([invalidarg], args):
392 def fn(ui, *args):
401 def fn(ui, *args):
393 ui.warn(_("error in definition for alias '%s': %s may only "
402 ui.warn(_("error in definition for alias '%s': %s may only "
394 "be given on the command line\n")
403 "be given on the command line\n")
395 % (self.name, invalidarg))
404 % (self.name, invalidarg))
396 return 1
405 return -1
397
406
398 self.fn = fn
407 self.fn = fn
399 self.badalias = True
408 self.badalias = True
400 return
409 return
401
410
402 try:
411 try:
403 tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
412 tableentry = cmdutil.findcmd(cmd, cmdtable, False)[1]
404 if len(tableentry) > 2:
413 if len(tableentry) > 2:
405 self.fn, self.opts, self.help = tableentry
414 self.fn, self.opts, self.help = tableentry
406 else:
415 else:
407 self.fn, self.opts = tableentry
416 self.fn, self.opts = tableentry
408
417
409 self.args = aliasargs(self.fn, args)
418 self.args = aliasargs(self.fn, args)
410 if cmd not in commands.norepo.split(' '):
419 if cmd not in commands.norepo.split(' '):
411 self.norepo = False
420 self.norepo = False
412 if cmd in commands.optionalrepo.split(' '):
421 if cmd in commands.optionalrepo.split(' '):
413 self.optionalrepo = True
422 self.optionalrepo = True
414 if self.help.startswith("hg " + cmd):
423 if self.help.startswith("hg " + cmd):
415 # drop prefix in old-style help lines so hg shows the alias
424 # drop prefix in old-style help lines so hg shows the alias
416 self.help = self.help[4 + len(cmd):]
425 self.help = self.help[4 + len(cmd):]
417 self.__doc__ = self.fn.__doc__
426 self.__doc__ = self.fn.__doc__
418
427
419 except error.UnknownCommand:
428 except error.UnknownCommand:
420 def fn(ui, *args):
429 def fn(ui, *args):
421 ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
430 ui.warn(_("alias '%s' resolves to unknown command '%s'\n") \
422 % (self.name, cmd))
431 % (self.name, cmd))
423 try:
432 try:
424 # check if the command is in a disabled extension
433 # check if the command is in a disabled extension
425 commands.help_(ui, cmd, unknowncmd=True)
434 commands.help_(ui, cmd, unknowncmd=True)
426 except error.UnknownCommand:
435 except error.UnknownCommand:
427 pass
436 pass
428 return 1
437 return -1
429 self.fn = fn
438 self.fn = fn
430 self.badalias = True
439 self.badalias = True
431 except error.AmbiguousCommand:
440 except error.AmbiguousCommand:
432 def fn(ui, *args):
441 def fn(ui, *args):
433 ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
442 ui.warn(_("alias '%s' resolves to ambiguous command '%s'\n") \
434 % (self.name, cmd))
443 % (self.name, cmd))
435 return 1
444 return -1
436 self.fn = fn
445 self.fn = fn
437 self.badalias = True
446 self.badalias = True
438
447
439 def __call__(self, ui, *args, **opts):
448 def __call__(self, ui, *args, **opts):
440 if self.shadows:
449 if self.shadows:
441 ui.debug("alias '%s' shadows command '%s'\n" %
450 ui.debug("alias '%s' shadows command '%s'\n" %
442 (self.name, self.cmdname))
451 (self.name, self.cmdname))
443
452
444 if util.safehasattr(self, 'shell'):
453 if util.safehasattr(self, 'shell'):
445 return self.fn(ui, *args, **opts)
454 return self.fn(ui, *args, **opts)
446 else:
455 else:
447 try:
456 try:
448 return util.checksignature(self.fn)(ui, *args, **opts)
457 return util.checksignature(self.fn)(ui, *args, **opts)
449 except error.SignatureError:
458 except error.SignatureError:
450 args = ' '.join([self.cmdname] + self.args)
459 args = ' '.join([self.cmdname] + self.args)
451 ui.debug("alias '%s' expands to '%s'\n" % (self.name, args))
460 ui.debug("alias '%s' expands to '%s'\n" % (self.name, args))
452 raise
461 raise
453
462
454 def addaliases(ui, cmdtable):
463 def addaliases(ui, cmdtable):
455 # aliases are processed after extensions have been loaded, so they
464 # aliases are processed after extensions have been loaded, so they
456 # may use extension commands. Aliases can also use other alias definitions,
465 # may use extension commands. Aliases can also use other alias definitions,
457 # but only if they have been defined prior to the current definition.
466 # but only if they have been defined prior to the current definition.
458 for alias, definition in ui.configitems('alias'):
467 for alias, definition in ui.configitems('alias'):
459 aliasdef = cmdalias(alias, definition, cmdtable)
468 aliasdef = cmdalias(alias, definition, cmdtable)
460
469
461 try:
470 try:
462 olddef = cmdtable[aliasdef.cmd][0]
471 olddef = cmdtable[aliasdef.cmd][0]
463 if olddef.definition == aliasdef.definition:
472 if olddef.definition == aliasdef.definition:
464 continue
473 continue
465 except (KeyError, AttributeError):
474 except (KeyError, AttributeError):
466 # definition might not exist or it might not be a cmdalias
475 # definition might not exist or it might not be a cmdalias
467 pass
476 pass
468
477
469 cmdtable[aliasdef.name] = (aliasdef, aliasdef.opts, aliasdef.help)
478 cmdtable[aliasdef.name] = (aliasdef, aliasdef.opts, aliasdef.help)
470 if aliasdef.norepo:
479 if aliasdef.norepo:
471 commands.norepo += ' %s' % alias
480 commands.norepo += ' %s' % alias
472 if aliasdef.optionalrepo:
481 if aliasdef.optionalrepo:
473 commands.optionalrepo += ' %s' % alias
482 commands.optionalrepo += ' %s' % alias
474
483
475 def _parse(ui, args):
484 def _parse(ui, args):
476 options = {}
485 options = {}
477 cmdoptions = {}
486 cmdoptions = {}
478
487
479 try:
488 try:
480 args = fancyopts.fancyopts(args, commands.globalopts, options)
489 args = fancyopts.fancyopts(args, commands.globalopts, options)
481 except fancyopts.getopt.GetoptError, inst:
490 except fancyopts.getopt.GetoptError, inst:
482 raise error.CommandError(None, inst)
491 raise error.CommandError(None, inst)
483
492
484 if args:
493 if args:
485 cmd, args = args[0], args[1:]
494 cmd, args = args[0], args[1:]
486 aliases, entry = cmdutil.findcmd(cmd, commands.table,
495 aliases, entry = cmdutil.findcmd(cmd, commands.table,
487 ui.configbool("ui", "strict"))
496 ui.configbool("ui", "strict"))
488 cmd = aliases[0]
497 cmd = aliases[0]
489 args = aliasargs(entry[0], args)
498 args = aliasargs(entry[0], args)
490 defaults = ui.config("defaults", cmd)
499 defaults = ui.config("defaults", cmd)
491 if defaults:
500 if defaults:
492 args = map(util.expandpath, shlex.split(defaults)) + args
501 args = map(util.expandpath, shlex.split(defaults)) + args
493 c = list(entry[1])
502 c = list(entry[1])
494 else:
503 else:
495 cmd = None
504 cmd = None
496 c = []
505 c = []
497
506
498 # combine global options into local
507 # combine global options into local
499 for o in commands.globalopts:
508 for o in commands.globalopts:
500 c.append((o[0], o[1], options[o[1]], o[3]))
509 c.append((o[0], o[1], options[o[1]], o[3]))
501
510
502 try:
511 try:
503 args = fancyopts.fancyopts(args, c, cmdoptions, True)
512 args = fancyopts.fancyopts(args, c, cmdoptions, True)
504 except fancyopts.getopt.GetoptError, inst:
513 except fancyopts.getopt.GetoptError, inst:
505 raise error.CommandError(cmd, inst)
514 raise error.CommandError(cmd, inst)
506
515
507 # separate global options back out
516 # separate global options back out
508 for o in commands.globalopts:
517 for o in commands.globalopts:
509 n = o[1]
518 n = o[1]
510 options[n] = cmdoptions[n]
519 options[n] = cmdoptions[n]
511 del cmdoptions[n]
520 del cmdoptions[n]
512
521
513 return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
522 return (cmd, cmd and entry[0] or None, args, options, cmdoptions)
514
523
515 def _parseconfig(ui, config):
524 def _parseconfig(ui, config):
516 """parse the --config options from the command line"""
525 """parse the --config options from the command line"""
517 configs = []
526 configs = []
518
527
519 for cfg in config:
528 for cfg in config:
520 try:
529 try:
521 name, value = cfg.split('=', 1)
530 name, value = cfg.split('=', 1)
522 section, name = name.split('.', 1)
531 section, name = name.split('.', 1)
523 if not section or not name:
532 if not section or not name:
524 raise IndexError
533 raise IndexError
525 ui.setconfig(section, name, value, '--config')
534 ui.setconfig(section, name, value, '--config')
526 configs.append((section, name, value))
535 configs.append((section, name, value))
527 except (IndexError, ValueError):
536 except (IndexError, ValueError):
528 raise util.Abort(_('malformed --config option: %r '
537 raise util.Abort(_('malformed --config option: %r '
529 '(use --config section.name=value)') % cfg)
538 '(use --config section.name=value)') % cfg)
530
539
531 return configs
540 return configs
532
541
533 def _earlygetopt(aliases, args):
542 def _earlygetopt(aliases, args):
534 """Return list of values for an option (or aliases).
543 """Return list of values for an option (or aliases).
535
544
536 The values are listed in the order they appear in args.
545 The values are listed in the order they appear in args.
537 The options and values are removed from args.
546 The options and values are removed from args.
538
547
539 >>> args = ['x', '--cwd', 'foo', 'y']
548 >>> args = ['x', '--cwd', 'foo', 'y']
540 >>> _earlygetopt(['--cwd'], args), args
549 >>> _earlygetopt(['--cwd'], args), args
541 (['foo'], ['x', 'y'])
550 (['foo'], ['x', 'y'])
542
551
543 >>> args = ['x', '--cwd=bar', 'y']
552 >>> args = ['x', '--cwd=bar', 'y']
544 >>> _earlygetopt(['--cwd'], args), args
553 >>> _earlygetopt(['--cwd'], args), args
545 (['bar'], ['x', 'y'])
554 (['bar'], ['x', 'y'])
546
555
547 >>> args = ['x', '-R', 'foo', 'y']
556 >>> args = ['x', '-R', 'foo', 'y']
548 >>> _earlygetopt(['-R'], args), args
557 >>> _earlygetopt(['-R'], args), args
549 (['foo'], ['x', 'y'])
558 (['foo'], ['x', 'y'])
550
559
551 >>> args = ['x', '-Rbar', 'y']
560 >>> args = ['x', '-Rbar', 'y']
552 >>> _earlygetopt(['-R'], args), args
561 >>> _earlygetopt(['-R'], args), args
553 (['bar'], ['x', 'y'])
562 (['bar'], ['x', 'y'])
554 """
563 """
555 try:
564 try:
556 argcount = args.index("--")
565 argcount = args.index("--")
557 except ValueError:
566 except ValueError:
558 argcount = len(args)
567 argcount = len(args)
559 shortopts = [opt for opt in aliases if len(opt) == 2]
568 shortopts = [opt for opt in aliases if len(opt) == 2]
560 values = []
569 values = []
561 pos = 0
570 pos = 0
562 while pos < argcount:
571 while pos < argcount:
563 fullarg = arg = args[pos]
572 fullarg = arg = args[pos]
564 equals = arg.find('=')
573 equals = arg.find('=')
565 if equals > -1:
574 if equals > -1:
566 arg = arg[:equals]
575 arg = arg[:equals]
567 if arg in aliases:
576 if arg in aliases:
568 del args[pos]
577 del args[pos]
569 if equals > -1:
578 if equals > -1:
570 values.append(fullarg[equals + 1:])
579 values.append(fullarg[equals + 1:])
571 argcount -= 1
580 argcount -= 1
572 else:
581 else:
573 if pos + 1 >= argcount:
582 if pos + 1 >= argcount:
574 # ignore and let getopt report an error if there is no value
583 # ignore and let getopt report an error if there is no value
575 break
584 break
576 values.append(args.pop(pos))
585 values.append(args.pop(pos))
577 argcount -= 2
586 argcount -= 2
578 elif arg[:2] in shortopts:
587 elif arg[:2] in shortopts:
579 # short option can have no following space, e.g. hg log -Rfoo
588 # short option can have no following space, e.g. hg log -Rfoo
580 values.append(args.pop(pos)[2:])
589 values.append(args.pop(pos)[2:])
581 argcount -= 1
590 argcount -= 1
582 else:
591 else:
583 pos += 1
592 pos += 1
584 return values
593 return values
585
594
586 def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
595 def runcommand(lui, repo, cmd, fullargs, ui, options, d, cmdpats, cmdoptions):
587 # run pre-hook, and abort if it fails
596 # run pre-hook, and abort if it fails
588 hook.hook(lui, repo, "pre-%s" % cmd, True, args=" ".join(fullargs),
597 hook.hook(lui, repo, "pre-%s" % cmd, True, args=" ".join(fullargs),
589 pats=cmdpats, opts=cmdoptions)
598 pats=cmdpats, opts=cmdoptions)
590 ret = _runcommand(ui, options, cmd, d)
599 ret = _runcommand(ui, options, cmd, d)
591 # run post-hook, passing command result
600 # run post-hook, passing command result
592 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
601 hook.hook(lui, repo, "post-%s" % cmd, False, args=" ".join(fullargs),
593 result=ret, pats=cmdpats, opts=cmdoptions)
602 result=ret, pats=cmdpats, opts=cmdoptions)
594 return ret
603 return ret
595
604
596 def _getlocal(ui, rpath):
605 def _getlocal(ui, rpath):
597 """Return (path, local ui object) for the given target path.
606 """Return (path, local ui object) for the given target path.
598
607
599 Takes paths in [cwd]/.hg/hgrc into account."
608 Takes paths in [cwd]/.hg/hgrc into account."
600 """
609 """
601 try:
610 try:
602 wd = os.getcwd()
611 wd = os.getcwd()
603 except OSError, e:
612 except OSError, e:
604 raise util.Abort(_("error getting current working directory: %s") %
613 raise util.Abort(_("error getting current working directory: %s") %
605 e.strerror)
614 e.strerror)
606 path = cmdutil.findrepo(wd) or ""
615 path = cmdutil.findrepo(wd) or ""
607 if not path:
616 if not path:
608 lui = ui
617 lui = ui
609 else:
618 else:
610 lui = ui.copy()
619 lui = ui.copy()
611 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
620 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
612
621
613 if rpath and rpath[-1]:
622 if rpath and rpath[-1]:
614 path = lui.expandpath(rpath[-1])
623 path = lui.expandpath(rpath[-1])
615 lui = ui.copy()
624 lui = ui.copy()
616 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
625 lui.readconfig(os.path.join(path, ".hg", "hgrc"), path)
617
626
618 return path, lui
627 return path, lui
619
628
620 def _checkshellalias(lui, ui, args):
629 def _checkshellalias(lui, ui, args):
621 options = {}
630 options = {}
622
631
623 try:
632 try:
624 args = fancyopts.fancyopts(args, commands.globalopts, options)
633 args = fancyopts.fancyopts(args, commands.globalopts, options)
625 except fancyopts.getopt.GetoptError:
634 except fancyopts.getopt.GetoptError:
626 return
635 return
627
636
628 if not args:
637 if not args:
629 return
638 return
630
639
631 norepo = commands.norepo
640 norepo = commands.norepo
632 optionalrepo = commands.optionalrepo
641 optionalrepo = commands.optionalrepo
633 def restorecommands():
642 def restorecommands():
634 commands.norepo = norepo
643 commands.norepo = norepo
635 commands.optionalrepo = optionalrepo
644 commands.optionalrepo = optionalrepo
636
645
637 cmdtable = commands.table.copy()
646 cmdtable = commands.table.copy()
638 addaliases(lui, cmdtable)
647 addaliases(lui, cmdtable)
639
648
640 cmd = args[0]
649 cmd = args[0]
641 try:
650 try:
642 aliases, entry = cmdutil.findcmd(cmd, cmdtable)
651 aliases, entry = cmdutil.findcmd(cmd, cmdtable)
643 except (error.AmbiguousCommand, error.UnknownCommand):
652 except (error.AmbiguousCommand, error.UnknownCommand):
644 restorecommands()
653 restorecommands()
645 return
654 return
646
655
647 cmd = aliases[0]
656 cmd = aliases[0]
648 fn = entry[0]
657 fn = entry[0]
649
658
650 if cmd and util.safehasattr(fn, 'shell'):
659 if cmd and util.safehasattr(fn, 'shell'):
651 d = lambda: fn(ui, *args[1:])
660 d = lambda: fn(ui, *args[1:])
652 return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d,
661 return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d,
653 [], {})
662 [], {})
654
663
655 restorecommands()
664 restorecommands()
656
665
657 _loaded = set()
666 _loaded = set()
658 def _dispatch(req):
667 def _dispatch(req):
659 args = req.args
668 args = req.args
660 ui = req.ui
669 ui = req.ui
661
670
662 # check for cwd
671 # check for cwd
663 cwd = _earlygetopt(['--cwd'], args)
672 cwd = _earlygetopt(['--cwd'], args)
664 if cwd:
673 if cwd:
665 os.chdir(cwd[-1])
674 os.chdir(cwd[-1])
666
675
667 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
676 rpath = _earlygetopt(["-R", "--repository", "--repo"], args)
668 path, lui = _getlocal(ui, rpath)
677 path, lui = _getlocal(ui, rpath)
669
678
670 # Now that we're operating in the right directory/repository with
679 # Now that we're operating in the right directory/repository with
671 # the right config settings, check for shell aliases
680 # the right config settings, check for shell aliases
672 shellaliasfn = _checkshellalias(lui, ui, args)
681 shellaliasfn = _checkshellalias(lui, ui, args)
673 if shellaliasfn:
682 if shellaliasfn:
674 return shellaliasfn()
683 return shellaliasfn()
675
684
676 # Configure extensions in phases: uisetup, extsetup, cmdtable, and
685 # Configure extensions in phases: uisetup, extsetup, cmdtable, and
677 # reposetup. Programs like TortoiseHg will call _dispatch several
686 # reposetup. Programs like TortoiseHg will call _dispatch several
678 # times so we keep track of configured extensions in _loaded.
687 # times so we keep track of configured extensions in _loaded.
679 extensions.loadall(lui)
688 extensions.loadall(lui)
680 exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
689 exts = [ext for ext in extensions.extensions() if ext[0] not in _loaded]
681 # Propagate any changes to lui.__class__ by extensions
690 # Propagate any changes to lui.__class__ by extensions
682 ui.__class__ = lui.__class__
691 ui.__class__ = lui.__class__
683
692
684 # (uisetup and extsetup are handled in extensions.loadall)
693 # (uisetup and extsetup are handled in extensions.loadall)
685
694
686 for name, module in exts:
695 for name, module in exts:
687 cmdtable = getattr(module, 'cmdtable', {})
696 cmdtable = getattr(module, 'cmdtable', {})
688 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
697 overrides = [cmd for cmd in cmdtable if cmd in commands.table]
689 if overrides:
698 if overrides:
690 ui.warn(_("extension '%s' overrides commands: %s\n")
699 ui.warn(_("extension '%s' overrides commands: %s\n")
691 % (name, " ".join(overrides)))
700 % (name, " ".join(overrides)))
692 commands.table.update(cmdtable)
701 commands.table.update(cmdtable)
693 _loaded.add(name)
702 _loaded.add(name)
694
703
695 # (reposetup is handled in hg.repository)
704 # (reposetup is handled in hg.repository)
696
705
697 addaliases(lui, commands.table)
706 addaliases(lui, commands.table)
698
707
699 # check for fallback encoding
708 # check for fallback encoding
700 fallback = lui.config('ui', 'fallbackencoding')
709 fallback = lui.config('ui', 'fallbackencoding')
701 if fallback:
710 if fallback:
702 encoding.fallbackencoding = fallback
711 encoding.fallbackencoding = fallback
703
712
704 fullargs = args
713 fullargs = args
705 cmd, func, args, options, cmdoptions = _parse(lui, args)
714 cmd, func, args, options, cmdoptions = _parse(lui, args)
706
715
707 if options["config"]:
716 if options["config"]:
708 raise util.Abort(_("option --config may not be abbreviated!"))
717 raise util.Abort(_("option --config may not be abbreviated!"))
709 if options["cwd"]:
718 if options["cwd"]:
710 raise util.Abort(_("option --cwd may not be abbreviated!"))
719 raise util.Abort(_("option --cwd may not be abbreviated!"))
711 if options["repository"]:
720 if options["repository"]:
712 raise util.Abort(_(
721 raise util.Abort(_(
713 "option -R has to be separated from other options (e.g. not -qR) "
722 "option -R has to be separated from other options (e.g. not -qR) "
714 "and --repository may only be abbreviated as --repo!"))
723 "and --repository may only be abbreviated as --repo!"))
715
724
716 if options["encoding"]:
725 if options["encoding"]:
717 encoding.encoding = options["encoding"]
726 encoding.encoding = options["encoding"]
718 if options["encodingmode"]:
727 if options["encodingmode"]:
719 encoding.encodingmode = options["encodingmode"]
728 encoding.encodingmode = options["encodingmode"]
720 if options["time"]:
729 if options["time"]:
721 def get_times():
730 def get_times():
722 t = os.times()
731 t = os.times()
723 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
732 if t[4] == 0.0: # Windows leaves this as zero, so use time.clock()
724 t = (t[0], t[1], t[2], t[3], time.clock())
733 t = (t[0], t[1], t[2], t[3], time.clock())
725 return t
734 return t
726 s = get_times()
735 s = get_times()
727 def print_time():
736 def print_time():
728 t = get_times()
737 t = get_times()
729 ui.warn(_("time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
738 ui.warn(_("time: real %.3f secs (user %.3f+%.3f sys %.3f+%.3f)\n") %
730 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
739 (t[4]-s[4], t[0]-s[0], t[2]-s[2], t[1]-s[1], t[3]-s[3]))
731 atexit.register(print_time)
740 atexit.register(print_time)
732
741
733 uis = set([ui, lui])
742 uis = set([ui, lui])
734
743
735 if req.repo:
744 if req.repo:
736 uis.add(req.repo.ui)
745 uis.add(req.repo.ui)
737
746
738 if options['verbose'] or options['debug'] or options['quiet']:
747 if options['verbose'] or options['debug'] or options['quiet']:
739 for opt in ('verbose', 'debug', 'quiet'):
748 for opt in ('verbose', 'debug', 'quiet'):
740 val = str(bool(options[opt]))
749 val = str(bool(options[opt]))
741 for ui_ in uis:
750 for ui_ in uis:
742 ui_.setconfig('ui', opt, val, '--' + opt)
751 ui_.setconfig('ui', opt, val, '--' + opt)
743
752
744 if options['traceback']:
753 if options['traceback']:
745 for ui_ in uis:
754 for ui_ in uis:
746 ui_.setconfig('ui', 'traceback', 'on', '--traceback')
755 ui_.setconfig('ui', 'traceback', 'on', '--traceback')
747
756
748 if options['noninteractive']:
757 if options['noninteractive']:
749 for ui_ in uis:
758 for ui_ in uis:
750 ui_.setconfig('ui', 'interactive', 'off', '-y')
759 ui_.setconfig('ui', 'interactive', 'off', '-y')
751
760
752 if cmdoptions.get('insecure', False):
761 if cmdoptions.get('insecure', False):
753 for ui_ in uis:
762 for ui_ in uis:
754 ui_.setconfig('web', 'cacerts', '', '--insecure')
763 ui_.setconfig('web', 'cacerts', '', '--insecure')
755
764
756 if options['version']:
765 if options['version']:
757 return commands.version_(ui)
766 return commands.version_(ui)
758 if options['help']:
767 if options['help']:
759 return commands.help_(ui, cmd)
768 return commands.help_(ui, cmd)
760 elif not cmd:
769 elif not cmd:
761 return commands.help_(ui, 'shortlist')
770 return commands.help_(ui, 'shortlist')
762
771
763 repo = None
772 repo = None
764 cmdpats = args[:]
773 cmdpats = args[:]
765 if cmd not in commands.norepo.split():
774 if cmd not in commands.norepo.split():
766 # use the repo from the request only if we don't have -R
775 # use the repo from the request only if we don't have -R
767 if not rpath and not cwd:
776 if not rpath and not cwd:
768 repo = req.repo
777 repo = req.repo
769
778
770 if repo:
779 if repo:
771 # set the descriptors of the repo ui to those of ui
780 # set the descriptors of the repo ui to those of ui
772 repo.ui.fin = ui.fin
781 repo.ui.fin = ui.fin
773 repo.ui.fout = ui.fout
782 repo.ui.fout = ui.fout
774 repo.ui.ferr = ui.ferr
783 repo.ui.ferr = ui.ferr
775 else:
784 else:
776 try:
785 try:
777 repo = hg.repository(ui, path=path)
786 repo = hg.repository(ui, path=path)
778 if not repo.local():
787 if not repo.local():
779 raise util.Abort(_("repository '%s' is not local") % path)
788 raise util.Abort(_("repository '%s' is not local") % path)
780 repo.ui.setconfig("bundle", "mainreporoot", repo.root, 'repo')
789 repo.ui.setconfig("bundle", "mainreporoot", repo.root, 'repo')
781 except error.RequirementError:
790 except error.RequirementError:
782 raise
791 raise
783 except error.RepoError:
792 except error.RepoError:
784 if cmd not in commands.optionalrepo.split():
793 if cmd not in commands.optionalrepo.split():
785 if (cmd in commands.inferrepo.split() and
794 if (cmd in commands.inferrepo.split() and
786 args and not path): # try to infer -R from command args
795 args and not path): # try to infer -R from command args
787 repos = map(cmdutil.findrepo, args)
796 repos = map(cmdutil.findrepo, args)
788 guess = repos[0]
797 guess = repos[0]
789 if guess and repos.count(guess) == len(repos):
798 if guess and repos.count(guess) == len(repos):
790 req.args = ['--repository', guess] + fullargs
799 req.args = ['--repository', guess] + fullargs
791 return _dispatch(req)
800 return _dispatch(req)
792 if not path:
801 if not path:
793 raise error.RepoError(_("no repository found in '%s'"
802 raise error.RepoError(_("no repository found in '%s'"
794 " (.hg not found)")
803 " (.hg not found)")
795 % os.getcwd())
804 % os.getcwd())
796 raise
805 raise
797 if repo:
806 if repo:
798 ui = repo.ui
807 ui = repo.ui
799 if options['hidden']:
808 if options['hidden']:
800 repo = repo.unfiltered()
809 repo = repo.unfiltered()
801 args.insert(0, repo)
810 args.insert(0, repo)
802 elif rpath:
811 elif rpath:
803 ui.warn(_("warning: --repository ignored\n"))
812 ui.warn(_("warning: --repository ignored\n"))
804
813
805 msg = ' '.join(' ' in a and repr(a) or a for a in fullargs)
814 msg = ' '.join(' ' in a and repr(a) or a for a in fullargs)
806 ui.log("command", '%s\n', msg)
815 ui.log("command", '%s\n', msg)
807 d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
816 d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
808 try:
817 try:
809 return runcommand(lui, repo, cmd, fullargs, ui, options, d,
818 return runcommand(lui, repo, cmd, fullargs, ui, options, d,
810 cmdpats, cmdoptions)
819 cmdpats, cmdoptions)
811 finally:
820 finally:
812 if repo and repo != req.repo:
821 if repo and repo != req.repo:
813 repo.close()
822 repo.close()
814
823
815 def lsprofile(ui, func, fp):
824 def lsprofile(ui, func, fp):
816 format = ui.config('profiling', 'format', default='text')
825 format = ui.config('profiling', 'format', default='text')
817 field = ui.config('profiling', 'sort', default='inlinetime')
826 field = ui.config('profiling', 'sort', default='inlinetime')
818 limit = ui.configint('profiling', 'limit', default=30)
827 limit = ui.configint('profiling', 'limit', default=30)
819 climit = ui.configint('profiling', 'nested', default=5)
828 climit = ui.configint('profiling', 'nested', default=5)
820
829
821 if format not in ['text', 'kcachegrind']:
830 if format not in ['text', 'kcachegrind']:
822 ui.warn(_("unrecognized profiling format '%s'"
831 ui.warn(_("unrecognized profiling format '%s'"
823 " - Ignored\n") % format)
832 " - Ignored\n") % format)
824 format = 'text'
833 format = 'text'
825
834
826 try:
835 try:
827 from mercurial import lsprof
836 from mercurial import lsprof
828 except ImportError:
837 except ImportError:
829 raise util.Abort(_(
838 raise util.Abort(_(
830 'lsprof not available - install from '
839 'lsprof not available - install from '
831 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
840 'http://codespeak.net/svn/user/arigo/hack/misc/lsprof/'))
832 p = lsprof.Profiler()
841 p = lsprof.Profiler()
833 p.enable(subcalls=True)
842 p.enable(subcalls=True)
834 try:
843 try:
835 return func()
844 return func()
836 finally:
845 finally:
837 p.disable()
846 p.disable()
838
847
839 if format == 'kcachegrind':
848 if format == 'kcachegrind':
840 import lsprofcalltree
849 import lsprofcalltree
841 calltree = lsprofcalltree.KCacheGrind(p)
850 calltree = lsprofcalltree.KCacheGrind(p)
842 calltree.output(fp)
851 calltree.output(fp)
843 else:
852 else:
844 # format == 'text'
853 # format == 'text'
845 stats = lsprof.Stats(p.getstats())
854 stats = lsprof.Stats(p.getstats())
846 stats.sort(field)
855 stats.sort(field)
847 stats.pprint(limit=limit, file=fp, climit=climit)
856 stats.pprint(limit=limit, file=fp, climit=climit)
848
857
849 def statprofile(ui, func, fp):
858 def statprofile(ui, func, fp):
850 try:
859 try:
851 import statprof
860 import statprof
852 except ImportError:
861 except ImportError:
853 raise util.Abort(_(
862 raise util.Abort(_(
854 'statprof not available - install using "easy_install statprof"'))
863 'statprof not available - install using "easy_install statprof"'))
855
864
856 freq = ui.configint('profiling', 'freq', default=1000)
865 freq = ui.configint('profiling', 'freq', default=1000)
857 if freq > 0:
866 if freq > 0:
858 statprof.reset(freq)
867 statprof.reset(freq)
859 else:
868 else:
860 ui.warn(_("invalid sampling frequency '%s' - ignoring\n") % freq)
869 ui.warn(_("invalid sampling frequency '%s' - ignoring\n") % freq)
861
870
862 statprof.start()
871 statprof.start()
863 try:
872 try:
864 return func()
873 return func()
865 finally:
874 finally:
866 statprof.stop()
875 statprof.stop()
867 statprof.display(fp)
876 statprof.display(fp)
868
877
869 def _runcommand(ui, options, cmd, cmdfunc):
878 def _runcommand(ui, options, cmd, cmdfunc):
870 def checkargs():
879 def checkargs():
871 try:
880 try:
872 return cmdfunc()
881 return cmdfunc()
873 except error.SignatureError:
882 except error.SignatureError:
874 raise error.CommandError(cmd, _("invalid arguments"))
883 raise error.CommandError(cmd, _("invalid arguments"))
875
884
876 if options['profile']:
885 if options['profile']:
877 profiler = os.getenv('HGPROF')
886 profiler = os.getenv('HGPROF')
878 if profiler is None:
887 if profiler is None:
879 profiler = ui.config('profiling', 'type', default='ls')
888 profiler = ui.config('profiling', 'type', default='ls')
880 if profiler not in ('ls', 'stat'):
889 if profiler not in ('ls', 'stat'):
881 ui.warn(_("unrecognized profiler '%s' - ignored\n") % profiler)
890 ui.warn(_("unrecognized profiler '%s' - ignored\n") % profiler)
882 profiler = 'ls'
891 profiler = 'ls'
883
892
884 output = ui.config('profiling', 'output')
893 output = ui.config('profiling', 'output')
885
894
886 if output:
895 if output:
887 path = ui.expandpath(output)
896 path = ui.expandpath(output)
888 fp = open(path, 'wb')
897 fp = open(path, 'wb')
889 else:
898 else:
890 fp = sys.stderr
899 fp = sys.stderr
891
900
892 try:
901 try:
893 if profiler == 'ls':
902 if profiler == 'ls':
894 return lsprofile(ui, checkargs, fp)
903 return lsprofile(ui, checkargs, fp)
895 else:
904 else:
896 return statprofile(ui, checkargs, fp)
905 return statprofile(ui, checkargs, fp)
897 finally:
906 finally:
898 if output:
907 if output:
899 fp.close()
908 fp.close()
900 else:
909 else:
901 return checkargs()
910 return checkargs()
@@ -1,144 +1,166 b''
1 import os, errno, stat
1 import os, errno, stat
2
2
3 import util
3 import util
4 from i18n import _
4 from i18n import _
5
5
6 class pathauditor(object):
6 class pathauditor(object):
7 '''ensure that a filesystem path contains no banned components.
7 '''ensure that a filesystem path contains no banned components.
8 the following properties of a path are checked:
8 the following properties of a path are checked:
9
9
10 - ends with a directory separator
10 - ends with a directory separator
11 - under top-level .hg
11 - under top-level .hg
12 - starts at the root of a windows drive
12 - starts at the root of a windows drive
13 - contains ".."
13 - contains ".."
14 - traverses a symlink (e.g. a/symlink_here/b)
14 - traverses a symlink (e.g. a/symlink_here/b)
15 - inside a nested repository (a callback can be used to approve
15 - inside a nested repository (a callback can be used to approve
16 some nested repositories, e.g., subrepositories)
16 some nested repositories, e.g., subrepositories)
17 '''
17 '''
18
18
19 def __init__(self, root, callback=None):
19 def __init__(self, root, callback=None):
20 self.audited = set()
20 self.audited = set()
21 self.auditeddir = set()
21 self.auditeddir = set()
22 self.root = root
22 self.root = root
23 self.callback = callback
23 self.callback = callback
24 if os.path.lexists(root) and not util.checkcase(root):
24 if os.path.lexists(root) and not util.checkcase(root):
25 self.normcase = util.normcase
25 self.normcase = util.normcase
26 else:
26 else:
27 self.normcase = lambda x: x
27 self.normcase = lambda x: x
28
28
29 def __call__(self, path):
29 def __call__(self, path):
30 '''Check the relative path.
30 '''Check the relative path.
31 path may contain a pattern (e.g. foodir/**.txt)'''
31 path may contain a pattern (e.g. foodir/**.txt)'''
32
32
33 path = util.localpath(path)
33 path = util.localpath(path)
34 normpath = self.normcase(path)
34 normpath = self.normcase(path)
35 if normpath in self.audited:
35 if normpath in self.audited:
36 return
36 return
37 # AIX ignores "/" at end of path, others raise EISDIR.
37 # AIX ignores "/" at end of path, others raise EISDIR.
38 if util.endswithsep(path):
38 if util.endswithsep(path):
39 raise util.Abort(_("path ends in directory separator: %s") % path)
39 raise util.Abort(_("path ends in directory separator: %s") % path)
40 parts = util.splitpath(path)
40 parts = util.splitpath(path)
41 if (os.path.splitdrive(path)[0]
41 if (os.path.splitdrive(path)[0]
42 or parts[0].lower() in ('.hg', '.hg.', '')
42 or parts[0].lower() in ('.hg', '.hg.', '')
43 or os.pardir in parts):
43 or os.pardir in parts):
44 raise util.Abort(_("path contains illegal component: %s") % path)
44 raise util.Abort(_("path contains illegal component: %s") % path)
45 if '.hg' in path.lower():
45 if '.hg' in path.lower():
46 lparts = [p.lower() for p in parts]
46 lparts = [p.lower() for p in parts]
47 for p in '.hg', '.hg.':
47 for p in '.hg', '.hg.':
48 if p in lparts[1:]:
48 if p in lparts[1:]:
49 pos = lparts.index(p)
49 pos = lparts.index(p)
50 base = os.path.join(*parts[:pos])
50 base = os.path.join(*parts[:pos])
51 raise util.Abort(_("path '%s' is inside nested repo %r")
51 raise util.Abort(_("path '%s' is inside nested repo %r")
52 % (path, base))
52 % (path, base))
53
53
54 normparts = util.splitpath(normpath)
54 normparts = util.splitpath(normpath)
55 assert len(parts) == len(normparts)
55 assert len(parts) == len(normparts)
56
56
57 parts.pop()
57 parts.pop()
58 normparts.pop()
58 normparts.pop()
59 prefixes = []
59 prefixes = []
60 while parts:
60 while parts:
61 prefix = os.sep.join(parts)
61 prefix = os.sep.join(parts)
62 normprefix = os.sep.join(normparts)
62 normprefix = os.sep.join(normparts)
63 if normprefix in self.auditeddir:
63 if normprefix in self.auditeddir:
64 break
64 break
65 curpath = os.path.join(self.root, prefix)
65 curpath = os.path.join(self.root, prefix)
66 try:
66 try:
67 st = os.lstat(curpath)
67 st = os.lstat(curpath)
68 except OSError, err:
68 except OSError, err:
69 # EINVAL can be raised as invalid path syntax under win32.
69 # EINVAL can be raised as invalid path syntax under win32.
70 # They must be ignored for patterns can be checked too.
70 # They must be ignored for patterns can be checked too.
71 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
71 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
72 raise
72 raise
73 else:
73 else:
74 if stat.S_ISLNK(st.st_mode):
74 if stat.S_ISLNK(st.st_mode):
75 raise util.Abort(
75 raise util.Abort(
76 _('path %r traverses symbolic link %r')
76 _('path %r traverses symbolic link %r')
77 % (path, prefix))
77 % (path, prefix))
78 elif (stat.S_ISDIR(st.st_mode) and
78 elif (stat.S_ISDIR(st.st_mode) and
79 os.path.isdir(os.path.join(curpath, '.hg'))):
79 os.path.isdir(os.path.join(curpath, '.hg'))):
80 if not self.callback or not self.callback(curpath):
80 if not self.callback or not self.callback(curpath):
81 raise util.Abort(_("path '%s' is inside nested "
81 raise util.Abort(_("path '%s' is inside nested "
82 "repo %r")
82 "repo %r")
83 % (path, prefix))
83 % (path, prefix))
84 prefixes.append(normprefix)
84 prefixes.append(normprefix)
85 parts.pop()
85 parts.pop()
86 normparts.pop()
86 normparts.pop()
87
87
88 self.audited.add(normpath)
88 self.audited.add(normpath)
89 # only add prefixes to the cache after checking everything: we don't
89 # only add prefixes to the cache after checking everything: we don't
90 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
90 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
91 self.auditeddir.update(prefixes)
91 self.auditeddir.update(prefixes)
92
92
93 def check(self, path):
93 def check(self, path):
94 try:
94 try:
95 self(path)
95 self(path)
96 return True
96 return True
97 except (OSError, util.Abort):
97 except (OSError, util.Abort):
98 return False
98 return False
99
99
100 def canonpath(root, cwd, myname, auditor=None):
100 def canonpath(root, cwd, myname, auditor=None):
101 '''return the canonical path of myname, given cwd and root'''
101 '''return the canonical path of myname, given cwd and root'''
102 if util.endswithsep(root):
102 if util.endswithsep(root):
103 rootsep = root
103 rootsep = root
104 else:
104 else:
105 rootsep = root + os.sep
105 rootsep = root + os.sep
106 name = myname
106 name = myname
107 if not os.path.isabs(name):
107 if not os.path.isabs(name):
108 name = os.path.join(root, cwd, name)
108 name = os.path.join(root, cwd, name)
109 name = os.path.normpath(name)
109 name = os.path.normpath(name)
110 if auditor is None:
110 if auditor is None:
111 auditor = pathauditor(root)
111 auditor = pathauditor(root)
112 if name != rootsep and name.startswith(rootsep):
112 if name != rootsep and name.startswith(rootsep):
113 name = name[len(rootsep):]
113 name = name[len(rootsep):]
114 auditor(name)
114 auditor(name)
115 return util.pconvert(name)
115 return util.pconvert(name)
116 elif name == root:
116 elif name == root:
117 return ''
117 return ''
118 else:
118 else:
119 # Determine whether `name' is in the hierarchy at or beneath `root',
119 # Determine whether `name' is in the hierarchy at or beneath `root',
120 # by iterating name=dirname(name) until that causes no change (can't
120 # by iterating name=dirname(name) until that causes no change (can't
121 # check name == '/', because that doesn't work on windows). The list
121 # check name == '/', because that doesn't work on windows). The list
122 # `rel' holds the reversed list of components making up the relative
122 # `rel' holds the reversed list of components making up the relative
123 # file name we want.
123 # file name we want.
124 rel = []
124 rel = []
125 while True:
125 while True:
126 try:
126 try:
127 s = util.samefile(name, root)
127 s = util.samefile(name, root)
128 except OSError:
128 except OSError:
129 s = False
129 s = False
130 if s:
130 if s:
131 if not rel:
131 if not rel:
132 # name was actually the same as root (maybe a symlink)
132 # name was actually the same as root (maybe a symlink)
133 return ''
133 return ''
134 rel.reverse()
134 rel.reverse()
135 name = os.path.join(*rel)
135 name = os.path.join(*rel)
136 auditor(name)
136 auditor(name)
137 return util.pconvert(name)
137 return util.pconvert(name)
138 dirname, basename = util.split(name)
138 dirname, basename = util.split(name)
139 rel.append(basename)
139 rel.append(basename)
140 if dirname == name:
140 if dirname == name:
141 break
141 break
142 name = dirname
142 name = dirname
143
143
144 raise util.Abort(_("%s not under root '%s'") % (myname, root))
144 raise util.Abort(_("%s not under root '%s'") % (myname, root))
145
146 def normasprefix(path):
147 '''normalize the specified path as path prefix
148
149 Returned vaule can be used safely for "p.startswith(prefix)",
150 "p[len(prefix):]", and so on.
151
152 For efficiency, this expects "path" argument to be already
153 normalized by "os.path.normpath", "os.path.realpath", and so on.
154
155 See also issue3033 for detail about need of this function.
156
157 >>> normasprefix('/foo/bar').replace(os.sep, '/')
158 '/foo/bar/'
159 >>> normasprefix('/').replace(os.sep, '/')
160 '/'
161 '''
162 d, p = os.path.splitdrive(path)
163 if len(p) != len(os.sep):
164 return path + os.sep
165 else:
166 return path
@@ -1,1578 +1,1580 b''
1 # subrepo.py - sub-repository handling for Mercurial
1 # subrepo.py - sub-repository handling for Mercurial
2 #
2 #
3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
3 # Copyright 2009-2010 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 import errno, os, re, shutil, posixpath, sys
8 import errno, os, re, shutil, posixpath, sys
9 import xml.dom.minidom
9 import xml.dom.minidom
10 import stat, subprocess, tarfile
10 import stat, subprocess, tarfile
11 from i18n import _
11 from i18n import _
12 import config, util, node, error, cmdutil, bookmarks, match as matchmod
12 import config, util, node, error, cmdutil, bookmarks, match as matchmod
13 import phases
13 import phases
14 import pathutil
14 import pathutil
15 hg = None
15 hg = None
16 propertycache = util.propertycache
16 propertycache = util.propertycache
17
17
18 nullstate = ('', '', 'empty')
18 nullstate = ('', '', 'empty')
19
19
20 def _expandedabspath(path):
20 def _expandedabspath(path):
21 '''
21 '''
22 get a path or url and if it is a path expand it and return an absolute path
22 get a path or url and if it is a path expand it and return an absolute path
23 '''
23 '''
24 expandedpath = util.urllocalpath(util.expandpath(path))
24 expandedpath = util.urllocalpath(util.expandpath(path))
25 u = util.url(expandedpath)
25 u = util.url(expandedpath)
26 if not u.scheme:
26 if not u.scheme:
27 path = util.normpath(os.path.abspath(u.path))
27 path = util.normpath(os.path.abspath(u.path))
28 return path
28 return path
29
29
30 def _getstorehashcachename(remotepath):
30 def _getstorehashcachename(remotepath):
31 '''get a unique filename for the store hash cache of a remote repository'''
31 '''get a unique filename for the store hash cache of a remote repository'''
32 return util.sha1(_expandedabspath(remotepath)).hexdigest()[0:12]
32 return util.sha1(_expandedabspath(remotepath)).hexdigest()[0:12]
33
33
34 def _calcfilehash(filename):
34 def _calcfilehash(filename):
35 data = ''
35 data = ''
36 if os.path.exists(filename):
36 if os.path.exists(filename):
37 fd = open(filename, 'rb')
37 fd = open(filename, 'rb')
38 data = fd.read()
38 data = fd.read()
39 fd.close()
39 fd.close()
40 return util.sha1(data).hexdigest()
40 return util.sha1(data).hexdigest()
41
41
42 class SubrepoAbort(error.Abort):
42 class SubrepoAbort(error.Abort):
43 """Exception class used to avoid handling a subrepo error more than once"""
43 """Exception class used to avoid handling a subrepo error more than once"""
44 def __init__(self, *args, **kw):
44 def __init__(self, *args, **kw):
45 error.Abort.__init__(self, *args, **kw)
45 error.Abort.__init__(self, *args, **kw)
46 self.subrepo = kw.get('subrepo')
46 self.subrepo = kw.get('subrepo')
47 self.cause = kw.get('cause')
47 self.cause = kw.get('cause')
48
48
49 def annotatesubrepoerror(func):
49 def annotatesubrepoerror(func):
50 def decoratedmethod(self, *args, **kargs):
50 def decoratedmethod(self, *args, **kargs):
51 try:
51 try:
52 res = func(self, *args, **kargs)
52 res = func(self, *args, **kargs)
53 except SubrepoAbort, ex:
53 except SubrepoAbort, ex:
54 # This exception has already been handled
54 # This exception has already been handled
55 raise ex
55 raise ex
56 except error.Abort, ex:
56 except error.Abort, ex:
57 subrepo = subrelpath(self)
57 subrepo = subrelpath(self)
58 errormsg = str(ex) + ' ' + _('(in subrepo %s)') % subrepo
58 errormsg = str(ex) + ' ' + _('(in subrepo %s)') % subrepo
59 # avoid handling this exception by raising a SubrepoAbort exception
59 # avoid handling this exception by raising a SubrepoAbort exception
60 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
60 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
61 cause=sys.exc_info())
61 cause=sys.exc_info())
62 return res
62 return res
63 return decoratedmethod
63 return decoratedmethod
64
64
65 def state(ctx, ui):
65 def state(ctx, ui):
66 """return a state dict, mapping subrepo paths configured in .hgsub
66 """return a state dict, mapping subrepo paths configured in .hgsub
67 to tuple: (source from .hgsub, revision from .hgsubstate, kind
67 to tuple: (source from .hgsub, revision from .hgsubstate, kind
68 (key in types dict))
68 (key in types dict))
69 """
69 """
70 p = config.config()
70 p = config.config()
71 def read(f, sections=None, remap=None):
71 def read(f, sections=None, remap=None):
72 if f in ctx:
72 if f in ctx:
73 try:
73 try:
74 data = ctx[f].data()
74 data = ctx[f].data()
75 except IOError, err:
75 except IOError, err:
76 if err.errno != errno.ENOENT:
76 if err.errno != errno.ENOENT:
77 raise
77 raise
78 # handle missing subrepo spec files as removed
78 # handle missing subrepo spec files as removed
79 ui.warn(_("warning: subrepo spec file %s not found\n") % f)
79 ui.warn(_("warning: subrepo spec file %s not found\n") % f)
80 return
80 return
81 p.parse(f, data, sections, remap, read)
81 p.parse(f, data, sections, remap, read)
82 else:
82 else:
83 raise util.Abort(_("subrepo spec file %s not found") % f)
83 raise util.Abort(_("subrepo spec file %s not found") % f)
84
84
85 if '.hgsub' in ctx:
85 if '.hgsub' in ctx:
86 read('.hgsub')
86 read('.hgsub')
87
87
88 for path, src in ui.configitems('subpaths'):
88 for path, src in ui.configitems('subpaths'):
89 p.set('subpaths', path, src, ui.configsource('subpaths', path))
89 p.set('subpaths', path, src, ui.configsource('subpaths', path))
90
90
91 rev = {}
91 rev = {}
92 if '.hgsubstate' in ctx:
92 if '.hgsubstate' in ctx:
93 try:
93 try:
94 for i, l in enumerate(ctx['.hgsubstate'].data().splitlines()):
94 for i, l in enumerate(ctx['.hgsubstate'].data().splitlines()):
95 l = l.lstrip()
95 l = l.lstrip()
96 if not l:
96 if not l:
97 continue
97 continue
98 try:
98 try:
99 revision, path = l.split(" ", 1)
99 revision, path = l.split(" ", 1)
100 except ValueError:
100 except ValueError:
101 raise util.Abort(_("invalid subrepository revision "
101 raise util.Abort(_("invalid subrepository revision "
102 "specifier in .hgsubstate line %d")
102 "specifier in .hgsubstate line %d")
103 % (i + 1))
103 % (i + 1))
104 rev[path] = revision
104 rev[path] = revision
105 except IOError, err:
105 except IOError, err:
106 if err.errno != errno.ENOENT:
106 if err.errno != errno.ENOENT:
107 raise
107 raise
108
108
109 def remap(src):
109 def remap(src):
110 for pattern, repl in p.items('subpaths'):
110 for pattern, repl in p.items('subpaths'):
111 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
111 # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
112 # does a string decode.
112 # does a string decode.
113 repl = repl.encode('string-escape')
113 repl = repl.encode('string-escape')
114 # However, we still want to allow back references to go
114 # However, we still want to allow back references to go
115 # through unharmed, so we turn r'\\1' into r'\1'. Again,
115 # through unharmed, so we turn r'\\1' into r'\1'. Again,
116 # extra escapes are needed because re.sub string decodes.
116 # extra escapes are needed because re.sub string decodes.
117 repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
117 repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
118 try:
118 try:
119 src = re.sub(pattern, repl, src, 1)
119 src = re.sub(pattern, repl, src, 1)
120 except re.error, e:
120 except re.error, e:
121 raise util.Abort(_("bad subrepository pattern in %s: %s")
121 raise util.Abort(_("bad subrepository pattern in %s: %s")
122 % (p.source('subpaths', pattern), e))
122 % (p.source('subpaths', pattern), e))
123 return src
123 return src
124
124
125 state = {}
125 state = {}
126 for path, src in p[''].items():
126 for path, src in p[''].items():
127 kind = 'hg'
127 kind = 'hg'
128 if src.startswith('['):
128 if src.startswith('['):
129 if ']' not in src:
129 if ']' not in src:
130 raise util.Abort(_('missing ] in subrepo source'))
130 raise util.Abort(_('missing ] in subrepo source'))
131 kind, src = src.split(']', 1)
131 kind, src = src.split(']', 1)
132 kind = kind[1:]
132 kind = kind[1:]
133 src = src.lstrip() # strip any extra whitespace after ']'
133 src = src.lstrip() # strip any extra whitespace after ']'
134
134
135 if not util.url(src).isabs():
135 if not util.url(src).isabs():
136 parent = _abssource(ctx._repo, abort=False)
136 parent = _abssource(ctx._repo, abort=False)
137 if parent:
137 if parent:
138 parent = util.url(parent)
138 parent = util.url(parent)
139 parent.path = posixpath.join(parent.path or '', src)
139 parent.path = posixpath.join(parent.path or '', src)
140 parent.path = posixpath.normpath(parent.path)
140 parent.path = posixpath.normpath(parent.path)
141 joined = str(parent)
141 joined = str(parent)
142 # Remap the full joined path and use it if it changes,
142 # Remap the full joined path and use it if it changes,
143 # else remap the original source.
143 # else remap the original source.
144 remapped = remap(joined)
144 remapped = remap(joined)
145 if remapped == joined:
145 if remapped == joined:
146 src = remap(src)
146 src = remap(src)
147 else:
147 else:
148 src = remapped
148 src = remapped
149
149
150 src = remap(src)
150 src = remap(src)
151 state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
151 state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
152
152
153 return state
153 return state
154
154
155 def writestate(repo, state):
155 def writestate(repo, state):
156 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
156 """rewrite .hgsubstate in (outer) repo with these subrepo states"""
157 lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)]
157 lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)]
158 repo.wwrite('.hgsubstate', ''.join(lines), '')
158 repo.wwrite('.hgsubstate', ''.join(lines), '')
159
159
160 def submerge(repo, wctx, mctx, actx, overwrite):
160 def submerge(repo, wctx, mctx, actx, overwrite):
161 """delegated from merge.applyupdates: merging of .hgsubstate file
161 """delegated from merge.applyupdates: merging of .hgsubstate file
162 in working context, merging context and ancestor context"""
162 in working context, merging context and ancestor context"""
163 if mctx == actx: # backwards?
163 if mctx == actx: # backwards?
164 actx = wctx.p1()
164 actx = wctx.p1()
165 s1 = wctx.substate
165 s1 = wctx.substate
166 s2 = mctx.substate
166 s2 = mctx.substate
167 sa = actx.substate
167 sa = actx.substate
168 sm = {}
168 sm = {}
169
169
170 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
170 repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
171
171
172 def debug(s, msg, r=""):
172 def debug(s, msg, r=""):
173 if r:
173 if r:
174 r = "%s:%s:%s" % r
174 r = "%s:%s:%s" % r
175 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
175 repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
176
176
177 for s, l in sorted(s1.iteritems()):
177 for s, l in sorted(s1.iteritems()):
178 a = sa.get(s, nullstate)
178 a = sa.get(s, nullstate)
179 ld = l # local state with possible dirty flag for compares
179 ld = l # local state with possible dirty flag for compares
180 if wctx.sub(s).dirty():
180 if wctx.sub(s).dirty():
181 ld = (l[0], l[1] + "+")
181 ld = (l[0], l[1] + "+")
182 if wctx == actx: # overwrite
182 if wctx == actx: # overwrite
183 a = ld
183 a = ld
184
184
185 if s in s2:
185 if s in s2:
186 r = s2[s]
186 r = s2[s]
187 if ld == r or r == a: # no change or local is newer
187 if ld == r or r == a: # no change or local is newer
188 sm[s] = l
188 sm[s] = l
189 continue
189 continue
190 elif ld == a: # other side changed
190 elif ld == a: # other side changed
191 debug(s, "other changed, get", r)
191 debug(s, "other changed, get", r)
192 wctx.sub(s).get(r, overwrite)
192 wctx.sub(s).get(r, overwrite)
193 sm[s] = r
193 sm[s] = r
194 elif ld[0] != r[0]: # sources differ
194 elif ld[0] != r[0]: # sources differ
195 if repo.ui.promptchoice(
195 if repo.ui.promptchoice(
196 _(' subrepository sources for %s differ\n'
196 _(' subrepository sources for %s differ\n'
197 'use (l)ocal source (%s) or (r)emote source (%s)?'
197 'use (l)ocal source (%s) or (r)emote source (%s)?'
198 '$$ &Local $$ &Remote') % (s, l[0], r[0]), 0):
198 '$$ &Local $$ &Remote') % (s, l[0], r[0]), 0):
199 debug(s, "prompt changed, get", r)
199 debug(s, "prompt changed, get", r)
200 wctx.sub(s).get(r, overwrite)
200 wctx.sub(s).get(r, overwrite)
201 sm[s] = r
201 sm[s] = r
202 elif ld[1] == a[1]: # local side is unchanged
202 elif ld[1] == a[1]: # local side is unchanged
203 debug(s, "other side changed, get", r)
203 debug(s, "other side changed, get", r)
204 wctx.sub(s).get(r, overwrite)
204 wctx.sub(s).get(r, overwrite)
205 sm[s] = r
205 sm[s] = r
206 else:
206 else:
207 debug(s, "both sides changed")
207 debug(s, "both sides changed")
208 srepo = wctx.sub(s)
208 srepo = wctx.sub(s)
209 option = repo.ui.promptchoice(
209 option = repo.ui.promptchoice(
210 _(' subrepository %s diverged (local revision: %s, '
210 _(' subrepository %s diverged (local revision: %s, '
211 'remote revision: %s)\n'
211 'remote revision: %s)\n'
212 '(M)erge, keep (l)ocal or keep (r)emote?'
212 '(M)erge, keep (l)ocal or keep (r)emote?'
213 '$$ &Merge $$ &Local $$ &Remote')
213 '$$ &Merge $$ &Local $$ &Remote')
214 % (s, srepo.shortid(l[1]), srepo.shortid(r[1])), 0)
214 % (s, srepo.shortid(l[1]), srepo.shortid(r[1])), 0)
215 if option == 0:
215 if option == 0:
216 wctx.sub(s).merge(r)
216 wctx.sub(s).merge(r)
217 sm[s] = l
217 sm[s] = l
218 debug(s, "merge with", r)
218 debug(s, "merge with", r)
219 elif option == 1:
219 elif option == 1:
220 sm[s] = l
220 sm[s] = l
221 debug(s, "keep local subrepo revision", l)
221 debug(s, "keep local subrepo revision", l)
222 else:
222 else:
223 wctx.sub(s).get(r, overwrite)
223 wctx.sub(s).get(r, overwrite)
224 sm[s] = r
224 sm[s] = r
225 debug(s, "get remote subrepo revision", r)
225 debug(s, "get remote subrepo revision", r)
226 elif ld == a: # remote removed, local unchanged
226 elif ld == a: # remote removed, local unchanged
227 debug(s, "remote removed, remove")
227 debug(s, "remote removed, remove")
228 wctx.sub(s).remove()
228 wctx.sub(s).remove()
229 elif a == nullstate: # not present in remote or ancestor
229 elif a == nullstate: # not present in remote or ancestor
230 debug(s, "local added, keep")
230 debug(s, "local added, keep")
231 sm[s] = l
231 sm[s] = l
232 continue
232 continue
233 else:
233 else:
234 if repo.ui.promptchoice(
234 if repo.ui.promptchoice(
235 _(' local changed subrepository %s which remote removed\n'
235 _(' local changed subrepository %s which remote removed\n'
236 'use (c)hanged version or (d)elete?'
236 'use (c)hanged version or (d)elete?'
237 '$$ &Changed $$ &Delete') % s, 0):
237 '$$ &Changed $$ &Delete') % s, 0):
238 debug(s, "prompt remove")
238 debug(s, "prompt remove")
239 wctx.sub(s).remove()
239 wctx.sub(s).remove()
240
240
241 for s, r in sorted(s2.items()):
241 for s, r in sorted(s2.items()):
242 if s in s1:
242 if s in s1:
243 continue
243 continue
244 elif s not in sa:
244 elif s not in sa:
245 debug(s, "remote added, get", r)
245 debug(s, "remote added, get", r)
246 mctx.sub(s).get(r)
246 mctx.sub(s).get(r)
247 sm[s] = r
247 sm[s] = r
248 elif r != sa[s]:
248 elif r != sa[s]:
249 if repo.ui.promptchoice(
249 if repo.ui.promptchoice(
250 _(' remote changed subrepository %s which local removed\n'
250 _(' remote changed subrepository %s which local removed\n'
251 'use (c)hanged version or (d)elete?'
251 'use (c)hanged version or (d)elete?'
252 '$$ &Changed $$ &Delete') % s, 0) == 0:
252 '$$ &Changed $$ &Delete') % s, 0) == 0:
253 debug(s, "prompt recreate", r)
253 debug(s, "prompt recreate", r)
254 wctx.sub(s).get(r)
254 wctx.sub(s).get(r)
255 sm[s] = r
255 sm[s] = r
256
256
257 # record merged .hgsubstate
257 # record merged .hgsubstate
258 writestate(repo, sm)
258 writestate(repo, sm)
259 return sm
259 return sm
260
260
261 def _updateprompt(ui, sub, dirty, local, remote):
261 def _updateprompt(ui, sub, dirty, local, remote):
262 if dirty:
262 if dirty:
263 msg = (_(' subrepository sources for %s differ\n'
263 msg = (_(' subrepository sources for %s differ\n'
264 'use (l)ocal source (%s) or (r)emote source (%s)?\n'
264 'use (l)ocal source (%s) or (r)emote source (%s)?\n'
265 '$$ &Local $$ &Remote')
265 '$$ &Local $$ &Remote')
266 % (subrelpath(sub), local, remote))
266 % (subrelpath(sub), local, remote))
267 else:
267 else:
268 msg = (_(' subrepository sources for %s differ (in checked out '
268 msg = (_(' subrepository sources for %s differ (in checked out '
269 'version)\n'
269 'version)\n'
270 'use (l)ocal source (%s) or (r)emote source (%s)?\n'
270 'use (l)ocal source (%s) or (r)emote source (%s)?\n'
271 '$$ &Local $$ &Remote')
271 '$$ &Local $$ &Remote')
272 % (subrelpath(sub), local, remote))
272 % (subrelpath(sub), local, remote))
273 return ui.promptchoice(msg, 0)
273 return ui.promptchoice(msg, 0)
274
274
275 def reporelpath(repo):
275 def reporelpath(repo):
276 """return path to this (sub)repo as seen from outermost repo"""
276 """return path to this (sub)repo as seen from outermost repo"""
277 parent = repo
277 parent = repo
278 while util.safehasattr(parent, '_subparent'):
278 while util.safehasattr(parent, '_subparent'):
279 parent = parent._subparent
279 parent = parent._subparent
280 p = parent.root.rstrip(os.sep)
280 return repo.root[len(pathutil.normasprefix(parent.root)):]
281 return repo.root[len(p) + 1:]
282
281
283 def subrelpath(sub):
282 def subrelpath(sub):
284 """return path to this subrepo as seen from outermost repo"""
283 """return path to this subrepo as seen from outermost repo"""
285 if util.safehasattr(sub, '_relpath'):
284 if util.safehasattr(sub, '_relpath'):
286 return sub._relpath
285 return sub._relpath
287 if not util.safehasattr(sub, '_repo'):
286 if not util.safehasattr(sub, '_repo'):
288 return sub._path
287 return sub._path
289 return reporelpath(sub._repo)
288 return reporelpath(sub._repo)
290
289
291 def _abssource(repo, push=False, abort=True):
290 def _abssource(repo, push=False, abort=True):
292 """return pull/push path of repo - either based on parent repo .hgsub info
291 """return pull/push path of repo - either based on parent repo .hgsub info
293 or on the top repo config. Abort or return None if no source found."""
292 or on the top repo config. Abort or return None if no source found."""
294 if util.safehasattr(repo, '_subparent'):
293 if util.safehasattr(repo, '_subparent'):
295 source = util.url(repo._subsource)
294 source = util.url(repo._subsource)
296 if source.isabs():
295 if source.isabs():
297 return str(source)
296 return str(source)
298 source.path = posixpath.normpath(source.path)
297 source.path = posixpath.normpath(source.path)
299 parent = _abssource(repo._subparent, push, abort=False)
298 parent = _abssource(repo._subparent, push, abort=False)
300 if parent:
299 if parent:
301 parent = util.url(util.pconvert(parent))
300 parent = util.url(util.pconvert(parent))
302 parent.path = posixpath.join(parent.path or '', source.path)
301 parent.path = posixpath.join(parent.path or '', source.path)
303 parent.path = posixpath.normpath(parent.path)
302 parent.path = posixpath.normpath(parent.path)
304 return str(parent)
303 return str(parent)
305 else: # recursion reached top repo
304 else: # recursion reached top repo
306 if util.safehasattr(repo, '_subtoppath'):
305 if util.safehasattr(repo, '_subtoppath'):
307 return repo._subtoppath
306 return repo._subtoppath
308 if push and repo.ui.config('paths', 'default-push'):
307 if push and repo.ui.config('paths', 'default-push'):
309 return repo.ui.config('paths', 'default-push')
308 return repo.ui.config('paths', 'default-push')
310 if repo.ui.config('paths', 'default'):
309 if repo.ui.config('paths', 'default'):
311 return repo.ui.config('paths', 'default')
310 return repo.ui.config('paths', 'default')
312 if repo.sharedpath != repo.path:
311 if repo.sharedpath != repo.path:
313 # chop off the .hg component to get the default path form
312 # chop off the .hg component to get the default path form
314 return os.path.dirname(repo.sharedpath)
313 return os.path.dirname(repo.sharedpath)
315 if abort:
314 if abort:
316 raise util.Abort(_("default path for subrepository not found"))
315 raise util.Abort(_("default path for subrepository not found"))
317
316
318 def _sanitize(ui, path):
317 def _sanitize(ui, path, ignore):
319 def v(arg, dirname, names):
318 for dirname, dirs, names in os.walk(path):
319 for i, d in enumerate(dirs):
320 if d.lower() == ignore:
321 del dirs[i]
322 break
320 if os.path.basename(dirname).lower() != '.hg':
323 if os.path.basename(dirname).lower() != '.hg':
321 return
324 continue
322 for f in names:
325 for f in names:
323 if f.lower() == 'hgrc':
326 if f.lower() == 'hgrc':
324 ui.warn(
327 ui.warn(_("warning: removing potentially hostile 'hgrc' "
325 _("warning: removing potentially hostile .hg/hgrc in '%s'")
328 "in '%s'\n") % dirname)
326 % path)
327 os.unlink(os.path.join(dirname, f))
329 os.unlink(os.path.join(dirname, f))
328 os.walk(path, v, None)
329
330
330 def subrepo(ctx, path):
331 def subrepo(ctx, path):
331 """return instance of the right subrepo class for subrepo in path"""
332 """return instance of the right subrepo class for subrepo in path"""
332 # subrepo inherently violates our import layering rules
333 # subrepo inherently violates our import layering rules
333 # because it wants to make repo objects from deep inside the stack
334 # because it wants to make repo objects from deep inside the stack
334 # so we manually delay the circular imports to not break
335 # so we manually delay the circular imports to not break
335 # scripts that don't use our demand-loading
336 # scripts that don't use our demand-loading
336 global hg
337 global hg
337 import hg as h
338 import hg as h
338 hg = h
339 hg = h
339
340
340 pathutil.pathauditor(ctx._repo.root)(path)
341 pathutil.pathauditor(ctx._repo.root)(path)
341 state = ctx.substate[path]
342 state = ctx.substate[path]
342 if state[2] not in types:
343 if state[2] not in types:
343 raise util.Abort(_('unknown subrepo type %s') % state[2])
344 raise util.Abort(_('unknown subrepo type %s') % state[2])
344 return types[state[2]](ctx, path, state[:2])
345 return types[state[2]](ctx, path, state[:2])
345
346
346 def newcommitphase(ui, ctx):
347 def newcommitphase(ui, ctx):
347 commitphase = phases.newcommitphase(ui)
348 commitphase = phases.newcommitphase(ui)
348 substate = getattr(ctx, "substate", None)
349 substate = getattr(ctx, "substate", None)
349 if not substate:
350 if not substate:
350 return commitphase
351 return commitphase
351 check = ui.config('phases', 'checksubrepos', 'follow')
352 check = ui.config('phases', 'checksubrepos', 'follow')
352 if check not in ('ignore', 'follow', 'abort'):
353 if check not in ('ignore', 'follow', 'abort'):
353 raise util.Abort(_('invalid phases.checksubrepos configuration: %s')
354 raise util.Abort(_('invalid phases.checksubrepos configuration: %s')
354 % (check))
355 % (check))
355 if check == 'ignore':
356 if check == 'ignore':
356 return commitphase
357 return commitphase
357 maxphase = phases.public
358 maxphase = phases.public
358 maxsub = None
359 maxsub = None
359 for s in sorted(substate):
360 for s in sorted(substate):
360 sub = ctx.sub(s)
361 sub = ctx.sub(s)
361 subphase = sub.phase(substate[s][1])
362 subphase = sub.phase(substate[s][1])
362 if maxphase < subphase:
363 if maxphase < subphase:
363 maxphase = subphase
364 maxphase = subphase
364 maxsub = s
365 maxsub = s
365 if commitphase < maxphase:
366 if commitphase < maxphase:
366 if check == 'abort':
367 if check == 'abort':
367 raise util.Abort(_("can't commit in %s phase"
368 raise util.Abort(_("can't commit in %s phase"
368 " conflicting %s from subrepository %s") %
369 " conflicting %s from subrepository %s") %
369 (phases.phasenames[commitphase],
370 (phases.phasenames[commitphase],
370 phases.phasenames[maxphase], maxsub))
371 phases.phasenames[maxphase], maxsub))
371 ui.warn(_("warning: changes are committed in"
372 ui.warn(_("warning: changes are committed in"
372 " %s phase from subrepository %s\n") %
373 " %s phase from subrepository %s\n") %
373 (phases.phasenames[maxphase], maxsub))
374 (phases.phasenames[maxphase], maxsub))
374 return maxphase
375 return maxphase
375 return commitphase
376 return commitphase
376
377
377 # subrepo classes need to implement the following abstract class:
378 # subrepo classes need to implement the following abstract class:
378
379
379 class abstractsubrepo(object):
380 class abstractsubrepo(object):
380
381
381 def storeclean(self, path):
382 def storeclean(self, path):
382 """
383 """
383 returns true if the repository has not changed since it was last
384 returns true if the repository has not changed since it was last
384 cloned from or pushed to a given repository.
385 cloned from or pushed to a given repository.
385 """
386 """
386 return False
387 return False
387
388
388 def dirty(self, ignoreupdate=False):
389 def dirty(self, ignoreupdate=False):
389 """returns true if the dirstate of the subrepo is dirty or does not
390 """returns true if the dirstate of the subrepo is dirty or does not
390 match current stored state. If ignoreupdate is true, only check
391 match current stored state. If ignoreupdate is true, only check
391 whether the subrepo has uncommitted changes in its dirstate.
392 whether the subrepo has uncommitted changes in its dirstate.
392 """
393 """
393 raise NotImplementedError
394 raise NotImplementedError
394
395
395 def basestate(self):
396 def basestate(self):
396 """current working directory base state, disregarding .hgsubstate
397 """current working directory base state, disregarding .hgsubstate
397 state and working directory modifications"""
398 state and working directory modifications"""
398 raise NotImplementedError
399 raise NotImplementedError
399
400
400 def checknested(self, path):
401 def checknested(self, path):
401 """check if path is a subrepository within this repository"""
402 """check if path is a subrepository within this repository"""
402 return False
403 return False
403
404
404 def commit(self, text, user, date):
405 def commit(self, text, user, date):
405 """commit the current changes to the subrepo with the given
406 """commit the current changes to the subrepo with the given
406 log message. Use given user and date if possible. Return the
407 log message. Use given user and date if possible. Return the
407 new state of the subrepo.
408 new state of the subrepo.
408 """
409 """
409 raise NotImplementedError
410 raise NotImplementedError
410
411
411 def phase(self, state):
412 def phase(self, state):
412 """returns phase of specified state in the subrepository.
413 """returns phase of specified state in the subrepository.
413 """
414 """
414 return phases.public
415 return phases.public
415
416
416 def remove(self):
417 def remove(self):
417 """remove the subrepo
418 """remove the subrepo
418
419
419 (should verify the dirstate is not dirty first)
420 (should verify the dirstate is not dirty first)
420 """
421 """
421 raise NotImplementedError
422 raise NotImplementedError
422
423
423 def get(self, state, overwrite=False):
424 def get(self, state, overwrite=False):
424 """run whatever commands are needed to put the subrepo into
425 """run whatever commands are needed to put the subrepo into
425 this state
426 this state
426 """
427 """
427 raise NotImplementedError
428 raise NotImplementedError
428
429
429 def merge(self, state):
430 def merge(self, state):
430 """merge currently-saved state with the new state."""
431 """merge currently-saved state with the new state."""
431 raise NotImplementedError
432 raise NotImplementedError
432
433
433 def push(self, opts):
434 def push(self, opts):
434 """perform whatever action is analogous to 'hg push'
435 """perform whatever action is analogous to 'hg push'
435
436
436 This may be a no-op on some systems.
437 This may be a no-op on some systems.
437 """
438 """
438 raise NotImplementedError
439 raise NotImplementedError
439
440
440 def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
441 def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
441 return []
442 return []
442
443
443 def cat(self, ui, match, prefix, **opts):
444 def cat(self, ui, match, prefix, **opts):
444 return 1
445 return 1
445
446
446 def status(self, rev2, **opts):
447 def status(self, rev2, **opts):
447 return [], [], [], [], [], [], []
448 return [], [], [], [], [], [], []
448
449
449 def diff(self, ui, diffopts, node2, match, prefix, **opts):
450 def diff(self, ui, diffopts, node2, match, prefix, **opts):
450 pass
451 pass
451
452
452 def outgoing(self, ui, dest, opts):
453 def outgoing(self, ui, dest, opts):
453 return 1
454 return 1
454
455
455 def incoming(self, ui, source, opts):
456 def incoming(self, ui, source, opts):
456 return 1
457 return 1
457
458
458 def files(self):
459 def files(self):
459 """return filename iterator"""
460 """return filename iterator"""
460 raise NotImplementedError
461 raise NotImplementedError
461
462
462 def filedata(self, name):
463 def filedata(self, name):
463 """return file data"""
464 """return file data"""
464 raise NotImplementedError
465 raise NotImplementedError
465
466
466 def fileflags(self, name):
467 def fileflags(self, name):
467 """return file flags"""
468 """return file flags"""
468 return ''
469 return ''
469
470
470 def archive(self, ui, archiver, prefix, match=None):
471 def archive(self, ui, archiver, prefix, match=None):
471 if match is not None:
472 if match is not None:
472 files = [f for f in self.files() if match(f)]
473 files = [f for f in self.files() if match(f)]
473 else:
474 else:
474 files = self.files()
475 files = self.files()
475 total = len(files)
476 total = len(files)
476 relpath = subrelpath(self)
477 relpath = subrelpath(self)
477 ui.progress(_('archiving (%s)') % relpath, 0,
478 ui.progress(_('archiving (%s)') % relpath, 0,
478 unit=_('files'), total=total)
479 unit=_('files'), total=total)
479 for i, name in enumerate(files):
480 for i, name in enumerate(files):
480 flags = self.fileflags(name)
481 flags = self.fileflags(name)
481 mode = 'x' in flags and 0755 or 0644
482 mode = 'x' in flags and 0755 or 0644
482 symlink = 'l' in flags
483 symlink = 'l' in flags
483 archiver.addfile(os.path.join(prefix, self._path, name),
484 archiver.addfile(os.path.join(prefix, self._path, name),
484 mode, symlink, self.filedata(name))
485 mode, symlink, self.filedata(name))
485 ui.progress(_('archiving (%s)') % relpath, i + 1,
486 ui.progress(_('archiving (%s)') % relpath, i + 1,
486 unit=_('files'), total=total)
487 unit=_('files'), total=total)
487 ui.progress(_('archiving (%s)') % relpath, None)
488 ui.progress(_('archiving (%s)') % relpath, None)
488 return total
489 return total
489
490
490 def walk(self, match):
491 def walk(self, match):
491 '''
492 '''
492 walk recursively through the directory tree, finding all files
493 walk recursively through the directory tree, finding all files
493 matched by the match function
494 matched by the match function
494 '''
495 '''
495 pass
496 pass
496
497
497 def forget(self, ui, match, prefix):
498 def forget(self, ui, match, prefix):
498 return ([], [])
499 return ([], [])
499
500
500 def revert(self, ui, substate, *pats, **opts):
501 def revert(self, ui, substate, *pats, **opts):
501 ui.warn('%s: reverting %s subrepos is unsupported\n' \
502 ui.warn('%s: reverting %s subrepos is unsupported\n' \
502 % (substate[0], substate[2]))
503 % (substate[0], substate[2]))
503 return []
504 return []
504
505
505 def shortid(self, revid):
506 def shortid(self, revid):
506 return revid
507 return revid
507
508
508 class hgsubrepo(abstractsubrepo):
509 class hgsubrepo(abstractsubrepo):
509 def __init__(self, ctx, path, state):
510 def __init__(self, ctx, path, state):
510 self._path = path
511 self._path = path
511 self._state = state
512 self._state = state
512 r = ctx._repo
513 r = ctx._repo
513 root = r.wjoin(path)
514 root = r.wjoin(path)
514 create = False
515 create = False
515 if not os.path.exists(os.path.join(root, '.hg')):
516 if not os.path.exists(os.path.join(root, '.hg')):
516 create = True
517 create = True
517 util.makedirs(root)
518 util.makedirs(root)
518 self._repo = hg.repository(r.baseui, root, create=create)
519 self._repo = hg.repository(r.baseui, root, create=create)
519 for s, k in [('ui', 'commitsubrepos')]:
520 for s, k in [('ui', 'commitsubrepos')]:
520 v = r.ui.config(s, k)
521 v = r.ui.config(s, k)
521 if v:
522 if v:
522 self._repo.ui.setconfig(s, k, v, 'subrepo')
523 self._repo.ui.setconfig(s, k, v, 'subrepo')
523 self._repo.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
524 self._repo.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
524 self._initrepo(r, state[0], create)
525 self._initrepo(r, state[0], create)
525
526
526 def storeclean(self, path):
527 def storeclean(self, path):
527 clean = True
528 clean = True
528 lock = self._repo.lock()
529 lock = self._repo.lock()
529 itercache = self._calcstorehash(path)
530 itercache = self._calcstorehash(path)
530 try:
531 try:
531 for filehash in self._readstorehashcache(path):
532 for filehash in self._readstorehashcache(path):
532 if filehash != itercache.next():
533 if filehash != itercache.next():
533 clean = False
534 clean = False
534 break
535 break
535 except StopIteration:
536 except StopIteration:
536 # the cached and current pull states have a different size
537 # the cached and current pull states have a different size
537 clean = False
538 clean = False
538 if clean:
539 if clean:
539 try:
540 try:
540 itercache.next()
541 itercache.next()
541 # the cached and current pull states have a different size
542 # the cached and current pull states have a different size
542 clean = False
543 clean = False
543 except StopIteration:
544 except StopIteration:
544 pass
545 pass
545 lock.release()
546 lock.release()
546 return clean
547 return clean
547
548
548 def _calcstorehash(self, remotepath):
549 def _calcstorehash(self, remotepath):
549 '''calculate a unique "store hash"
550 '''calculate a unique "store hash"
550
551
551 This method is used to to detect when there are changes that may
552 This method is used to to detect when there are changes that may
552 require a push to a given remote path.'''
553 require a push to a given remote path.'''
553 # sort the files that will be hashed in increasing (likely) file size
554 # sort the files that will be hashed in increasing (likely) file size
554 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
555 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
555 yield '# %s\n' % _expandedabspath(remotepath)
556 yield '# %s\n' % _expandedabspath(remotepath)
556 for relname in filelist:
557 for relname in filelist:
557 absname = os.path.normpath(self._repo.join(relname))
558 absname = os.path.normpath(self._repo.join(relname))
558 yield '%s = %s\n' % (relname, _calcfilehash(absname))
559 yield '%s = %s\n' % (relname, _calcfilehash(absname))
559
560
560 def _getstorehashcachepath(self, remotepath):
561 def _getstorehashcachepath(self, remotepath):
561 '''get a unique path for the store hash cache'''
562 '''get a unique path for the store hash cache'''
562 return self._repo.join(os.path.join(
563 return self._repo.join(os.path.join(
563 'cache', 'storehash', _getstorehashcachename(remotepath)))
564 'cache', 'storehash', _getstorehashcachename(remotepath)))
564
565
565 def _readstorehashcache(self, remotepath):
566 def _readstorehashcache(self, remotepath):
566 '''read the store hash cache for a given remote repository'''
567 '''read the store hash cache for a given remote repository'''
567 cachefile = self._getstorehashcachepath(remotepath)
568 cachefile = self._getstorehashcachepath(remotepath)
568 if not os.path.exists(cachefile):
569 if not os.path.exists(cachefile):
569 return ''
570 return ''
570 fd = open(cachefile, 'r')
571 fd = open(cachefile, 'r')
571 pullstate = fd.readlines()
572 pullstate = fd.readlines()
572 fd.close()
573 fd.close()
573 return pullstate
574 return pullstate
574
575
575 def _cachestorehash(self, remotepath):
576 def _cachestorehash(self, remotepath):
576 '''cache the current store hash
577 '''cache the current store hash
577
578
578 Each remote repo requires its own store hash cache, because a subrepo
579 Each remote repo requires its own store hash cache, because a subrepo
579 store may be "clean" versus a given remote repo, but not versus another
580 store may be "clean" versus a given remote repo, but not versus another
580 '''
581 '''
581 cachefile = self._getstorehashcachepath(remotepath)
582 cachefile = self._getstorehashcachepath(remotepath)
582 lock = self._repo.lock()
583 lock = self._repo.lock()
583 storehash = list(self._calcstorehash(remotepath))
584 storehash = list(self._calcstorehash(remotepath))
584 cachedir = os.path.dirname(cachefile)
585 cachedir = os.path.dirname(cachefile)
585 if not os.path.exists(cachedir):
586 if not os.path.exists(cachedir):
586 util.makedirs(cachedir, notindexed=True)
587 util.makedirs(cachedir, notindexed=True)
587 fd = open(cachefile, 'w')
588 fd = open(cachefile, 'w')
588 fd.writelines(storehash)
589 fd.writelines(storehash)
589 fd.close()
590 fd.close()
590 lock.release()
591 lock.release()
591
592
592 @annotatesubrepoerror
593 @annotatesubrepoerror
593 def _initrepo(self, parentrepo, source, create):
594 def _initrepo(self, parentrepo, source, create):
594 self._repo._subparent = parentrepo
595 self._repo._subparent = parentrepo
595 self._repo._subsource = source
596 self._repo._subsource = source
596
597
597 if create:
598 if create:
598 fp = self._repo.opener("hgrc", "w", text=True)
599 fp = self._repo.opener("hgrc", "w", text=True)
599 fp.write('[paths]\n')
600 fp.write('[paths]\n')
600
601
601 def addpathconfig(key, value):
602 def addpathconfig(key, value):
602 if value:
603 if value:
603 fp.write('%s = %s\n' % (key, value))
604 fp.write('%s = %s\n' % (key, value))
604 self._repo.ui.setconfig('paths', key, value, 'subrepo')
605 self._repo.ui.setconfig('paths', key, value, 'subrepo')
605
606
606 defpath = _abssource(self._repo, abort=False)
607 defpath = _abssource(self._repo, abort=False)
607 defpushpath = _abssource(self._repo, True, abort=False)
608 defpushpath = _abssource(self._repo, True, abort=False)
608 addpathconfig('default', defpath)
609 addpathconfig('default', defpath)
609 if defpath != defpushpath:
610 if defpath != defpushpath:
610 addpathconfig('default-push', defpushpath)
611 addpathconfig('default-push', defpushpath)
611 fp.close()
612 fp.close()
612
613
613 @annotatesubrepoerror
614 @annotatesubrepoerror
614 def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
615 def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
615 return cmdutil.add(ui, self._repo, match, dryrun, listsubrepos,
616 return cmdutil.add(ui, self._repo, match, dryrun, listsubrepos,
616 os.path.join(prefix, self._path), explicitonly)
617 os.path.join(prefix, self._path), explicitonly)
617
618
618 @annotatesubrepoerror
619 @annotatesubrepoerror
619 def cat(self, ui, match, prefix, **opts):
620 def cat(self, ui, match, prefix, **opts):
620 rev = self._state[1]
621 rev = self._state[1]
621 ctx = self._repo[rev]
622 ctx = self._repo[rev]
622 return cmdutil.cat(ui, self._repo, ctx, match, prefix, **opts)
623 return cmdutil.cat(ui, self._repo, ctx, match, prefix, **opts)
623
624
624 @annotatesubrepoerror
625 @annotatesubrepoerror
625 def status(self, rev2, **opts):
626 def status(self, rev2, **opts):
626 try:
627 try:
627 rev1 = self._state[1]
628 rev1 = self._state[1]
628 ctx1 = self._repo[rev1]
629 ctx1 = self._repo[rev1]
629 ctx2 = self._repo[rev2]
630 ctx2 = self._repo[rev2]
630 return self._repo.status(ctx1, ctx2, **opts)
631 return self._repo.status(ctx1, ctx2, **opts)
631 except error.RepoLookupError, inst:
632 except error.RepoLookupError, inst:
632 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
633 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
633 % (inst, subrelpath(self)))
634 % (inst, subrelpath(self)))
634 return [], [], [], [], [], [], []
635 return [], [], [], [], [], [], []
635
636
636 @annotatesubrepoerror
637 @annotatesubrepoerror
637 def diff(self, ui, diffopts, node2, match, prefix, **opts):
638 def diff(self, ui, diffopts, node2, match, prefix, **opts):
638 try:
639 try:
639 node1 = node.bin(self._state[1])
640 node1 = node.bin(self._state[1])
640 # We currently expect node2 to come from substate and be
641 # We currently expect node2 to come from substate and be
641 # in hex format
642 # in hex format
642 if node2 is not None:
643 if node2 is not None:
643 node2 = node.bin(node2)
644 node2 = node.bin(node2)
644 cmdutil.diffordiffstat(ui, self._repo, diffopts,
645 cmdutil.diffordiffstat(ui, self._repo, diffopts,
645 node1, node2, match,
646 node1, node2, match,
646 prefix=posixpath.join(prefix, self._path),
647 prefix=posixpath.join(prefix, self._path),
647 listsubrepos=True, **opts)
648 listsubrepos=True, **opts)
648 except error.RepoLookupError, inst:
649 except error.RepoLookupError, inst:
649 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
650 self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
650 % (inst, subrelpath(self)))
651 % (inst, subrelpath(self)))
651
652
652 @annotatesubrepoerror
653 @annotatesubrepoerror
653 def archive(self, ui, archiver, prefix, match=None):
654 def archive(self, ui, archiver, prefix, match=None):
654 self._get(self._state + ('hg',))
655 self._get(self._state + ('hg',))
655 total = abstractsubrepo.archive(self, ui, archiver, prefix, match)
656 total = abstractsubrepo.archive(self, ui, archiver, prefix, match)
656 rev = self._state[1]
657 rev = self._state[1]
657 ctx = self._repo[rev]
658 ctx = self._repo[rev]
658 for subpath in ctx.substate:
659 for subpath in ctx.substate:
659 s = subrepo(ctx, subpath)
660 s = subrepo(ctx, subpath)
660 submatch = matchmod.narrowmatcher(subpath, match)
661 submatch = matchmod.narrowmatcher(subpath, match)
661 total += s.archive(
662 total += s.archive(
662 ui, archiver, os.path.join(prefix, self._path), submatch)
663 ui, archiver, os.path.join(prefix, self._path), submatch)
663 return total
664 return total
664
665
665 @annotatesubrepoerror
666 @annotatesubrepoerror
666 def dirty(self, ignoreupdate=False):
667 def dirty(self, ignoreupdate=False):
667 r = self._state[1]
668 r = self._state[1]
668 if r == '' and not ignoreupdate: # no state recorded
669 if r == '' and not ignoreupdate: # no state recorded
669 return True
670 return True
670 w = self._repo[None]
671 w = self._repo[None]
671 if r != w.p1().hex() and not ignoreupdate:
672 if r != w.p1().hex() and not ignoreupdate:
672 # different version checked out
673 # different version checked out
673 return True
674 return True
674 return w.dirty() # working directory changed
675 return w.dirty() # working directory changed
675
676
676 def basestate(self):
677 def basestate(self):
677 return self._repo['.'].hex()
678 return self._repo['.'].hex()
678
679
679 def checknested(self, path):
680 def checknested(self, path):
680 return self._repo._checknested(self._repo.wjoin(path))
681 return self._repo._checknested(self._repo.wjoin(path))
681
682
682 @annotatesubrepoerror
683 @annotatesubrepoerror
683 def commit(self, text, user, date):
684 def commit(self, text, user, date):
684 # don't bother committing in the subrepo if it's only been
685 # don't bother committing in the subrepo if it's only been
685 # updated
686 # updated
686 if not self.dirty(True):
687 if not self.dirty(True):
687 return self._repo['.'].hex()
688 return self._repo['.'].hex()
688 self._repo.ui.debug("committing subrepo %s\n" % subrelpath(self))
689 self._repo.ui.debug("committing subrepo %s\n" % subrelpath(self))
689 n = self._repo.commit(text, user, date)
690 n = self._repo.commit(text, user, date)
690 if not n:
691 if not n:
691 return self._repo['.'].hex() # different version checked out
692 return self._repo['.'].hex() # different version checked out
692 return node.hex(n)
693 return node.hex(n)
693
694
694 @annotatesubrepoerror
695 @annotatesubrepoerror
695 def phase(self, state):
696 def phase(self, state):
696 return self._repo[state].phase()
697 return self._repo[state].phase()
697
698
698 @annotatesubrepoerror
699 @annotatesubrepoerror
699 def remove(self):
700 def remove(self):
700 # we can't fully delete the repository as it may contain
701 # we can't fully delete the repository as it may contain
701 # local-only history
702 # local-only history
702 self._repo.ui.note(_('removing subrepo %s\n') % subrelpath(self))
703 self._repo.ui.note(_('removing subrepo %s\n') % subrelpath(self))
703 hg.clean(self._repo, node.nullid, False)
704 hg.clean(self._repo, node.nullid, False)
704
705
705 def _get(self, state):
706 def _get(self, state):
706 source, revision, kind = state
707 source, revision, kind = state
707 if revision in self._repo.unfiltered():
708 if revision in self._repo.unfiltered():
708 return True
709 return True
709 self._repo._subsource = source
710 self._repo._subsource = source
710 srcurl = _abssource(self._repo)
711 srcurl = _abssource(self._repo)
711 other = hg.peer(self._repo, {}, srcurl)
712 other = hg.peer(self._repo, {}, srcurl)
712 if len(self._repo) == 0:
713 if len(self._repo) == 0:
713 self._repo.ui.status(_('cloning subrepo %s from %s\n')
714 self._repo.ui.status(_('cloning subrepo %s from %s\n')
714 % (subrelpath(self), srcurl))
715 % (subrelpath(self), srcurl))
715 parentrepo = self._repo._subparent
716 parentrepo = self._repo._subparent
716 shutil.rmtree(self._repo.path)
717 shutil.rmtree(self._repo.path)
717 other, cloned = hg.clone(self._repo._subparent.baseui, {},
718 other, cloned = hg.clone(self._repo._subparent.baseui, {},
718 other, self._repo.root,
719 other, self._repo.root,
719 update=False)
720 update=False)
720 self._repo = cloned.local()
721 self._repo = cloned.local()
721 self._initrepo(parentrepo, source, create=True)
722 self._initrepo(parentrepo, source, create=True)
722 self._cachestorehash(srcurl)
723 self._cachestorehash(srcurl)
723 else:
724 else:
724 self._repo.ui.status(_('pulling subrepo %s from %s\n')
725 self._repo.ui.status(_('pulling subrepo %s from %s\n')
725 % (subrelpath(self), srcurl))
726 % (subrelpath(self), srcurl))
726 cleansub = self.storeclean(srcurl)
727 cleansub = self.storeclean(srcurl)
727 remotebookmarks = other.listkeys('bookmarks')
728 remotebookmarks = other.listkeys('bookmarks')
728 self._repo.pull(other)
729 self._repo.pull(other)
729 bookmarks.updatefromremote(self._repo.ui, self._repo,
730 bookmarks.updatefromremote(self._repo.ui, self._repo,
730 remotebookmarks, srcurl)
731 remotebookmarks, srcurl)
731 if cleansub:
732 if cleansub:
732 # keep the repo clean after pull
733 # keep the repo clean after pull
733 self._cachestorehash(srcurl)
734 self._cachestorehash(srcurl)
734 return False
735 return False
735
736
736 @annotatesubrepoerror
737 @annotatesubrepoerror
737 def get(self, state, overwrite=False):
738 def get(self, state, overwrite=False):
738 inrepo = self._get(state)
739 inrepo = self._get(state)
739 source, revision, kind = state
740 source, revision, kind = state
740 repo = self._repo
741 repo = self._repo
741 repo.ui.debug("getting subrepo %s\n" % self._path)
742 repo.ui.debug("getting subrepo %s\n" % self._path)
742 if inrepo:
743 if inrepo:
743 urepo = repo.unfiltered()
744 urepo = repo.unfiltered()
744 ctx = urepo[revision]
745 ctx = urepo[revision]
745 if ctx.hidden():
746 if ctx.hidden():
746 urepo.ui.warn(
747 urepo.ui.warn(
747 _('revision %s in subrepo %s is hidden\n') \
748 _('revision %s in subrepo %s is hidden\n') \
748 % (revision[0:12], self._path))
749 % (revision[0:12], self._path))
749 repo = urepo
750 repo = urepo
750 hg.updaterepo(repo, revision, overwrite)
751 hg.updaterepo(repo, revision, overwrite)
751
752
752 @annotatesubrepoerror
753 @annotatesubrepoerror
753 def merge(self, state):
754 def merge(self, state):
754 self._get(state)
755 self._get(state)
755 cur = self._repo['.']
756 cur = self._repo['.']
756 dst = self._repo[state[1]]
757 dst = self._repo[state[1]]
757 anc = dst.ancestor(cur)
758 anc = dst.ancestor(cur)
758
759
759 def mergefunc():
760 def mergefunc():
760 if anc == cur and dst.branch() == cur.branch():
761 if anc == cur and dst.branch() == cur.branch():
761 self._repo.ui.debug("updating subrepo %s\n" % subrelpath(self))
762 self._repo.ui.debug("updating subrepo %s\n" % subrelpath(self))
762 hg.update(self._repo, state[1])
763 hg.update(self._repo, state[1])
763 elif anc == dst:
764 elif anc == dst:
764 self._repo.ui.debug("skipping subrepo %s\n" % subrelpath(self))
765 self._repo.ui.debug("skipping subrepo %s\n" % subrelpath(self))
765 else:
766 else:
766 self._repo.ui.debug("merging subrepo %s\n" % subrelpath(self))
767 self._repo.ui.debug("merging subrepo %s\n" % subrelpath(self))
767 hg.merge(self._repo, state[1], remind=False)
768 hg.merge(self._repo, state[1], remind=False)
768
769
769 wctx = self._repo[None]
770 wctx = self._repo[None]
770 if self.dirty():
771 if self.dirty():
771 if anc != dst:
772 if anc != dst:
772 if _updateprompt(self._repo.ui, self, wctx.dirty(), cur, dst):
773 if _updateprompt(self._repo.ui, self, wctx.dirty(), cur, dst):
773 mergefunc()
774 mergefunc()
774 else:
775 else:
775 mergefunc()
776 mergefunc()
776 else:
777 else:
777 mergefunc()
778 mergefunc()
778
779
779 @annotatesubrepoerror
780 @annotatesubrepoerror
780 def push(self, opts):
781 def push(self, opts):
781 force = opts.get('force')
782 force = opts.get('force')
782 newbranch = opts.get('new_branch')
783 newbranch = opts.get('new_branch')
783 ssh = opts.get('ssh')
784 ssh = opts.get('ssh')
784
785
785 # push subrepos depth-first for coherent ordering
786 # push subrepos depth-first for coherent ordering
786 c = self._repo['']
787 c = self._repo['']
787 subs = c.substate # only repos that are committed
788 subs = c.substate # only repos that are committed
788 for s in sorted(subs):
789 for s in sorted(subs):
789 if c.sub(s).push(opts) == 0:
790 if c.sub(s).push(opts) == 0:
790 return False
791 return False
791
792
792 dsturl = _abssource(self._repo, True)
793 dsturl = _abssource(self._repo, True)
793 if not force:
794 if not force:
794 if self.storeclean(dsturl):
795 if self.storeclean(dsturl):
795 self._repo.ui.status(
796 self._repo.ui.status(
796 _('no changes made to subrepo %s since last push to %s\n')
797 _('no changes made to subrepo %s since last push to %s\n')
797 % (subrelpath(self), dsturl))
798 % (subrelpath(self), dsturl))
798 return None
799 return None
799 self._repo.ui.status(_('pushing subrepo %s to %s\n') %
800 self._repo.ui.status(_('pushing subrepo %s to %s\n') %
800 (subrelpath(self), dsturl))
801 (subrelpath(self), dsturl))
801 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
802 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
802 res = self._repo.push(other, force, newbranch=newbranch)
803 res = self._repo.push(other, force, newbranch=newbranch)
803
804
804 # the repo is now clean
805 # the repo is now clean
805 self._cachestorehash(dsturl)
806 self._cachestorehash(dsturl)
806 return res
807 return res
807
808
808 @annotatesubrepoerror
809 @annotatesubrepoerror
809 def outgoing(self, ui, dest, opts):
810 def outgoing(self, ui, dest, opts):
810 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
811 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
811
812
812 @annotatesubrepoerror
813 @annotatesubrepoerror
813 def incoming(self, ui, source, opts):
814 def incoming(self, ui, source, opts):
814 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
815 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
815
816
816 @annotatesubrepoerror
817 @annotatesubrepoerror
817 def files(self):
818 def files(self):
818 rev = self._state[1]
819 rev = self._state[1]
819 ctx = self._repo[rev]
820 ctx = self._repo[rev]
820 return ctx.manifest()
821 return ctx.manifest()
821
822
822 def filedata(self, name):
823 def filedata(self, name):
823 rev = self._state[1]
824 rev = self._state[1]
824 return self._repo[rev][name].data()
825 return self._repo[rev][name].data()
825
826
826 def fileflags(self, name):
827 def fileflags(self, name):
827 rev = self._state[1]
828 rev = self._state[1]
828 ctx = self._repo[rev]
829 ctx = self._repo[rev]
829 return ctx.flags(name)
830 return ctx.flags(name)
830
831
831 def walk(self, match):
832 def walk(self, match):
832 ctx = self._repo[None]
833 ctx = self._repo[None]
833 return ctx.walk(match)
834 return ctx.walk(match)
834
835
835 @annotatesubrepoerror
836 @annotatesubrepoerror
836 def forget(self, ui, match, prefix):
837 def forget(self, ui, match, prefix):
837 return cmdutil.forget(ui, self._repo, match,
838 return cmdutil.forget(ui, self._repo, match,
838 os.path.join(prefix, self._path), True)
839 os.path.join(prefix, self._path), True)
839
840
840 @annotatesubrepoerror
841 @annotatesubrepoerror
841 def revert(self, ui, substate, *pats, **opts):
842 def revert(self, ui, substate, *pats, **opts):
842 # reverting a subrepo is a 2 step process:
843 # reverting a subrepo is a 2 step process:
843 # 1. if the no_backup is not set, revert all modified
844 # 1. if the no_backup is not set, revert all modified
844 # files inside the subrepo
845 # files inside the subrepo
845 # 2. update the subrepo to the revision specified in
846 # 2. update the subrepo to the revision specified in
846 # the corresponding substate dictionary
847 # the corresponding substate dictionary
847 ui.status(_('reverting subrepo %s\n') % substate[0])
848 ui.status(_('reverting subrepo %s\n') % substate[0])
848 if not opts.get('no_backup'):
849 if not opts.get('no_backup'):
849 # Revert all files on the subrepo, creating backups
850 # Revert all files on the subrepo, creating backups
850 # Note that this will not recursively revert subrepos
851 # Note that this will not recursively revert subrepos
851 # We could do it if there was a set:subrepos() predicate
852 # We could do it if there was a set:subrepos() predicate
852 opts = opts.copy()
853 opts = opts.copy()
853 opts['date'] = None
854 opts['date'] = None
854 opts['rev'] = substate[1]
855 opts['rev'] = substate[1]
855
856
856 pats = []
857 pats = []
857 if not opts.get('all'):
858 if not opts.get('all'):
858 pats = ['set:modified()']
859 pats = ['set:modified()']
859 self.filerevert(ui, *pats, **opts)
860 self.filerevert(ui, *pats, **opts)
860
861
861 # Update the repo to the revision specified in the given substate
862 # Update the repo to the revision specified in the given substate
862 self.get(substate, overwrite=True)
863 self.get(substate, overwrite=True)
863
864
864 def filerevert(self, ui, *pats, **opts):
865 def filerevert(self, ui, *pats, **opts):
865 ctx = self._repo[opts['rev']]
866 ctx = self._repo[opts['rev']]
866 parents = self._repo.dirstate.parents()
867 parents = self._repo.dirstate.parents()
867 if opts.get('all'):
868 if opts.get('all'):
868 pats = ['set:modified()']
869 pats = ['set:modified()']
869 else:
870 else:
870 pats = []
871 pats = []
871 cmdutil.revert(ui, self._repo, ctx, parents, *pats, **opts)
872 cmdutil.revert(ui, self._repo, ctx, parents, *pats, **opts)
872
873
873 def shortid(self, revid):
874 def shortid(self, revid):
874 return revid[:12]
875 return revid[:12]
875
876
876 class svnsubrepo(abstractsubrepo):
877 class svnsubrepo(abstractsubrepo):
877 def __init__(self, ctx, path, state):
878 def __init__(self, ctx, path, state):
878 self._path = path
879 self._path = path
879 self._state = state
880 self._state = state
880 self._ctx = ctx
881 self._ctx = ctx
881 self._ui = ctx._repo.ui
882 self._ui = ctx._repo.ui
882 self._exe = util.findexe('svn')
883 self._exe = util.findexe('svn')
883 if not self._exe:
884 if not self._exe:
884 raise util.Abort(_("'svn' executable not found for subrepo '%s'")
885 raise util.Abort(_("'svn' executable not found for subrepo '%s'")
885 % self._path)
886 % self._path)
886
887
887 def _svncommand(self, commands, filename='', failok=False):
888 def _svncommand(self, commands, filename='', failok=False):
888 cmd = [self._exe]
889 cmd = [self._exe]
889 extrakw = {}
890 extrakw = {}
890 if not self._ui.interactive():
891 if not self._ui.interactive():
891 # Making stdin be a pipe should prevent svn from behaving
892 # Making stdin be a pipe should prevent svn from behaving
892 # interactively even if we can't pass --non-interactive.
893 # interactively even if we can't pass --non-interactive.
893 extrakw['stdin'] = subprocess.PIPE
894 extrakw['stdin'] = subprocess.PIPE
894 # Starting in svn 1.5 --non-interactive is a global flag
895 # Starting in svn 1.5 --non-interactive is a global flag
895 # instead of being per-command, but we need to support 1.4 so
896 # instead of being per-command, but we need to support 1.4 so
896 # we have to be intelligent about what commands take
897 # we have to be intelligent about what commands take
897 # --non-interactive.
898 # --non-interactive.
898 if commands[0] in ('update', 'checkout', 'commit'):
899 if commands[0] in ('update', 'checkout', 'commit'):
899 cmd.append('--non-interactive')
900 cmd.append('--non-interactive')
900 cmd.extend(commands)
901 cmd.extend(commands)
901 if filename is not None:
902 if filename is not None:
902 path = os.path.join(self._ctx._repo.origroot, self._path, filename)
903 path = os.path.join(self._ctx._repo.origroot, self._path, filename)
903 cmd.append(path)
904 cmd.append(path)
904 env = dict(os.environ)
905 env = dict(os.environ)
905 # Avoid localized output, preserve current locale for everything else.
906 # Avoid localized output, preserve current locale for everything else.
906 lc_all = env.get('LC_ALL')
907 lc_all = env.get('LC_ALL')
907 if lc_all:
908 if lc_all:
908 env['LANG'] = lc_all
909 env['LANG'] = lc_all
909 del env['LC_ALL']
910 del env['LC_ALL']
910 env['LC_MESSAGES'] = 'C'
911 env['LC_MESSAGES'] = 'C'
911 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
912 p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
912 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
913 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
913 universal_newlines=True, env=env, **extrakw)
914 universal_newlines=True, env=env, **extrakw)
914 stdout, stderr = p.communicate()
915 stdout, stderr = p.communicate()
915 stderr = stderr.strip()
916 stderr = stderr.strip()
916 if not failok:
917 if not failok:
917 if p.returncode:
918 if p.returncode:
918 raise util.Abort(stderr or 'exited with code %d' % p.returncode)
919 raise util.Abort(stderr or 'exited with code %d' % p.returncode)
919 if stderr:
920 if stderr:
920 self._ui.warn(stderr + '\n')
921 self._ui.warn(stderr + '\n')
921 return stdout, stderr
922 return stdout, stderr
922
923
923 @propertycache
924 @propertycache
924 def _svnversion(self):
925 def _svnversion(self):
925 output, err = self._svncommand(['--version', '--quiet'], filename=None)
926 output, err = self._svncommand(['--version', '--quiet'], filename=None)
926 m = re.search(r'^(\d+)\.(\d+)', output)
927 m = re.search(r'^(\d+)\.(\d+)', output)
927 if not m:
928 if not m:
928 raise util.Abort(_('cannot retrieve svn tool version'))
929 raise util.Abort(_('cannot retrieve svn tool version'))
929 return (int(m.group(1)), int(m.group(2)))
930 return (int(m.group(1)), int(m.group(2)))
930
931
931 def _wcrevs(self):
932 def _wcrevs(self):
932 # Get the working directory revision as well as the last
933 # Get the working directory revision as well as the last
933 # commit revision so we can compare the subrepo state with
934 # commit revision so we can compare the subrepo state with
934 # both. We used to store the working directory one.
935 # both. We used to store the working directory one.
935 output, err = self._svncommand(['info', '--xml'])
936 output, err = self._svncommand(['info', '--xml'])
936 doc = xml.dom.minidom.parseString(output)
937 doc = xml.dom.minidom.parseString(output)
937 entries = doc.getElementsByTagName('entry')
938 entries = doc.getElementsByTagName('entry')
938 lastrev, rev = '0', '0'
939 lastrev, rev = '0', '0'
939 if entries:
940 if entries:
940 rev = str(entries[0].getAttribute('revision')) or '0'
941 rev = str(entries[0].getAttribute('revision')) or '0'
941 commits = entries[0].getElementsByTagName('commit')
942 commits = entries[0].getElementsByTagName('commit')
942 if commits:
943 if commits:
943 lastrev = str(commits[0].getAttribute('revision')) or '0'
944 lastrev = str(commits[0].getAttribute('revision')) or '0'
944 return (lastrev, rev)
945 return (lastrev, rev)
945
946
946 def _wcrev(self):
947 def _wcrev(self):
947 return self._wcrevs()[0]
948 return self._wcrevs()[0]
948
949
949 def _wcchanged(self):
950 def _wcchanged(self):
950 """Return (changes, extchanges, missing) where changes is True
951 """Return (changes, extchanges, missing) where changes is True
951 if the working directory was changed, extchanges is
952 if the working directory was changed, extchanges is
952 True if any of these changes concern an external entry and missing
953 True if any of these changes concern an external entry and missing
953 is True if any change is a missing entry.
954 is True if any change is a missing entry.
954 """
955 """
955 output, err = self._svncommand(['status', '--xml'])
956 output, err = self._svncommand(['status', '--xml'])
956 externals, changes, missing = [], [], []
957 externals, changes, missing = [], [], []
957 doc = xml.dom.minidom.parseString(output)
958 doc = xml.dom.minidom.parseString(output)
958 for e in doc.getElementsByTagName('entry'):
959 for e in doc.getElementsByTagName('entry'):
959 s = e.getElementsByTagName('wc-status')
960 s = e.getElementsByTagName('wc-status')
960 if not s:
961 if not s:
961 continue
962 continue
962 item = s[0].getAttribute('item')
963 item = s[0].getAttribute('item')
963 props = s[0].getAttribute('props')
964 props = s[0].getAttribute('props')
964 path = e.getAttribute('path')
965 path = e.getAttribute('path')
965 if item == 'external':
966 if item == 'external':
966 externals.append(path)
967 externals.append(path)
967 elif item == 'missing':
968 elif item == 'missing':
968 missing.append(path)
969 missing.append(path)
969 if (item not in ('', 'normal', 'unversioned', 'external')
970 if (item not in ('', 'normal', 'unversioned', 'external')
970 or props not in ('', 'none', 'normal')):
971 or props not in ('', 'none', 'normal')):
971 changes.append(path)
972 changes.append(path)
972 for path in changes:
973 for path in changes:
973 for ext in externals:
974 for ext in externals:
974 if path == ext or path.startswith(ext + os.sep):
975 if path == ext or path.startswith(ext + os.sep):
975 return True, True, bool(missing)
976 return True, True, bool(missing)
976 return bool(changes), False, bool(missing)
977 return bool(changes), False, bool(missing)
977
978
978 def dirty(self, ignoreupdate=False):
979 def dirty(self, ignoreupdate=False):
979 if not self._wcchanged()[0]:
980 if not self._wcchanged()[0]:
980 if self._state[1] in self._wcrevs() or ignoreupdate:
981 if self._state[1] in self._wcrevs() or ignoreupdate:
981 return False
982 return False
982 return True
983 return True
983
984
984 def basestate(self):
985 def basestate(self):
985 lastrev, rev = self._wcrevs()
986 lastrev, rev = self._wcrevs()
986 if lastrev != rev:
987 if lastrev != rev:
987 # Last committed rev is not the same than rev. We would
988 # Last committed rev is not the same than rev. We would
988 # like to take lastrev but we do not know if the subrepo
989 # like to take lastrev but we do not know if the subrepo
989 # URL exists at lastrev. Test it and fallback to rev it
990 # URL exists at lastrev. Test it and fallback to rev it
990 # is not there.
991 # is not there.
991 try:
992 try:
992 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
993 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
993 return lastrev
994 return lastrev
994 except error.Abort:
995 except error.Abort:
995 pass
996 pass
996 return rev
997 return rev
997
998
998 @annotatesubrepoerror
999 @annotatesubrepoerror
999 def commit(self, text, user, date):
1000 def commit(self, text, user, date):
1000 # user and date are out of our hands since svn is centralized
1001 # user and date are out of our hands since svn is centralized
1001 changed, extchanged, missing = self._wcchanged()
1002 changed, extchanged, missing = self._wcchanged()
1002 if not changed:
1003 if not changed:
1003 return self.basestate()
1004 return self.basestate()
1004 if extchanged:
1005 if extchanged:
1005 # Do not try to commit externals
1006 # Do not try to commit externals
1006 raise util.Abort(_('cannot commit svn externals'))
1007 raise util.Abort(_('cannot commit svn externals'))
1007 if missing:
1008 if missing:
1008 # svn can commit with missing entries but aborting like hg
1009 # svn can commit with missing entries but aborting like hg
1009 # seems a better approach.
1010 # seems a better approach.
1010 raise util.Abort(_('cannot commit missing svn entries'))
1011 raise util.Abort(_('cannot commit missing svn entries'))
1011 commitinfo, err = self._svncommand(['commit', '-m', text])
1012 commitinfo, err = self._svncommand(['commit', '-m', text])
1012 self._ui.status(commitinfo)
1013 self._ui.status(commitinfo)
1013 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1014 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1014 if not newrev:
1015 if not newrev:
1015 if not commitinfo.strip():
1016 if not commitinfo.strip():
1016 # Sometimes, our definition of "changed" differs from
1017 # Sometimes, our definition of "changed" differs from
1017 # svn one. For instance, svn ignores missing files
1018 # svn one. For instance, svn ignores missing files
1018 # when committing. If there are only missing files, no
1019 # when committing. If there are only missing files, no
1019 # commit is made, no output and no error code.
1020 # commit is made, no output and no error code.
1020 raise util.Abort(_('failed to commit svn changes'))
1021 raise util.Abort(_('failed to commit svn changes'))
1021 raise util.Abort(commitinfo.splitlines()[-1])
1022 raise util.Abort(commitinfo.splitlines()[-1])
1022 newrev = newrev.groups()[0]
1023 newrev = newrev.groups()[0]
1023 self._ui.status(self._svncommand(['update', '-r', newrev])[0])
1024 self._ui.status(self._svncommand(['update', '-r', newrev])[0])
1024 return newrev
1025 return newrev
1025
1026
1026 @annotatesubrepoerror
1027 @annotatesubrepoerror
1027 def remove(self):
1028 def remove(self):
1028 if self.dirty():
1029 if self.dirty():
1029 self._ui.warn(_('not removing repo %s because '
1030 self._ui.warn(_('not removing repo %s because '
1030 'it has changes.\n') % self._path)
1031 'it has changes.\n') % self._path)
1031 return
1032 return
1032 self._ui.note(_('removing subrepo %s\n') % self._path)
1033 self._ui.note(_('removing subrepo %s\n') % self._path)
1033
1034
1034 def onerror(function, path, excinfo):
1035 def onerror(function, path, excinfo):
1035 if function is not os.remove:
1036 if function is not os.remove:
1036 raise
1037 raise
1037 # read-only files cannot be unlinked under Windows
1038 # read-only files cannot be unlinked under Windows
1038 s = os.stat(path)
1039 s = os.stat(path)
1039 if (s.st_mode & stat.S_IWRITE) != 0:
1040 if (s.st_mode & stat.S_IWRITE) != 0:
1040 raise
1041 raise
1041 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
1042 os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
1042 os.remove(path)
1043 os.remove(path)
1043
1044
1044 path = self._ctx._repo.wjoin(self._path)
1045 path = self._ctx._repo.wjoin(self._path)
1045 shutil.rmtree(path, onerror=onerror)
1046 shutil.rmtree(path, onerror=onerror)
1046 try:
1047 try:
1047 os.removedirs(os.path.dirname(path))
1048 os.removedirs(os.path.dirname(path))
1048 except OSError:
1049 except OSError:
1049 pass
1050 pass
1050
1051
1051 @annotatesubrepoerror
1052 @annotatesubrepoerror
1052 def get(self, state, overwrite=False):
1053 def get(self, state, overwrite=False):
1053 if overwrite:
1054 if overwrite:
1054 self._svncommand(['revert', '--recursive'])
1055 self._svncommand(['revert', '--recursive'])
1055 args = ['checkout']
1056 args = ['checkout']
1056 if self._svnversion >= (1, 5):
1057 if self._svnversion >= (1, 5):
1057 args.append('--force')
1058 args.append('--force')
1058 # The revision must be specified at the end of the URL to properly
1059 # The revision must be specified at the end of the URL to properly
1059 # update to a directory which has since been deleted and recreated.
1060 # update to a directory which has since been deleted and recreated.
1060 args.append('%s@%s' % (state[0], state[1]))
1061 args.append('%s@%s' % (state[0], state[1]))
1061 status, err = self._svncommand(args, failok=True)
1062 status, err = self._svncommand(args, failok=True)
1062 _sanitize(self._ui, self._path)
1063 _sanitize(self._ui, self._ctx._repo.wjoin(self._path), '.svn')
1063 if not re.search('Checked out revision [0-9]+.', status):
1064 if not re.search('Checked out revision [0-9]+.', status):
1064 if ('is already a working copy for a different URL' in err
1065 if ('is already a working copy for a different URL' in err
1065 and (self._wcchanged()[:2] == (False, False))):
1066 and (self._wcchanged()[:2] == (False, False))):
1066 # obstructed but clean working copy, so just blow it away.
1067 # obstructed but clean working copy, so just blow it away.
1067 self.remove()
1068 self.remove()
1068 self.get(state, overwrite=False)
1069 self.get(state, overwrite=False)
1069 return
1070 return
1070 raise util.Abort((status or err).splitlines()[-1])
1071 raise util.Abort((status or err).splitlines()[-1])
1071 self._ui.status(status)
1072 self._ui.status(status)
1072
1073
1073 @annotatesubrepoerror
1074 @annotatesubrepoerror
1074 def merge(self, state):
1075 def merge(self, state):
1075 old = self._state[1]
1076 old = self._state[1]
1076 new = state[1]
1077 new = state[1]
1077 wcrev = self._wcrev()
1078 wcrev = self._wcrev()
1078 if new != wcrev:
1079 if new != wcrev:
1079 dirty = old == wcrev or self._wcchanged()[0]
1080 dirty = old == wcrev or self._wcchanged()[0]
1080 if _updateprompt(self._ui, self, dirty, wcrev, new):
1081 if _updateprompt(self._ui, self, dirty, wcrev, new):
1081 self.get(state, False)
1082 self.get(state, False)
1082
1083
1083 def push(self, opts):
1084 def push(self, opts):
1084 # push is a no-op for SVN
1085 # push is a no-op for SVN
1085 return True
1086 return True
1086
1087
1087 @annotatesubrepoerror
1088 @annotatesubrepoerror
1088 def files(self):
1089 def files(self):
1089 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1090 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1090 doc = xml.dom.minidom.parseString(output)
1091 doc = xml.dom.minidom.parseString(output)
1091 paths = []
1092 paths = []
1092 for e in doc.getElementsByTagName('entry'):
1093 for e in doc.getElementsByTagName('entry'):
1093 kind = str(e.getAttribute('kind'))
1094 kind = str(e.getAttribute('kind'))
1094 if kind != 'file':
1095 if kind != 'file':
1095 continue
1096 continue
1096 name = ''.join(c.data for c
1097 name = ''.join(c.data for c
1097 in e.getElementsByTagName('name')[0].childNodes
1098 in e.getElementsByTagName('name')[0].childNodes
1098 if c.nodeType == c.TEXT_NODE)
1099 if c.nodeType == c.TEXT_NODE)
1099 paths.append(name.encode('utf-8'))
1100 paths.append(name.encode('utf-8'))
1100 return paths
1101 return paths
1101
1102
1102 def filedata(self, name):
1103 def filedata(self, name):
1103 return self._svncommand(['cat'], name)[0]
1104 return self._svncommand(['cat'], name)[0]
1104
1105
1105
1106
1106 class gitsubrepo(abstractsubrepo):
1107 class gitsubrepo(abstractsubrepo):
1107 def __init__(self, ctx, path, state):
1108 def __init__(self, ctx, path, state):
1108 self._state = state
1109 self._state = state
1109 self._ctx = ctx
1110 self._ctx = ctx
1110 self._path = path
1111 self._path = path
1111 self._relpath = os.path.join(reporelpath(ctx._repo), path)
1112 self._relpath = os.path.join(reporelpath(ctx._repo), path)
1112 self._abspath = ctx._repo.wjoin(path)
1113 self._abspath = ctx._repo.wjoin(path)
1113 self._subparent = ctx._repo
1114 self._subparent = ctx._repo
1114 self._ui = ctx._repo.ui
1115 self._ui = ctx._repo.ui
1115 self._ensuregit()
1116 self._ensuregit()
1116
1117
1117 def _ensuregit(self):
1118 def _ensuregit(self):
1118 try:
1119 try:
1119 self._gitexecutable = 'git'
1120 self._gitexecutable = 'git'
1120 out, err = self._gitnodir(['--version'])
1121 out, err = self._gitnodir(['--version'])
1121 except OSError, e:
1122 except OSError, e:
1122 if e.errno != 2 or os.name != 'nt':
1123 if e.errno != 2 or os.name != 'nt':
1123 raise
1124 raise
1124 self._gitexecutable = 'git.cmd'
1125 self._gitexecutable = 'git.cmd'
1125 out, err = self._gitnodir(['--version'])
1126 out, err = self._gitnodir(['--version'])
1126 versionstatus = self._checkversion(out)
1127 versionstatus = self._checkversion(out)
1127 if versionstatus == 'unknown':
1128 if versionstatus == 'unknown':
1128 self._ui.warn(_('cannot retrieve git version\n'))
1129 self._ui.warn(_('cannot retrieve git version\n'))
1129 elif versionstatus == 'abort':
1130 elif versionstatus == 'abort':
1130 raise util.Abort(_('git subrepo requires at least 1.6.0 or later'))
1131 raise util.Abort(_('git subrepo requires at least 1.6.0 or later'))
1131 elif versionstatus == 'warning':
1132 elif versionstatus == 'warning':
1132 self._ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1133 self._ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1133
1134
1134 @staticmethod
1135 @staticmethod
1135 def _checkversion(out):
1136 def _checkversion(out):
1136 '''ensure git version is new enough
1137 '''ensure git version is new enough
1137
1138
1138 >>> _checkversion = gitsubrepo._checkversion
1139 >>> _checkversion = gitsubrepo._checkversion
1139 >>> _checkversion('git version 1.6.0')
1140 >>> _checkversion('git version 1.6.0')
1140 'ok'
1141 'ok'
1141 >>> _checkversion('git version 1.8.5')
1142 >>> _checkversion('git version 1.8.5')
1142 'ok'
1143 'ok'
1143 >>> _checkversion('git version 1.4.0')
1144 >>> _checkversion('git version 1.4.0')
1144 'abort'
1145 'abort'
1145 >>> _checkversion('git version 1.5.0')
1146 >>> _checkversion('git version 1.5.0')
1146 'warning'
1147 'warning'
1147 >>> _checkversion('git version 1.9-rc0')
1148 >>> _checkversion('git version 1.9-rc0')
1148 'ok'
1149 'ok'
1149 >>> _checkversion('git version 1.9.0.265.g81cdec2')
1150 >>> _checkversion('git version 1.9.0.265.g81cdec2')
1150 'ok'
1151 'ok'
1151 >>> _checkversion('git version 1.9.0.GIT')
1152 >>> _checkversion('git version 1.9.0.GIT')
1152 'ok'
1153 'ok'
1153 >>> _checkversion('git version 12345')
1154 >>> _checkversion('git version 12345')
1154 'unknown'
1155 'unknown'
1155 >>> _checkversion('no')
1156 >>> _checkversion('no')
1156 'unknown'
1157 'unknown'
1157 '''
1158 '''
1158 m = re.search(r'^git version (\d+)\.(\d+)', out)
1159 m = re.search(r'^git version (\d+)\.(\d+)', out)
1159 if not m:
1160 if not m:
1160 return 'unknown'
1161 return 'unknown'
1161 version = (int(m.group(1)), int(m.group(2)))
1162 version = (int(m.group(1)), int(m.group(2)))
1162 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1163 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1163 # despite the docstring comment. For now, error on 1.4.0, warn on
1164 # despite the docstring comment. For now, error on 1.4.0, warn on
1164 # 1.5.0 but attempt to continue.
1165 # 1.5.0 but attempt to continue.
1165 if version < (1, 5):
1166 if version < (1, 5):
1166 return 'abort'
1167 return 'abort'
1167 elif version < (1, 6):
1168 elif version < (1, 6):
1168 return 'warning'
1169 return 'warning'
1169 return 'ok'
1170 return 'ok'
1170
1171
1171 def _gitcommand(self, commands, env=None, stream=False):
1172 def _gitcommand(self, commands, env=None, stream=False):
1172 return self._gitdir(commands, env=env, stream=stream)[0]
1173 return self._gitdir(commands, env=env, stream=stream)[0]
1173
1174
1174 def _gitdir(self, commands, env=None, stream=False):
1175 def _gitdir(self, commands, env=None, stream=False):
1175 return self._gitnodir(commands, env=env, stream=stream,
1176 return self._gitnodir(commands, env=env, stream=stream,
1176 cwd=self._abspath)
1177 cwd=self._abspath)
1177
1178
1178 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1179 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1179 """Calls the git command
1180 """Calls the git command
1180
1181
1181 The methods tries to call the git command. versions prior to 1.6.0
1182 The methods tries to call the git command. versions prior to 1.6.0
1182 are not supported and very probably fail.
1183 are not supported and very probably fail.
1183 """
1184 """
1184 self._ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1185 self._ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1185 # unless ui.quiet is set, print git's stderr,
1186 # unless ui.quiet is set, print git's stderr,
1186 # which is mostly progress and useful info
1187 # which is mostly progress and useful info
1187 errpipe = None
1188 errpipe = None
1188 if self._ui.quiet:
1189 if self._ui.quiet:
1189 errpipe = open(os.devnull, 'w')
1190 errpipe = open(os.devnull, 'w')
1190 p = subprocess.Popen([self._gitexecutable] + commands, bufsize=-1,
1191 p = subprocess.Popen([self._gitexecutable] + commands, bufsize=-1,
1191 cwd=cwd, env=env, close_fds=util.closefds,
1192 cwd=cwd, env=env, close_fds=util.closefds,
1192 stdout=subprocess.PIPE, stderr=errpipe)
1193 stdout=subprocess.PIPE, stderr=errpipe)
1193 if stream:
1194 if stream:
1194 return p.stdout, None
1195 return p.stdout, None
1195
1196
1196 retdata = p.stdout.read().strip()
1197 retdata = p.stdout.read().strip()
1197 # wait for the child to exit to avoid race condition.
1198 # wait for the child to exit to avoid race condition.
1198 p.wait()
1199 p.wait()
1199
1200
1200 if p.returncode != 0 and p.returncode != 1:
1201 if p.returncode != 0 and p.returncode != 1:
1201 # there are certain error codes that are ok
1202 # there are certain error codes that are ok
1202 command = commands[0]
1203 command = commands[0]
1203 if command in ('cat-file', 'symbolic-ref'):
1204 if command in ('cat-file', 'symbolic-ref'):
1204 return retdata, p.returncode
1205 return retdata, p.returncode
1205 # for all others, abort
1206 # for all others, abort
1206 raise util.Abort('git %s error %d in %s' %
1207 raise util.Abort('git %s error %d in %s' %
1207 (command, p.returncode, self._relpath))
1208 (command, p.returncode, self._relpath))
1208
1209
1209 return retdata, p.returncode
1210 return retdata, p.returncode
1210
1211
1211 def _gitmissing(self):
1212 def _gitmissing(self):
1212 return not os.path.exists(os.path.join(self._abspath, '.git'))
1213 return not os.path.exists(os.path.join(self._abspath, '.git'))
1213
1214
1214 def _gitstate(self):
1215 def _gitstate(self):
1215 return self._gitcommand(['rev-parse', 'HEAD'])
1216 return self._gitcommand(['rev-parse', 'HEAD'])
1216
1217
1217 def _gitcurrentbranch(self):
1218 def _gitcurrentbranch(self):
1218 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1219 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1219 if err:
1220 if err:
1220 current = None
1221 current = None
1221 return current
1222 return current
1222
1223
1223 def _gitremote(self, remote):
1224 def _gitremote(self, remote):
1224 out = self._gitcommand(['remote', 'show', '-n', remote])
1225 out = self._gitcommand(['remote', 'show', '-n', remote])
1225 line = out.split('\n')[1]
1226 line = out.split('\n')[1]
1226 i = line.index('URL: ') + len('URL: ')
1227 i = line.index('URL: ') + len('URL: ')
1227 return line[i:]
1228 return line[i:]
1228
1229
1229 def _githavelocally(self, revision):
1230 def _githavelocally(self, revision):
1230 out, code = self._gitdir(['cat-file', '-e', revision])
1231 out, code = self._gitdir(['cat-file', '-e', revision])
1231 return code == 0
1232 return code == 0
1232
1233
1233 def _gitisancestor(self, r1, r2):
1234 def _gitisancestor(self, r1, r2):
1234 base = self._gitcommand(['merge-base', r1, r2])
1235 base = self._gitcommand(['merge-base', r1, r2])
1235 return base == r1
1236 return base == r1
1236
1237
1237 def _gitisbare(self):
1238 def _gitisbare(self):
1238 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1239 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1239
1240
1240 def _gitupdatestat(self):
1241 def _gitupdatestat(self):
1241 """This must be run before git diff-index.
1242 """This must be run before git diff-index.
1242 diff-index only looks at changes to file stat;
1243 diff-index only looks at changes to file stat;
1243 this command looks at file contents and updates the stat."""
1244 this command looks at file contents and updates the stat."""
1244 self._gitcommand(['update-index', '-q', '--refresh'])
1245 self._gitcommand(['update-index', '-q', '--refresh'])
1245
1246
1246 def _gitbranchmap(self):
1247 def _gitbranchmap(self):
1247 '''returns 2 things:
1248 '''returns 2 things:
1248 a map from git branch to revision
1249 a map from git branch to revision
1249 a map from revision to branches'''
1250 a map from revision to branches'''
1250 branch2rev = {}
1251 branch2rev = {}
1251 rev2branch = {}
1252 rev2branch = {}
1252
1253
1253 out = self._gitcommand(['for-each-ref', '--format',
1254 out = self._gitcommand(['for-each-ref', '--format',
1254 '%(objectname) %(refname)'])
1255 '%(objectname) %(refname)'])
1255 for line in out.split('\n'):
1256 for line in out.split('\n'):
1256 revision, ref = line.split(' ')
1257 revision, ref = line.split(' ')
1257 if (not ref.startswith('refs/heads/') and
1258 if (not ref.startswith('refs/heads/') and
1258 not ref.startswith('refs/remotes/')):
1259 not ref.startswith('refs/remotes/')):
1259 continue
1260 continue
1260 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1261 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1261 continue # ignore remote/HEAD redirects
1262 continue # ignore remote/HEAD redirects
1262 branch2rev[ref] = revision
1263 branch2rev[ref] = revision
1263 rev2branch.setdefault(revision, []).append(ref)
1264 rev2branch.setdefault(revision, []).append(ref)
1264 return branch2rev, rev2branch
1265 return branch2rev, rev2branch
1265
1266
1266 def _gittracking(self, branches):
1267 def _gittracking(self, branches):
1267 'return map of remote branch to local tracking branch'
1268 'return map of remote branch to local tracking branch'
1268 # assumes no more than one local tracking branch for each remote
1269 # assumes no more than one local tracking branch for each remote
1269 tracking = {}
1270 tracking = {}
1270 for b in branches:
1271 for b in branches:
1271 if b.startswith('refs/remotes/'):
1272 if b.startswith('refs/remotes/'):
1272 continue
1273 continue
1273 bname = b.split('/', 2)[2]
1274 bname = b.split('/', 2)[2]
1274 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1275 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1275 if remote:
1276 if remote:
1276 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1277 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1277 tracking['refs/remotes/%s/%s' %
1278 tracking['refs/remotes/%s/%s' %
1278 (remote, ref.split('/', 2)[2])] = b
1279 (remote, ref.split('/', 2)[2])] = b
1279 return tracking
1280 return tracking
1280
1281
1281 def _abssource(self, source):
1282 def _abssource(self, source):
1282 if '://' not in source:
1283 if '://' not in source:
1283 # recognize the scp syntax as an absolute source
1284 # recognize the scp syntax as an absolute source
1284 colon = source.find(':')
1285 colon = source.find(':')
1285 if colon != -1 and '/' not in source[:colon]:
1286 if colon != -1 and '/' not in source[:colon]:
1286 return source
1287 return source
1287 self._subsource = source
1288 self._subsource = source
1288 return _abssource(self)
1289 return _abssource(self)
1289
1290
1290 def _fetch(self, source, revision):
1291 def _fetch(self, source, revision):
1291 if self._gitmissing():
1292 if self._gitmissing():
1292 source = self._abssource(source)
1293 source = self._abssource(source)
1293 self._ui.status(_('cloning subrepo %s from %s\n') %
1294 self._ui.status(_('cloning subrepo %s from %s\n') %
1294 (self._relpath, source))
1295 (self._relpath, source))
1295 self._gitnodir(['clone', source, self._abspath])
1296 self._gitnodir(['clone', source, self._abspath])
1296 if self._githavelocally(revision):
1297 if self._githavelocally(revision):
1297 return
1298 return
1298 self._ui.status(_('pulling subrepo %s from %s\n') %
1299 self._ui.status(_('pulling subrepo %s from %s\n') %
1299 (self._relpath, self._gitremote('origin')))
1300 (self._relpath, self._gitremote('origin')))
1300 # try only origin: the originally cloned repo
1301 # try only origin: the originally cloned repo
1301 self._gitcommand(['fetch'])
1302 self._gitcommand(['fetch'])
1302 if not self._githavelocally(revision):
1303 if not self._githavelocally(revision):
1303 raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
1304 raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
1304 (revision, self._relpath))
1305 (revision, self._relpath))
1305
1306
1306 @annotatesubrepoerror
1307 @annotatesubrepoerror
1307 def dirty(self, ignoreupdate=False):
1308 def dirty(self, ignoreupdate=False):
1308 if self._gitmissing():
1309 if self._gitmissing():
1309 return self._state[1] != ''
1310 return self._state[1] != ''
1310 if self._gitisbare():
1311 if self._gitisbare():
1311 return True
1312 return True
1312 if not ignoreupdate and self._state[1] != self._gitstate():
1313 if not ignoreupdate and self._state[1] != self._gitstate():
1313 # different version checked out
1314 # different version checked out
1314 return True
1315 return True
1315 # check for staged changes or modified files; ignore untracked files
1316 # check for staged changes or modified files; ignore untracked files
1316 self._gitupdatestat()
1317 self._gitupdatestat()
1317 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1318 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1318 return code == 1
1319 return code == 1
1319
1320
1320 def basestate(self):
1321 def basestate(self):
1321 return self._gitstate()
1322 return self._gitstate()
1322
1323
1323 @annotatesubrepoerror
1324 @annotatesubrepoerror
1324 def get(self, state, overwrite=False):
1325 def get(self, state, overwrite=False):
1325 source, revision, kind = state
1326 source, revision, kind = state
1326 if not revision:
1327 if not revision:
1327 self.remove()
1328 self.remove()
1328 return
1329 return
1329 self._fetch(source, revision)
1330 self._fetch(source, revision)
1330 # if the repo was set to be bare, unbare it
1331 # if the repo was set to be bare, unbare it
1331 if self._gitisbare():
1332 if self._gitisbare():
1332 self._gitcommand(['config', 'core.bare', 'false'])
1333 self._gitcommand(['config', 'core.bare', 'false'])
1333 if self._gitstate() == revision:
1334 if self._gitstate() == revision:
1334 self._gitcommand(['reset', '--hard', 'HEAD'])
1335 self._gitcommand(['reset', '--hard', 'HEAD'])
1335 return
1336 return
1336 elif self._gitstate() == revision:
1337 elif self._gitstate() == revision:
1337 if overwrite:
1338 if overwrite:
1338 # first reset the index to unmark new files for commit, because
1339 # first reset the index to unmark new files for commit, because
1339 # reset --hard will otherwise throw away files added for commit,
1340 # reset --hard will otherwise throw away files added for commit,
1340 # not just unmark them.
1341 # not just unmark them.
1341 self._gitcommand(['reset', 'HEAD'])
1342 self._gitcommand(['reset', 'HEAD'])
1342 self._gitcommand(['reset', '--hard', 'HEAD'])
1343 self._gitcommand(['reset', '--hard', 'HEAD'])
1343 return
1344 return
1344 branch2rev, rev2branch = self._gitbranchmap()
1345 branch2rev, rev2branch = self._gitbranchmap()
1345
1346
1346 def checkout(args):
1347 def checkout(args):
1347 cmd = ['checkout']
1348 cmd = ['checkout']
1348 if overwrite:
1349 if overwrite:
1349 # first reset the index to unmark new files for commit, because
1350 # first reset the index to unmark new files for commit, because
1350 # the -f option will otherwise throw away files added for
1351 # the -f option will otherwise throw away files added for
1351 # commit, not just unmark them.
1352 # commit, not just unmark them.
1352 self._gitcommand(['reset', 'HEAD'])
1353 self._gitcommand(['reset', 'HEAD'])
1353 cmd.append('-f')
1354 cmd.append('-f')
1354 self._gitcommand(cmd + args)
1355 self._gitcommand(cmd + args)
1355 _sanitize(self._ui, self._path)
1356 _sanitize(self._ui, self._abspath, '.git')
1356
1357
1357 def rawcheckout():
1358 def rawcheckout():
1358 # no branch to checkout, check it out with no branch
1359 # no branch to checkout, check it out with no branch
1359 self._ui.warn(_('checking out detached HEAD in subrepo %s\n') %
1360 self._ui.warn(_('checking out detached HEAD in subrepo %s\n') %
1360 self._relpath)
1361 self._relpath)
1361 self._ui.warn(_('check out a git branch if you intend '
1362 self._ui.warn(_('check out a git branch if you intend '
1362 'to make changes\n'))
1363 'to make changes\n'))
1363 checkout(['-q', revision])
1364 checkout(['-q', revision])
1364
1365
1365 if revision not in rev2branch:
1366 if revision not in rev2branch:
1366 rawcheckout()
1367 rawcheckout()
1367 return
1368 return
1368 branches = rev2branch[revision]
1369 branches = rev2branch[revision]
1369 firstlocalbranch = None
1370 firstlocalbranch = None
1370 for b in branches:
1371 for b in branches:
1371 if b == 'refs/heads/master':
1372 if b == 'refs/heads/master':
1372 # master trumps all other branches
1373 # master trumps all other branches
1373 checkout(['refs/heads/master'])
1374 checkout(['refs/heads/master'])
1374 return
1375 return
1375 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1376 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1376 firstlocalbranch = b
1377 firstlocalbranch = b
1377 if firstlocalbranch:
1378 if firstlocalbranch:
1378 checkout([firstlocalbranch])
1379 checkout([firstlocalbranch])
1379 return
1380 return
1380
1381
1381 tracking = self._gittracking(branch2rev.keys())
1382 tracking = self._gittracking(branch2rev.keys())
1382 # choose a remote branch already tracked if possible
1383 # choose a remote branch already tracked if possible
1383 remote = branches[0]
1384 remote = branches[0]
1384 if remote not in tracking:
1385 if remote not in tracking:
1385 for b in branches:
1386 for b in branches:
1386 if b in tracking:
1387 if b in tracking:
1387 remote = b
1388 remote = b
1388 break
1389 break
1389
1390
1390 if remote not in tracking:
1391 if remote not in tracking:
1391 # create a new local tracking branch
1392 # create a new local tracking branch
1392 local = remote.split('/', 3)[3]
1393 local = remote.split('/', 3)[3]
1393 checkout(['-b', local, remote])
1394 checkout(['-b', local, remote])
1394 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1395 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1395 # When updating to a tracked remote branch,
1396 # When updating to a tracked remote branch,
1396 # if the local tracking branch is downstream of it,
1397 # if the local tracking branch is downstream of it,
1397 # a normal `git pull` would have performed a "fast-forward merge"
1398 # a normal `git pull` would have performed a "fast-forward merge"
1398 # which is equivalent to updating the local branch to the remote.
1399 # which is equivalent to updating the local branch to the remote.
1399 # Since we are only looking at branching at update, we need to
1400 # Since we are only looking at branching at update, we need to
1400 # detect this situation and perform this action lazily.
1401 # detect this situation and perform this action lazily.
1401 if tracking[remote] != self._gitcurrentbranch():
1402 if tracking[remote] != self._gitcurrentbranch():
1402 checkout([tracking[remote]])
1403 checkout([tracking[remote]])
1403 self._gitcommand(['merge', '--ff', remote])
1404 self._gitcommand(['merge', '--ff', remote])
1405 _sanitize(self._ui, self._abspath, '.git')
1404 else:
1406 else:
1405 # a real merge would be required, just checkout the revision
1407 # a real merge would be required, just checkout the revision
1406 rawcheckout()
1408 rawcheckout()
1407
1409
1408 @annotatesubrepoerror
1410 @annotatesubrepoerror
1409 def commit(self, text, user, date):
1411 def commit(self, text, user, date):
1410 if self._gitmissing():
1412 if self._gitmissing():
1411 raise util.Abort(_("subrepo %s is missing") % self._relpath)
1413 raise util.Abort(_("subrepo %s is missing") % self._relpath)
1412 cmd = ['commit', '-a', '-m', text]
1414 cmd = ['commit', '-a', '-m', text]
1413 env = os.environ.copy()
1415 env = os.environ.copy()
1414 if user:
1416 if user:
1415 cmd += ['--author', user]
1417 cmd += ['--author', user]
1416 if date:
1418 if date:
1417 # git's date parser silently ignores when seconds < 1e9
1419 # git's date parser silently ignores when seconds < 1e9
1418 # convert to ISO8601
1420 # convert to ISO8601
1419 env['GIT_AUTHOR_DATE'] = util.datestr(date,
1421 env['GIT_AUTHOR_DATE'] = util.datestr(date,
1420 '%Y-%m-%dT%H:%M:%S %1%2')
1422 '%Y-%m-%dT%H:%M:%S %1%2')
1421 self._gitcommand(cmd, env=env)
1423 self._gitcommand(cmd, env=env)
1422 # make sure commit works otherwise HEAD might not exist under certain
1424 # make sure commit works otherwise HEAD might not exist under certain
1423 # circumstances
1425 # circumstances
1424 return self._gitstate()
1426 return self._gitstate()
1425
1427
1426 @annotatesubrepoerror
1428 @annotatesubrepoerror
1427 def merge(self, state):
1429 def merge(self, state):
1428 source, revision, kind = state
1430 source, revision, kind = state
1429 self._fetch(source, revision)
1431 self._fetch(source, revision)
1430 base = self._gitcommand(['merge-base', revision, self._state[1]])
1432 base = self._gitcommand(['merge-base', revision, self._state[1]])
1431 self._gitupdatestat()
1433 self._gitupdatestat()
1432 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1434 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1433
1435
1434 def mergefunc():
1436 def mergefunc():
1435 if base == revision:
1437 if base == revision:
1436 self.get(state) # fast forward merge
1438 self.get(state) # fast forward merge
1437 elif base != self._state[1]:
1439 elif base != self._state[1]:
1438 self._gitcommand(['merge', '--no-commit', revision])
1440 self._gitcommand(['merge', '--no-commit', revision])
1439 _sanitize(self._ui, self._path)
1441 _sanitize(self._ui, self._abspath, '.git')
1440
1442
1441 if self.dirty():
1443 if self.dirty():
1442 if self._gitstate() != revision:
1444 if self._gitstate() != revision:
1443 dirty = self._gitstate() == self._state[1] or code != 0
1445 dirty = self._gitstate() == self._state[1] or code != 0
1444 if _updateprompt(self._ui, self, dirty,
1446 if _updateprompt(self._ui, self, dirty,
1445 self._state[1][:7], revision[:7]):
1447 self._state[1][:7], revision[:7]):
1446 mergefunc()
1448 mergefunc()
1447 else:
1449 else:
1448 mergefunc()
1450 mergefunc()
1449
1451
1450 @annotatesubrepoerror
1452 @annotatesubrepoerror
1451 def push(self, opts):
1453 def push(self, opts):
1452 force = opts.get('force')
1454 force = opts.get('force')
1453
1455
1454 if not self._state[1]:
1456 if not self._state[1]:
1455 return True
1457 return True
1456 if self._gitmissing():
1458 if self._gitmissing():
1457 raise util.Abort(_("subrepo %s is missing") % self._relpath)
1459 raise util.Abort(_("subrepo %s is missing") % self._relpath)
1458 # if a branch in origin contains the revision, nothing to do
1460 # if a branch in origin contains the revision, nothing to do
1459 branch2rev, rev2branch = self._gitbranchmap()
1461 branch2rev, rev2branch = self._gitbranchmap()
1460 if self._state[1] in rev2branch:
1462 if self._state[1] in rev2branch:
1461 for b in rev2branch[self._state[1]]:
1463 for b in rev2branch[self._state[1]]:
1462 if b.startswith('refs/remotes/origin/'):
1464 if b.startswith('refs/remotes/origin/'):
1463 return True
1465 return True
1464 for b, revision in branch2rev.iteritems():
1466 for b, revision in branch2rev.iteritems():
1465 if b.startswith('refs/remotes/origin/'):
1467 if b.startswith('refs/remotes/origin/'):
1466 if self._gitisancestor(self._state[1], revision):
1468 if self._gitisancestor(self._state[1], revision):
1467 return True
1469 return True
1468 # otherwise, try to push the currently checked out branch
1470 # otherwise, try to push the currently checked out branch
1469 cmd = ['push']
1471 cmd = ['push']
1470 if force:
1472 if force:
1471 cmd.append('--force')
1473 cmd.append('--force')
1472
1474
1473 current = self._gitcurrentbranch()
1475 current = self._gitcurrentbranch()
1474 if current:
1476 if current:
1475 # determine if the current branch is even useful
1477 # determine if the current branch is even useful
1476 if not self._gitisancestor(self._state[1], current):
1478 if not self._gitisancestor(self._state[1], current):
1477 self._ui.warn(_('unrelated git branch checked out '
1479 self._ui.warn(_('unrelated git branch checked out '
1478 'in subrepo %s\n') % self._relpath)
1480 'in subrepo %s\n') % self._relpath)
1479 return False
1481 return False
1480 self._ui.status(_('pushing branch %s of subrepo %s\n') %
1482 self._ui.status(_('pushing branch %s of subrepo %s\n') %
1481 (current.split('/', 2)[2], self._relpath))
1483 (current.split('/', 2)[2], self._relpath))
1482 ret = self._gitdir(cmd + ['origin', current])
1484 ret = self._gitdir(cmd + ['origin', current])
1483 return ret[1] == 0
1485 return ret[1] == 0
1484 else:
1486 else:
1485 self._ui.warn(_('no branch checked out in subrepo %s\n'
1487 self._ui.warn(_('no branch checked out in subrepo %s\n'
1486 'cannot push revision %s\n') %
1488 'cannot push revision %s\n') %
1487 (self._relpath, self._state[1]))
1489 (self._relpath, self._state[1]))
1488 return False
1490 return False
1489
1491
1490 @annotatesubrepoerror
1492 @annotatesubrepoerror
1491 def remove(self):
1493 def remove(self):
1492 if self._gitmissing():
1494 if self._gitmissing():
1493 return
1495 return
1494 if self.dirty():
1496 if self.dirty():
1495 self._ui.warn(_('not removing repo %s because '
1497 self._ui.warn(_('not removing repo %s because '
1496 'it has changes.\n') % self._relpath)
1498 'it has changes.\n') % self._relpath)
1497 return
1499 return
1498 # we can't fully delete the repository as it may contain
1500 # we can't fully delete the repository as it may contain
1499 # local-only history
1501 # local-only history
1500 self._ui.note(_('removing subrepo %s\n') % self._relpath)
1502 self._ui.note(_('removing subrepo %s\n') % self._relpath)
1501 self._gitcommand(['config', 'core.bare', 'true'])
1503 self._gitcommand(['config', 'core.bare', 'true'])
1502 for f in os.listdir(self._abspath):
1504 for f in os.listdir(self._abspath):
1503 if f == '.git':
1505 if f == '.git':
1504 continue
1506 continue
1505 path = os.path.join(self._abspath, f)
1507 path = os.path.join(self._abspath, f)
1506 if os.path.isdir(path) and not os.path.islink(path):
1508 if os.path.isdir(path) and not os.path.islink(path):
1507 shutil.rmtree(path)
1509 shutil.rmtree(path)
1508 else:
1510 else:
1509 os.remove(path)
1511 os.remove(path)
1510
1512
1511 def archive(self, ui, archiver, prefix, match=None):
1513 def archive(self, ui, archiver, prefix, match=None):
1512 total = 0
1514 total = 0
1513 source, revision = self._state
1515 source, revision = self._state
1514 if not revision:
1516 if not revision:
1515 return total
1517 return total
1516 self._fetch(source, revision)
1518 self._fetch(source, revision)
1517
1519
1518 # Parse git's native archive command.
1520 # Parse git's native archive command.
1519 # This should be much faster than manually traversing the trees
1521 # This should be much faster than manually traversing the trees
1520 # and objects with many subprocess calls.
1522 # and objects with many subprocess calls.
1521 tarstream = self._gitcommand(['archive', revision], stream=True)
1523 tarstream = self._gitcommand(['archive', revision], stream=True)
1522 tar = tarfile.open(fileobj=tarstream, mode='r|')
1524 tar = tarfile.open(fileobj=tarstream, mode='r|')
1523 relpath = subrelpath(self)
1525 relpath = subrelpath(self)
1524 ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1526 ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
1525 for i, info in enumerate(tar):
1527 for i, info in enumerate(tar):
1526 if info.isdir():
1528 if info.isdir():
1527 continue
1529 continue
1528 if match and not match(info.name):
1530 if match and not match(info.name):
1529 continue
1531 continue
1530 if info.issym():
1532 if info.issym():
1531 data = info.linkname
1533 data = info.linkname
1532 else:
1534 else:
1533 data = tar.extractfile(info).read()
1535 data = tar.extractfile(info).read()
1534 archiver.addfile(os.path.join(prefix, self._path, info.name),
1536 archiver.addfile(os.path.join(prefix, self._path, info.name),
1535 info.mode, info.issym(), data)
1537 info.mode, info.issym(), data)
1536 total += 1
1538 total += 1
1537 ui.progress(_('archiving (%s)') % relpath, i + 1,
1539 ui.progress(_('archiving (%s)') % relpath, i + 1,
1538 unit=_('files'))
1540 unit=_('files'))
1539 ui.progress(_('archiving (%s)') % relpath, None)
1541 ui.progress(_('archiving (%s)') % relpath, None)
1540 return total
1542 return total
1541
1543
1542
1544
1543 @annotatesubrepoerror
1545 @annotatesubrepoerror
1544 def status(self, rev2, **opts):
1546 def status(self, rev2, **opts):
1545 rev1 = self._state[1]
1547 rev1 = self._state[1]
1546 if self._gitmissing() or not rev1:
1548 if self._gitmissing() or not rev1:
1547 # if the repo is missing, return no results
1549 # if the repo is missing, return no results
1548 return [], [], [], [], [], [], []
1550 return [], [], [], [], [], [], []
1549 modified, added, removed = [], [], []
1551 modified, added, removed = [], [], []
1550 self._gitupdatestat()
1552 self._gitupdatestat()
1551 if rev2:
1553 if rev2:
1552 command = ['diff-tree', rev1, rev2]
1554 command = ['diff-tree', rev1, rev2]
1553 else:
1555 else:
1554 command = ['diff-index', rev1]
1556 command = ['diff-index', rev1]
1555 out = self._gitcommand(command)
1557 out = self._gitcommand(command)
1556 for line in out.split('\n'):
1558 for line in out.split('\n'):
1557 tab = line.find('\t')
1559 tab = line.find('\t')
1558 if tab == -1:
1560 if tab == -1:
1559 continue
1561 continue
1560 status, f = line[tab - 1], line[tab + 1:]
1562 status, f = line[tab - 1], line[tab + 1:]
1561 if status == 'M':
1563 if status == 'M':
1562 modified.append(f)
1564 modified.append(f)
1563 elif status == 'A':
1565 elif status == 'A':
1564 added.append(f)
1566 added.append(f)
1565 elif status == 'D':
1567 elif status == 'D':
1566 removed.append(f)
1568 removed.append(f)
1567
1569
1568 deleted = unknown = ignored = clean = []
1570 deleted = unknown = ignored = clean = []
1569 return modified, added, removed, deleted, unknown, ignored, clean
1571 return modified, added, removed, deleted, unknown, ignored, clean
1570
1572
1571 def shortid(self, revid):
1573 def shortid(self, revid):
1572 return revid[:7]
1574 return revid[:7]
1573
1575
1574 types = {
1576 types = {
1575 'hg': hgsubrepo,
1577 'hg': hgsubrepo,
1576 'svn': svnsubrepo,
1578 'svn': svnsubrepo,
1577 'git': gitsubrepo,
1579 'git': gitsubrepo,
1578 }
1580 }
@@ -1,464 +1,474 b''
1 $ HGFOO=BAR; export HGFOO
1 $ HGFOO=BAR; export HGFOO
2 $ cat >> $HGRCPATH <<EOF
2 $ cat >> $HGRCPATH <<EOF
3 > [alias]
3 > [alias]
4 > # should clobber ci but not commit (issue2993)
4 > # should clobber ci but not commit (issue2993)
5 > ci = version
5 > ci = version
6 > myinit = init
6 > myinit = init
7 > mycommit = commit
7 > mycommit = commit
8 > optionalrepo = showconfig alias.myinit
8 > optionalrepo = showconfig alias.myinit
9 > cleanstatus = status -c
9 > cleanstatus = status -c
10 > unknown = bargle
10 > unknown = bargle
11 > ambiguous = s
11 > ambiguous = s
12 > recursive = recursive
12 > recursive = recursive
13 > nodefinition =
13 > nodefinition =
14 > noclosingquotation = '
14 > no--cwd = status --cwd elsewhere
15 > no--cwd = status --cwd elsewhere
15 > no-R = status -R elsewhere
16 > no-R = status -R elsewhere
16 > no--repo = status --repo elsewhere
17 > no--repo = status --repo elsewhere
17 > no--repository = status --repository elsewhere
18 > no--repository = status --repository elsewhere
18 > no--config = status --config a.config=1
19 > no--config = status --config a.config=1
19 > mylog = log
20 > mylog = log
20 > lognull = log -r null
21 > lognull = log -r null
21 > shortlog = log --template '{rev} {node|short} | {date|isodate}\n'
22 > shortlog = log --template '{rev} {node|short} | {date|isodate}\n'
22 > positional = log --template '{\$2} {\$1} | {date|isodate}\n'
23 > positional = log --template '{\$2} {\$1} | {date|isodate}\n'
23 > dln = lognull --debug
24 > dln = lognull --debug
24 > nousage = rollback
25 > nousage = rollback
25 > put = export -r 0 -o "\$FOO/%R.diff"
26 > put = export -r 0 -o "\$FOO/%R.diff"
26 > blank = !printf '\n'
27 > blank = !printf '\n'
27 > self = !printf '\$0\n'
28 > self = !printf '\$0\n'
28 > echoall = !printf '\$@\n'
29 > echoall = !printf '\$@\n'
29 > echo1 = !printf '\$1\n'
30 > echo1 = !printf '\$1\n'
30 > echo2 = !printf '\$2\n'
31 > echo2 = !printf '\$2\n'
31 > echo13 = !printf '\$1 \$3\n'
32 > echo13 = !printf '\$1 \$3\n'
32 > count = !hg log -r "\$@" --template=. | wc -c | sed -e 's/ //g'
33 > count = !hg log -r "\$@" --template=. | wc -c | sed -e 's/ //g'
33 > mcount = !hg log \$@ --template=. | wc -c | sed -e 's/ //g'
34 > mcount = !hg log \$@ --template=. | wc -c | sed -e 's/ //g'
34 > rt = root
35 > rt = root
35 > tglog = log -G --template "{rev}:{node|short}: '{desc}' {branches}\n"
36 > tglog = log -G --template "{rev}:{node|short}: '{desc}' {branches}\n"
36 > idalias = id
37 > idalias = id
37 > idaliaslong = id
38 > idaliaslong = id
38 > idaliasshell = !echo test
39 > idaliasshell = !echo test
39 > parentsshell1 = !echo one
40 > parentsshell1 = !echo one
40 > parentsshell2 = !echo two
41 > parentsshell2 = !echo two
41 > escaped1 = !printf 'test\$\$test\n'
42 > escaped1 = !printf 'test\$\$test\n'
42 > escaped2 = !sh -c 'echo "HGFOO is \$\$HGFOO"'
43 > escaped2 = !sh -c 'echo "HGFOO is \$\$HGFOO"'
43 > escaped3 = !sh -c 'echo "\$1 is \$\$\$1"'
44 > escaped3 = !sh -c 'echo "\$1 is \$\$\$1"'
44 > escaped4 = !printf '\$\$0 \$\$@\n'
45 > escaped4 = !printf '\$\$0 \$\$@\n'
45 > exit1 = !sh -c 'exit 1'
46 > exit1 = !sh -c 'exit 1'
46 >
47 >
47 > [defaults]
48 > [defaults]
48 > mylog = -q
49 > mylog = -q
49 > lognull = -q
50 > lognull = -q
50 > log = -v
51 > log = -v
51 > EOF
52 > EOF
52
53
53
54
54 basic
55 basic
55
56
56 $ hg myinit alias
57 $ hg myinit alias
57
58
58
59
59 unknown
60 unknown
60
61
61 $ hg unknown
62 $ hg unknown
62 alias 'unknown' resolves to unknown command 'bargle'
63 alias 'unknown' resolves to unknown command 'bargle'
63 [1]
64 [255]
64 $ hg help unknown
65 $ hg help unknown
65 alias 'unknown' resolves to unknown command 'bargle'
66 alias 'unknown' resolves to unknown command 'bargle'
66
67
67
68
68 ambiguous
69 ambiguous
69
70
70 $ hg ambiguous
71 $ hg ambiguous
71 alias 'ambiguous' resolves to ambiguous command 's'
72 alias 'ambiguous' resolves to ambiguous command 's'
72 [1]
73 [255]
73 $ hg help ambiguous
74 $ hg help ambiguous
74 alias 'ambiguous' resolves to ambiguous command 's'
75 alias 'ambiguous' resolves to ambiguous command 's'
75
76
76
77
77 recursive
78 recursive
78
79
79 $ hg recursive
80 $ hg recursive
80 alias 'recursive' resolves to unknown command 'recursive'
81 alias 'recursive' resolves to unknown command 'recursive'
81 [1]
82 [255]
82 $ hg help recursive
83 $ hg help recursive
83 alias 'recursive' resolves to unknown command 'recursive'
84 alias 'recursive' resolves to unknown command 'recursive'
84
85
85
86
86 no definition
87 no definition
87
88
88 $ hg nodef
89 $ hg nodef
89 no definition for alias 'nodefinition'
90 no definition for alias 'nodefinition'
90 [1]
91 [255]
91 $ hg help nodef
92 $ hg help nodef
92 no definition for alias 'nodefinition'
93 no definition for alias 'nodefinition'
93
94
94
95
96 no closing quotation
97
98 $ hg noclosing
99 error in definition for alias 'noclosingquotation': No closing quotation
100 [255]
101 $ hg help noclosing
102 error in definition for alias 'noclosingquotation': No closing quotation
103
104
95 invalid options
105 invalid options
96
106
97 $ hg no--cwd
107 $ hg no--cwd
98 error in definition for alias 'no--cwd': --cwd may only be given on the command line
108 error in definition for alias 'no--cwd': --cwd may only be given on the command line
99 [1]
109 [255]
100 $ hg help no--cwd
110 $ hg help no--cwd
101 error in definition for alias 'no--cwd': --cwd may only be given on the command line
111 error in definition for alias 'no--cwd': --cwd may only be given on the command line
102 $ hg no-R
112 $ hg no-R
103 error in definition for alias 'no-R': -R may only be given on the command line
113 error in definition for alias 'no-R': -R may only be given on the command line
104 [1]
114 [255]
105 $ hg help no-R
115 $ hg help no-R
106 error in definition for alias 'no-R': -R may only be given on the command line
116 error in definition for alias 'no-R': -R may only be given on the command line
107 $ hg no--repo
117 $ hg no--repo
108 error in definition for alias 'no--repo': --repo may only be given on the command line
118 error in definition for alias 'no--repo': --repo may only be given on the command line
109 [1]
119 [255]
110 $ hg help no--repo
120 $ hg help no--repo
111 error in definition for alias 'no--repo': --repo may only be given on the command line
121 error in definition for alias 'no--repo': --repo may only be given on the command line
112 $ hg no--repository
122 $ hg no--repository
113 error in definition for alias 'no--repository': --repository may only be given on the command line
123 error in definition for alias 'no--repository': --repository may only be given on the command line
114 [1]
124 [255]
115 $ hg help no--repository
125 $ hg help no--repository
116 error in definition for alias 'no--repository': --repository may only be given on the command line
126 error in definition for alias 'no--repository': --repository may only be given on the command line
117 $ hg no--config
127 $ hg no--config
118 error in definition for alias 'no--config': --config may only be given on the command line
128 error in definition for alias 'no--config': --config may only be given on the command line
119 [1]
129 [255]
120
130
121 optional repository
131 optional repository
122
132
123 #if no-outer-repo
133 #if no-outer-repo
124 $ hg optionalrepo
134 $ hg optionalrepo
125 init
135 init
126 #endif
136 #endif
127 $ cd alias
137 $ cd alias
128 $ cat > .hg/hgrc <<EOF
138 $ cat > .hg/hgrc <<EOF
129 > [alias]
139 > [alias]
130 > myinit = init -q
140 > myinit = init -q
131 > EOF
141 > EOF
132 $ hg optionalrepo
142 $ hg optionalrepo
133 init -q
143 init -q
134
144
135 no usage
145 no usage
136
146
137 $ hg nousage
147 $ hg nousage
138 no rollback information available
148 no rollback information available
139 [1]
149 [1]
140
150
141 $ echo foo > foo
151 $ echo foo > foo
142 $ hg commit -Amfoo
152 $ hg commit -Amfoo
143 adding foo
153 adding foo
144
154
145
155
146 with opts
156 with opts
147
157
148 $ hg cleanst
158 $ hg cleanst
149 C foo
159 C foo
150
160
151
161
152 with opts and whitespace
162 with opts and whitespace
153
163
154 $ hg shortlog
164 $ hg shortlog
155 0 e63c23eaa88a | 1970-01-01 00:00 +0000
165 0 e63c23eaa88a | 1970-01-01 00:00 +0000
156
166
157 positional arguments
167 positional arguments
158
168
159 $ hg positional
169 $ hg positional
160 abort: too few arguments for command alias
170 abort: too few arguments for command alias
161 [255]
171 [255]
162 $ hg positional a
172 $ hg positional a
163 abort: too few arguments for command alias
173 abort: too few arguments for command alias
164 [255]
174 [255]
165 $ hg positional 'node|short' rev
175 $ hg positional 'node|short' rev
166 0 e63c23eaa88a | 1970-01-01 00:00 +0000
176 0 e63c23eaa88a | 1970-01-01 00:00 +0000
167
177
168 interaction with defaults
178 interaction with defaults
169
179
170 $ hg mylog
180 $ hg mylog
171 0:e63c23eaa88a
181 0:e63c23eaa88a
172 $ hg lognull
182 $ hg lognull
173 -1:000000000000
183 -1:000000000000
174
184
175
185
176 properly recursive
186 properly recursive
177
187
178 $ hg dln
188 $ hg dln
179 changeset: -1:0000000000000000000000000000000000000000
189 changeset: -1:0000000000000000000000000000000000000000
180 parent: -1:0000000000000000000000000000000000000000
190 parent: -1:0000000000000000000000000000000000000000
181 parent: -1:0000000000000000000000000000000000000000
191 parent: -1:0000000000000000000000000000000000000000
182 manifest: -1:0000000000000000000000000000000000000000
192 manifest: -1:0000000000000000000000000000000000000000
183 user:
193 user:
184 date: Thu Jan 01 00:00:00 1970 +0000
194 date: Thu Jan 01 00:00:00 1970 +0000
185 extra: branch=default
195 extra: branch=default
186
196
187
197
188
198
189 path expanding
199 path expanding
190
200
191 $ FOO=`pwd` hg put
201 $ FOO=`pwd` hg put
192 $ cat 0.diff
202 $ cat 0.diff
193 # HG changeset patch
203 # HG changeset patch
194 # User test
204 # User test
195 # Date 0 0
205 # Date 0 0
196 # Thu Jan 01 00:00:00 1970 +0000
206 # Thu Jan 01 00:00:00 1970 +0000
197 # Node ID e63c23eaa88ae77967edcf4ea194d31167c478b0
207 # Node ID e63c23eaa88ae77967edcf4ea194d31167c478b0
198 # Parent 0000000000000000000000000000000000000000
208 # Parent 0000000000000000000000000000000000000000
199 foo
209 foo
200
210
201 diff -r 000000000000 -r e63c23eaa88a foo
211 diff -r 000000000000 -r e63c23eaa88a foo
202 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
212 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
203 +++ b/foo Thu Jan 01 00:00:00 1970 +0000
213 +++ b/foo Thu Jan 01 00:00:00 1970 +0000
204 @@ -0,0 +1,1 @@
214 @@ -0,0 +1,1 @@
205 +foo
215 +foo
206
216
207
217
208 simple shell aliases
218 simple shell aliases
209
219
210 $ hg blank
220 $ hg blank
211
221
212 $ hg blank foo
222 $ hg blank foo
213
223
214 $ hg self
224 $ hg self
215 self
225 self
216 $ hg echoall
226 $ hg echoall
217
227
218 $ hg echoall foo
228 $ hg echoall foo
219 foo
229 foo
220 $ hg echoall 'test $2' foo
230 $ hg echoall 'test $2' foo
221 test $2 foo
231 test $2 foo
222 $ hg echo1 foo bar baz
232 $ hg echo1 foo bar baz
223 foo
233 foo
224 $ hg echo2 foo bar baz
234 $ hg echo2 foo bar baz
225 bar
235 bar
226 $ hg echo13 foo bar baz test
236 $ hg echo13 foo bar baz test
227 foo baz
237 foo baz
228 $ hg echo2 foo
238 $ hg echo2 foo
229
239
230 $ echo bar > bar
240 $ echo bar > bar
231 $ hg commit -qA -m bar
241 $ hg commit -qA -m bar
232 $ hg count .
242 $ hg count .
233 1
243 1
234 $ hg count 'branch(default)'
244 $ hg count 'branch(default)'
235 2
245 2
236 $ hg mcount -r '"branch(default)"'
246 $ hg mcount -r '"branch(default)"'
237 2
247 2
238
248
239 $ hg tglog
249 $ hg tglog
240 @ 1:042423737847: 'bar'
250 @ 1:042423737847: 'bar'
241 |
251 |
242 o 0:e63c23eaa88a: 'foo'
252 o 0:e63c23eaa88a: 'foo'
243
253
244
254
245
255
246 shadowing
256 shadowing
247
257
248 $ hg i
258 $ hg i
249 hg: command 'i' is ambiguous:
259 hg: command 'i' is ambiguous:
250 idalias idaliaslong idaliasshell identify import incoming init
260 idalias idaliaslong idaliasshell identify import incoming init
251 [255]
261 [255]
252 $ hg id
262 $ hg id
253 042423737847 tip
263 042423737847 tip
254 $ hg ida
264 $ hg ida
255 hg: command 'ida' is ambiguous:
265 hg: command 'ida' is ambiguous:
256 idalias idaliaslong idaliasshell
266 idalias idaliaslong idaliasshell
257 [255]
267 [255]
258 $ hg idalias
268 $ hg idalias
259 042423737847 tip
269 042423737847 tip
260 $ hg idaliasl
270 $ hg idaliasl
261 042423737847 tip
271 042423737847 tip
262 $ hg idaliass
272 $ hg idaliass
263 test
273 test
264 $ hg parentsshell
274 $ hg parentsshell
265 hg: command 'parentsshell' is ambiguous:
275 hg: command 'parentsshell' is ambiguous:
266 parentsshell1 parentsshell2
276 parentsshell1 parentsshell2
267 [255]
277 [255]
268 $ hg parentsshell1
278 $ hg parentsshell1
269 one
279 one
270 $ hg parentsshell2
280 $ hg parentsshell2
271 two
281 two
272
282
273
283
274 shell aliases with global options
284 shell aliases with global options
275
285
276 $ hg init sub
286 $ hg init sub
277 $ cd sub
287 $ cd sub
278 $ hg count 'branch(default)'
288 $ hg count 'branch(default)'
279 abort: unknown revision 'default'!
289 abort: unknown revision 'default'!
280 0
290 0
281 $ hg -v count 'branch(default)'
291 $ hg -v count 'branch(default)'
282 abort: unknown revision 'default'!
292 abort: unknown revision 'default'!
283 0
293 0
284 $ hg -R .. count 'branch(default)'
294 $ hg -R .. count 'branch(default)'
285 abort: unknown revision 'default'!
295 abort: unknown revision 'default'!
286 0
296 0
287 $ hg --cwd .. count 'branch(default)'
297 $ hg --cwd .. count 'branch(default)'
288 2
298 2
289 $ hg echoall --cwd ..
299 $ hg echoall --cwd ..
290
300
291
301
292
302
293 repo specific shell aliases
303 repo specific shell aliases
294
304
295 $ cat >> .hg/hgrc <<EOF
305 $ cat >> .hg/hgrc <<EOF
296 > [alias]
306 > [alias]
297 > subalias = !echo sub
307 > subalias = !echo sub
298 > EOF
308 > EOF
299 $ cat >> ../.hg/hgrc <<EOF
309 $ cat >> ../.hg/hgrc <<EOF
300 > [alias]
310 > [alias]
301 > mainalias = !echo main
311 > mainalias = !echo main
302 > EOF
312 > EOF
303
313
304
314
305 shell alias defined in current repo
315 shell alias defined in current repo
306
316
307 $ hg subalias
317 $ hg subalias
308 sub
318 sub
309 $ hg --cwd .. subalias > /dev/null
319 $ hg --cwd .. subalias > /dev/null
310 hg: unknown command 'subalias'
320 hg: unknown command 'subalias'
311 [255]
321 [255]
312 $ hg -R .. subalias > /dev/null
322 $ hg -R .. subalias > /dev/null
313 hg: unknown command 'subalias'
323 hg: unknown command 'subalias'
314 [255]
324 [255]
315
325
316
326
317 shell alias defined in other repo
327 shell alias defined in other repo
318
328
319 $ hg mainalias > /dev/null
329 $ hg mainalias > /dev/null
320 hg: unknown command 'mainalias'
330 hg: unknown command 'mainalias'
321 [255]
331 [255]
322 $ hg -R .. mainalias
332 $ hg -R .. mainalias
323 main
333 main
324 $ hg --cwd .. mainalias
334 $ hg --cwd .. mainalias
325 main
335 main
326
336
327
337
328 shell aliases with escaped $ chars
338 shell aliases with escaped $ chars
329
339
330 $ hg escaped1
340 $ hg escaped1
331 test$test
341 test$test
332 $ hg escaped2
342 $ hg escaped2
333 HGFOO is BAR
343 HGFOO is BAR
334 $ hg escaped3 HGFOO
344 $ hg escaped3 HGFOO
335 HGFOO is BAR
345 HGFOO is BAR
336 $ hg escaped4 test
346 $ hg escaped4 test
337 $0 $@
347 $0 $@
338
348
339 abbreviated name, which matches against both shell alias and the
349 abbreviated name, which matches against both shell alias and the
340 command provided extension, should be aborted.
350 command provided extension, should be aborted.
341
351
342 $ cat >> .hg/hgrc <<EOF
352 $ cat >> .hg/hgrc <<EOF
343 > [extensions]
353 > [extensions]
344 > hgext.rebase =
354 > hgext.rebase =
345 > [alias]
355 > [alias]
346 > rebate = !echo this is rebate
356 > rebate = !echo this is rebate
347 > EOF
357 > EOF
348 $ hg reba
358 $ hg reba
349 hg: command 'reba' is ambiguous:
359 hg: command 'reba' is ambiguous:
350 rebase rebate
360 rebase rebate
351 [255]
361 [255]
352 $ hg rebat
362 $ hg rebat
353 this is rebate
363 this is rebate
354
364
355 invalid arguments
365 invalid arguments
356
366
357 $ hg rt foo
367 $ hg rt foo
358 hg rt: invalid arguments
368 hg rt: invalid arguments
359 hg rt
369 hg rt
360
370
361 alias for: hg root
371 alias for: hg root
362
372
363 use "hg help rt" to show the full help text
373 use "hg help rt" to show the full help text
364 [255]
374 [255]
365
375
366 invalid global arguments for normal commands, aliases, and shell aliases
376 invalid global arguments for normal commands, aliases, and shell aliases
367
377
368 $ hg --invalid root
378 $ hg --invalid root
369 hg: option --invalid not recognized
379 hg: option --invalid not recognized
370 Mercurial Distributed SCM
380 Mercurial Distributed SCM
371
381
372 basic commands:
382 basic commands:
373
383
374 add add the specified files on the next commit
384 add add the specified files on the next commit
375 annotate show changeset information by line for each file
385 annotate show changeset information by line for each file
376 clone make a copy of an existing repository
386 clone make a copy of an existing repository
377 commit commit the specified files or all outstanding changes
387 commit commit the specified files or all outstanding changes
378 diff diff repository (or selected files)
388 diff diff repository (or selected files)
379 export dump the header and diffs for one or more changesets
389 export dump the header and diffs for one or more changesets
380 forget forget the specified files on the next commit
390 forget forget the specified files on the next commit
381 init create a new repository in the given directory
391 init create a new repository in the given directory
382 log show revision history of entire repository or files
392 log show revision history of entire repository or files
383 merge merge working directory with another revision
393 merge merge working directory with another revision
384 pull pull changes from the specified source
394 pull pull changes from the specified source
385 push push changes to the specified destination
395 push push changes to the specified destination
386 remove remove the specified files on the next commit
396 remove remove the specified files on the next commit
387 serve start stand-alone webserver
397 serve start stand-alone webserver
388 status show changed files in the working directory
398 status show changed files in the working directory
389 summary summarize working directory state
399 summary summarize working directory state
390 update update working directory (or switch revisions)
400 update update working directory (or switch revisions)
391
401
392 use "hg help" for the full list of commands or "hg -v" for details
402 use "hg help" for the full list of commands or "hg -v" for details
393 [255]
403 [255]
394 $ hg --invalid mylog
404 $ hg --invalid mylog
395 hg: option --invalid not recognized
405 hg: option --invalid not recognized
396 Mercurial Distributed SCM
406 Mercurial Distributed SCM
397
407
398 basic commands:
408 basic commands:
399
409
400 add add the specified files on the next commit
410 add add the specified files on the next commit
401 annotate show changeset information by line for each file
411 annotate show changeset information by line for each file
402 clone make a copy of an existing repository
412 clone make a copy of an existing repository
403 commit commit the specified files or all outstanding changes
413 commit commit the specified files or all outstanding changes
404 diff diff repository (or selected files)
414 diff diff repository (or selected files)
405 export dump the header and diffs for one or more changesets
415 export dump the header and diffs for one or more changesets
406 forget forget the specified files on the next commit
416 forget forget the specified files on the next commit
407 init create a new repository in the given directory
417 init create a new repository in the given directory
408 log show revision history of entire repository or files
418 log show revision history of entire repository or files
409 merge merge working directory with another revision
419 merge merge working directory with another revision
410 pull pull changes from the specified source
420 pull pull changes from the specified source
411 push push changes to the specified destination
421 push push changes to the specified destination
412 remove remove the specified files on the next commit
422 remove remove the specified files on the next commit
413 serve start stand-alone webserver
423 serve start stand-alone webserver
414 status show changed files in the working directory
424 status show changed files in the working directory
415 summary summarize working directory state
425 summary summarize working directory state
416 update update working directory (or switch revisions)
426 update update working directory (or switch revisions)
417
427
418 use "hg help" for the full list of commands or "hg -v" for details
428 use "hg help" for the full list of commands or "hg -v" for details
419 [255]
429 [255]
420 $ hg --invalid blank
430 $ hg --invalid blank
421 hg: option --invalid not recognized
431 hg: option --invalid not recognized
422 Mercurial Distributed SCM
432 Mercurial Distributed SCM
423
433
424 basic commands:
434 basic commands:
425
435
426 add add the specified files on the next commit
436 add add the specified files on the next commit
427 annotate show changeset information by line for each file
437 annotate show changeset information by line for each file
428 clone make a copy of an existing repository
438 clone make a copy of an existing repository
429 commit commit the specified files or all outstanding changes
439 commit commit the specified files or all outstanding changes
430 diff diff repository (or selected files)
440 diff diff repository (or selected files)
431 export dump the header and diffs for one or more changesets
441 export dump the header and diffs for one or more changesets
432 forget forget the specified files on the next commit
442 forget forget the specified files on the next commit
433 init create a new repository in the given directory
443 init create a new repository in the given directory
434 log show revision history of entire repository or files
444 log show revision history of entire repository or files
435 merge merge working directory with another revision
445 merge merge working directory with another revision
436 pull pull changes from the specified source
446 pull pull changes from the specified source
437 push push changes to the specified destination
447 push push changes to the specified destination
438 remove remove the specified files on the next commit
448 remove remove the specified files on the next commit
439 serve start stand-alone webserver
449 serve start stand-alone webserver
440 status show changed files in the working directory
450 status show changed files in the working directory
441 summary summarize working directory state
451 summary summarize working directory state
442 update update working directory (or switch revisions)
452 update update working directory (or switch revisions)
443
453
444 use "hg help" for the full list of commands or "hg -v" for details
454 use "hg help" for the full list of commands or "hg -v" for details
445 [255]
455 [255]
446
456
447 This should show id:
457 This should show id:
448
458
449 $ hg --config alias.log='id' log
459 $ hg --config alias.log='id' log
450 000000000000 tip
460 000000000000 tip
451
461
452 This shouldn't:
462 This shouldn't:
453
463
454 $ hg --config alias.log='id' history
464 $ hg --config alias.log='id' history
455
465
456 $ cd ../..
466 $ cd ../..
457
467
458 return code of command and shell aliases:
468 return code of command and shell aliases:
459
469
460 $ hg mycommit -R alias
470 $ hg mycommit -R alias
461 nothing changed
471 nothing changed
462 [1]
472 [1]
463 $ hg exit1
473 $ hg exit1
464 [1]
474 [1]
@@ -1,32 +1,33 b''
1 # this is hack to make sure no escape characters are inserted into the output
1 # this is hack to make sure no escape characters are inserted into the output
2 import os, sys
2 import os, sys
3 if 'TERM' in os.environ:
3 if 'TERM' in os.environ:
4 del os.environ['TERM']
4 del os.environ['TERM']
5 import doctest
5 import doctest
6
6
7 def testmod(name, optionflags=0, testtarget=None):
7 def testmod(name, optionflags=0, testtarget=None):
8 __import__(name)
8 __import__(name)
9 mod = sys.modules[name]
9 mod = sys.modules[name]
10 if testtarget is not None:
10 if testtarget is not None:
11 mod = getattr(mod, testtarget)
11 mod = getattr(mod, testtarget)
12 doctest.testmod(mod, optionflags=optionflags)
12 doctest.testmod(mod, optionflags=optionflags)
13
13
14 testmod('mercurial.changelog')
14 testmod('mercurial.changelog')
15 testmod('mercurial.dagparser', optionflags=doctest.NORMALIZE_WHITESPACE)
15 testmod('mercurial.dagparser', optionflags=doctest.NORMALIZE_WHITESPACE)
16 testmod('mercurial.dispatch')
16 testmod('mercurial.dispatch')
17 testmod('mercurial.encoding')
17 testmod('mercurial.encoding')
18 testmod('mercurial.hg')
18 testmod('mercurial.hg')
19 testmod('mercurial.hgweb.hgwebdir_mod')
19 testmod('mercurial.hgweb.hgwebdir_mod')
20 testmod('mercurial.match')
20 testmod('mercurial.match')
21 testmod('mercurial.minirst')
21 testmod('mercurial.minirst')
22 testmod('mercurial.pathutil')
22 testmod('mercurial.revset')
23 testmod('mercurial.revset')
23 testmod('mercurial.store')
24 testmod('mercurial.store')
24 testmod('mercurial.subrepo')
25 testmod('mercurial.subrepo')
25 testmod('mercurial.templatefilters')
26 testmod('mercurial.templatefilters')
26 testmod('mercurial.ui')
27 testmod('mercurial.ui')
27 testmod('mercurial.url')
28 testmod('mercurial.url')
28 testmod('mercurial.util')
29 testmod('mercurial.util')
29 testmod('mercurial.util', testtarget='platform')
30 testmod('mercurial.util', testtarget='platform')
30 testmod('hgext.convert.cvsps')
31 testmod('hgext.convert.cvsps')
31 testmod('hgext.convert.filemap')
32 testmod('hgext.convert.filemap')
32 testmod('hgext.convert.subversion')
33 testmod('hgext.convert.subversion')
@@ -1,144 +1,152 b''
1 Test alignment of multibyte characters
1 Test alignment of multibyte characters
2
2
3 $ HGENCODING=utf-8
3 $ HGENCODING=utf-8
4 $ export HGENCODING
4 $ export HGENCODING
5 $ hg init t
5 $ hg init t
6 $ cd t
6 $ cd t
7 $ python << EOF
7 $ python << EOF
8 > # (byte, width) = (6, 4)
8 > # (byte, width) = (6, 4)
9 > s = "\xe7\x9f\xad\xe5\x90\x8d"
9 > s = "\xe7\x9f\xad\xe5\x90\x8d"
10 > # (byte, width) = (7, 7): odd width is good for alignment test
10 > # (byte, width) = (7, 7): odd width is good for alignment test
11 > m = "MIDDLE_"
11 > m = "MIDDLE_"
12 > # (byte, width) = (18, 12)
12 > # (byte, width) = (18, 12)
13 > l = "\xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d"
13 > l = "\xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d"
14 > f = file('s', 'w'); f.write(s); f.close()
14 > f = file('s', 'w'); f.write(s); f.close()
15 > f = file('m', 'w'); f.write(m); f.close()
15 > f = file('m', 'w'); f.write(m); f.close()
16 > f = file('l', 'w'); f.write(l); f.close()
16 > f = file('l', 'w'); f.write(l); f.close()
17 > # instant extension to show list of options
17 > # instant extension to show list of options
18 > f = file('showoptlist.py', 'w'); f.write("""# encoding: utf-8
18 > f = file('showoptlist.py', 'w'); f.write("""# encoding: utf-8
19 > from mercurial import cmdutil
19 > from mercurial import cmdutil
20 > cmdtable = {}
20 > cmdtable = {}
21 > command = cmdutil.command(cmdtable)
21 > command = cmdutil.command(cmdtable)
22 >
22 >
23 > @command('showoptlist',
23 > @command('showoptlist',
24 > [('s', 'opt1', '', 'short width' + ' %(s)s' * 8, '%(s)s'),
24 > [('s', 'opt1', '', 'short width' + ' %(s)s' * 8, '%(s)s'),
25 > ('m', 'opt2', '', 'middle width' + ' %(m)s' * 8, '%(m)s'),
25 > ('m', 'opt2', '', 'middle width' + ' %(m)s' * 8, '%(m)s'),
26 > ('l', 'opt3', '', 'long width' + ' %(l)s' * 8, '%(l)s')],
26 > ('l', 'opt3', '', 'long width' + ' %(l)s' * 8, '%(l)s')],
27 > '')
27 > '')
28 > def showoptlist(ui, repo, *pats, **opts):
28 > def showoptlist(ui, repo, *pats, **opts):
29 > '''dummy command to show option descriptions'''
29 > '''dummy command to show option descriptions'''
30 > return 0
30 > return 0
31 > """ % globals())
31 > """ % globals())
32 > f.close()
32 > f.close()
33 > EOF
33 > EOF
34 $ S=`cat s`
34 $ S=`cat s`
35 $ M=`cat m`
35 $ M=`cat m`
36 $ L=`cat l`
36 $ L=`cat l`
37
37
38 alignment of option descriptions in help
38 alignment of option descriptions in help
39
39
40 $ cat <<EOF > .hg/hgrc
40 $ cat <<EOF > .hg/hgrc
41 > [extensions]
41 > [extensions]
42 > ja_ext = `pwd`/showoptlist.py
42 > ja_ext = `pwd`/showoptlist.py
43 > EOF
43 > EOF
44
44
45 check alignment of option descriptions in help
45 check alignment of option descriptions in help
46
46
47 $ hg help showoptlist
47 $ hg help showoptlist
48 hg showoptlist
48 hg showoptlist
49
49
50 dummy command to show option descriptions
50 dummy command to show option descriptions
51
51
52 options:
52 options:
53
53
54 -s --opt1 \xe7\x9f\xad\xe5\x90\x8d short width \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d (esc)
54 -s --opt1 \xe7\x9f\xad\xe5\x90\x8d short width \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d \xe7\x9f\xad\xe5\x90\x8d (esc)
55 -m --opt2 MIDDLE_ middle width MIDDLE_ MIDDLE_ MIDDLE_ MIDDLE_ MIDDLE_
55 -m --opt2 MIDDLE_ middle width MIDDLE_ MIDDLE_ MIDDLE_ MIDDLE_ MIDDLE_
56 MIDDLE_ MIDDLE_ MIDDLE_
56 MIDDLE_ MIDDLE_ MIDDLE_
57 -l --opt3 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d long width \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
57 -l --opt3 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d long width \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
58 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
58 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
59 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
59 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
60
60
61 use "hg -v help showoptlist" to show the global options
61 use "hg -v help showoptlist" to show the global options
62
62
63
63
64 $ rm -f s; touch s
64 $ rm -f s; touch s
65 $ rm -f m; touch m
65 $ rm -f m; touch m
66 $ rm -f l; touch l
66 $ rm -f l; touch l
67
67
68 add files
68 add files
69
69
70 $ cp s $S
70 $ cp s $S
71 $ hg add $S
71 $ hg add $S
72 $ cp m $M
72 $ cp m $M
73 $ hg add $M
73 $ hg add $M
74 $ cp l $L
74 $ cp l $L
75 $ hg add $L
75 $ hg add $L
76
76
77 commit(1)
77 commit(1)
78
78
79 $ echo 'first line(1)' >> s; cp s $S
79 $ echo 'first line(1)' >> s; cp s $S
80 $ echo 'first line(2)' >> m; cp m $M
80 $ echo 'first line(2)' >> m; cp m $M
81 $ echo 'first line(3)' >> l; cp l $L
81 $ echo 'first line(3)' >> l; cp l $L
82 $ hg commit -m 'first commit' -u $S
82 $ hg commit -m 'first commit' -u $S
83
83
84 commit(2)
84 commit(2)
85
85
86 $ echo 'second line(1)' >> s; cp s $S
86 $ echo 'second line(1)' >> s; cp s $S
87 $ echo 'second line(2)' >> m; cp m $M
87 $ echo 'second line(2)' >> m; cp m $M
88 $ echo 'second line(3)' >> l; cp l $L
88 $ echo 'second line(3)' >> l; cp l $L
89 $ hg commit -m 'second commit' -u $M
89 $ hg commit -m 'second commit' -u $M
90
90
91 commit(3)
91 commit(3)
92
92
93 $ echo 'third line(1)' >> s; cp s $S
93 $ echo 'third line(1)' >> s; cp s $S
94 $ echo 'third line(2)' >> m; cp m $M
94 $ echo 'third line(2)' >> m; cp m $M
95 $ echo 'third line(3)' >> l; cp l $L
95 $ echo 'third line(3)' >> l; cp l $L
96 $ hg commit -m 'third commit' -u $L
96 $ hg commit -m 'third commit' -u $L
97
97
98 check alignment of user names in annotate
98 check alignment of user names in annotate
99
99
100 $ hg annotate -u $M
100 $ hg annotate -u $M
101 \xe7\x9f\xad\xe5\x90\x8d: first line(2) (esc)
101 \xe7\x9f\xad\xe5\x90\x8d: first line(2) (esc)
102 MIDDLE_: second line(2)
102 MIDDLE_: second line(2)
103 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d: third line(2) (esc)
103 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d: third line(2) (esc)
104
104
105 check alignment of filenames in diffstat
105 check alignment of filenames in diffstat
106
106
107 $ hg diff -c tip --stat
107 $ hg diff -c tip --stat
108 MIDDLE_ | 1 +
108 MIDDLE_ | 1 +
109 \xe7\x9f\xad\xe5\x90\x8d | 1 + (esc)
109 \xe7\x9f\xad\xe5\x90\x8d | 1 + (esc)
110 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d | 1 + (esc)
110 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d | 1 + (esc)
111 3 files changed, 3 insertions(+), 0 deletions(-)
111 3 files changed, 3 insertions(+), 0 deletions(-)
112
112
113 add branches/tags
113 add branches/tags
114
114
115 $ hg branch $S
115 $ hg branch $S
116 marked working directory as branch \xe7\x9f\xad\xe5\x90\x8d (esc)
116 marked working directory as branch \xe7\x9f\xad\xe5\x90\x8d (esc)
117 (branches are permanent and global, did you want a bookmark?)
117 (branches are permanent and global, did you want a bookmark?)
118 $ hg tag $S
118 $ hg tag $S
119 $ hg book -f $S
119 $ hg branch $M
120 $ hg branch $M
120 marked working directory as branch MIDDLE_
121 marked working directory as branch MIDDLE_
121 (branches are permanent and global, did you want a bookmark?)
122 (branches are permanent and global, did you want a bookmark?)
122 $ hg tag $M
123 $ hg tag $M
124 $ hg book -f $M
123 $ hg branch $L
125 $ hg branch $L
124 marked working directory as branch \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
126 marked working directory as branch \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d (esc)
125 (branches are permanent and global, did you want a bookmark?)
127 (branches are permanent and global, did you want a bookmark?)
126 $ hg tag $L
128 $ hg tag $L
129 $ hg book -f $L
127
130
128 check alignment of branches
131 check alignment of branches
129
132
130 $ hg tags
133 $ hg branches
131 tip 5:d745ff46155b
134 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d 5:d745ff46155b (esc)
132 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d 4:9259be597f19 (esc)
135 MIDDLE_ 4:9259be597f19 (inactive)
133 MIDDLE_ 3:b06c5b6def9e
136 \xe7\x9f\xad\xe5\x90\x8d 3:b06c5b6def9e (inactive) (esc)
134 \xe7\x9f\xad\xe5\x90\x8d 2:64a70663cee8 (esc)
137 default 2:64a70663cee8 (inactive)
135
138
136 check alignment of tags
139 check alignment of tags
137
140
138 $ hg tags
141 $ hg tags
139 tip 5:d745ff46155b
142 tip 5:d745ff46155b
140 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d 4:9259be597f19 (esc)
143 \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d 4:9259be597f19 (esc)
141 MIDDLE_ 3:b06c5b6def9e
144 MIDDLE_ 3:b06c5b6def9e
142 \xe7\x9f\xad\xe5\x90\x8d 2:64a70663cee8 (esc)
145 \xe7\x9f\xad\xe5\x90\x8d 2:64a70663cee8 (esc)
143
146
144 $ cd ..
147 check alignment of bookmarks
148
149 $ hg book
150 MIDDLE_ 5:d745ff46155b
151 \xe7\x9f\xad\xe5\x90\x8d 4:9259be597f19 (esc)
152 * \xe9\x95\xb7\xe3\x81\x84\xe9\x95\xb7\xe3\x81\x84\xe5\x90\x8d\xe5\x89\x8d 5:d745ff46155b (esc)
@@ -1,568 +1,670 b''
1 $ "$TESTDIR/hghave" git || exit 80
1 $ "$TESTDIR/hghave" git || exit 80
2
2
3 make git commits repeatable
3 make git commits repeatable
4
4
5 $ echo "[core]" >> $HOME/.gitconfig
5 $ echo "[core]" >> $HOME/.gitconfig
6 $ echo "autocrlf = false" >> $HOME/.gitconfig
6 $ echo "autocrlf = false" >> $HOME/.gitconfig
7 $ GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
7 $ GIT_AUTHOR_NAME='test'; export GIT_AUTHOR_NAME
8 $ GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
8 $ GIT_AUTHOR_EMAIL='test@example.org'; export GIT_AUTHOR_EMAIL
9 $ GIT_AUTHOR_DATE='1234567891 +0000'; export GIT_AUTHOR_DATE
9 $ GIT_AUTHOR_DATE='1234567891 +0000'; export GIT_AUTHOR_DATE
10 $ GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
10 $ GIT_COMMITTER_NAME="$GIT_AUTHOR_NAME"; export GIT_COMMITTER_NAME
11 $ GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
11 $ GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"; export GIT_COMMITTER_EMAIL
12 $ GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
12 $ GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"; export GIT_COMMITTER_DATE
13
13
14 root hg repo
14 root hg repo
15
15
16 $ hg init t
16 $ hg init t
17 $ cd t
17 $ cd t
18 $ echo a > a
18 $ echo a > a
19 $ hg add a
19 $ hg add a
20 $ hg commit -m a
20 $ hg commit -m a
21 $ cd ..
21 $ cd ..
22
22
23 new external git repo
23 new external git repo
24
24
25 $ mkdir gitroot
25 $ mkdir gitroot
26 $ cd gitroot
26 $ cd gitroot
27 $ git init -q
27 $ git init -q
28 $ echo g > g
28 $ echo g > g
29 $ git add g
29 $ git add g
30 $ git commit -q -m g
30 $ git commit -q -m g
31
31
32 add subrepo clone
32 add subrepo clone
33
33
34 $ cd ../t
34 $ cd ../t
35 $ echo 's = [git]../gitroot' > .hgsub
35 $ echo 's = [git]../gitroot' > .hgsub
36 $ git clone -q ../gitroot s
36 $ git clone -q ../gitroot s
37 $ hg add .hgsub
37 $ hg add .hgsub
38 $ hg commit -m 'new git subrepo'
38 $ hg commit -m 'new git subrepo'
39 $ hg debugsub
39 $ hg debugsub
40 path s
40 path s
41 source ../gitroot
41 source ../gitroot
42 revision da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
42 revision da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
43
43
44 record a new commit from upstream from a different branch
44 record a new commit from upstream from a different branch
45
45
46 $ cd ../gitroot
46 $ cd ../gitroot
47 $ git checkout -q -b testing
47 $ git checkout -q -b testing
48 $ echo gg >> g
48 $ echo gg >> g
49 $ git commit -q -a -m gg
49 $ git commit -q -a -m gg
50
50
51 $ cd ../t/s
51 $ cd ../t/s
52 $ git pull -q >/dev/null 2>/dev/null
52 $ git pull -q >/dev/null 2>/dev/null
53 $ git checkout -q -b testing origin/testing >/dev/null
53 $ git checkout -q -b testing origin/testing >/dev/null
54
54
55 $ cd ..
55 $ cd ..
56 $ hg status --subrepos
56 $ hg status --subrepos
57 M s/g
57 M s/g
58 $ hg commit -m 'update git subrepo'
58 $ hg commit -m 'update git subrepo'
59 $ hg debugsub
59 $ hg debugsub
60 path s
60 path s
61 source ../gitroot
61 source ../gitroot
62 revision 126f2a14290cd5ce061fdedc430170e8d39e1c5a
62 revision 126f2a14290cd5ce061fdedc430170e8d39e1c5a
63
63
64 make $GITROOT pushable, by replacing it with a clone with nothing checked out
64 make $GITROOT pushable, by replacing it with a clone with nothing checked out
65
65
66 $ cd ..
66 $ cd ..
67 $ git clone gitroot gitrootbare --bare -q
67 $ git clone gitroot gitrootbare --bare -q
68 $ rm -rf gitroot
68 $ rm -rf gitroot
69 $ mv gitrootbare gitroot
69 $ mv gitrootbare gitroot
70
70
71 clone root
71 clone root
72
72
73 $ cd t
73 $ cd t
74 $ hg clone . ../tc 2> /dev/null
74 $ hg clone . ../tc 2> /dev/null
75 updating to branch default
75 updating to branch default
76 cloning subrepo s from $TESTTMP/gitroot
76 cloning subrepo s from $TESTTMP/gitroot
77 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
77 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
78 $ cd ../tc
78 $ cd ../tc
79 $ hg debugsub
79 $ hg debugsub
80 path s
80 path s
81 source ../gitroot
81 source ../gitroot
82 revision 126f2a14290cd5ce061fdedc430170e8d39e1c5a
82 revision 126f2a14290cd5ce061fdedc430170e8d39e1c5a
83
83
84 update to previous substate
84 update to previous substate
85
85
86 $ hg update 1 -q
86 $ hg update 1 -q
87 $ cat s/g
87 $ cat s/g
88 g
88 g
89 $ hg debugsub
89 $ hg debugsub
90 path s
90 path s
91 source ../gitroot
91 source ../gitroot
92 revision da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
92 revision da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
93
93
94 clone root, make local change
94 clone root, make local change
95
95
96 $ cd ../t
96 $ cd ../t
97 $ hg clone . ../ta 2> /dev/null
97 $ hg clone . ../ta 2> /dev/null
98 updating to branch default
98 updating to branch default
99 cloning subrepo s from $TESTTMP/gitroot
99 cloning subrepo s from $TESTTMP/gitroot
100 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
100 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
101
101
102 $ cd ../ta
102 $ cd ../ta
103 $ echo ggg >> s/g
103 $ echo ggg >> s/g
104 $ hg status --subrepos
104 $ hg status --subrepos
105 M s/g
105 M s/g
106 $ hg commit --subrepos -m ggg
106 $ hg commit --subrepos -m ggg
107 committing subrepository s
107 committing subrepository s
108 $ hg debugsub
108 $ hg debugsub
109 path s
109 path s
110 source ../gitroot
110 source ../gitroot
111 revision 79695940086840c99328513acbe35f90fcd55e57
111 revision 79695940086840c99328513acbe35f90fcd55e57
112
112
113 clone root separately, make different local change
113 clone root separately, make different local change
114
114
115 $ cd ../t
115 $ cd ../t
116 $ hg clone . ../tb 2> /dev/null
116 $ hg clone . ../tb 2> /dev/null
117 updating to branch default
117 updating to branch default
118 cloning subrepo s from $TESTTMP/gitroot
118 cloning subrepo s from $TESTTMP/gitroot
119 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
119 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
120
120
121 $ cd ../tb/s
121 $ cd ../tb/s
122 $ echo f > f
122 $ echo f > f
123 $ git add f
123 $ git add f
124 $ cd ..
124 $ cd ..
125
125
126 $ hg status --subrepos
126 $ hg status --subrepos
127 A s/f
127 A s/f
128 $ hg commit --subrepos -m f
128 $ hg commit --subrepos -m f
129 committing subrepository s
129 committing subrepository s
130 $ hg debugsub
130 $ hg debugsub
131 path s
131 path s
132 source ../gitroot
132 source ../gitroot
133 revision aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
133 revision aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
134
134
135 user b push changes
135 user b push changes
136
136
137 $ hg push 2>/dev/null
137 $ hg push 2>/dev/null
138 pushing to $TESTTMP/t (glob)
138 pushing to $TESTTMP/t (glob)
139 pushing branch testing of subrepo s
139 pushing branch testing of subrepo s
140 searching for changes
140 searching for changes
141 adding changesets
141 adding changesets
142 adding manifests
142 adding manifests
143 adding file changes
143 adding file changes
144 added 1 changesets with 1 changes to 1 files
144 added 1 changesets with 1 changes to 1 files
145
145
146 user a pulls, merges, commits
146 user a pulls, merges, commits
147
147
148 $ cd ../ta
148 $ cd ../ta
149 $ hg pull
149 $ hg pull
150 pulling from $TESTTMP/t (glob)
150 pulling from $TESTTMP/t (glob)
151 searching for changes
151 searching for changes
152 adding changesets
152 adding changesets
153 adding manifests
153 adding manifests
154 adding file changes
154 adding file changes
155 added 1 changesets with 1 changes to 1 files (+1 heads)
155 added 1 changesets with 1 changes to 1 files (+1 heads)
156 (run 'hg heads' to see heads, 'hg merge' to merge)
156 (run 'hg heads' to see heads, 'hg merge' to merge)
157 $ hg merge 2>/dev/null
157 $ hg merge 2>/dev/null
158 subrepository s diverged (local revision: 7969594, remote revision: aa84837)
158 subrepository s diverged (local revision: 7969594, remote revision: aa84837)
159 (M)erge, keep (l)ocal or keep (r)emote? m
159 (M)erge, keep (l)ocal or keep (r)emote? m
160 pulling subrepo s from $TESTTMP/gitroot
160 pulling subrepo s from $TESTTMP/gitroot
161 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
161 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
162 (branch merge, don't forget to commit)
162 (branch merge, don't forget to commit)
163 $ cat s/f
163 $ cat s/f
164 f
164 f
165 $ cat s/g
165 $ cat s/g
166 g
166 g
167 gg
167 gg
168 ggg
168 ggg
169 $ hg commit --subrepos -m 'merge'
169 $ hg commit --subrepos -m 'merge'
170 committing subrepository s
170 committing subrepository s
171 $ hg status --subrepos --rev 1:5
171 $ hg status --subrepos --rev 1:5
172 M .hgsubstate
172 M .hgsubstate
173 M s/g
173 M s/g
174 A s/f
174 A s/f
175 $ hg debugsub
175 $ hg debugsub
176 path s
176 path s
177 source ../gitroot
177 source ../gitroot
178 revision f47b465e1bce645dbf37232a00574aa1546ca8d3
178 revision f47b465e1bce645dbf37232a00574aa1546ca8d3
179 $ hg push 2>/dev/null
179 $ hg push 2>/dev/null
180 pushing to $TESTTMP/t (glob)
180 pushing to $TESTTMP/t (glob)
181 pushing branch testing of subrepo s
181 pushing branch testing of subrepo s
182 searching for changes
182 searching for changes
183 adding changesets
183 adding changesets
184 adding manifests
184 adding manifests
185 adding file changes
185 adding file changes
186 added 2 changesets with 2 changes to 1 files
186 added 2 changesets with 2 changes to 1 files
187
187
188 make upstream git changes
188 make upstream git changes
189
189
190 $ cd ..
190 $ cd ..
191 $ git clone -q gitroot gitclone
191 $ git clone -q gitroot gitclone
192 $ cd gitclone
192 $ cd gitclone
193 $ echo ff >> f
193 $ echo ff >> f
194 $ git commit -q -a -m ff
194 $ git commit -q -a -m ff
195 $ echo fff >> f
195 $ echo fff >> f
196 $ git commit -q -a -m fff
196 $ git commit -q -a -m fff
197 $ git push origin testing 2>/dev/null
197 $ git push origin testing 2>/dev/null
198
198
199 make and push changes to hg without updating the subrepo
199 make and push changes to hg without updating the subrepo
200
200
201 $ cd ../t
201 $ cd ../t
202 $ hg clone . ../td 2>&1 | egrep -v '^Cloning into|^done\.'
202 $ hg clone . ../td 2>&1 | egrep -v '^Cloning into|^done\.'
203 updating to branch default
203 updating to branch default
204 cloning subrepo s from $TESTTMP/gitroot
204 cloning subrepo s from $TESTTMP/gitroot
205 checking out detached HEAD in subrepo s
205 checking out detached HEAD in subrepo s
206 check out a git branch if you intend to make changes
206 check out a git branch if you intend to make changes
207 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
207 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
208 $ cd ../td
208 $ cd ../td
209 $ echo aa >> a
209 $ echo aa >> a
210 $ hg commit -m aa
210 $ hg commit -m aa
211 $ hg push
211 $ hg push
212 pushing to $TESTTMP/t (glob)
212 pushing to $TESTTMP/t (glob)
213 searching for changes
213 searching for changes
214 adding changesets
214 adding changesets
215 adding manifests
215 adding manifests
216 adding file changes
216 adding file changes
217 added 1 changesets with 1 changes to 1 files
217 added 1 changesets with 1 changes to 1 files
218
218
219 sync to upstream git, distribute changes
219 sync to upstream git, distribute changes
220
220
221 $ cd ../ta
221 $ cd ../ta
222 $ hg pull -u -q
222 $ hg pull -u -q
223 $ cd s
223 $ cd s
224 $ git pull -q >/dev/null 2>/dev/null
224 $ git pull -q >/dev/null 2>/dev/null
225 $ cd ..
225 $ cd ..
226 $ hg commit -m 'git upstream sync'
226 $ hg commit -m 'git upstream sync'
227 $ hg debugsub
227 $ hg debugsub
228 path s
228 path s
229 source ../gitroot
229 source ../gitroot
230 revision 32a343883b74769118bb1d3b4b1fbf9156f4dddc
230 revision 32a343883b74769118bb1d3b4b1fbf9156f4dddc
231 $ hg push -q
231 $ hg push -q
232
232
233 $ cd ../tb
233 $ cd ../tb
234 $ hg pull -q
234 $ hg pull -q
235 $ hg update 2>/dev/null
235 $ hg update 2>/dev/null
236 pulling subrepo s from $TESTTMP/gitroot
236 pulling subrepo s from $TESTTMP/gitroot
237 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
237 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
238 $ hg debugsub
238 $ hg debugsub
239 path s
239 path s
240 source ../gitroot
240 source ../gitroot
241 revision 32a343883b74769118bb1d3b4b1fbf9156f4dddc
241 revision 32a343883b74769118bb1d3b4b1fbf9156f4dddc
242
242
243 create a new git branch
243 create a new git branch
244
244
245 $ cd s
245 $ cd s
246 $ git checkout -b b2
246 $ git checkout -b b2
247 Switched to a new branch 'b2'
247 Switched to a new branch 'b2'
248 $ echo a>a
248 $ echo a>a
249 $ git add a
249 $ git add a
250 $ git commit -qm 'add a'
250 $ git commit -qm 'add a'
251 $ cd ..
251 $ cd ..
252 $ hg commit -m 'add branch in s'
252 $ hg commit -m 'add branch in s'
253
253
254 pulling new git branch should not create tracking branch named 'origin/b2'
254 pulling new git branch should not create tracking branch named 'origin/b2'
255 (issue3870)
255 (issue3870)
256 $ cd ../td/s
256 $ cd ../td/s
257 $ git remote set-url origin $TESTTMP/tb/s
257 $ git remote set-url origin $TESTTMP/tb/s
258 $ git branch --no-track oldtesting
258 $ git branch --no-track oldtesting
259 $ cd ..
259 $ cd ..
260 $ hg pull -q ../tb
260 $ hg pull -q ../tb
261 $ hg up
261 $ hg up
262 From $TESTTMP/tb/s
262 From $TESTTMP/tb/s
263 * [new branch] b2 -> origin/b2
263 * [new branch] b2 -> origin/b2
264 Previous HEAD position was f47b465... merge
264 Previous HEAD position was f47b465... merge
265 Switched to a new branch 'b2'
265 Switched to a new branch 'b2'
266 pulling subrepo s from $TESTTMP/tb/s
266 pulling subrepo s from $TESTTMP/tb/s
267 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
267 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
268
268
269 update to a revision without the subrepo, keeping the local git repository
269 update to a revision without the subrepo, keeping the local git repository
270
270
271 $ cd ../t
271 $ cd ../t
272 $ hg up 0
272 $ hg up 0
273 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
273 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
274 $ ls -a s
274 $ ls -a s
275 .
275 .
276 ..
276 ..
277 .git
277 .git
278
278
279 $ hg up 2
279 $ hg up 2
280 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
280 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
281 $ ls -a s
281 $ ls -a s
282 .
282 .
283 ..
283 ..
284 .git
284 .git
285 g
285 g
286
286
287 archive subrepos
287 archive subrepos
288
288
289 $ cd ../tc
289 $ cd ../tc
290 $ hg pull -q
290 $ hg pull -q
291 $ hg archive --subrepos -r 5 ../archive 2>/dev/null
291 $ hg archive --subrepos -r 5 ../archive 2>/dev/null
292 pulling subrepo s from $TESTTMP/gitroot
292 pulling subrepo s from $TESTTMP/gitroot
293 $ cd ../archive
293 $ cd ../archive
294 $ cat s/f
294 $ cat s/f
295 f
295 f
296 $ cat s/g
296 $ cat s/g
297 g
297 g
298 gg
298 gg
299 ggg
299 ggg
300
300
301 $ hg -R ../tc archive --subrepo -r 5 -X ../tc/**f ../archive_x 2>/dev/null
301 $ hg -R ../tc archive --subrepo -r 5 -X ../tc/**f ../archive_x 2>/dev/null
302 $ find ../archive_x | sort | grep -v pax_global_header
302 $ find ../archive_x | sort | grep -v pax_global_header
303 ../archive_x
303 ../archive_x
304 ../archive_x/.hg_archival.txt
304 ../archive_x/.hg_archival.txt
305 ../archive_x/.hgsub
305 ../archive_x/.hgsub
306 ../archive_x/.hgsubstate
306 ../archive_x/.hgsubstate
307 ../archive_x/a
307 ../archive_x/a
308 ../archive_x/s
308 ../archive_x/s
309 ../archive_x/s/g
309 ../archive_x/s/g
310
310
311 create nested repo
311 create nested repo
312
312
313 $ cd ..
313 $ cd ..
314 $ hg init outer
314 $ hg init outer
315 $ cd outer
315 $ cd outer
316 $ echo b>b
316 $ echo b>b
317 $ hg add b
317 $ hg add b
318 $ hg commit -m b
318 $ hg commit -m b
319
319
320 $ hg clone ../t inner 2> /dev/null
320 $ hg clone ../t inner 2> /dev/null
321 updating to branch default
321 updating to branch default
322 cloning subrepo s from $TESTTMP/gitroot
322 cloning subrepo s from $TESTTMP/gitroot
323 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
323 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
324 $ echo inner = inner > .hgsub
324 $ echo inner = inner > .hgsub
325 $ hg add .hgsub
325 $ hg add .hgsub
326 $ hg commit -m 'nested sub'
326 $ hg commit -m 'nested sub'
327
327
328 nested commit
328 nested commit
329
329
330 $ echo ffff >> inner/s/f
330 $ echo ffff >> inner/s/f
331 $ hg status --subrepos
331 $ hg status --subrepos
332 M inner/s/f
332 M inner/s/f
333 $ hg commit --subrepos -m nested
333 $ hg commit --subrepos -m nested
334 committing subrepository inner
334 committing subrepository inner
335 committing subrepository inner/s (glob)
335 committing subrepository inner/s (glob)
336
336
337 nested archive
337 nested archive
338
338
339 $ hg archive --subrepos ../narchive
339 $ hg archive --subrepos ../narchive
340 $ ls ../narchive/inner/s | grep -v pax_global_header
340 $ ls ../narchive/inner/s | grep -v pax_global_header
341 f
341 f
342 g
342 g
343
343
344 relative source expansion
344 relative source expansion
345
345
346 $ cd ..
346 $ cd ..
347 $ mkdir d
347 $ mkdir d
348 $ hg clone t d/t 2> /dev/null
348 $ hg clone t d/t 2> /dev/null
349 updating to branch default
349 updating to branch default
350 cloning subrepo s from $TESTTMP/gitroot
350 cloning subrepo s from $TESTTMP/gitroot
351 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
351 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
352
352
353 Don't crash if the subrepo is missing
353 Don't crash if the subrepo is missing
354
354
355 $ hg clone t missing -q
355 $ hg clone t missing -q
356 $ cd missing
356 $ cd missing
357 $ rm -rf s
357 $ rm -rf s
358 $ hg status -S
358 $ hg status -S
359 $ hg sum | grep commit
359 $ hg sum | grep commit
360 commit: 1 subrepos
360 commit: 1 subrepos
361 $ hg push -q
361 $ hg push -q
362 abort: subrepo s is missing (in subrepo s)
362 abort: subrepo s is missing (in subrepo s)
363 [255]
363 [255]
364 $ hg commit --subrepos -qm missing
364 $ hg commit --subrepos -qm missing
365 abort: subrepo s is missing (in subrepo s)
365 abort: subrepo s is missing (in subrepo s)
366 [255]
366 [255]
367 $ hg update -C 2> /dev/null
367 $ hg update -C 2> /dev/null
368 cloning subrepo s from $TESTTMP/gitroot
368 cloning subrepo s from $TESTTMP/gitroot
369 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
369 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
370 $ hg sum | grep commit
370 $ hg sum | grep commit
371 commit: (clean)
371 commit: (clean)
372
372
373 Don't crash if the .hgsubstate entry is missing
373 Don't crash if the .hgsubstate entry is missing
374
374
375 $ hg update 1 -q
375 $ hg update 1 -q
376 $ hg rm .hgsubstate
376 $ hg rm .hgsubstate
377 $ hg commit .hgsubstate -m 'no substate'
377 $ hg commit .hgsubstate -m 'no substate'
378 nothing changed
378 nothing changed
379 [1]
379 [1]
380 $ hg tag -l nosubstate
380 $ hg tag -l nosubstate
381 $ hg manifest
381 $ hg manifest
382 .hgsub
382 .hgsub
383 .hgsubstate
383 .hgsubstate
384 a
384 a
385
385
386 $ hg status -S
386 $ hg status -S
387 R .hgsubstate
387 R .hgsubstate
388 $ hg sum | grep commit
388 $ hg sum | grep commit
389 commit: 1 removed, 1 subrepos (new branch head)
389 commit: 1 removed, 1 subrepos (new branch head)
390
390
391 $ hg commit -m 'restore substate'
391 $ hg commit -m 'restore substate'
392 nothing changed
392 nothing changed
393 [1]
393 [1]
394 $ hg manifest
394 $ hg manifest
395 .hgsub
395 .hgsub
396 .hgsubstate
396 .hgsubstate
397 a
397 a
398 $ hg sum | grep commit
398 $ hg sum | grep commit
399 commit: 1 removed, 1 subrepos (new branch head)
399 commit: 1 removed, 1 subrepos (new branch head)
400
400
401 $ hg update -qC nosubstate
401 $ hg update -qC nosubstate
402 $ ls s
402 $ ls s
403 g
403 g
404
404
405 issue3109: false positives in git diff-index
405 issue3109: false positives in git diff-index
406
406
407 $ hg update -q
407 $ hg update -q
408 $ touch -t 200001010000 s/g
408 $ touch -t 200001010000 s/g
409 $ hg status --subrepos
409 $ hg status --subrepos
410 $ touch -t 200001010000 s/g
410 $ touch -t 200001010000 s/g
411 $ hg sum | grep commit
411 $ hg sum | grep commit
412 commit: (clean)
412 commit: (clean)
413
413
414 Check hg update --clean
414 Check hg update --clean
415 $ cd $TESTTMP/ta
415 $ cd $TESTTMP/ta
416 $ echo > s/g
416 $ echo > s/g
417 $ cd s
417 $ cd s
418 $ echo c1 > f1
418 $ echo c1 > f1
419 $ echo c1 > f2
419 $ echo c1 > f2
420 $ git add f1
420 $ git add f1
421 $ cd ..
421 $ cd ..
422 $ hg status -S
422 $ hg status -S
423 M s/g
423 M s/g
424 A s/f1
424 A s/f1
425 $ ls s
425 $ ls s
426 f
426 f
427 f1
427 f1
428 f2
428 f2
429 g
429 g
430 $ hg update --clean
430 $ hg update --clean
431 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
431 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
432 $ hg status -S
432 $ hg status -S
433 $ ls s
433 $ ls s
434 f
434 f
435 f1
435 f1
436 f2
436 f2
437 g
437 g
438
438
439 Sticky subrepositories, no changes
439 Sticky subrepositories, no changes
440 $ cd $TESTTMP/ta
440 $ cd $TESTTMP/ta
441 $ hg id -n
441 $ hg id -n
442 7
442 7
443 $ cd s
443 $ cd s
444 $ git rev-parse HEAD
444 $ git rev-parse HEAD
445 32a343883b74769118bb1d3b4b1fbf9156f4dddc
445 32a343883b74769118bb1d3b4b1fbf9156f4dddc
446 $ cd ..
446 $ cd ..
447 $ hg update 1 > /dev/null 2>&1
447 $ hg update 1 > /dev/null 2>&1
448 $ hg id -n
448 $ hg id -n
449 1
449 1
450 $ cd s
450 $ cd s
451 $ git rev-parse HEAD
451 $ git rev-parse HEAD
452 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
452 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
453 $ cd ..
453 $ cd ..
454
454
455 Sticky subrepositories, file changes
455 Sticky subrepositories, file changes
456 $ touch s/f1
456 $ touch s/f1
457 $ cd s
457 $ cd s
458 $ git add f1
458 $ git add f1
459 $ cd ..
459 $ cd ..
460 $ hg id -n
460 $ hg id -n
461 1+
461 1+
462 $ cd s
462 $ cd s
463 $ git rev-parse HEAD
463 $ git rev-parse HEAD
464 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
464 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
465 $ cd ..
465 $ cd ..
466 $ hg update 4
466 $ hg update 4
467 subrepository s diverged (local revision: da5f5b1, remote revision: aa84837)
467 subrepository s diverged (local revision: da5f5b1, remote revision: aa84837)
468 (M)erge, keep (l)ocal or keep (r)emote? m
468 (M)erge, keep (l)ocal or keep (r)emote? m
469 subrepository sources for s differ
469 subrepository sources for s differ
470 use (l)ocal source (da5f5b1) or (r)emote source (aa84837)?
470 use (l)ocal source (da5f5b1) or (r)emote source (aa84837)?
471 l
471 l
472 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
472 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
473 $ hg id -n
473 $ hg id -n
474 4+
474 4+
475 $ cd s
475 $ cd s
476 $ git rev-parse HEAD
476 $ git rev-parse HEAD
477 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
477 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
478 $ cd ..
478 $ cd ..
479 $ hg update --clean tip > /dev/null 2>&1
479 $ hg update --clean tip > /dev/null 2>&1
480
480
481 Sticky subrepository, revision updates
481 Sticky subrepository, revision updates
482 $ hg id -n
482 $ hg id -n
483 7
483 7
484 $ cd s
484 $ cd s
485 $ git rev-parse HEAD
485 $ git rev-parse HEAD
486 32a343883b74769118bb1d3b4b1fbf9156f4dddc
486 32a343883b74769118bb1d3b4b1fbf9156f4dddc
487 $ cd ..
487 $ cd ..
488 $ cd s
488 $ cd s
489 $ git checkout aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
489 $ git checkout aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
490 Previous HEAD position was 32a3438... fff
490 Previous HEAD position was 32a3438... fff
491 HEAD is now at aa84837... f
491 HEAD is now at aa84837... f
492 $ cd ..
492 $ cd ..
493 $ hg update 1
493 $ hg update 1
494 subrepository s diverged (local revision: 32a3438, remote revision: da5f5b1)
494 subrepository s diverged (local revision: 32a3438, remote revision: da5f5b1)
495 (M)erge, keep (l)ocal or keep (r)emote? m
495 (M)erge, keep (l)ocal or keep (r)emote? m
496 subrepository sources for s differ (in checked out version)
496 subrepository sources for s differ (in checked out version)
497 use (l)ocal source (32a3438) or (r)emote source (da5f5b1)?
497 use (l)ocal source (32a3438) or (r)emote source (da5f5b1)?
498 l
498 l
499 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
499 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
500 $ hg id -n
500 $ hg id -n
501 1+
501 1+
502 $ cd s
502 $ cd s
503 $ git rev-parse HEAD
503 $ git rev-parse HEAD
504 aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
504 aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
505 $ cd ..
505 $ cd ..
506
506
507 Sticky subrepository, file changes and revision updates
507 Sticky subrepository, file changes and revision updates
508 $ touch s/f1
508 $ touch s/f1
509 $ cd s
509 $ cd s
510 $ git add f1
510 $ git add f1
511 $ git rev-parse HEAD
511 $ git rev-parse HEAD
512 aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
512 aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
513 $ cd ..
513 $ cd ..
514 $ hg id -n
514 $ hg id -n
515 1+
515 1+
516 $ hg update 7
516 $ hg update 7
517 subrepository s diverged (local revision: 32a3438, remote revision: 32a3438)
517 subrepository s diverged (local revision: 32a3438, remote revision: 32a3438)
518 (M)erge, keep (l)ocal or keep (r)emote? m
518 (M)erge, keep (l)ocal or keep (r)emote? m
519 subrepository sources for s differ
519 subrepository sources for s differ
520 use (l)ocal source (32a3438) or (r)emote source (32a3438)?
520 use (l)ocal source (32a3438) or (r)emote source (32a3438)?
521 l
521 l
522 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
522 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
523 $ hg id -n
523 $ hg id -n
524 7+
524 7+
525 $ cd s
525 $ cd s
526 $ git rev-parse HEAD
526 $ git rev-parse HEAD
527 aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
527 aa84837ccfbdfedcdcdeeedc309d73e6eb069edc
528 $ cd ..
528 $ cd ..
529
529
530 Sticky repository, update --clean
530 Sticky repository, update --clean
531 $ hg update --clean tip 2>/dev/null
531 $ hg update --clean tip 2>/dev/null
532 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
532 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
533 $ hg id -n
533 $ hg id -n
534 7
534 7
535 $ cd s
535 $ cd s
536 $ git rev-parse HEAD
536 $ git rev-parse HEAD
537 32a343883b74769118bb1d3b4b1fbf9156f4dddc
537 32a343883b74769118bb1d3b4b1fbf9156f4dddc
538 $ cd ..
538 $ cd ..
539
539
540 Test subrepo already at intended revision:
540 Test subrepo already at intended revision:
541 $ cd s
541 $ cd s
542 $ git checkout 32a343883b74769118bb1d3b4b1fbf9156f4dddc
542 $ git checkout 32a343883b74769118bb1d3b4b1fbf9156f4dddc
543 HEAD is now at 32a3438... fff
543 HEAD is now at 32a3438... fff
544 $ cd ..
544 $ cd ..
545 $ hg update 1
545 $ hg update 1
546 Previous HEAD position was 32a3438... fff
546 Previous HEAD position was 32a3438... fff
547 HEAD is now at da5f5b1... g
547 HEAD is now at da5f5b1... g
548 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
548 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
549 $ hg id -n
549 $ hg id -n
550 1
550 1
551 $ cd s
551 $ cd s
552 $ git rev-parse HEAD
552 $ git rev-parse HEAD
553 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
553 da5f5b1d8ffcf62fb8327bcd3c89a4367a6018e7
554 $ cd ..
554 $ cd ..
555
555
556 Test forgetting files, not implemented in git subrepo, used to
556 Test forgetting files, not implemented in git subrepo, used to
557 traceback
557 traceback
558 #if no-windows
558 #if no-windows
559 $ hg forget 'notafile*'
559 $ hg forget 'notafile*'
560 notafile*: No such file or directory
560 notafile*: No such file or directory
561 [1]
561 [1]
562 #else
562 #else
563 $ hg forget 'notafile'
563 $ hg forget 'notafile'
564 notafile: * (glob)
564 notafile: * (glob)
565 [1]
565 [1]
566 #endif
566 #endif
567
567
568 $ cd ..
568 $ cd ..
569
570 Test sanitizing ".hg/hgrc" in subrepo
571
572 $ cd t
573 $ hg tip -q
574 7:af6d2edbb0d3
575 $ hg update -q -C af6d2edbb0d3
576 $ cd s
577 $ git checkout -q -b sanitize-test
578 $ mkdir .hg
579 $ echo '.hg/hgrc in git repo' > .hg/hgrc
580 $ mkdir -p sub/.hg
581 $ echo 'sub/.hg/hgrc in git repo' > sub/.hg/hgrc
582 $ git add .hg sub
583 $ git commit -qm 'add .hg/hgrc to be sanitized at hg update'
584 $ git push -q origin sanitize-test
585 $ cd ..
586 $ grep ' s$' .hgsubstate
587 32a343883b74769118bb1d3b4b1fbf9156f4dddc s
588 $ hg commit -qm 'commit with git revision including .hg/hgrc'
589 $ hg parents -q
590 8:3473d20bddcf
591 $ grep ' s$' .hgsubstate
592 c4069473b459cf27fd4d7c2f50c4346b4e936599 s
593 $ cd ..
594
595 $ hg -R tc pull -q
596 $ hg -R tc update -q -C 3473d20bddcf 2>&1 | sort
597 warning: removing potentially hostile 'hgrc' in '$TESTTMP/tc/s/.hg' (glob)
598 warning: removing potentially hostile 'hgrc' in '$TESTTMP/tc/s/sub/.hg' (glob)
599 $ cd tc
600 $ hg parents -q
601 8:3473d20bddcf
602 $ grep ' s$' .hgsubstate
603 c4069473b459cf27fd4d7c2f50c4346b4e936599 s
604 $ cat s/.hg/hgrc
605 cat: s/.hg/hgrc: No such file or directory
606 [1]
607 $ cat s/sub/.hg/hgrc
608 cat: s/sub/.hg/hgrc: No such file or directory
609 [1]
610 $ cd ..
611
612 additional test for "git merge --ff" route:
613
614 $ cd t
615 $ hg tip -q
616 8:3473d20bddcf
617 $ hg update -q -C af6d2edbb0d3
618 $ cd s
619 $ git checkout -q testing
620 $ mkdir .hg
621 $ echo '.hg/hgrc in git repo' > .hg/hgrc
622 $ mkdir -p sub/.hg
623 $ echo 'sub/.hg/hgrc in git repo' > sub/.hg/hgrc
624 $ git add .hg sub
625 $ git commit -qm 'add .hg/hgrc to be sanitized at hg update (git merge --ff)'
626 $ git push -q origin testing
627 $ cd ..
628 $ grep ' s$' .hgsubstate
629 32a343883b74769118bb1d3b4b1fbf9156f4dddc s
630 $ hg commit -qm 'commit with git revision including .hg/hgrc'
631 $ hg parents -q
632 9:ed23f7fe024e
633 $ grep ' s$' .hgsubstate
634 f262643c1077219fbd3858d54e78ef050ef84fbf s
635 $ cd ..
636
637 $ cd tc
638 $ hg update -q -C af6d2edbb0d3
639 $ cat s/.hg/hgrc
640 cat: s/.hg/hgrc: No such file or directory
641 [1]
642 $ cat s/sub/.hg/hgrc
643 cat: s/sub/.hg/hgrc: No such file or directory
644 [1]
645 $ cd ..
646 $ hg -R tc pull -q
647 $ hg -R tc update -q -C ed23f7fe024e 2>&1 | sort
648 warning: removing potentially hostile 'hgrc' in '$TESTTMP/tc/s/.hg' (glob)
649 warning: removing potentially hostile 'hgrc' in '$TESTTMP/tc/s/sub/.hg' (glob)
650 $ cd tc
651 $ hg parents -q
652 9:ed23f7fe024e
653 $ grep ' s$' .hgsubstate
654 f262643c1077219fbd3858d54e78ef050ef84fbf s
655 $ cat s/.hg/hgrc
656 cat: s/.hg/hgrc: No such file or directory
657 [1]
658 $ cat s/sub/.hg/hgrc
659 cat: s/sub/.hg/hgrc: No such file or directory
660 [1]
661
662 Test that sanitizing is omitted in meta data area:
663
664 $ mkdir s/.git/.hg
665 $ echo '.hg/hgrc in git metadata area' > s/.git/.hg/hgrc
666 $ hg update -q -C af6d2edbb0d3
667 checking out detached HEAD in subrepo s
668 check out a git branch if you intend to make changes
669
670 $ cd ..
@@ -1,637 +1,688 b''
1 $ "$TESTDIR/hghave" svn15 || exit 80
1 $ "$TESTDIR/hghave" svn15 || exit 80
2
2
3 $ SVNREPOPATH=`pwd`/svn-repo
3 $ SVNREPOPATH=`pwd`/svn-repo
4 #if windows
4 #if windows
5 $ SVNREPOURL=file:///`python -c "import urllib, sys; sys.stdout.write(urllib.quote(sys.argv[1]))" "$SVNREPOPATH"`
5 $ SVNREPOURL=file:///`python -c "import urllib, sys; sys.stdout.write(urllib.quote(sys.argv[1]))" "$SVNREPOPATH"`
6 #else
6 #else
7 $ SVNREPOURL=file://`python -c "import urllib, sys; sys.stdout.write(urllib.quote(sys.argv[1]))" "$SVNREPOPATH"`
7 $ SVNREPOURL=file://`python -c "import urllib, sys; sys.stdout.write(urllib.quote(sys.argv[1]))" "$SVNREPOPATH"`
8 #endif
8 #endif
9
9
10 create subversion repo
10 create subversion repo
11
11
12 $ WCROOT="`pwd`/svn-wc"
12 $ WCROOT="`pwd`/svn-wc"
13 $ svnadmin create svn-repo
13 $ svnadmin create svn-repo
14 $ svn co "$SVNREPOURL" svn-wc
14 $ svn co "$SVNREPOURL" svn-wc
15 Checked out revision 0.
15 Checked out revision 0.
16 $ cd svn-wc
16 $ cd svn-wc
17 $ mkdir src
17 $ mkdir src
18 $ echo alpha > src/alpha
18 $ echo alpha > src/alpha
19 $ svn add src
19 $ svn add src
20 A src
20 A src
21 A src/alpha (glob)
21 A src/alpha (glob)
22 $ mkdir externals
22 $ mkdir externals
23 $ echo other > externals/other
23 $ echo other > externals/other
24 $ svn add externals
24 $ svn add externals
25 A externals
25 A externals
26 A externals/other (glob)
26 A externals/other (glob)
27 $ svn ci -m 'Add alpha'
27 $ svn ci -m 'Add alpha'
28 Adding externals
28 Adding externals
29 Adding externals/other (glob)
29 Adding externals/other (glob)
30 Adding src
30 Adding src
31 Adding src/alpha (glob)
31 Adding src/alpha (glob)
32 Transmitting file data ..
32 Transmitting file data ..
33 Committed revision 1.
33 Committed revision 1.
34 $ svn up -q
34 $ svn up -q
35 $ echo "externals -r1 $SVNREPOURL/externals" > extdef
35 $ echo "externals -r1 $SVNREPOURL/externals" > extdef
36 $ svn propset -F extdef svn:externals src
36 $ svn propset -F extdef svn:externals src
37 property 'svn:externals' set on 'src'
37 property 'svn:externals' set on 'src'
38 $ svn ci -m 'Setting externals'
38 $ svn ci -m 'Setting externals'
39 Sending src
39 Sending src
40
40
41 Committed revision 2.
41 Committed revision 2.
42 $ cd ..
42 $ cd ..
43
43
44 create hg repo
44 create hg repo
45
45
46 $ mkdir sub
46 $ mkdir sub
47 $ cd sub
47 $ cd sub
48 $ hg init t
48 $ hg init t
49 $ cd t
49 $ cd t
50
50
51 first revision, no sub
51 first revision, no sub
52
52
53 $ echo a > a
53 $ echo a > a
54 $ hg ci -Am0
54 $ hg ci -Am0
55 adding a
55 adding a
56
56
57 add first svn sub with leading whitespaces
57 add first svn sub with leading whitespaces
58
58
59 $ echo "s = [svn] $SVNREPOURL/src" >> .hgsub
59 $ echo "s = [svn] $SVNREPOURL/src" >> .hgsub
60 $ echo "subdir/s = [svn] $SVNREPOURL/src" >> .hgsub
60 $ echo "subdir/s = [svn] $SVNREPOURL/src" >> .hgsub
61 $ svn co --quiet "$SVNREPOURL"/src s
61 $ svn co --quiet "$SVNREPOURL"/src s
62 $ mkdir subdir
62 $ mkdir subdir
63 $ svn co --quiet "$SVNREPOURL"/src subdir/s
63 $ svn co --quiet "$SVNREPOURL"/src subdir/s
64 $ hg add .hgsub
64 $ hg add .hgsub
65 $ hg ci -m1
65 $ hg ci -m1
66
66
67 make sure we avoid empty commits (issue2445)
67 make sure we avoid empty commits (issue2445)
68
68
69 $ hg sum
69 $ hg sum
70 parent: 1:* tip (glob)
70 parent: 1:* tip (glob)
71 1
71 1
72 branch: default
72 branch: default
73 commit: (clean)
73 commit: (clean)
74 update: (current)
74 update: (current)
75 $ hg ci -moops
75 $ hg ci -moops
76 nothing changed
76 nothing changed
77 [1]
77 [1]
78
78
79 debugsub
79 debugsub
80
80
81 $ hg debugsub
81 $ hg debugsub
82 path s
82 path s
83 source file://*/svn-repo/src (glob)
83 source file://*/svn-repo/src (glob)
84 revision 2
84 revision 2
85 path subdir/s
85 path subdir/s
86 source file://*/svn-repo/src (glob)
86 source file://*/svn-repo/src (glob)
87 revision 2
87 revision 2
88
88
89 change file in svn and hg, commit
89 change file in svn and hg, commit
90
90
91 $ echo a >> a
91 $ echo a >> a
92 $ echo alpha >> s/alpha
92 $ echo alpha >> s/alpha
93 $ hg sum
93 $ hg sum
94 parent: 1:* tip (glob)
94 parent: 1:* tip (glob)
95 1
95 1
96 branch: default
96 branch: default
97 commit: 1 modified, 1 subrepos
97 commit: 1 modified, 1 subrepos
98 update: (current)
98 update: (current)
99 $ hg commit --subrepos -m 'Message!' | grep -v Updating
99 $ hg commit --subrepos -m 'Message!' | grep -v Updating
100 committing subrepository s
100 committing subrepository s
101 Sending*s/alpha (glob)
101 Sending*s/alpha (glob)
102 Transmitting file data .
102 Transmitting file data .
103 Committed revision 3.
103 Committed revision 3.
104
104
105 Fetching external item into '*s/externals'* (glob)
105 Fetching external item into '*s/externals'* (glob)
106 External at revision 1.
106 External at revision 1.
107
107
108 At revision 3.
108 At revision 3.
109 $ hg debugsub
109 $ hg debugsub
110 path s
110 path s
111 source file://*/svn-repo/src (glob)
111 source file://*/svn-repo/src (glob)
112 revision 3
112 revision 3
113 path subdir/s
113 path subdir/s
114 source file://*/svn-repo/src (glob)
114 source file://*/svn-repo/src (glob)
115 revision 2
115 revision 2
116
116
117 missing svn file, commit should fail
117 missing svn file, commit should fail
118
118
119 $ rm s/alpha
119 $ rm s/alpha
120 $ hg commit --subrepos -m 'abort on missing file'
120 $ hg commit --subrepos -m 'abort on missing file'
121 committing subrepository s
121 committing subrepository s
122 abort: cannot commit missing svn entries (in subrepo s)
122 abort: cannot commit missing svn entries (in subrepo s)
123 [255]
123 [255]
124 $ svn revert s/alpha > /dev/null
124 $ svn revert s/alpha > /dev/null
125
125
126 add an unrelated revision in svn and update the subrepo to without
126 add an unrelated revision in svn and update the subrepo to without
127 bringing any changes.
127 bringing any changes.
128
128
129 $ svn mkdir "$SVNREPOURL/unrelated" -m 'create unrelated'
129 $ svn mkdir "$SVNREPOURL/unrelated" -m 'create unrelated'
130
130
131 Committed revision 4.
131 Committed revision 4.
132 $ svn up -q s
132 $ svn up -q s
133 $ hg sum
133 $ hg sum
134 parent: 2:* tip (glob)
134 parent: 2:* tip (glob)
135 Message!
135 Message!
136 branch: default
136 branch: default
137 commit: (clean)
137 commit: (clean)
138 update: (current)
138 update: (current)
139
139
140 $ echo a > s/a
140 $ echo a > s/a
141
141
142 should be empty despite change to s/a
142 should be empty despite change to s/a
143
143
144 $ hg st
144 $ hg st
145
145
146 add a commit from svn
146 add a commit from svn
147
147
148 $ cd "$WCROOT/src"
148 $ cd "$WCROOT/src"
149 $ svn up -q
149 $ svn up -q
150 $ echo xyz >> alpha
150 $ echo xyz >> alpha
151 $ svn propset svn:mime-type 'text/xml' alpha
151 $ svn propset svn:mime-type 'text/xml' alpha
152 property 'svn:mime-type' set on 'alpha'
152 property 'svn:mime-type' set on 'alpha'
153 $ svn ci -m 'amend a from svn'
153 $ svn ci -m 'amend a from svn'
154 Sending *alpha (glob)
154 Sending *alpha (glob)
155 Transmitting file data .
155 Transmitting file data .
156 Committed revision 5.
156 Committed revision 5.
157 $ cd ../../sub/t
157 $ cd ../../sub/t
158
158
159 this commit from hg will fail
159 this commit from hg will fail
160
160
161 $ echo zzz >> s/alpha
161 $ echo zzz >> s/alpha
162 $ (hg ci --subrepos -m 'amend alpha from hg' 2>&1; echo "[$?]") | grep -vi 'out of date'
162 $ (hg ci --subrepos -m 'amend alpha from hg' 2>&1; echo "[$?]") | grep -vi 'out of date'
163 committing subrepository s
163 committing subrepository s
164 abort: svn:*Commit failed (details follow): (glob)
164 abort: svn:*Commit failed (details follow): (glob)
165 [255]
165 [255]
166 $ svn revert -q s/alpha
166 $ svn revert -q s/alpha
167
167
168 this commit fails because of meta changes
168 this commit fails because of meta changes
169
169
170 $ svn propset svn:mime-type 'text/html' s/alpha
170 $ svn propset svn:mime-type 'text/html' s/alpha
171 property 'svn:mime-type' set on 's/alpha' (glob)
171 property 'svn:mime-type' set on 's/alpha' (glob)
172 $ (hg ci --subrepos -m 'amend alpha from hg' 2>&1; echo "[$?]") | grep -vi 'out of date'
172 $ (hg ci --subrepos -m 'amend alpha from hg' 2>&1; echo "[$?]") | grep -vi 'out of date'
173 committing subrepository s
173 committing subrepository s
174 abort: svn:*Commit failed (details follow): (glob)
174 abort: svn:*Commit failed (details follow): (glob)
175 [255]
175 [255]
176 $ svn revert -q s/alpha
176 $ svn revert -q s/alpha
177
177
178 this commit fails because of externals changes
178 this commit fails because of externals changes
179
179
180 $ echo zzz > s/externals/other
180 $ echo zzz > s/externals/other
181 $ hg ci --subrepos -m 'amend externals from hg'
181 $ hg ci --subrepos -m 'amend externals from hg'
182 committing subrepository s
182 committing subrepository s
183 abort: cannot commit svn externals (in subrepo s)
183 abort: cannot commit svn externals (in subrepo s)
184 [255]
184 [255]
185 $ hg diff --subrepos -r 1:2 | grep -v diff
185 $ hg diff --subrepos -r 1:2 | grep -v diff
186 --- a/.hgsubstate Thu Jan 01 00:00:00 1970 +0000
186 --- a/.hgsubstate Thu Jan 01 00:00:00 1970 +0000
187 +++ b/.hgsubstate Thu Jan 01 00:00:00 1970 +0000
187 +++ b/.hgsubstate Thu Jan 01 00:00:00 1970 +0000
188 @@ -1,2 +1,2 @@
188 @@ -1,2 +1,2 @@
189 -2 s
189 -2 s
190 +3 s
190 +3 s
191 2 subdir/s
191 2 subdir/s
192 --- a/a Thu Jan 01 00:00:00 1970 +0000
192 --- a/a Thu Jan 01 00:00:00 1970 +0000
193 +++ b/a Thu Jan 01 00:00:00 1970 +0000
193 +++ b/a Thu Jan 01 00:00:00 1970 +0000
194 @@ -1,1 +1,2 @@
194 @@ -1,1 +1,2 @@
195 a
195 a
196 +a
196 +a
197 $ svn revert -q s/externals/other
197 $ svn revert -q s/externals/other
198
198
199 this commit fails because of externals meta changes
199 this commit fails because of externals meta changes
200
200
201 $ svn propset svn:mime-type 'text/html' s/externals/other
201 $ svn propset svn:mime-type 'text/html' s/externals/other
202 property 'svn:mime-type' set on 's/externals/other' (glob)
202 property 'svn:mime-type' set on 's/externals/other' (glob)
203 $ hg ci --subrepos -m 'amend externals from hg'
203 $ hg ci --subrepos -m 'amend externals from hg'
204 committing subrepository s
204 committing subrepository s
205 abort: cannot commit svn externals (in subrepo s)
205 abort: cannot commit svn externals (in subrepo s)
206 [255]
206 [255]
207 $ svn revert -q s/externals/other
207 $ svn revert -q s/externals/other
208
208
209 clone
209 clone
210
210
211 $ cd ..
211 $ cd ..
212 $ hg clone t tc
212 $ hg clone t tc
213 updating to branch default
213 updating to branch default
214 A tc/s/alpha (glob)
214 A tc/s/alpha (glob)
215 U tc/s (glob)
215 U tc/s (glob)
216
216
217 Fetching external item into 'tc/s/externals'* (glob)
217 Fetching external item into 'tc/s/externals'* (glob)
218 A tc/s/externals/other (glob)
218 A tc/s/externals/other (glob)
219 Checked out external at revision 1.
219 Checked out external at revision 1.
220
220
221 Checked out revision 3.
221 Checked out revision 3.
222 A tc/subdir/s/alpha (glob)
222 A tc/subdir/s/alpha (glob)
223 U tc/subdir/s (glob)
223 U tc/subdir/s (glob)
224
224
225 Fetching external item into 'tc/subdir/s/externals'* (glob)
225 Fetching external item into 'tc/subdir/s/externals'* (glob)
226 A tc/subdir/s/externals/other (glob)
226 A tc/subdir/s/externals/other (glob)
227 Checked out external at revision 1.
227 Checked out external at revision 1.
228
228
229 Checked out revision 2.
229 Checked out revision 2.
230 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
230 3 files updated, 0 files merged, 0 files removed, 0 files unresolved
231 $ cd tc
231 $ cd tc
232
232
233 debugsub in clone
233 debugsub in clone
234
234
235 $ hg debugsub
235 $ hg debugsub
236 path s
236 path s
237 source file://*/svn-repo/src (glob)
237 source file://*/svn-repo/src (glob)
238 revision 3
238 revision 3
239 path subdir/s
239 path subdir/s
240 source file://*/svn-repo/src (glob)
240 source file://*/svn-repo/src (glob)
241 revision 2
241 revision 2
242
242
243 verify subrepo is contained within the repo directory
243 verify subrepo is contained within the repo directory
244
244
245 $ python -c "import os.path; print os.path.exists('s')"
245 $ python -c "import os.path; print os.path.exists('s')"
246 True
246 True
247
247
248 update to nullrev (must delete the subrepo)
248 update to nullrev (must delete the subrepo)
249
249
250 $ hg up null
250 $ hg up null
251 0 files updated, 0 files merged, 3 files removed, 0 files unresolved
251 0 files updated, 0 files merged, 3 files removed, 0 files unresolved
252 $ ls
252 $ ls
253
253
254 Check hg update --clean
254 Check hg update --clean
255 $ cd "$TESTTMP/sub/t"
255 $ cd "$TESTTMP/sub/t"
256 $ cd s
256 $ cd s
257 $ echo c0 > alpha
257 $ echo c0 > alpha
258 $ echo c1 > f1
258 $ echo c1 > f1
259 $ echo c1 > f2
259 $ echo c1 > f2
260 $ svn add f1 -q
260 $ svn add f1 -q
261 $ svn status | sort
261 $ svn status | sort
262
262
263 ? * a (glob)
263 ? * a (glob)
264 ? * f2 (glob)
264 ? * f2 (glob)
265 A * f1 (glob)
265 A * f1 (glob)
266 M * alpha (glob)
266 M * alpha (glob)
267 Performing status on external item at 'externals'* (glob)
267 Performing status on external item at 'externals'* (glob)
268 X * externals (glob)
268 X * externals (glob)
269 $ cd ../..
269 $ cd ../..
270 $ hg -R t update -C
270 $ hg -R t update -C
271
271
272 Fetching external item into 't/s/externals'* (glob)
272 Fetching external item into 't/s/externals'* (glob)
273 Checked out external at revision 1.
273 Checked out external at revision 1.
274
274
275 Checked out revision 3.
275 Checked out revision 3.
276 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
276 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
277 $ cd t/s
277 $ cd t/s
278 $ svn status | sort
278 $ svn status | sort
279
279
280 ? * a (glob)
280 ? * a (glob)
281 ? * f1 (glob)
281 ? * f1 (glob)
282 ? * f2 (glob)
282 ? * f2 (glob)
283 Performing status on external item at 'externals'* (glob)
283 Performing status on external item at 'externals'* (glob)
284 X * externals (glob)
284 X * externals (glob)
285
285
286 Sticky subrepositories, no changes
286 Sticky subrepositories, no changes
287 $ cd "$TESTTMP/sub/t"
287 $ cd "$TESTTMP/sub/t"
288 $ hg id -n
288 $ hg id -n
289 2
289 2
290 $ cd s
290 $ cd s
291 $ svnversion
291 $ svnversion
292 3
292 3
293 $ cd ..
293 $ cd ..
294 $ hg update 1
294 $ hg update 1
295 U *s/alpha (glob)
295 U *s/alpha (glob)
296
296
297 Fetching external item into '*s/externals'* (glob)
297 Fetching external item into '*s/externals'* (glob)
298 Checked out external at revision 1.
298 Checked out external at revision 1.
299
299
300 Checked out revision 2.
300 Checked out revision 2.
301 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
301 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
302 $ hg id -n
302 $ hg id -n
303 1
303 1
304 $ cd s
304 $ cd s
305 $ svnversion
305 $ svnversion
306 2
306 2
307 $ cd ..
307 $ cd ..
308
308
309 Sticky subrepositories, file changes
309 Sticky subrepositories, file changes
310 $ touch s/f1
310 $ touch s/f1
311 $ cd s
311 $ cd s
312 $ svn add f1
312 $ svn add f1
313 A f1
313 A f1
314 $ cd ..
314 $ cd ..
315 $ hg id -n
315 $ hg id -n
316 1+
316 1+
317 $ cd s
317 $ cd s
318 $ svnversion
318 $ svnversion
319 2M
319 2M
320 $ cd ..
320 $ cd ..
321 $ hg update tip
321 $ hg update tip
322 subrepository s diverged (local revision: 2, remote revision: 3)
322 subrepository s diverged (local revision: 2, remote revision: 3)
323 (M)erge, keep (l)ocal or keep (r)emote? m
323 (M)erge, keep (l)ocal or keep (r)emote? m
324 subrepository sources for s differ
324 subrepository sources for s differ
325 use (l)ocal source (2) or (r)emote source (3)?
325 use (l)ocal source (2) or (r)emote source (3)?
326 l
326 l
327 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
327 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
328 $ hg id -n
328 $ hg id -n
329 2+
329 2+
330 $ cd s
330 $ cd s
331 $ svnversion
331 $ svnversion
332 2M
332 2M
333 $ cd ..
333 $ cd ..
334 $ hg update --clean tip
334 $ hg update --clean tip
335 U *s/alpha (glob)
335 U *s/alpha (glob)
336
336
337 Fetching external item into '*s/externals'* (glob)
337 Fetching external item into '*s/externals'* (glob)
338 Checked out external at revision 1.
338 Checked out external at revision 1.
339
339
340 Checked out revision 3.
340 Checked out revision 3.
341 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
341 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
342
342
343 Sticky subrepository, revision updates
343 Sticky subrepository, revision updates
344 $ hg id -n
344 $ hg id -n
345 2
345 2
346 $ cd s
346 $ cd s
347 $ svnversion
347 $ svnversion
348 3
348 3
349 $ cd ..
349 $ cd ..
350 $ cd s
350 $ cd s
351 $ svn update -qr 1
351 $ svn update -qr 1
352 $ cd ..
352 $ cd ..
353 $ hg update 1
353 $ hg update 1
354 subrepository s diverged (local revision: 3, remote revision: 2)
354 subrepository s diverged (local revision: 3, remote revision: 2)
355 (M)erge, keep (l)ocal or keep (r)emote? m
355 (M)erge, keep (l)ocal or keep (r)emote? m
356 subrepository sources for s differ (in checked out version)
356 subrepository sources for s differ (in checked out version)
357 use (l)ocal source (1) or (r)emote source (2)?
357 use (l)ocal source (1) or (r)emote source (2)?
358 l
358 l
359 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
359 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
360 $ hg id -n
360 $ hg id -n
361 1+
361 1+
362 $ cd s
362 $ cd s
363 $ svnversion
363 $ svnversion
364 1
364 1
365 $ cd ..
365 $ cd ..
366
366
367 Sticky subrepository, file changes and revision updates
367 Sticky subrepository, file changes and revision updates
368 $ touch s/f1
368 $ touch s/f1
369 $ cd s
369 $ cd s
370 $ svn add f1
370 $ svn add f1
371 A f1
371 A f1
372 $ svnversion
372 $ svnversion
373 1M
373 1M
374 $ cd ..
374 $ cd ..
375 $ hg id -n
375 $ hg id -n
376 1+
376 1+
377 $ hg update tip
377 $ hg update tip
378 subrepository s diverged (local revision: 3, remote revision: 3)
378 subrepository s diverged (local revision: 3, remote revision: 3)
379 (M)erge, keep (l)ocal or keep (r)emote? m
379 (M)erge, keep (l)ocal or keep (r)emote? m
380 subrepository sources for s differ
380 subrepository sources for s differ
381 use (l)ocal source (1) or (r)emote source (3)?
381 use (l)ocal source (1) or (r)emote source (3)?
382 l
382 l
383 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
383 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
384 $ hg id -n
384 $ hg id -n
385 2+
385 2+
386 $ cd s
386 $ cd s
387 $ svnversion
387 $ svnversion
388 1M
388 1M
389 $ cd ..
389 $ cd ..
390
390
391 Sticky repository, update --clean
391 Sticky repository, update --clean
392 $ hg update --clean tip | grep -v 's[/\]externals[/\]other'
392 $ hg update --clean tip | grep -v 's[/\]externals[/\]other'
393 U *s/alpha (glob)
393 U *s/alpha (glob)
394 U *s (glob)
394 U *s (glob)
395
395
396 Fetching external item into '*s/externals'* (glob)
396 Fetching external item into '*s/externals'* (glob)
397 Checked out external at revision 1.
397 Checked out external at revision 1.
398
398
399 Checked out revision 3.
399 Checked out revision 3.
400 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
400 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
401 $ hg id -n
401 $ hg id -n
402 2
402 2
403 $ cd s
403 $ cd s
404 $ svnversion
404 $ svnversion
405 3
405 3
406 $ cd ..
406 $ cd ..
407
407
408 Test subrepo already at intended revision:
408 Test subrepo already at intended revision:
409 $ cd s
409 $ cd s
410 $ svn update -qr 2
410 $ svn update -qr 2
411 $ cd ..
411 $ cd ..
412 $ hg update 1
412 $ hg update 1
413 subrepository s diverged (local revision: 3, remote revision: 2)
413 subrepository s diverged (local revision: 3, remote revision: 2)
414 (M)erge, keep (l)ocal or keep (r)emote? m
414 (M)erge, keep (l)ocal or keep (r)emote? m
415 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
415 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
416 $ hg id -n
416 $ hg id -n
417 1+
417 1+
418 $ cd s
418 $ cd s
419 $ svnversion
419 $ svnversion
420 2
420 2
421 $ cd ..
421 $ cd ..
422
422
423 Test case where subversion would fail to update the subrepo because there
423 Test case where subversion would fail to update the subrepo because there
424 are unknown directories being replaced by tracked ones (happens with rebase).
424 are unknown directories being replaced by tracked ones (happens with rebase).
425
425
426 $ cd "$WCROOT/src"
426 $ cd "$WCROOT/src"
427 $ mkdir dir
427 $ mkdir dir
428 $ echo epsilon.py > dir/epsilon.py
428 $ echo epsilon.py > dir/epsilon.py
429 $ svn add dir
429 $ svn add dir
430 A dir
430 A dir
431 A dir/epsilon.py (glob)
431 A dir/epsilon.py (glob)
432 $ svn ci -m 'Add dir/epsilon.py'
432 $ svn ci -m 'Add dir/epsilon.py'
433 Adding *dir (glob)
433 Adding *dir (glob)
434 Adding *dir/epsilon.py (glob)
434 Adding *dir/epsilon.py (glob)
435 Transmitting file data .
435 Transmitting file data .
436 Committed revision 6.
436 Committed revision 6.
437 $ cd ../..
437 $ cd ../..
438 $ hg init rebaserepo
438 $ hg init rebaserepo
439 $ cd rebaserepo
439 $ cd rebaserepo
440 $ svn co -r5 --quiet "$SVNREPOURL"/src s
440 $ svn co -r5 --quiet "$SVNREPOURL"/src s
441 $ echo "s = [svn] $SVNREPOURL/src" >> .hgsub
441 $ echo "s = [svn] $SVNREPOURL/src" >> .hgsub
442 $ hg add .hgsub
442 $ hg add .hgsub
443 $ hg ci -m addsub
443 $ hg ci -m addsub
444 $ echo a > a
444 $ echo a > a
445 $ hg ci -Am adda
445 $ hg ci -Am adda
446 adding a
446 adding a
447 $ hg up 0
447 $ hg up 0
448 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
448 0 files updated, 0 files merged, 1 files removed, 0 files unresolved
449 $ svn up -qr6 s
449 $ svn up -qr6 s
450 $ hg ci -m updatesub
450 $ hg ci -m updatesub
451 created new head
451 created new head
452 $ echo pyc > s/dir/epsilon.pyc
452 $ echo pyc > s/dir/epsilon.pyc
453 $ hg up 1
453 $ hg up 1
454 D *s/dir (glob)
454 D *s/dir (glob)
455
455
456 Fetching external item into '*s/externals'* (glob)
456 Fetching external item into '*s/externals'* (glob)
457 Checked out external at revision 1.
457 Checked out external at revision 1.
458
458
459 Checked out revision 5.
459 Checked out revision 5.
460 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
460 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
461 $ hg up -q 2
461 $ hg up -q 2
462
462
463 Modify one of the externals to point to a different path so we can
463 Modify one of the externals to point to a different path so we can
464 test having obstructions when switching branches on checkout:
464 test having obstructions when switching branches on checkout:
465 $ hg checkout tip
465 $ hg checkout tip
466 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
466 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
467 $ echo "obstruct = [svn] $SVNREPOURL/externals" >> .hgsub
467 $ echo "obstruct = [svn] $SVNREPOURL/externals" >> .hgsub
468 $ svn co -r5 --quiet "$SVNREPOURL"/externals obstruct
468 $ svn co -r5 --quiet "$SVNREPOURL"/externals obstruct
469 $ hg commit -m 'Start making obstructed working copy'
469 $ hg commit -m 'Start making obstructed working copy'
470 $ hg book other
470 $ hg book other
471 $ hg co -r 'p1(tip)'
471 $ hg co -r 'p1(tip)'
472 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
472 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
473 (leaving bookmark other)
473 (leaving bookmark other)
474 $ echo "obstruct = [svn] $SVNREPOURL/src" >> .hgsub
474 $ echo "obstruct = [svn] $SVNREPOURL/src" >> .hgsub
475 $ svn co -r5 --quiet "$SVNREPOURL"/src obstruct
475 $ svn co -r5 --quiet "$SVNREPOURL"/src obstruct
476 $ hg commit -m 'Other branch which will be obstructed'
476 $ hg commit -m 'Other branch which will be obstructed'
477 created new head
477 created new head
478
478
479 Switching back to the head where we have another path mapped to the
479 Switching back to the head where we have another path mapped to the
480 same subrepo should work if the subrepo is clean.
480 same subrepo should work if the subrepo is clean.
481 $ hg co other
481 $ hg co other
482 A *obstruct/other (glob)
482 A *obstruct/other (glob)
483 Checked out revision 1.
483 Checked out revision 1.
484 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
484 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
485 (activating bookmark other)
485 (activating bookmark other)
486
486
487 This is surprising, but is also correct based on the current code:
487 This is surprising, but is also correct based on the current code:
488 $ echo "updating should (maybe) fail" > obstruct/other
488 $ echo "updating should (maybe) fail" > obstruct/other
489 $ hg co tip
489 $ hg co tip
490 abort: uncommitted changes
490 abort: uncommitted changes
491 (commit or update --clean to discard changes)
491 (commit or update --clean to discard changes)
492 [255]
492 [255]
493
493
494 Point to a Subversion branch which has since been deleted and recreated
494 Point to a Subversion branch which has since been deleted and recreated
495 First, create that condition in the repository.
495 First, create that condition in the repository.
496
496
497 $ hg ci --subrepos -m cleanup | grep -v Updating
497 $ hg ci --subrepos -m cleanup | grep -v Updating
498 committing subrepository obstruct
498 committing subrepository obstruct
499 Sending obstruct/other (glob)
499 Sending obstruct/other (glob)
500 Transmitting file data .
500 Transmitting file data .
501 Committed revision 7.
501 Committed revision 7.
502 At revision 7.
502 At revision 7.
503 $ svn mkdir -m "baseline" $SVNREPOURL/trunk
503 $ svn mkdir -m "baseline" $SVNREPOURL/trunk
504
504
505 Committed revision 8.
505 Committed revision 8.
506 $ svn copy -m "initial branch" $SVNREPOURL/trunk $SVNREPOURL/branch
506 $ svn copy -m "initial branch" $SVNREPOURL/trunk $SVNREPOURL/branch
507
507
508 Committed revision 9.
508 Committed revision 9.
509 $ svn co --quiet "$SVNREPOURL"/branch tempwc
509 $ svn co --quiet "$SVNREPOURL"/branch tempwc
510 $ cd tempwc
510 $ cd tempwc
511 $ echo "something old" > somethingold
511 $ echo "something old" > somethingold
512 $ svn add somethingold
512 $ svn add somethingold
513 A somethingold
513 A somethingold
514 $ svn ci -m 'Something old'
514 $ svn ci -m 'Something old'
515 Adding somethingold
515 Adding somethingold
516 Transmitting file data .
516 Transmitting file data .
517 Committed revision 10.
517 Committed revision 10.
518 $ svn rm -m "remove branch" $SVNREPOURL/branch
518 $ svn rm -m "remove branch" $SVNREPOURL/branch
519
519
520 Committed revision 11.
520 Committed revision 11.
521 $ svn copy -m "recreate branch" $SVNREPOURL/trunk $SVNREPOURL/branch
521 $ svn copy -m "recreate branch" $SVNREPOURL/trunk $SVNREPOURL/branch
522
522
523 Committed revision 12.
523 Committed revision 12.
524 $ svn up -q
524 $ svn up -q
525 $ echo "something new" > somethingnew
525 $ echo "something new" > somethingnew
526 $ svn add somethingnew
526 $ svn add somethingnew
527 A somethingnew
527 A somethingnew
528 $ svn ci -m 'Something new'
528 $ svn ci -m 'Something new'
529 Adding somethingnew
529 Adding somethingnew
530 Transmitting file data .
530 Transmitting file data .
531 Committed revision 13.
531 Committed revision 13.
532 $ cd ..
532 $ cd ..
533 $ rm -rf tempwc
533 $ rm -rf tempwc
534 $ svn co "$SVNREPOURL/branch"@10 recreated
534 $ svn co "$SVNREPOURL/branch"@10 recreated
535 A recreated/somethingold (glob)
535 A recreated/somethingold (glob)
536 Checked out revision 10.
536 Checked out revision 10.
537 $ echo "recreated = [svn] $SVNREPOURL/branch" >> .hgsub
537 $ echo "recreated = [svn] $SVNREPOURL/branch" >> .hgsub
538 $ hg ci -m addsub
538 $ hg ci -m addsub
539 $ cd recreated
539 $ cd recreated
540 $ svn up -q
540 $ svn up -q
541 $ cd ..
541 $ cd ..
542 $ hg ci -m updatesub
542 $ hg ci -m updatesub
543 $ hg up -r-2
543 $ hg up -r-2
544 D *recreated/somethingnew (glob)
544 D *recreated/somethingnew (glob)
545 A *recreated/somethingold (glob)
545 A *recreated/somethingold (glob)
546 Checked out revision 10.
546 Checked out revision 10.
547 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
547 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
548 (leaving bookmark other)
548 (leaving bookmark other)
549 $ test -f recreated/somethingold
549 $ test -f recreated/somethingold
550
550
551 Test archive
551 Test archive
552
552
553 $ hg archive -S ../archive-all --debug
553 $ hg archive -S ../archive-all --debug
554 archiving: 0/2 files (0.00%)
554 archiving: 0/2 files (0.00%)
555 archiving: .hgsub 1/2 files (50.00%)
555 archiving: .hgsub 1/2 files (50.00%)
556 archiving: .hgsubstate 2/2 files (100.00%)
556 archiving: .hgsubstate 2/2 files (100.00%)
557 archiving (obstruct): 0/1 files (0.00%)
557 archiving (obstruct): 0/1 files (0.00%)
558 archiving (obstruct): 1/1 files (100.00%)
558 archiving (obstruct): 1/1 files (100.00%)
559 archiving (recreated): 0/1 files (0.00%)
559 archiving (recreated): 0/1 files (0.00%)
560 archiving (recreated): 1/1 files (100.00%)
560 archiving (recreated): 1/1 files (100.00%)
561 archiving (s): 0/2 files (0.00%)
561 archiving (s): 0/2 files (0.00%)
562 archiving (s): 1/2 files (50.00%)
562 archiving (s): 1/2 files (50.00%)
563 archiving (s): 2/2 files (100.00%)
563 archiving (s): 2/2 files (100.00%)
564
564
565 $ hg archive -S ../archive-exclude --debug -X **old
565 $ hg archive -S ../archive-exclude --debug -X **old
566 archiving: 0/2 files (0.00%)
566 archiving: 0/2 files (0.00%)
567 archiving: .hgsub 1/2 files (50.00%)
567 archiving: .hgsub 1/2 files (50.00%)
568 archiving: .hgsubstate 2/2 files (100.00%)
568 archiving: .hgsubstate 2/2 files (100.00%)
569 archiving (obstruct): 0/1 files (0.00%)
569 archiving (obstruct): 0/1 files (0.00%)
570 archiving (obstruct): 1/1 files (100.00%)
570 archiving (obstruct): 1/1 files (100.00%)
571 archiving (recreated): 0 files
571 archiving (recreated): 0 files
572 archiving (s): 0/2 files (0.00%)
572 archiving (s): 0/2 files (0.00%)
573 archiving (s): 1/2 files (50.00%)
573 archiving (s): 1/2 files (50.00%)
574 archiving (s): 2/2 files (100.00%)
574 archiving (s): 2/2 files (100.00%)
575 $ find ../archive-exclude | sort
575 $ find ../archive-exclude | sort
576 ../archive-exclude
576 ../archive-exclude
577 ../archive-exclude/.hg_archival.txt
577 ../archive-exclude/.hg_archival.txt
578 ../archive-exclude/.hgsub
578 ../archive-exclude/.hgsub
579 ../archive-exclude/.hgsubstate
579 ../archive-exclude/.hgsubstate
580 ../archive-exclude/obstruct
580 ../archive-exclude/obstruct
581 ../archive-exclude/obstruct/other
581 ../archive-exclude/obstruct/other
582 ../archive-exclude/s
582 ../archive-exclude/s
583 ../archive-exclude/s/alpha
583 ../archive-exclude/s/alpha
584 ../archive-exclude/s/dir
584 ../archive-exclude/s/dir
585 ../archive-exclude/s/dir/epsilon.py
585 ../archive-exclude/s/dir/epsilon.py
586
586
587 Test forgetting files, not implemented in svn subrepo, used to
587 Test forgetting files, not implemented in svn subrepo, used to
588 traceback
588 traceback
589
589
590 #if no-windows
590 #if no-windows
591 $ hg forget 'notafile*'
591 $ hg forget 'notafile*'
592 notafile*: No such file or directory
592 notafile*: No such file or directory
593 [1]
593 [1]
594 #else
594 #else
595 $ hg forget 'notafile'
595 $ hg forget 'notafile'
596 notafile: * (glob)
596 notafile: * (glob)
597 [1]
597 [1]
598 #endif
598 #endif
599
599
600 Test a subrepo referencing a just moved svn path. Last commit rev will
600 Test a subrepo referencing a just moved svn path. Last commit rev will
601 be different from the revision, and the path will be different as
601 be different from the revision, and the path will be different as
602 well.
602 well.
603
603
604 $ cd "$WCROOT"
604 $ cd "$WCROOT"
605 $ svn up > /dev/null
605 $ svn up > /dev/null
606 $ mkdir trunk/subdir branches
606 $ mkdir trunk/subdir branches
607 $ echo a > trunk/subdir/a
607 $ echo a > trunk/subdir/a
608 $ svn add trunk/subdir branches
608 $ svn add trunk/subdir branches
609 A trunk/subdir (glob)
609 A trunk/subdir (glob)
610 A trunk/subdir/a (glob)
610 A trunk/subdir/a (glob)
611 A branches
611 A branches
612 $ svn ci -m addsubdir
612 $ svn ci -m addsubdir
613 Adding branches
613 Adding branches
614 Adding trunk/subdir (glob)
614 Adding trunk/subdir (glob)
615 Adding trunk/subdir/a (glob)
615 Adding trunk/subdir/a (glob)
616 Transmitting file data .
616 Transmitting file data .
617 Committed revision 14.
617 Committed revision 14.
618 $ svn cp -m branchtrunk $SVNREPOURL/trunk $SVNREPOURL/branches/somebranch
618 $ svn cp -m branchtrunk $SVNREPOURL/trunk $SVNREPOURL/branches/somebranch
619
619
620 Committed revision 15.
620 Committed revision 15.
621 $ cd ..
621 $ cd ..
622
622
623 $ hg init repo2
623 $ hg init repo2
624 $ cd repo2
624 $ cd repo2
625 $ svn co $SVNREPOURL/branches/somebranch/subdir
625 $ svn co $SVNREPOURL/branches/somebranch/subdir
626 A subdir/a (glob)
626 A subdir/a (glob)
627 Checked out revision 15.
627 Checked out revision 15.
628 $ echo "subdir = [svn] $SVNREPOURL/branches/somebranch/subdir" > .hgsub
628 $ echo "subdir = [svn] $SVNREPOURL/branches/somebranch/subdir" > .hgsub
629 $ hg add .hgsub
629 $ hg add .hgsub
630 $ hg ci -m addsub
630 $ hg ci -m addsub
631 $ hg up null
631 $ hg up null
632 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
632 0 files updated, 0 files merged, 2 files removed, 0 files unresolved
633 $ hg up
633 $ hg up
634 A *subdir/a (glob)
634 A *subdir/a (glob)
635 Checked out revision 15.
635 Checked out revision 15.
636 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
636 2 files updated, 0 files merged, 0 files removed, 0 files unresolved
637 $ cd ..
637 $ cd ..
638
639 Test sanitizing ".hg/hgrc" in subrepo
640
641 $ cd sub/t
642 $ hg update -q -C tip
643 $ cd s
644 $ mkdir .hg
645 $ echo '.hg/hgrc in svn repo' > .hg/hgrc
646 $ mkdir -p sub/.hg
647 $ echo 'sub/.hg/hgrc in svn repo' > sub/.hg/hgrc
648 $ svn add .hg sub
649 A .hg
650 A .hg/hgrc (glob)
651 A sub
652 A sub/.hg (glob)
653 A sub/.hg/hgrc (glob)
654 $ svn ci -m 'add .hg/hgrc to be sanitized at hg update'
655 Adding .hg
656 Adding .hg/hgrc (glob)
657 Adding sub
658 Adding sub/.hg (glob)
659 Adding sub/.hg/hgrc (glob)
660 Transmitting file data ..
661 Committed revision 16.
662 $ svn up -q
663 $ cd ..
664 $ hg commit -S -m 'commit with svn revision including .hg/hgrc'
665 $ grep ' s$' .hgsubstate
666 16 s
667 $ cd ..
668
669 $ hg -R tc pull -u -q 2>&1 | sort
670 warning: removing potentially hostile 'hgrc' in '$TESTTMP/sub/tc/s/.hg' (glob)
671 warning: removing potentially hostile 'hgrc' in '$TESTTMP/sub/tc/s/sub/.hg' (glob)
672 $ cd tc
673 $ grep ' s$' .hgsubstate
674 16 s
675 $ cat s/.hg/hgrc
676 cat: s/.hg/hgrc: No such file or directory
677 [1]
678 $ cat s/sub/.hg/hgrc
679 cat: s/sub/.hg/hgrc: No such file or directory
680 [1]
681
682 Test that sanitizing is omitted in meta data area:
683
684 $ mkdir s/.svn/.hg
685 $ echo '.hg/hgrc in svn metadata area' > s/.svn/.hg/hgrc
686 $ hg update -q -C '.^1'
687
688 $ cd ../..
General Comments 0
You need to be logged in to leave comments. Login now