##// END OF EJS Templates
Do not display passwords with pull/push/incoming/outgoing...
Manuel Holtgrewe -
r5525:dcbda0c4 default
parent child Browse files
Show More
@@ -1,3166 +1,3166 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
5 # This software may be used and distributed according to the terms
6 # of the GNU General Public License, incorporated herein by reference.
6 # of the GNU General Public License, incorporated herein by reference.
7
7
8 from node import *
8 from node import *
9 from i18n import _
9 from i18n import _
10 import os, re, sys, urllib
10 import os, re, sys, urllib
11 import hg, util, revlog, bundlerepo, extensions
11 import hg, util, revlog, bundlerepo, extensions
12 import difflib, patch, time, help, mdiff, tempfile
12 import difflib, patch, time, help, mdiff, tempfile
13 import errno, version, socket
13 import errno, version, socket
14 import archival, changegroup, cmdutil, hgweb.server, sshserver
14 import archival, changegroup, cmdutil, hgweb.server, sshserver
15
15
16 # Commands start here, listed alphabetically
16 # Commands start here, listed alphabetically
17
17
18 def add(ui, repo, *pats, **opts):
18 def add(ui, repo, *pats, **opts):
19 """add the specified files on the next commit
19 """add the specified files on the next commit
20
20
21 Schedule files to be version controlled and added to the repository.
21 Schedule files to be version controlled and added to the repository.
22
22
23 The files will be added to the repository at the next commit. To
23 The files will be added to the repository at the next commit. To
24 undo an add before that, see hg revert.
24 undo an add before that, see hg revert.
25
25
26 If no names are given, add all files in the repository.
26 If no names are given, add all files in the repository.
27 """
27 """
28
28
29 names = []
29 names = []
30 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
30 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
31 if exact:
31 if exact:
32 if ui.verbose:
32 if ui.verbose:
33 ui.status(_('adding %s\n') % rel)
33 ui.status(_('adding %s\n') % rel)
34 names.append(abs)
34 names.append(abs)
35 elif abs not in repo.dirstate:
35 elif abs not in repo.dirstate:
36 ui.status(_('adding %s\n') % rel)
36 ui.status(_('adding %s\n') % rel)
37 names.append(abs)
37 names.append(abs)
38 if not opts.get('dry_run'):
38 if not opts.get('dry_run'):
39 repo.add(names)
39 repo.add(names)
40
40
41 def addremove(ui, repo, *pats, **opts):
41 def addremove(ui, repo, *pats, **opts):
42 """add all new files, delete all missing files
42 """add all new files, delete all missing files
43
43
44 Add all new files and remove all missing files from the repository.
44 Add all new files and remove all missing files from the repository.
45
45
46 New files are ignored if they match any of the patterns in .hgignore. As
46 New files are ignored if they match any of the patterns in .hgignore. As
47 with add, these changes take effect at the next commit.
47 with add, these changes take effect at the next commit.
48
48
49 Use the -s option to detect renamed files. With a parameter > 0,
49 Use the -s option to detect renamed files. With a parameter > 0,
50 this compares every removed file with every added file and records
50 this compares every removed file with every added file and records
51 those similar enough as renames. This option takes a percentage
51 those similar enough as renames. This option takes a percentage
52 between 0 (disabled) and 100 (files must be identical) as its
52 between 0 (disabled) and 100 (files must be identical) as its
53 parameter. Detecting renamed files this way can be expensive.
53 parameter. Detecting renamed files this way can be expensive.
54 """
54 """
55 try:
55 try:
56 sim = float(opts.get('similarity') or 0)
56 sim = float(opts.get('similarity') or 0)
57 except ValueError:
57 except ValueError:
58 raise util.Abort(_('similarity must be a number'))
58 raise util.Abort(_('similarity must be a number'))
59 if sim < 0 or sim > 100:
59 if sim < 0 or sim > 100:
60 raise util.Abort(_('similarity must be between 0 and 100'))
60 raise util.Abort(_('similarity must be between 0 and 100'))
61 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
61 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
62
62
63 def annotate(ui, repo, *pats, **opts):
63 def annotate(ui, repo, *pats, **opts):
64 """show changeset information per file line
64 """show changeset information per file line
65
65
66 List changes in files, showing the revision id responsible for each line
66 List changes in files, showing the revision id responsible for each line
67
67
68 This command is useful to discover who did a change or when a change took
68 This command is useful to discover who did a change or when a change took
69 place.
69 place.
70
70
71 Without the -a option, annotate will avoid processing files it
71 Without the -a option, annotate will avoid processing files it
72 detects as binary. With -a, annotate will generate an annotation
72 detects as binary. With -a, annotate will generate an annotation
73 anyway, probably with undesirable results.
73 anyway, probably with undesirable results.
74 """
74 """
75 getdate = util.cachefunc(lambda x: util.datestr(x[0].date()))
75 getdate = util.cachefunc(lambda x: util.datestr(x[0].date()))
76
76
77 if not pats:
77 if not pats:
78 raise util.Abort(_('at least one file name or pattern required'))
78 raise util.Abort(_('at least one file name or pattern required'))
79
79
80 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
80 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
81 ('number', lambda x: str(x[0].rev())),
81 ('number', lambda x: str(x[0].rev())),
82 ('changeset', lambda x: short(x[0].node())),
82 ('changeset', lambda x: short(x[0].node())),
83 ('date', getdate),
83 ('date', getdate),
84 ('follow', lambda x: x[0].path()),
84 ('follow', lambda x: x[0].path()),
85 ]
85 ]
86
86
87 if (not opts['user'] and not opts['changeset'] and not opts['date']
87 if (not opts['user'] and not opts['changeset'] and not opts['date']
88 and not opts['follow']):
88 and not opts['follow']):
89 opts['number'] = 1
89 opts['number'] = 1
90
90
91 linenumber = opts.get('line_number') is not None
91 linenumber = opts.get('line_number') is not None
92 if (linenumber and (not opts['changeset']) and (not opts['number'])):
92 if (linenumber and (not opts['changeset']) and (not opts['number'])):
93 raise util.Abort(_('at least one of -n/-c is required for -l'))
93 raise util.Abort(_('at least one of -n/-c is required for -l'))
94
94
95 funcmap = [func for op, func in opmap if opts.get(op)]
95 funcmap = [func for op, func in opmap if opts.get(op)]
96 if linenumber:
96 if linenumber:
97 lastfunc = funcmap[-1]
97 lastfunc = funcmap[-1]
98 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
98 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
99
99
100 ctx = repo.changectx(opts['rev'])
100 ctx = repo.changectx(opts['rev'])
101
101
102 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
102 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
103 node=ctx.node()):
103 node=ctx.node()):
104 fctx = ctx.filectx(abs)
104 fctx = ctx.filectx(abs)
105 if not opts['text'] and util.binary(fctx.data()):
105 if not opts['text'] and util.binary(fctx.data()):
106 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
106 ui.write(_("%s: binary file\n") % ((pats and rel) or abs))
107 continue
107 continue
108
108
109 lines = fctx.annotate(follow=opts.get('follow'),
109 lines = fctx.annotate(follow=opts.get('follow'),
110 linenumber=linenumber)
110 linenumber=linenumber)
111 pieces = []
111 pieces = []
112
112
113 for f in funcmap:
113 for f in funcmap:
114 l = [f(n) for n, dummy in lines]
114 l = [f(n) for n, dummy in lines]
115 if l:
115 if l:
116 m = max(map(len, l))
116 m = max(map(len, l))
117 pieces.append(["%*s" % (m, x) for x in l])
117 pieces.append(["%*s" % (m, x) for x in l])
118
118
119 if pieces:
119 if pieces:
120 for p, l in zip(zip(*pieces), lines):
120 for p, l in zip(zip(*pieces), lines):
121 ui.write("%s: %s" % (" ".join(p), l[1]))
121 ui.write("%s: %s" % (" ".join(p), l[1]))
122
122
123 def archive(ui, repo, dest, **opts):
123 def archive(ui, repo, dest, **opts):
124 '''create unversioned archive of a repository revision
124 '''create unversioned archive of a repository revision
125
125
126 By default, the revision used is the parent of the working
126 By default, the revision used is the parent of the working
127 directory; use "-r" to specify a different revision.
127 directory; use "-r" to specify a different revision.
128
128
129 To specify the type of archive to create, use "-t". Valid
129 To specify the type of archive to create, use "-t". Valid
130 types are:
130 types are:
131
131
132 "files" (default): a directory full of files
132 "files" (default): a directory full of files
133 "tar": tar archive, uncompressed
133 "tar": tar archive, uncompressed
134 "tbz2": tar archive, compressed using bzip2
134 "tbz2": tar archive, compressed using bzip2
135 "tgz": tar archive, compressed using gzip
135 "tgz": tar archive, compressed using gzip
136 "uzip": zip archive, uncompressed
136 "uzip": zip archive, uncompressed
137 "zip": zip archive, compressed using deflate
137 "zip": zip archive, compressed using deflate
138
138
139 The exact name of the destination archive or directory is given
139 The exact name of the destination archive or directory is given
140 using a format string; see "hg help export" for details.
140 using a format string; see "hg help export" for details.
141
141
142 Each member added to an archive file has a directory prefix
142 Each member added to an archive file has a directory prefix
143 prepended. Use "-p" to specify a format string for the prefix.
143 prepended. Use "-p" to specify a format string for the prefix.
144 The default is the basename of the archive, with suffixes removed.
144 The default is the basename of the archive, with suffixes removed.
145 '''
145 '''
146
146
147 ctx = repo.changectx(opts['rev'])
147 ctx = repo.changectx(opts['rev'])
148 if not ctx:
148 if not ctx:
149 raise util.Abort(_('repository has no revisions'))
149 raise util.Abort(_('repository has no revisions'))
150 node = ctx.node()
150 node = ctx.node()
151 dest = cmdutil.make_filename(repo, dest, node)
151 dest = cmdutil.make_filename(repo, dest, node)
152 if os.path.realpath(dest) == repo.root:
152 if os.path.realpath(dest) == repo.root:
153 raise util.Abort(_('repository root cannot be destination'))
153 raise util.Abort(_('repository root cannot be destination'))
154 dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
154 dummy, matchfn, dummy = cmdutil.matchpats(repo, [], opts)
155 kind = opts.get('type') or 'files'
155 kind = opts.get('type') or 'files'
156 prefix = opts['prefix']
156 prefix = opts['prefix']
157 if dest == '-':
157 if dest == '-':
158 if kind == 'files':
158 if kind == 'files':
159 raise util.Abort(_('cannot archive plain files to stdout'))
159 raise util.Abort(_('cannot archive plain files to stdout'))
160 dest = sys.stdout
160 dest = sys.stdout
161 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
161 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
162 prefix = cmdutil.make_filename(repo, prefix, node)
162 prefix = cmdutil.make_filename(repo, prefix, node)
163 archival.archive(repo, dest, node, kind, not opts['no_decode'],
163 archival.archive(repo, dest, node, kind, not opts['no_decode'],
164 matchfn, prefix)
164 matchfn, prefix)
165
165
166 def backout(ui, repo, node=None, rev=None, **opts):
166 def backout(ui, repo, node=None, rev=None, **opts):
167 '''reverse effect of earlier changeset
167 '''reverse effect of earlier changeset
168
168
169 Commit the backed out changes as a new changeset. The new
169 Commit the backed out changes as a new changeset. The new
170 changeset is a child of the backed out changeset.
170 changeset is a child of the backed out changeset.
171
171
172 If you back out a changeset other than the tip, a new head is
172 If you back out a changeset other than the tip, a new head is
173 created. This head is the parent of the working directory. If
173 created. This head is the parent of the working directory. If
174 you back out an old changeset, your working directory will appear
174 you back out an old changeset, your working directory will appear
175 old after the backout. You should merge the backout changeset
175 old after the backout. You should merge the backout changeset
176 with another head.
176 with another head.
177
177
178 The --merge option remembers the parent of the working directory
178 The --merge option remembers the parent of the working directory
179 before starting the backout, then merges the new head with that
179 before starting the backout, then merges the new head with that
180 changeset afterwards. This saves you from doing the merge by
180 changeset afterwards. This saves you from doing the merge by
181 hand. The result of this merge is not committed, as for a normal
181 hand. The result of this merge is not committed, as for a normal
182 merge.'''
182 merge.'''
183 if rev and node:
183 if rev and node:
184 raise util.Abort(_("please specify just one revision"))
184 raise util.Abort(_("please specify just one revision"))
185
185
186 if not rev:
186 if not rev:
187 rev = node
187 rev = node
188
188
189 if not rev:
189 if not rev:
190 raise util.Abort(_("please specify a revision to backout"))
190 raise util.Abort(_("please specify a revision to backout"))
191
191
192 cmdutil.bail_if_changed(repo)
192 cmdutil.bail_if_changed(repo)
193 op1, op2 = repo.dirstate.parents()
193 op1, op2 = repo.dirstate.parents()
194 if op2 != nullid:
194 if op2 != nullid:
195 raise util.Abort(_('outstanding uncommitted merge'))
195 raise util.Abort(_('outstanding uncommitted merge'))
196 node = repo.lookup(rev)
196 node = repo.lookup(rev)
197 p1, p2 = repo.changelog.parents(node)
197 p1, p2 = repo.changelog.parents(node)
198 if p1 == nullid:
198 if p1 == nullid:
199 raise util.Abort(_('cannot back out a change with no parents'))
199 raise util.Abort(_('cannot back out a change with no parents'))
200 if p2 != nullid:
200 if p2 != nullid:
201 if not opts['parent']:
201 if not opts['parent']:
202 raise util.Abort(_('cannot back out a merge changeset without '
202 raise util.Abort(_('cannot back out a merge changeset without '
203 '--parent'))
203 '--parent'))
204 p = repo.lookup(opts['parent'])
204 p = repo.lookup(opts['parent'])
205 if p not in (p1, p2):
205 if p not in (p1, p2):
206 raise util.Abort(_('%s is not a parent of %s') %
206 raise util.Abort(_('%s is not a parent of %s') %
207 (short(p), short(node)))
207 (short(p), short(node)))
208 parent = p
208 parent = p
209 else:
209 else:
210 if opts['parent']:
210 if opts['parent']:
211 raise util.Abort(_('cannot use --parent on non-merge changeset'))
211 raise util.Abort(_('cannot use --parent on non-merge changeset'))
212 parent = p1
212 parent = p1
213 hg.clean(repo, node, show_stats=False)
213 hg.clean(repo, node, show_stats=False)
214 revert_opts = opts.copy()
214 revert_opts = opts.copy()
215 revert_opts['date'] = None
215 revert_opts['date'] = None
216 revert_opts['all'] = True
216 revert_opts['all'] = True
217 revert_opts['rev'] = hex(parent)
217 revert_opts['rev'] = hex(parent)
218 revert(ui, repo, **revert_opts)
218 revert(ui, repo, **revert_opts)
219 commit_opts = opts.copy()
219 commit_opts = opts.copy()
220 commit_opts['addremove'] = False
220 commit_opts['addremove'] = False
221 if not commit_opts['message'] and not commit_opts['logfile']:
221 if not commit_opts['message'] and not commit_opts['logfile']:
222 commit_opts['message'] = _("Backed out changeset %s") % (short(node))
222 commit_opts['message'] = _("Backed out changeset %s") % (short(node))
223 commit_opts['force_editor'] = True
223 commit_opts['force_editor'] = True
224 commit(ui, repo, **commit_opts)
224 commit(ui, repo, **commit_opts)
225 def nice(node):
225 def nice(node):
226 return '%d:%s' % (repo.changelog.rev(node), short(node))
226 return '%d:%s' % (repo.changelog.rev(node), short(node))
227 ui.status(_('changeset %s backs out changeset %s\n') %
227 ui.status(_('changeset %s backs out changeset %s\n') %
228 (nice(repo.changelog.tip()), nice(node)))
228 (nice(repo.changelog.tip()), nice(node)))
229 if op1 != node:
229 if op1 != node:
230 if opts['merge']:
230 if opts['merge']:
231 ui.status(_('merging with changeset %s\n') % nice(op1))
231 ui.status(_('merging with changeset %s\n') % nice(op1))
232 hg.merge(repo, hex(op1))
232 hg.merge(repo, hex(op1))
233 else:
233 else:
234 ui.status(_('the backout changeset is a new head - '
234 ui.status(_('the backout changeset is a new head - '
235 'do not forget to merge\n'))
235 'do not forget to merge\n'))
236 ui.status(_('(use "backout --merge" '
236 ui.status(_('(use "backout --merge" '
237 'if you want to auto-merge)\n'))
237 'if you want to auto-merge)\n'))
238
238
239 def branch(ui, repo, label=None, **opts):
239 def branch(ui, repo, label=None, **opts):
240 """set or show the current branch name
240 """set or show the current branch name
241
241
242 With no argument, show the current branch name. With one argument,
242 With no argument, show the current branch name. With one argument,
243 set the working directory branch name (the branch does not exist in
243 set the working directory branch name (the branch does not exist in
244 the repository until the next commit).
244 the repository until the next commit).
245
245
246 Unless --force is specified, branch will not let you set a
246 Unless --force is specified, branch will not let you set a
247 branch name that shadows an existing branch.
247 branch name that shadows an existing branch.
248 """
248 """
249
249
250 if label:
250 if label:
251 if not opts.get('force') and label in repo.branchtags():
251 if not opts.get('force') and label in repo.branchtags():
252 if label not in [p.branch() for p in repo.workingctx().parents()]:
252 if label not in [p.branch() for p in repo.workingctx().parents()]:
253 raise util.Abort(_('a branch of the same name already exists'
253 raise util.Abort(_('a branch of the same name already exists'
254 ' (use --force to override)'))
254 ' (use --force to override)'))
255 repo.dirstate.setbranch(util.fromlocal(label))
255 repo.dirstate.setbranch(util.fromlocal(label))
256 ui.status(_('marked working directory as branch %s\n') % label)
256 ui.status(_('marked working directory as branch %s\n') % label)
257 else:
257 else:
258 ui.write("%s\n" % util.tolocal(repo.dirstate.branch()))
258 ui.write("%s\n" % util.tolocal(repo.dirstate.branch()))
259
259
260 def branches(ui, repo, active=False):
260 def branches(ui, repo, active=False):
261 """list repository named branches
261 """list repository named branches
262
262
263 List the repository's named branches, indicating which ones are
263 List the repository's named branches, indicating which ones are
264 inactive. If active is specified, only show active branches.
264 inactive. If active is specified, only show active branches.
265
265
266 A branch is considered active if it contains unmerged heads.
266 A branch is considered active if it contains unmerged heads.
267 """
267 """
268 b = repo.branchtags()
268 b = repo.branchtags()
269 heads = dict.fromkeys(repo.heads(), 1)
269 heads = dict.fromkeys(repo.heads(), 1)
270 l = [((n in heads), repo.changelog.rev(n), n, t) for t, n in b.items()]
270 l = [((n in heads), repo.changelog.rev(n), n, t) for t, n in b.items()]
271 l.sort()
271 l.sort()
272 l.reverse()
272 l.reverse()
273 for ishead, r, n, t in l:
273 for ishead, r, n, t in l:
274 if active and not ishead:
274 if active and not ishead:
275 # If we're only displaying active branches, abort the loop on
275 # If we're only displaying active branches, abort the loop on
276 # encountering the first inactive head
276 # encountering the first inactive head
277 break
277 break
278 else:
278 else:
279 hexfunc = ui.debugflag and hex or short
279 hexfunc = ui.debugflag and hex or short
280 if ui.quiet:
280 if ui.quiet:
281 ui.write("%s\n" % t)
281 ui.write("%s\n" % t)
282 else:
282 else:
283 spaces = " " * (30 - util.locallen(t))
283 spaces = " " * (30 - util.locallen(t))
284 # The code only gets here if inactive branches are being
284 # The code only gets here if inactive branches are being
285 # displayed or the branch is active.
285 # displayed or the branch is active.
286 isinactive = ((not ishead) and " (inactive)") or ''
286 isinactive = ((not ishead) and " (inactive)") or ''
287 ui.write("%s%s %s:%s%s\n" % (t, spaces, r, hexfunc(n), isinactive))
287 ui.write("%s%s %s:%s%s\n" % (t, spaces, r, hexfunc(n), isinactive))
288
288
289 def bundle(ui, repo, fname, dest=None, **opts):
289 def bundle(ui, repo, fname, dest=None, **opts):
290 """create a changegroup file
290 """create a changegroup file
291
291
292 Generate a compressed changegroup file collecting changesets not
292 Generate a compressed changegroup file collecting changesets not
293 found in the other repository.
293 found in the other repository.
294
294
295 If no destination repository is specified the destination is assumed
295 If no destination repository is specified the destination is assumed
296 to have all the nodes specified by one or more --base parameters.
296 to have all the nodes specified by one or more --base parameters.
297
297
298 The bundle file can then be transferred using conventional means and
298 The bundle file can then be transferred using conventional means and
299 applied to another repository with the unbundle or pull command.
299 applied to another repository with the unbundle or pull command.
300 This is useful when direct push and pull are not available or when
300 This is useful when direct push and pull are not available or when
301 exporting an entire repository is undesirable.
301 exporting an entire repository is undesirable.
302
302
303 Applying bundles preserves all changeset contents including
303 Applying bundles preserves all changeset contents including
304 permissions, copy/rename information, and revision history.
304 permissions, copy/rename information, and revision history.
305 """
305 """
306 revs = opts.get('rev') or None
306 revs = opts.get('rev') or None
307 if revs:
307 if revs:
308 revs = [repo.lookup(rev) for rev in revs]
308 revs = [repo.lookup(rev) for rev in revs]
309 base = opts.get('base')
309 base = opts.get('base')
310 if base:
310 if base:
311 if dest:
311 if dest:
312 raise util.Abort(_("--base is incompatible with specifiying "
312 raise util.Abort(_("--base is incompatible with specifiying "
313 "a destination"))
313 "a destination"))
314 base = [repo.lookup(rev) for rev in base]
314 base = [repo.lookup(rev) for rev in base]
315 # create the right base
315 # create the right base
316 # XXX: nodesbetween / changegroup* should be "fixed" instead
316 # XXX: nodesbetween / changegroup* should be "fixed" instead
317 o = []
317 o = []
318 has = {nullid: None}
318 has = {nullid: None}
319 for n in base:
319 for n in base:
320 has.update(repo.changelog.reachable(n))
320 has.update(repo.changelog.reachable(n))
321 if revs:
321 if revs:
322 visit = list(revs)
322 visit = list(revs)
323 else:
323 else:
324 visit = repo.changelog.heads()
324 visit = repo.changelog.heads()
325 seen = {}
325 seen = {}
326 while visit:
326 while visit:
327 n = visit.pop(0)
327 n = visit.pop(0)
328 parents = [p for p in repo.changelog.parents(n) if p not in has]
328 parents = [p for p in repo.changelog.parents(n) if p not in has]
329 if len(parents) == 0:
329 if len(parents) == 0:
330 o.insert(0, n)
330 o.insert(0, n)
331 else:
331 else:
332 for p in parents:
332 for p in parents:
333 if p not in seen:
333 if p not in seen:
334 seen[p] = 1
334 seen[p] = 1
335 visit.append(p)
335 visit.append(p)
336 else:
336 else:
337 cmdutil.setremoteconfig(ui, opts)
337 cmdutil.setremoteconfig(ui, opts)
338 dest, revs, checkout = hg.parseurl(
338 dest, revs, checkout = hg.parseurl(
339 ui.expandpath(dest or 'default-push', dest or 'default'), revs)
339 ui.expandpath(dest or 'default-push', dest or 'default'), revs)
340 other = hg.repository(ui, dest)
340 other = hg.repository(ui, dest)
341 o = repo.findoutgoing(other, force=opts['force'])
341 o = repo.findoutgoing(other, force=opts['force'])
342
342
343 if revs:
343 if revs:
344 cg = repo.changegroupsubset(o, revs, 'bundle')
344 cg = repo.changegroupsubset(o, revs, 'bundle')
345 else:
345 else:
346 cg = repo.changegroup(o, 'bundle')
346 cg = repo.changegroup(o, 'bundle')
347 changegroup.writebundle(cg, fname, "HG10BZ")
347 changegroup.writebundle(cg, fname, "HG10BZ")
348
348
349 def cat(ui, repo, file1, *pats, **opts):
349 def cat(ui, repo, file1, *pats, **opts):
350 """output the current or given revision of files
350 """output the current or given revision of files
351
351
352 Print the specified files as they were at the given revision.
352 Print the specified files as they were at the given revision.
353 If no revision is given, the parent of the working directory is used,
353 If no revision is given, the parent of the working directory is used,
354 or tip if no revision is checked out.
354 or tip if no revision is checked out.
355
355
356 Output may be to a file, in which case the name of the file is
356 Output may be to a file, in which case the name of the file is
357 given using a format string. The formatting rules are the same as
357 given using a format string. The formatting rules are the same as
358 for the export command, with the following additions:
358 for the export command, with the following additions:
359
359
360 %s basename of file being printed
360 %s basename of file being printed
361 %d dirname of file being printed, or '.' if in repo root
361 %d dirname of file being printed, or '.' if in repo root
362 %p root-relative path name of file being printed
362 %p root-relative path name of file being printed
363 """
363 """
364 ctx = repo.changectx(opts['rev'])
364 ctx = repo.changectx(opts['rev'])
365 err = 1
365 err = 1
366 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
366 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
367 ctx.node()):
367 ctx.node()):
368 fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
368 fp = cmdutil.make_file(repo, opts['output'], ctx.node(), pathname=abs)
369 fp.write(ctx.filectx(abs).data())
369 fp.write(ctx.filectx(abs).data())
370 err = 0
370 err = 0
371 return err
371 return err
372
372
373 def clone(ui, source, dest=None, **opts):
373 def clone(ui, source, dest=None, **opts):
374 """make a copy of an existing repository
374 """make a copy of an existing repository
375
375
376 Create a copy of an existing repository in a new directory.
376 Create a copy of an existing repository in a new directory.
377
377
378 If no destination directory name is specified, it defaults to the
378 If no destination directory name is specified, it defaults to the
379 basename of the source.
379 basename of the source.
380
380
381 The location of the source is added to the new repository's
381 The location of the source is added to the new repository's
382 .hg/hgrc file, as the default to be used for future pulls.
382 .hg/hgrc file, as the default to be used for future pulls.
383
383
384 For efficiency, hardlinks are used for cloning whenever the source
384 For efficiency, hardlinks are used for cloning whenever the source
385 and destination are on the same filesystem (note this applies only
385 and destination are on the same filesystem (note this applies only
386 to the repository data, not to the checked out files). Some
386 to the repository data, not to the checked out files). Some
387 filesystems, such as AFS, implement hardlinking incorrectly, but
387 filesystems, such as AFS, implement hardlinking incorrectly, but
388 do not report errors. In these cases, use the --pull option to
388 do not report errors. In these cases, use the --pull option to
389 avoid hardlinking.
389 avoid hardlinking.
390
390
391 You can safely clone repositories and checked out files using full
391 You can safely clone repositories and checked out files using full
392 hardlinks with
392 hardlinks with
393
393
394 $ cp -al REPO REPOCLONE
394 $ cp -al REPO REPOCLONE
395
395
396 which is the fastest way to clone. However, the operation is not
396 which is the fastest way to clone. However, the operation is not
397 atomic (making sure REPO is not modified during the operation is
397 atomic (making sure REPO is not modified during the operation is
398 up to you) and you have to make sure your editor breaks hardlinks
398 up to you) and you have to make sure your editor breaks hardlinks
399 (Emacs and most Linux Kernel tools do so).
399 (Emacs and most Linux Kernel tools do so).
400
400
401 If you use the -r option to clone up to a specific revision, no
401 If you use the -r option to clone up to a specific revision, no
402 subsequent revisions will be present in the cloned repository.
402 subsequent revisions will be present in the cloned repository.
403 This option implies --pull, even on local repositories.
403 This option implies --pull, even on local repositories.
404
404
405 See pull for valid source format details.
405 See pull for valid source format details.
406
406
407 It is possible to specify an ssh:// URL as the destination, but no
407 It is possible to specify an ssh:// URL as the destination, but no
408 .hg/hgrc and working directory will be created on the remote side.
408 .hg/hgrc and working directory will be created on the remote side.
409 Look at the help text for the pull command for important details
409 Look at the help text for the pull command for important details
410 about ssh:// URLs.
410 about ssh:// URLs.
411 """
411 """
412 cmdutil.setremoteconfig(ui, opts)
412 cmdutil.setremoteconfig(ui, opts)
413 hg.clone(ui, source, dest,
413 hg.clone(ui, source, dest,
414 pull=opts['pull'],
414 pull=opts['pull'],
415 stream=opts['uncompressed'],
415 stream=opts['uncompressed'],
416 rev=opts['rev'],
416 rev=opts['rev'],
417 update=not opts['noupdate'])
417 update=not opts['noupdate'])
418
418
419 def commit(ui, repo, *pats, **opts):
419 def commit(ui, repo, *pats, **opts):
420 """commit the specified files or all outstanding changes
420 """commit the specified files or all outstanding changes
421
421
422 Commit changes to the given files into the repository.
422 Commit changes to the given files into the repository.
423
423
424 If a list of files is omitted, all changes reported by "hg status"
424 If a list of files is omitted, all changes reported by "hg status"
425 will be committed.
425 will be committed.
426
426
427 If no commit message is specified, the editor configured in your hgrc
427 If no commit message is specified, the editor configured in your hgrc
428 or in the EDITOR environment variable is started to enter a message.
428 or in the EDITOR environment variable is started to enter a message.
429 """
429 """
430 def commitfunc(ui, repo, files, message, match, opts):
430 def commitfunc(ui, repo, files, message, match, opts):
431 return repo.commit(files, message, opts['user'], opts['date'], match,
431 return repo.commit(files, message, opts['user'], opts['date'], match,
432 force_editor=opts.get('force_editor'))
432 force_editor=opts.get('force_editor'))
433 cmdutil.commit(ui, repo, commitfunc, pats, opts)
433 cmdutil.commit(ui, repo, commitfunc, pats, opts)
434
434
435 def docopy(ui, repo, pats, opts):
435 def docopy(ui, repo, pats, opts):
436 # called with the repo lock held
436 # called with the repo lock held
437 #
437 #
438 # hgsep => pathname that uses "/" to separate directories
438 # hgsep => pathname that uses "/" to separate directories
439 # ossep => pathname that uses os.sep to separate directories
439 # ossep => pathname that uses os.sep to separate directories
440 cwd = repo.getcwd()
440 cwd = repo.getcwd()
441 errors = 0
441 errors = 0
442 copied = []
442 copied = []
443 targets = {}
443 targets = {}
444
444
445 # abs: hgsep
445 # abs: hgsep
446 # rel: ossep
446 # rel: ossep
447 # return: hgsep
447 # return: hgsep
448 def okaytocopy(abs, rel, exact):
448 def okaytocopy(abs, rel, exact):
449 reasons = {'?': _('is not managed'),
449 reasons = {'?': _('is not managed'),
450 'r': _('has been marked for remove')}
450 'r': _('has been marked for remove')}
451 state = repo.dirstate[abs]
451 state = repo.dirstate[abs]
452 reason = reasons.get(state)
452 reason = reasons.get(state)
453 if reason:
453 if reason:
454 if exact:
454 if exact:
455 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
455 ui.warn(_('%s: not copying - file %s\n') % (rel, reason))
456 else:
456 else:
457 if state == 'a':
457 if state == 'a':
458 origsrc = repo.dirstate.copied(abs)
458 origsrc = repo.dirstate.copied(abs)
459 if origsrc is not None:
459 if origsrc is not None:
460 return origsrc
460 return origsrc
461 return abs
461 return abs
462
462
463 # origsrc: hgsep
463 # origsrc: hgsep
464 # abssrc: hgsep
464 # abssrc: hgsep
465 # relsrc: ossep
465 # relsrc: ossep
466 # otarget: ossep
466 # otarget: ossep
467 def copy(origsrc, abssrc, relsrc, otarget, exact):
467 def copy(origsrc, abssrc, relsrc, otarget, exact):
468 abstarget = util.canonpath(repo.root, cwd, otarget)
468 abstarget = util.canonpath(repo.root, cwd, otarget)
469 reltarget = repo.pathto(abstarget, cwd)
469 reltarget = repo.pathto(abstarget, cwd)
470 prevsrc = targets.get(abstarget)
470 prevsrc = targets.get(abstarget)
471 src = repo.wjoin(abssrc)
471 src = repo.wjoin(abssrc)
472 target = repo.wjoin(abstarget)
472 target = repo.wjoin(abstarget)
473 if prevsrc is not None:
473 if prevsrc is not None:
474 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
474 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
475 (reltarget, repo.pathto(abssrc, cwd),
475 (reltarget, repo.pathto(abssrc, cwd),
476 repo.pathto(prevsrc, cwd)))
476 repo.pathto(prevsrc, cwd)))
477 return
477 return
478 if (not opts['after'] and os.path.exists(target) or
478 if (not opts['after'] and os.path.exists(target) or
479 opts['after'] and repo.dirstate[abstarget] in 'mn'):
479 opts['after'] and repo.dirstate[abstarget] in 'mn'):
480 if not opts['force']:
480 if not opts['force']:
481 ui.warn(_('%s: not overwriting - file exists\n') %
481 ui.warn(_('%s: not overwriting - file exists\n') %
482 reltarget)
482 reltarget)
483 return
483 return
484 if not opts['after'] and not opts.get('dry_run'):
484 if not opts['after'] and not opts.get('dry_run'):
485 os.unlink(target)
485 os.unlink(target)
486 if opts['after']:
486 if opts['after']:
487 if not os.path.exists(target):
487 if not os.path.exists(target):
488 return
488 return
489 else:
489 else:
490 targetdir = os.path.dirname(target) or '.'
490 targetdir = os.path.dirname(target) or '.'
491 if not os.path.isdir(targetdir) and not opts.get('dry_run'):
491 if not os.path.isdir(targetdir) and not opts.get('dry_run'):
492 os.makedirs(targetdir)
492 os.makedirs(targetdir)
493 try:
493 try:
494 restore = repo.dirstate[abstarget] == 'r'
494 restore = repo.dirstate[abstarget] == 'r'
495 if restore and not opts.get('dry_run'):
495 if restore and not opts.get('dry_run'):
496 repo.undelete([abstarget])
496 repo.undelete([abstarget])
497 try:
497 try:
498 if not opts.get('dry_run'):
498 if not opts.get('dry_run'):
499 util.copyfile(src, target)
499 util.copyfile(src, target)
500 restore = False
500 restore = False
501 finally:
501 finally:
502 if restore:
502 if restore:
503 repo.remove([abstarget])
503 repo.remove([abstarget])
504 except IOError, inst:
504 except IOError, inst:
505 if inst.errno == errno.ENOENT:
505 if inst.errno == errno.ENOENT:
506 ui.warn(_('%s: deleted in working copy\n') % relsrc)
506 ui.warn(_('%s: deleted in working copy\n') % relsrc)
507 else:
507 else:
508 ui.warn(_('%s: cannot copy - %s\n') %
508 ui.warn(_('%s: cannot copy - %s\n') %
509 (relsrc, inst.strerror))
509 (relsrc, inst.strerror))
510 errors += 1
510 errors += 1
511 return
511 return
512 if ui.verbose or not exact:
512 if ui.verbose or not exact:
513 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
513 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
514 targets[abstarget] = abssrc
514 targets[abstarget] = abssrc
515 if abstarget != origsrc:
515 if abstarget != origsrc:
516 if repo.dirstate[origsrc] == 'a':
516 if repo.dirstate[origsrc] == 'a':
517 if not ui.quiet:
517 if not ui.quiet:
518 ui.warn(_("%s has not been committed yet, so no copy "
518 ui.warn(_("%s has not been committed yet, so no copy "
519 "data will be stored for %s.\n")
519 "data will be stored for %s.\n")
520 % (repo.pathto(origsrc, cwd), reltarget))
520 % (repo.pathto(origsrc, cwd), reltarget))
521 if abstarget not in repo.dirstate and not opts.get('dry_run'):
521 if abstarget not in repo.dirstate and not opts.get('dry_run'):
522 repo.add([abstarget])
522 repo.add([abstarget])
523 elif not opts.get('dry_run'):
523 elif not opts.get('dry_run'):
524 repo.copy(origsrc, abstarget)
524 repo.copy(origsrc, abstarget)
525 copied.append((abssrc, relsrc, exact))
525 copied.append((abssrc, relsrc, exact))
526
526
527 # pat: ossep
527 # pat: ossep
528 # dest ossep
528 # dest ossep
529 # srcs: list of (hgsep, hgsep, ossep, bool)
529 # srcs: list of (hgsep, hgsep, ossep, bool)
530 # return: function that takes hgsep and returns ossep
530 # return: function that takes hgsep and returns ossep
531 def targetpathfn(pat, dest, srcs):
531 def targetpathfn(pat, dest, srcs):
532 if os.path.isdir(pat):
532 if os.path.isdir(pat):
533 abspfx = util.canonpath(repo.root, cwd, pat)
533 abspfx = util.canonpath(repo.root, cwd, pat)
534 abspfx = util.localpath(abspfx)
534 abspfx = util.localpath(abspfx)
535 if destdirexists:
535 if destdirexists:
536 striplen = len(os.path.split(abspfx)[0])
536 striplen = len(os.path.split(abspfx)[0])
537 else:
537 else:
538 striplen = len(abspfx)
538 striplen = len(abspfx)
539 if striplen:
539 if striplen:
540 striplen += len(os.sep)
540 striplen += len(os.sep)
541 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
541 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
542 elif destdirexists:
542 elif destdirexists:
543 res = lambda p: os.path.join(dest,
543 res = lambda p: os.path.join(dest,
544 os.path.basename(util.localpath(p)))
544 os.path.basename(util.localpath(p)))
545 else:
545 else:
546 res = lambda p: dest
546 res = lambda p: dest
547 return res
547 return res
548
548
549 # pat: ossep
549 # pat: ossep
550 # dest ossep
550 # dest ossep
551 # srcs: list of (hgsep, hgsep, ossep, bool)
551 # srcs: list of (hgsep, hgsep, ossep, bool)
552 # return: function that takes hgsep and returns ossep
552 # return: function that takes hgsep and returns ossep
553 def targetpathafterfn(pat, dest, srcs):
553 def targetpathafterfn(pat, dest, srcs):
554 if util.patkind(pat, None)[0]:
554 if util.patkind(pat, None)[0]:
555 # a mercurial pattern
555 # a mercurial pattern
556 res = lambda p: os.path.join(dest,
556 res = lambda p: os.path.join(dest,
557 os.path.basename(util.localpath(p)))
557 os.path.basename(util.localpath(p)))
558 else:
558 else:
559 abspfx = util.canonpath(repo.root, cwd, pat)
559 abspfx = util.canonpath(repo.root, cwd, pat)
560 if len(abspfx) < len(srcs[0][0]):
560 if len(abspfx) < len(srcs[0][0]):
561 # A directory. Either the target path contains the last
561 # A directory. Either the target path contains the last
562 # component of the source path or it does not.
562 # component of the source path or it does not.
563 def evalpath(striplen):
563 def evalpath(striplen):
564 score = 0
564 score = 0
565 for s in srcs:
565 for s in srcs:
566 t = os.path.join(dest, util.localpath(s[0])[striplen:])
566 t = os.path.join(dest, util.localpath(s[0])[striplen:])
567 if os.path.exists(t):
567 if os.path.exists(t):
568 score += 1
568 score += 1
569 return score
569 return score
570
570
571 abspfx = util.localpath(abspfx)
571 abspfx = util.localpath(abspfx)
572 striplen = len(abspfx)
572 striplen = len(abspfx)
573 if striplen:
573 if striplen:
574 striplen += len(os.sep)
574 striplen += len(os.sep)
575 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
575 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
576 score = evalpath(striplen)
576 score = evalpath(striplen)
577 striplen1 = len(os.path.split(abspfx)[0])
577 striplen1 = len(os.path.split(abspfx)[0])
578 if striplen1:
578 if striplen1:
579 striplen1 += len(os.sep)
579 striplen1 += len(os.sep)
580 if evalpath(striplen1) > score:
580 if evalpath(striplen1) > score:
581 striplen = striplen1
581 striplen = striplen1
582 res = lambda p: os.path.join(dest,
582 res = lambda p: os.path.join(dest,
583 util.localpath(p)[striplen:])
583 util.localpath(p)[striplen:])
584 else:
584 else:
585 # a file
585 # a file
586 if destdirexists:
586 if destdirexists:
587 res = lambda p: os.path.join(dest,
587 res = lambda p: os.path.join(dest,
588 os.path.basename(util.localpath(p)))
588 os.path.basename(util.localpath(p)))
589 else:
589 else:
590 res = lambda p: dest
590 res = lambda p: dest
591 return res
591 return res
592
592
593
593
594 pats = util.expand_glob(pats)
594 pats = util.expand_glob(pats)
595 if not pats:
595 if not pats:
596 raise util.Abort(_('no source or destination specified'))
596 raise util.Abort(_('no source or destination specified'))
597 if len(pats) == 1:
597 if len(pats) == 1:
598 raise util.Abort(_('no destination specified'))
598 raise util.Abort(_('no destination specified'))
599 dest = pats.pop()
599 dest = pats.pop()
600 destdirexists = os.path.isdir(dest)
600 destdirexists = os.path.isdir(dest)
601 if not destdirexists:
601 if not destdirexists:
602 if len(pats) > 1 or util.patkind(pats[0], None)[0]:
602 if len(pats) > 1 or util.patkind(pats[0], None)[0]:
603 raise util.Abort(_('with multiple sources, destination must be an '
603 raise util.Abort(_('with multiple sources, destination must be an '
604 'existing directory'))
604 'existing directory'))
605 if dest.endswith(os.sep) or os.altsep and dest.endswith(os.altsep):
605 if dest.endswith(os.sep) or os.altsep and dest.endswith(os.altsep):
606 raise util.Abort(_('destination %s is not a directory') % dest)
606 raise util.Abort(_('destination %s is not a directory') % dest)
607 if opts['after']:
607 if opts['after']:
608 tfn = targetpathafterfn
608 tfn = targetpathafterfn
609 else:
609 else:
610 tfn = targetpathfn
610 tfn = targetpathfn
611 copylist = []
611 copylist = []
612 for pat in pats:
612 for pat in pats:
613 srcs = []
613 srcs = []
614 for tag, abssrc, relsrc, exact in cmdutil.walk(repo, [pat], opts,
614 for tag, abssrc, relsrc, exact in cmdutil.walk(repo, [pat], opts,
615 globbed=True):
615 globbed=True):
616 origsrc = okaytocopy(abssrc, relsrc, exact)
616 origsrc = okaytocopy(abssrc, relsrc, exact)
617 if origsrc:
617 if origsrc:
618 srcs.append((origsrc, abssrc, relsrc, exact))
618 srcs.append((origsrc, abssrc, relsrc, exact))
619 if not srcs:
619 if not srcs:
620 continue
620 continue
621 copylist.append((tfn(pat, dest, srcs), srcs))
621 copylist.append((tfn(pat, dest, srcs), srcs))
622 if not copylist:
622 if not copylist:
623 raise util.Abort(_('no files to copy'))
623 raise util.Abort(_('no files to copy'))
624
624
625 for targetpath, srcs in copylist:
625 for targetpath, srcs in copylist:
626 for origsrc, abssrc, relsrc, exact in srcs:
626 for origsrc, abssrc, relsrc, exact in srcs:
627 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
627 copy(origsrc, abssrc, relsrc, targetpath(abssrc), exact)
628
628
629 if errors:
629 if errors:
630 ui.warn(_('(consider using --after)\n'))
630 ui.warn(_('(consider using --after)\n'))
631 return errors, copied
631 return errors, copied
632
632
633 def copy(ui, repo, *pats, **opts):
633 def copy(ui, repo, *pats, **opts):
634 """mark files as copied for the next commit
634 """mark files as copied for the next commit
635
635
636 Mark dest as having copies of source files. If dest is a
636 Mark dest as having copies of source files. If dest is a
637 directory, copies are put in that directory. If dest is a file,
637 directory, copies are put in that directory. If dest is a file,
638 there can only be one source.
638 there can only be one source.
639
639
640 By default, this command copies the contents of files as they
640 By default, this command copies the contents of files as they
641 stand in the working directory. If invoked with --after, the
641 stand in the working directory. If invoked with --after, the
642 operation is recorded, but no copying is performed.
642 operation is recorded, but no copying is performed.
643
643
644 This command takes effect in the next commit. To undo a copy
644 This command takes effect in the next commit. To undo a copy
645 before that, see hg revert.
645 before that, see hg revert.
646 """
646 """
647 wlock = repo.wlock(False)
647 wlock = repo.wlock(False)
648 try:
648 try:
649 errs, copied = docopy(ui, repo, pats, opts)
649 errs, copied = docopy(ui, repo, pats, opts)
650 finally:
650 finally:
651 del wlock
651 del wlock
652 return errs
652 return errs
653
653
654 def debugancestor(ui, index, rev1, rev2):
654 def debugancestor(ui, index, rev1, rev2):
655 """find the ancestor revision of two revisions in a given index"""
655 """find the ancestor revision of two revisions in a given index"""
656 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
656 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
657 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
657 a = r.ancestor(r.lookup(rev1), r.lookup(rev2))
658 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
658 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
659
659
660 def debugcomplete(ui, cmd='', **opts):
660 def debugcomplete(ui, cmd='', **opts):
661 """returns the completion list associated with the given command"""
661 """returns the completion list associated with the given command"""
662
662
663 if opts['options']:
663 if opts['options']:
664 options = []
664 options = []
665 otables = [globalopts]
665 otables = [globalopts]
666 if cmd:
666 if cmd:
667 aliases, entry = cmdutil.findcmd(ui, cmd, table)
667 aliases, entry = cmdutil.findcmd(ui, cmd, table)
668 otables.append(entry[1])
668 otables.append(entry[1])
669 for t in otables:
669 for t in otables:
670 for o in t:
670 for o in t:
671 if o[0]:
671 if o[0]:
672 options.append('-%s' % o[0])
672 options.append('-%s' % o[0])
673 options.append('--%s' % o[1])
673 options.append('--%s' % o[1])
674 ui.write("%s\n" % "\n".join(options))
674 ui.write("%s\n" % "\n".join(options))
675 return
675 return
676
676
677 clist = cmdutil.findpossible(ui, cmd, table).keys()
677 clist = cmdutil.findpossible(ui, cmd, table).keys()
678 clist.sort()
678 clist.sort()
679 ui.write("%s\n" % "\n".join(clist))
679 ui.write("%s\n" % "\n".join(clist))
680
680
681 def debugrebuildstate(ui, repo, rev=""):
681 def debugrebuildstate(ui, repo, rev=""):
682 """rebuild the dirstate as it would look like for the given revision"""
682 """rebuild the dirstate as it would look like for the given revision"""
683 if rev == "":
683 if rev == "":
684 rev = repo.changelog.tip()
684 rev = repo.changelog.tip()
685 ctx = repo.changectx(rev)
685 ctx = repo.changectx(rev)
686 files = ctx.manifest()
686 files = ctx.manifest()
687 wlock = repo.wlock()
687 wlock = repo.wlock()
688 try:
688 try:
689 repo.dirstate.rebuild(rev, files)
689 repo.dirstate.rebuild(rev, files)
690 finally:
690 finally:
691 del wlock
691 del wlock
692
692
693 def debugcheckstate(ui, repo):
693 def debugcheckstate(ui, repo):
694 """validate the correctness of the current dirstate"""
694 """validate the correctness of the current dirstate"""
695 parent1, parent2 = repo.dirstate.parents()
695 parent1, parent2 = repo.dirstate.parents()
696 m1 = repo.changectx(parent1).manifest()
696 m1 = repo.changectx(parent1).manifest()
697 m2 = repo.changectx(parent2).manifest()
697 m2 = repo.changectx(parent2).manifest()
698 errors = 0
698 errors = 0
699 for f in repo.dirstate:
699 for f in repo.dirstate:
700 state = repo.dirstate[f]
700 state = repo.dirstate[f]
701 if state in "nr" and f not in m1:
701 if state in "nr" and f not in m1:
702 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
702 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
703 errors += 1
703 errors += 1
704 if state in "a" and f in m1:
704 if state in "a" and f in m1:
705 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
705 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
706 errors += 1
706 errors += 1
707 if state in "m" and f not in m1 and f not in m2:
707 if state in "m" and f not in m1 and f not in m2:
708 ui.warn(_("%s in state %s, but not in either manifest\n") %
708 ui.warn(_("%s in state %s, but not in either manifest\n") %
709 (f, state))
709 (f, state))
710 errors += 1
710 errors += 1
711 for f in m1:
711 for f in m1:
712 state = repo.dirstate[f]
712 state = repo.dirstate[f]
713 if state not in "nrm":
713 if state not in "nrm":
714 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
714 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
715 errors += 1
715 errors += 1
716 if errors:
716 if errors:
717 error = _(".hg/dirstate inconsistent with current parent's manifest")
717 error = _(".hg/dirstate inconsistent with current parent's manifest")
718 raise util.Abort(error)
718 raise util.Abort(error)
719
719
720 def showconfig(ui, repo, *values, **opts):
720 def showconfig(ui, repo, *values, **opts):
721 """show combined config settings from all hgrc files
721 """show combined config settings from all hgrc files
722
722
723 With no args, print names and values of all config items.
723 With no args, print names and values of all config items.
724
724
725 With one arg of the form section.name, print just the value of
725 With one arg of the form section.name, print just the value of
726 that config item.
726 that config item.
727
727
728 With multiple args, print names and values of all config items
728 With multiple args, print names and values of all config items
729 with matching section names."""
729 with matching section names."""
730
730
731 untrusted = bool(opts.get('untrusted'))
731 untrusted = bool(opts.get('untrusted'))
732 if values:
732 if values:
733 if len([v for v in values if '.' in v]) > 1:
733 if len([v for v in values if '.' in v]) > 1:
734 raise util.Abort(_('only one config item permitted'))
734 raise util.Abort(_('only one config item permitted'))
735 for section, name, value in ui.walkconfig(untrusted=untrusted):
735 for section, name, value in ui.walkconfig(untrusted=untrusted):
736 sectname = section + '.' + name
736 sectname = section + '.' + name
737 if values:
737 if values:
738 for v in values:
738 for v in values:
739 if v == section:
739 if v == section:
740 ui.write('%s=%s\n' % (sectname, value))
740 ui.write('%s=%s\n' % (sectname, value))
741 elif v == sectname:
741 elif v == sectname:
742 ui.write(value, '\n')
742 ui.write(value, '\n')
743 else:
743 else:
744 ui.write('%s=%s\n' % (sectname, value))
744 ui.write('%s=%s\n' % (sectname, value))
745
745
746 def debugsetparents(ui, repo, rev1, rev2=None):
746 def debugsetparents(ui, repo, rev1, rev2=None):
747 """manually set the parents of the current working directory
747 """manually set the parents of the current working directory
748
748
749 This is useful for writing repository conversion tools, but should
749 This is useful for writing repository conversion tools, but should
750 be used with care.
750 be used with care.
751 """
751 """
752
752
753 if not rev2:
753 if not rev2:
754 rev2 = hex(nullid)
754 rev2 = hex(nullid)
755
755
756 wlock = repo.wlock()
756 wlock = repo.wlock()
757 try:
757 try:
758 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
758 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
759 finally:
759 finally:
760 del wlock
760 del wlock
761
761
762 def debugstate(ui, repo):
762 def debugstate(ui, repo):
763 """show the contents of the current dirstate"""
763 """show the contents of the current dirstate"""
764 k = repo.dirstate._map.items()
764 k = repo.dirstate._map.items()
765 k.sort()
765 k.sort()
766 for file_, ent in k:
766 for file_, ent in k:
767 if ent[3] == -1:
767 if ent[3] == -1:
768 # Pad or slice to locale representation
768 # Pad or slice to locale representation
769 locale_len = len(time.strftime("%x %X", time.localtime(0)))
769 locale_len = len(time.strftime("%x %X", time.localtime(0)))
770 timestr = 'unset'
770 timestr = 'unset'
771 timestr = timestr[:locale_len] + ' '*(locale_len - len(timestr))
771 timestr = timestr[:locale_len] + ' '*(locale_len - len(timestr))
772 else:
772 else:
773 timestr = time.strftime("%x %X", time.localtime(ent[3]))
773 timestr = time.strftime("%x %X", time.localtime(ent[3]))
774 if ent[1] & 020000:
774 if ent[1] & 020000:
775 mode = 'lnk'
775 mode = 'lnk'
776 else:
776 else:
777 mode = '%3o' % (ent[1] & 0777)
777 mode = '%3o' % (ent[1] & 0777)
778 ui.write("%c %s %10d %s %s\n" % (ent[0], mode, ent[2], timestr, file_))
778 ui.write("%c %s %10d %s %s\n" % (ent[0], mode, ent[2], timestr, file_))
779 for f in repo.dirstate.copies():
779 for f in repo.dirstate.copies():
780 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
780 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
781
781
782 def debugdata(ui, file_, rev):
782 def debugdata(ui, file_, rev):
783 """dump the contents of a data file revision"""
783 """dump the contents of a data file revision"""
784 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
784 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
785 try:
785 try:
786 ui.write(r.revision(r.lookup(rev)))
786 ui.write(r.revision(r.lookup(rev)))
787 except KeyError:
787 except KeyError:
788 raise util.Abort(_('invalid revision identifier %s') % rev)
788 raise util.Abort(_('invalid revision identifier %s') % rev)
789
789
790 def debugdate(ui, date, range=None, **opts):
790 def debugdate(ui, date, range=None, **opts):
791 """parse and display a date"""
791 """parse and display a date"""
792 if opts["extended"]:
792 if opts["extended"]:
793 d = util.parsedate(date, util.extendeddateformats)
793 d = util.parsedate(date, util.extendeddateformats)
794 else:
794 else:
795 d = util.parsedate(date)
795 d = util.parsedate(date)
796 ui.write("internal: %s %s\n" % d)
796 ui.write("internal: %s %s\n" % d)
797 ui.write("standard: %s\n" % util.datestr(d))
797 ui.write("standard: %s\n" % util.datestr(d))
798 if range:
798 if range:
799 m = util.matchdate(range)
799 m = util.matchdate(range)
800 ui.write("match: %s\n" % m(d[0]))
800 ui.write("match: %s\n" % m(d[0]))
801
801
802 def debugindex(ui, file_):
802 def debugindex(ui, file_):
803 """dump the contents of an index file"""
803 """dump the contents of an index file"""
804 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
804 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
805 ui.write(" rev offset length base linkrev" +
805 ui.write(" rev offset length base linkrev" +
806 " nodeid p1 p2\n")
806 " nodeid p1 p2\n")
807 for i in xrange(r.count()):
807 for i in xrange(r.count()):
808 node = r.node(i)
808 node = r.node(i)
809 try:
809 try:
810 pp = r.parents(node)
810 pp = r.parents(node)
811 except:
811 except:
812 pp = [nullid, nullid]
812 pp = [nullid, nullid]
813 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
813 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
814 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
814 i, r.start(i), r.length(i), r.base(i), r.linkrev(node),
815 short(node), short(pp[0]), short(pp[1])))
815 short(node), short(pp[0]), short(pp[1])))
816
816
817 def debugindexdot(ui, file_):
817 def debugindexdot(ui, file_):
818 """dump an index DAG as a .dot file"""
818 """dump an index DAG as a .dot file"""
819 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
819 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
820 ui.write("digraph G {\n")
820 ui.write("digraph G {\n")
821 for i in xrange(r.count()):
821 for i in xrange(r.count()):
822 node = r.node(i)
822 node = r.node(i)
823 pp = r.parents(node)
823 pp = r.parents(node)
824 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
824 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
825 if pp[1] != nullid:
825 if pp[1] != nullid:
826 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
826 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
827 ui.write("}\n")
827 ui.write("}\n")
828
828
829 def debuginstall(ui):
829 def debuginstall(ui):
830 '''test Mercurial installation'''
830 '''test Mercurial installation'''
831
831
832 def writetemp(contents):
832 def writetemp(contents):
833 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
833 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
834 f = os.fdopen(fd, "wb")
834 f = os.fdopen(fd, "wb")
835 f.write(contents)
835 f.write(contents)
836 f.close()
836 f.close()
837 return name
837 return name
838
838
839 problems = 0
839 problems = 0
840
840
841 # encoding
841 # encoding
842 ui.status(_("Checking encoding (%s)...\n") % util._encoding)
842 ui.status(_("Checking encoding (%s)...\n") % util._encoding)
843 try:
843 try:
844 util.fromlocal("test")
844 util.fromlocal("test")
845 except util.Abort, inst:
845 except util.Abort, inst:
846 ui.write(" %s\n" % inst)
846 ui.write(" %s\n" % inst)
847 ui.write(_(" (check that your locale is properly set)\n"))
847 ui.write(_(" (check that your locale is properly set)\n"))
848 problems += 1
848 problems += 1
849
849
850 # compiled modules
850 # compiled modules
851 ui.status(_("Checking extensions...\n"))
851 ui.status(_("Checking extensions...\n"))
852 try:
852 try:
853 import bdiff, mpatch, base85
853 import bdiff, mpatch, base85
854 except Exception, inst:
854 except Exception, inst:
855 ui.write(" %s\n" % inst)
855 ui.write(" %s\n" % inst)
856 ui.write(_(" One or more extensions could not be found"))
856 ui.write(_(" One or more extensions could not be found"))
857 ui.write(_(" (check that you compiled the extensions)\n"))
857 ui.write(_(" (check that you compiled the extensions)\n"))
858 problems += 1
858 problems += 1
859
859
860 # templates
860 # templates
861 ui.status(_("Checking templates...\n"))
861 ui.status(_("Checking templates...\n"))
862 try:
862 try:
863 import templater
863 import templater
864 t = templater.templater(templater.templatepath("map-cmdline.default"))
864 t = templater.templater(templater.templatepath("map-cmdline.default"))
865 except Exception, inst:
865 except Exception, inst:
866 ui.write(" %s\n" % inst)
866 ui.write(" %s\n" % inst)
867 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
867 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
868 problems += 1
868 problems += 1
869
869
870 # patch
870 # patch
871 ui.status(_("Checking patch...\n"))
871 ui.status(_("Checking patch...\n"))
872 patchproblems = 0
872 patchproblems = 0
873 a = "1\n2\n3\n4\n"
873 a = "1\n2\n3\n4\n"
874 b = "1\n2\n3\ninsert\n4\n"
874 b = "1\n2\n3\ninsert\n4\n"
875 fa = writetemp(a)
875 fa = writetemp(a)
876 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
876 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
877 os.path.basename(fa))
877 os.path.basename(fa))
878 fd = writetemp(d)
878 fd = writetemp(d)
879
879
880 files = {}
880 files = {}
881 try:
881 try:
882 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
882 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
883 except util.Abort, e:
883 except util.Abort, e:
884 ui.write(_(" patch call failed:\n"))
884 ui.write(_(" patch call failed:\n"))
885 ui.write(" " + str(e) + "\n")
885 ui.write(" " + str(e) + "\n")
886 patchproblems += 1
886 patchproblems += 1
887 else:
887 else:
888 if list(files) != [os.path.basename(fa)]:
888 if list(files) != [os.path.basename(fa)]:
889 ui.write(_(" unexpected patch output!\n"))
889 ui.write(_(" unexpected patch output!\n"))
890 patchproblems += 1
890 patchproblems += 1
891 a = file(fa).read()
891 a = file(fa).read()
892 if a != b:
892 if a != b:
893 ui.write(_(" patch test failed!\n"))
893 ui.write(_(" patch test failed!\n"))
894 patchproblems += 1
894 patchproblems += 1
895
895
896 if patchproblems:
896 if patchproblems:
897 if ui.config('ui', 'patch'):
897 if ui.config('ui', 'patch'):
898 ui.write(_(" (Current patch tool may be incompatible with patch,"
898 ui.write(_(" (Current patch tool may be incompatible with patch,"
899 " or misconfigured. Please check your .hgrc file)\n"))
899 " or misconfigured. Please check your .hgrc file)\n"))
900 else:
900 else:
901 ui.write(_(" Internal patcher failure, please report this error"
901 ui.write(_(" Internal patcher failure, please report this error"
902 " to http://www.selenic.com/mercurial/bts\n"))
902 " to http://www.selenic.com/mercurial/bts\n"))
903 problems += patchproblems
903 problems += patchproblems
904
904
905 os.unlink(fa)
905 os.unlink(fa)
906 os.unlink(fd)
906 os.unlink(fd)
907
907
908 # merge helper
908 # merge helper
909 ui.status(_("Checking merge helper...\n"))
909 ui.status(_("Checking merge helper...\n"))
910 cmd = (os.environ.get("HGMERGE") or ui.config("ui", "merge")
910 cmd = (os.environ.get("HGMERGE") or ui.config("ui", "merge")
911 or "hgmerge")
911 or "hgmerge")
912 cmdpath = util.find_exe(cmd) or util.find_exe(cmd.split()[0])
912 cmdpath = util.find_exe(cmd) or util.find_exe(cmd.split()[0])
913 if not cmdpath:
913 if not cmdpath:
914 if cmd == 'hgmerge':
914 if cmd == 'hgmerge':
915 ui.write(_(" No merge helper set and can't find default"
915 ui.write(_(" No merge helper set and can't find default"
916 " hgmerge script in PATH\n"))
916 " hgmerge script in PATH\n"))
917 ui.write(_(" (specify a merge helper in your .hgrc file)\n"))
917 ui.write(_(" (specify a merge helper in your .hgrc file)\n"))
918 else:
918 else:
919 ui.write(_(" Can't find merge helper '%s' in PATH\n") % cmd)
919 ui.write(_(" Can't find merge helper '%s' in PATH\n") % cmd)
920 ui.write(_(" (specify a merge helper in your .hgrc file)\n"))
920 ui.write(_(" (specify a merge helper in your .hgrc file)\n"))
921 problems += 1
921 problems += 1
922 else:
922 else:
923 # actually attempt a patch here
923 # actually attempt a patch here
924 fa = writetemp("1\n2\n3\n4\n")
924 fa = writetemp("1\n2\n3\n4\n")
925 fl = writetemp("1\n2\n3\ninsert\n4\n")
925 fl = writetemp("1\n2\n3\ninsert\n4\n")
926 fr = writetemp("begin\n1\n2\n3\n4\n")
926 fr = writetemp("begin\n1\n2\n3\n4\n")
927 r = util.system('%s "%s" "%s" "%s"' % (cmd, fl, fa, fr))
927 r = util.system('%s "%s" "%s" "%s"' % (cmd, fl, fa, fr))
928 if r:
928 if r:
929 ui.write(_(" Got unexpected merge error %d!\n") % r)
929 ui.write(_(" Got unexpected merge error %d!\n") % r)
930 problems += 1
930 problems += 1
931 m = file(fl).read()
931 m = file(fl).read()
932 if m != "begin\n1\n2\n3\ninsert\n4\n":
932 if m != "begin\n1\n2\n3\ninsert\n4\n":
933 ui.write(_(" Got unexpected merge results!\n"))
933 ui.write(_(" Got unexpected merge results!\n"))
934 ui.write(_(" (your merge helper may have the"
934 ui.write(_(" (your merge helper may have the"
935 " wrong argument order)\n"))
935 " wrong argument order)\n"))
936 ui.write(_(" Result: %r\n") % m)
936 ui.write(_(" Result: %r\n") % m)
937 problems += 1
937 problems += 1
938 os.unlink(fa)
938 os.unlink(fa)
939 os.unlink(fl)
939 os.unlink(fl)
940 os.unlink(fr)
940 os.unlink(fr)
941
941
942 # editor
942 # editor
943 ui.status(_("Checking commit editor...\n"))
943 ui.status(_("Checking commit editor...\n"))
944 editor = (os.environ.get("HGEDITOR") or
944 editor = (os.environ.get("HGEDITOR") or
945 ui.config("ui", "editor") or
945 ui.config("ui", "editor") or
946 os.environ.get("EDITOR", "vi"))
946 os.environ.get("EDITOR", "vi"))
947 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
947 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
948 if not cmdpath:
948 if not cmdpath:
949 if editor == 'vi':
949 if editor == 'vi':
950 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
950 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
951 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
951 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
952 else:
952 else:
953 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
953 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
954 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
954 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
955 problems += 1
955 problems += 1
956
956
957 # check username
957 # check username
958 ui.status(_("Checking username...\n"))
958 ui.status(_("Checking username...\n"))
959 user = os.environ.get("HGUSER")
959 user = os.environ.get("HGUSER")
960 if user is None:
960 if user is None:
961 user = ui.config("ui", "username")
961 user = ui.config("ui", "username")
962 if user is None:
962 if user is None:
963 user = os.environ.get("EMAIL")
963 user = os.environ.get("EMAIL")
964 if not user:
964 if not user:
965 ui.warn(" ")
965 ui.warn(" ")
966 ui.username()
966 ui.username()
967 ui.write(_(" (specify a username in your .hgrc file)\n"))
967 ui.write(_(" (specify a username in your .hgrc file)\n"))
968
968
969 if not problems:
969 if not problems:
970 ui.status(_("No problems detected\n"))
970 ui.status(_("No problems detected\n"))
971 else:
971 else:
972 ui.write(_("%s problems detected,"
972 ui.write(_("%s problems detected,"
973 " please check your install!\n") % problems)
973 " please check your install!\n") % problems)
974
974
975 return problems
975 return problems
976
976
977 def debugrename(ui, repo, file1, *pats, **opts):
977 def debugrename(ui, repo, file1, *pats, **opts):
978 """dump rename information"""
978 """dump rename information"""
979
979
980 ctx = repo.changectx(opts.get('rev', 'tip'))
980 ctx = repo.changectx(opts.get('rev', 'tip'))
981 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
981 for src, abs, rel, exact in cmdutil.walk(repo, (file1,) + pats, opts,
982 ctx.node()):
982 ctx.node()):
983 m = ctx.filectx(abs).renamed()
983 m = ctx.filectx(abs).renamed()
984 if m:
984 if m:
985 ui.write(_("%s renamed from %s:%s\n") % (rel, m[0], hex(m[1])))
985 ui.write(_("%s renamed from %s:%s\n") % (rel, m[0], hex(m[1])))
986 else:
986 else:
987 ui.write(_("%s not renamed\n") % rel)
987 ui.write(_("%s not renamed\n") % rel)
988
988
989 def debugwalk(ui, repo, *pats, **opts):
989 def debugwalk(ui, repo, *pats, **opts):
990 """show how files match on given patterns"""
990 """show how files match on given patterns"""
991 items = list(cmdutil.walk(repo, pats, opts))
991 items = list(cmdutil.walk(repo, pats, opts))
992 if not items:
992 if not items:
993 return
993 return
994 fmt = '%%s %%-%ds %%-%ds %%s' % (
994 fmt = '%%s %%-%ds %%-%ds %%s' % (
995 max([len(abs) for (src, abs, rel, exact) in items]),
995 max([len(abs) for (src, abs, rel, exact) in items]),
996 max([len(rel) for (src, abs, rel, exact) in items]))
996 max([len(rel) for (src, abs, rel, exact) in items]))
997 for src, abs, rel, exact in items:
997 for src, abs, rel, exact in items:
998 line = fmt % (src, abs, rel, exact and 'exact' or '')
998 line = fmt % (src, abs, rel, exact and 'exact' or '')
999 ui.write("%s\n" % line.rstrip())
999 ui.write("%s\n" % line.rstrip())
1000
1000
1001 def diff(ui, repo, *pats, **opts):
1001 def diff(ui, repo, *pats, **opts):
1002 """diff repository (or selected files)
1002 """diff repository (or selected files)
1003
1003
1004 Show differences between revisions for the specified files.
1004 Show differences between revisions for the specified files.
1005
1005
1006 Differences between files are shown using the unified diff format.
1006 Differences between files are shown using the unified diff format.
1007
1007
1008 NOTE: diff may generate unexpected results for merges, as it will
1008 NOTE: diff may generate unexpected results for merges, as it will
1009 default to comparing against the working directory's first parent
1009 default to comparing against the working directory's first parent
1010 changeset if no revisions are specified.
1010 changeset if no revisions are specified.
1011
1011
1012 When two revision arguments are given, then changes are shown
1012 When two revision arguments are given, then changes are shown
1013 between those revisions. If only one revision is specified then
1013 between those revisions. If only one revision is specified then
1014 that revision is compared to the working directory, and, when no
1014 that revision is compared to the working directory, and, when no
1015 revisions are specified, the working directory files are compared
1015 revisions are specified, the working directory files are compared
1016 to its parent.
1016 to its parent.
1017
1017
1018 Without the -a option, diff will avoid generating diffs of files
1018 Without the -a option, diff will avoid generating diffs of files
1019 it detects as binary. With -a, diff will generate a diff anyway,
1019 it detects as binary. With -a, diff will generate a diff anyway,
1020 probably with undesirable results.
1020 probably with undesirable results.
1021 """
1021 """
1022 node1, node2 = cmdutil.revpair(repo, opts['rev'])
1022 node1, node2 = cmdutil.revpair(repo, opts['rev'])
1023
1023
1024 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
1024 fns, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
1025
1025
1026 patch.diff(repo, node1, node2, fns, match=matchfn,
1026 patch.diff(repo, node1, node2, fns, match=matchfn,
1027 opts=patch.diffopts(ui, opts))
1027 opts=patch.diffopts(ui, opts))
1028
1028
1029 def export(ui, repo, *changesets, **opts):
1029 def export(ui, repo, *changesets, **opts):
1030 """dump the header and diffs for one or more changesets
1030 """dump the header and diffs for one or more changesets
1031
1031
1032 Print the changeset header and diffs for one or more revisions.
1032 Print the changeset header and diffs for one or more revisions.
1033
1033
1034 The information shown in the changeset header is: author,
1034 The information shown in the changeset header is: author,
1035 changeset hash, parent(s) and commit comment.
1035 changeset hash, parent(s) and commit comment.
1036
1036
1037 NOTE: export may generate unexpected diff output for merge changesets,
1037 NOTE: export may generate unexpected diff output for merge changesets,
1038 as it will compare the merge changeset against its first parent only.
1038 as it will compare the merge changeset against its first parent only.
1039
1039
1040 Output may be to a file, in which case the name of the file is
1040 Output may be to a file, in which case the name of the file is
1041 given using a format string. The formatting rules are as follows:
1041 given using a format string. The formatting rules are as follows:
1042
1042
1043 %% literal "%" character
1043 %% literal "%" character
1044 %H changeset hash (40 bytes of hexadecimal)
1044 %H changeset hash (40 bytes of hexadecimal)
1045 %N number of patches being generated
1045 %N number of patches being generated
1046 %R changeset revision number
1046 %R changeset revision number
1047 %b basename of the exporting repository
1047 %b basename of the exporting repository
1048 %h short-form changeset hash (12 bytes of hexadecimal)
1048 %h short-form changeset hash (12 bytes of hexadecimal)
1049 %n zero-padded sequence number, starting at 1
1049 %n zero-padded sequence number, starting at 1
1050 %r zero-padded changeset revision number
1050 %r zero-padded changeset revision number
1051
1051
1052 Without the -a option, export will avoid generating diffs of files
1052 Without the -a option, export will avoid generating diffs of files
1053 it detects as binary. With -a, export will generate a diff anyway,
1053 it detects as binary. With -a, export will generate a diff anyway,
1054 probably with undesirable results.
1054 probably with undesirable results.
1055
1055
1056 With the --switch-parent option, the diff will be against the second
1056 With the --switch-parent option, the diff will be against the second
1057 parent. It can be useful to review a merge.
1057 parent. It can be useful to review a merge.
1058 """
1058 """
1059 if not changesets:
1059 if not changesets:
1060 raise util.Abort(_("export requires at least one changeset"))
1060 raise util.Abort(_("export requires at least one changeset"))
1061 revs = cmdutil.revrange(repo, changesets)
1061 revs = cmdutil.revrange(repo, changesets)
1062 if len(revs) > 1:
1062 if len(revs) > 1:
1063 ui.note(_('exporting patches:\n'))
1063 ui.note(_('exporting patches:\n'))
1064 else:
1064 else:
1065 ui.note(_('exporting patch:\n'))
1065 ui.note(_('exporting patch:\n'))
1066 patch.export(repo, revs, template=opts['output'],
1066 patch.export(repo, revs, template=opts['output'],
1067 switch_parent=opts['switch_parent'],
1067 switch_parent=opts['switch_parent'],
1068 opts=patch.diffopts(ui, opts))
1068 opts=patch.diffopts(ui, opts))
1069
1069
1070 def grep(ui, repo, pattern, *pats, **opts):
1070 def grep(ui, repo, pattern, *pats, **opts):
1071 """search for a pattern in specified files and revisions
1071 """search for a pattern in specified files and revisions
1072
1072
1073 Search revisions of files for a regular expression.
1073 Search revisions of files for a regular expression.
1074
1074
1075 This command behaves differently than Unix grep. It only accepts
1075 This command behaves differently than Unix grep. It only accepts
1076 Python/Perl regexps. It searches repository history, not the
1076 Python/Perl regexps. It searches repository history, not the
1077 working directory. It always prints the revision number in which
1077 working directory. It always prints the revision number in which
1078 a match appears.
1078 a match appears.
1079
1079
1080 By default, grep only prints output for the first revision of a
1080 By default, grep only prints output for the first revision of a
1081 file in which it finds a match. To get it to print every revision
1081 file in which it finds a match. To get it to print every revision
1082 that contains a change in match status ("-" for a match that
1082 that contains a change in match status ("-" for a match that
1083 becomes a non-match, or "+" for a non-match that becomes a match),
1083 becomes a non-match, or "+" for a non-match that becomes a match),
1084 use the --all flag.
1084 use the --all flag.
1085 """
1085 """
1086 reflags = 0
1086 reflags = 0
1087 if opts['ignore_case']:
1087 if opts['ignore_case']:
1088 reflags |= re.I
1088 reflags |= re.I
1089 try:
1089 try:
1090 regexp = re.compile(pattern, reflags)
1090 regexp = re.compile(pattern, reflags)
1091 except Exception, inst:
1091 except Exception, inst:
1092 ui.warn(_("grep: invalid match pattern: %s!\n") % inst)
1092 ui.warn(_("grep: invalid match pattern: %s!\n") % inst)
1093 return None
1093 return None
1094 sep, eol = ':', '\n'
1094 sep, eol = ':', '\n'
1095 if opts['print0']:
1095 if opts['print0']:
1096 sep = eol = '\0'
1096 sep = eol = '\0'
1097
1097
1098 fcache = {}
1098 fcache = {}
1099 def getfile(fn):
1099 def getfile(fn):
1100 if fn not in fcache:
1100 if fn not in fcache:
1101 fcache[fn] = repo.file(fn)
1101 fcache[fn] = repo.file(fn)
1102 return fcache[fn]
1102 return fcache[fn]
1103
1103
1104 def matchlines(body):
1104 def matchlines(body):
1105 begin = 0
1105 begin = 0
1106 linenum = 0
1106 linenum = 0
1107 while True:
1107 while True:
1108 match = regexp.search(body, begin)
1108 match = regexp.search(body, begin)
1109 if not match:
1109 if not match:
1110 break
1110 break
1111 mstart, mend = match.span()
1111 mstart, mend = match.span()
1112 linenum += body.count('\n', begin, mstart) + 1
1112 linenum += body.count('\n', begin, mstart) + 1
1113 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1113 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1114 lend = body.find('\n', mend)
1114 lend = body.find('\n', mend)
1115 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1115 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1116 begin = lend + 1
1116 begin = lend + 1
1117
1117
1118 class linestate(object):
1118 class linestate(object):
1119 def __init__(self, line, linenum, colstart, colend):
1119 def __init__(self, line, linenum, colstart, colend):
1120 self.line = line
1120 self.line = line
1121 self.linenum = linenum
1121 self.linenum = linenum
1122 self.colstart = colstart
1122 self.colstart = colstart
1123 self.colend = colend
1123 self.colend = colend
1124
1124
1125 def __eq__(self, other):
1125 def __eq__(self, other):
1126 return self.line == other.line
1126 return self.line == other.line
1127
1127
1128 matches = {}
1128 matches = {}
1129 copies = {}
1129 copies = {}
1130 def grepbody(fn, rev, body):
1130 def grepbody(fn, rev, body):
1131 matches[rev].setdefault(fn, [])
1131 matches[rev].setdefault(fn, [])
1132 m = matches[rev][fn]
1132 m = matches[rev][fn]
1133 for lnum, cstart, cend, line in matchlines(body):
1133 for lnum, cstart, cend, line in matchlines(body):
1134 s = linestate(line, lnum, cstart, cend)
1134 s = linestate(line, lnum, cstart, cend)
1135 m.append(s)
1135 m.append(s)
1136
1136
1137 def difflinestates(a, b):
1137 def difflinestates(a, b):
1138 sm = difflib.SequenceMatcher(None, a, b)
1138 sm = difflib.SequenceMatcher(None, a, b)
1139 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1139 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1140 if tag == 'insert':
1140 if tag == 'insert':
1141 for i in xrange(blo, bhi):
1141 for i in xrange(blo, bhi):
1142 yield ('+', b[i])
1142 yield ('+', b[i])
1143 elif tag == 'delete':
1143 elif tag == 'delete':
1144 for i in xrange(alo, ahi):
1144 for i in xrange(alo, ahi):
1145 yield ('-', a[i])
1145 yield ('-', a[i])
1146 elif tag == 'replace':
1146 elif tag == 'replace':
1147 for i in xrange(alo, ahi):
1147 for i in xrange(alo, ahi):
1148 yield ('-', a[i])
1148 yield ('-', a[i])
1149 for i in xrange(blo, bhi):
1149 for i in xrange(blo, bhi):
1150 yield ('+', b[i])
1150 yield ('+', b[i])
1151
1151
1152 prev = {}
1152 prev = {}
1153 def display(fn, rev, states, prevstates):
1153 def display(fn, rev, states, prevstates):
1154 found = False
1154 found = False
1155 filerevmatches = {}
1155 filerevmatches = {}
1156 r = prev.get(fn, -1)
1156 r = prev.get(fn, -1)
1157 if opts['all']:
1157 if opts['all']:
1158 iter = difflinestates(states, prevstates)
1158 iter = difflinestates(states, prevstates)
1159 else:
1159 else:
1160 iter = [('', l) for l in prevstates]
1160 iter = [('', l) for l in prevstates]
1161 for change, l in iter:
1161 for change, l in iter:
1162 cols = [fn, str(r)]
1162 cols = [fn, str(r)]
1163 if opts['line_number']:
1163 if opts['line_number']:
1164 cols.append(str(l.linenum))
1164 cols.append(str(l.linenum))
1165 if opts['all']:
1165 if opts['all']:
1166 cols.append(change)
1166 cols.append(change)
1167 if opts['user']:
1167 if opts['user']:
1168 cols.append(ui.shortuser(get(r)[1]))
1168 cols.append(ui.shortuser(get(r)[1]))
1169 if opts['files_with_matches']:
1169 if opts['files_with_matches']:
1170 c = (fn, r)
1170 c = (fn, r)
1171 if c in filerevmatches:
1171 if c in filerevmatches:
1172 continue
1172 continue
1173 filerevmatches[c] = 1
1173 filerevmatches[c] = 1
1174 else:
1174 else:
1175 cols.append(l.line)
1175 cols.append(l.line)
1176 ui.write(sep.join(cols), eol)
1176 ui.write(sep.join(cols), eol)
1177 found = True
1177 found = True
1178 return found
1178 return found
1179
1179
1180 fstate = {}
1180 fstate = {}
1181 skip = {}
1181 skip = {}
1182 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1182 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1183 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1183 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1184 found = False
1184 found = False
1185 follow = opts.get('follow')
1185 follow = opts.get('follow')
1186 for st, rev, fns in changeiter:
1186 for st, rev, fns in changeiter:
1187 if st == 'window':
1187 if st == 'window':
1188 matches.clear()
1188 matches.clear()
1189 elif st == 'add':
1189 elif st == 'add':
1190 mf = repo.changectx(rev).manifest()
1190 mf = repo.changectx(rev).manifest()
1191 matches[rev] = {}
1191 matches[rev] = {}
1192 for fn in fns:
1192 for fn in fns:
1193 if fn in skip:
1193 if fn in skip:
1194 continue
1194 continue
1195 try:
1195 try:
1196 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1196 grepbody(fn, rev, getfile(fn).read(mf[fn]))
1197 fstate.setdefault(fn, [])
1197 fstate.setdefault(fn, [])
1198 if follow:
1198 if follow:
1199 copied = getfile(fn).renamed(mf[fn])
1199 copied = getfile(fn).renamed(mf[fn])
1200 if copied:
1200 if copied:
1201 copies.setdefault(rev, {})[fn] = copied[0]
1201 copies.setdefault(rev, {})[fn] = copied[0]
1202 except KeyError:
1202 except KeyError:
1203 pass
1203 pass
1204 elif st == 'iter':
1204 elif st == 'iter':
1205 states = matches[rev].items()
1205 states = matches[rev].items()
1206 states.sort()
1206 states.sort()
1207 for fn, m in states:
1207 for fn, m in states:
1208 copy = copies.get(rev, {}).get(fn)
1208 copy = copies.get(rev, {}).get(fn)
1209 if fn in skip:
1209 if fn in skip:
1210 if copy:
1210 if copy:
1211 skip[copy] = True
1211 skip[copy] = True
1212 continue
1212 continue
1213 if fn in prev or fstate[fn]:
1213 if fn in prev or fstate[fn]:
1214 r = display(fn, rev, m, fstate[fn])
1214 r = display(fn, rev, m, fstate[fn])
1215 found = found or r
1215 found = found or r
1216 if r and not opts['all']:
1216 if r and not opts['all']:
1217 skip[fn] = True
1217 skip[fn] = True
1218 if copy:
1218 if copy:
1219 skip[copy] = True
1219 skip[copy] = True
1220 fstate[fn] = m
1220 fstate[fn] = m
1221 if copy:
1221 if copy:
1222 fstate[copy] = m
1222 fstate[copy] = m
1223 prev[fn] = rev
1223 prev[fn] = rev
1224
1224
1225 fstate = fstate.items()
1225 fstate = fstate.items()
1226 fstate.sort()
1226 fstate.sort()
1227 for fn, state in fstate:
1227 for fn, state in fstate:
1228 if fn in skip:
1228 if fn in skip:
1229 continue
1229 continue
1230 if fn not in copies.get(prev[fn], {}):
1230 if fn not in copies.get(prev[fn], {}):
1231 found = display(fn, rev, {}, state) or found
1231 found = display(fn, rev, {}, state) or found
1232 return (not found and 1) or 0
1232 return (not found and 1) or 0
1233
1233
1234 def heads(ui, repo, *branchrevs, **opts):
1234 def heads(ui, repo, *branchrevs, **opts):
1235 """show current repository heads or show branch heads
1235 """show current repository heads or show branch heads
1236
1236
1237 With no arguments, show all repository head changesets.
1237 With no arguments, show all repository head changesets.
1238
1238
1239 If branch or revisions names are given this will show the heads of
1239 If branch or revisions names are given this will show the heads of
1240 the specified branches or the branches those revisions are tagged
1240 the specified branches or the branches those revisions are tagged
1241 with.
1241 with.
1242
1242
1243 Repository "heads" are changesets that don't have child
1243 Repository "heads" are changesets that don't have child
1244 changesets. They are where development generally takes place and
1244 changesets. They are where development generally takes place and
1245 are the usual targets for update and merge operations.
1245 are the usual targets for update and merge operations.
1246
1246
1247 Branch heads are changesets that have a given branch tag, but have
1247 Branch heads are changesets that have a given branch tag, but have
1248 no child changesets with that tag. They are usually where
1248 no child changesets with that tag. They are usually where
1249 development on the given branch takes place.
1249 development on the given branch takes place.
1250 """
1250 """
1251 if opts['rev']:
1251 if opts['rev']:
1252 start = repo.lookup(opts['rev'])
1252 start = repo.lookup(opts['rev'])
1253 else:
1253 else:
1254 start = None
1254 start = None
1255 if not branchrevs:
1255 if not branchrevs:
1256 # Assume we're looking repo-wide heads if no revs were specified.
1256 # Assume we're looking repo-wide heads if no revs were specified.
1257 heads = repo.heads(start)
1257 heads = repo.heads(start)
1258 else:
1258 else:
1259 heads = []
1259 heads = []
1260 visitedset = util.set()
1260 visitedset = util.set()
1261 for branchrev in branchrevs:
1261 for branchrev in branchrevs:
1262 branch = repo.changectx(branchrev).branch()
1262 branch = repo.changectx(branchrev).branch()
1263 if branch in visitedset:
1263 if branch in visitedset:
1264 continue
1264 continue
1265 visitedset.add(branch)
1265 visitedset.add(branch)
1266 bheads = repo.branchheads(branch, start)
1266 bheads = repo.branchheads(branch, start)
1267 if not bheads:
1267 if not bheads:
1268 if branch != branchrev:
1268 if branch != branchrev:
1269 ui.warn(_("no changes on branch %s containing %s are "
1269 ui.warn(_("no changes on branch %s containing %s are "
1270 "reachable from %s\n")
1270 "reachable from %s\n")
1271 % (branch, branchrev, opts['rev']))
1271 % (branch, branchrev, opts['rev']))
1272 else:
1272 else:
1273 ui.warn(_("no changes on branch %s are reachable from %s\n")
1273 ui.warn(_("no changes on branch %s are reachable from %s\n")
1274 % (branch, opts['rev']))
1274 % (branch, opts['rev']))
1275 heads.extend(bheads)
1275 heads.extend(bheads)
1276 if not heads:
1276 if not heads:
1277 return 1
1277 return 1
1278 displayer = cmdutil.show_changeset(ui, repo, opts)
1278 displayer = cmdutil.show_changeset(ui, repo, opts)
1279 for n in heads:
1279 for n in heads:
1280 displayer.show(changenode=n)
1280 displayer.show(changenode=n)
1281
1281
1282 def help_(ui, name=None, with_version=False):
1282 def help_(ui, name=None, with_version=False):
1283 """show help for a command, extension, or list of commands
1283 """show help for a command, extension, or list of commands
1284
1284
1285 With no arguments, print a list of commands and short help.
1285 With no arguments, print a list of commands and short help.
1286
1286
1287 Given a command name, print help for that command.
1287 Given a command name, print help for that command.
1288
1288
1289 Given an extension name, print help for that extension, and the
1289 Given an extension name, print help for that extension, and the
1290 commands it provides."""
1290 commands it provides."""
1291 option_lists = []
1291 option_lists = []
1292
1292
1293 def addglobalopts(aliases):
1293 def addglobalopts(aliases):
1294 if ui.verbose:
1294 if ui.verbose:
1295 option_lists.append((_("global options:"), globalopts))
1295 option_lists.append((_("global options:"), globalopts))
1296 if name == 'shortlist':
1296 if name == 'shortlist':
1297 option_lists.append((_('use "hg help" for the full list '
1297 option_lists.append((_('use "hg help" for the full list '
1298 'of commands'), ()))
1298 'of commands'), ()))
1299 else:
1299 else:
1300 if name == 'shortlist':
1300 if name == 'shortlist':
1301 msg = _('use "hg help" for the full list of commands '
1301 msg = _('use "hg help" for the full list of commands '
1302 'or "hg -v" for details')
1302 'or "hg -v" for details')
1303 elif aliases:
1303 elif aliases:
1304 msg = _('use "hg -v help%s" to show aliases and '
1304 msg = _('use "hg -v help%s" to show aliases and '
1305 'global options') % (name and " " + name or "")
1305 'global options') % (name and " " + name or "")
1306 else:
1306 else:
1307 msg = _('use "hg -v help %s" to show global options') % name
1307 msg = _('use "hg -v help %s" to show global options') % name
1308 option_lists.append((msg, ()))
1308 option_lists.append((msg, ()))
1309
1309
1310 def helpcmd(name):
1310 def helpcmd(name):
1311 if with_version:
1311 if with_version:
1312 version_(ui)
1312 version_(ui)
1313 ui.write('\n')
1313 ui.write('\n')
1314 aliases, i = cmdutil.findcmd(ui, name, table)
1314 aliases, i = cmdutil.findcmd(ui, name, table)
1315 # synopsis
1315 # synopsis
1316 ui.write("%s\n\n" % i[2])
1316 ui.write("%s\n\n" % i[2])
1317
1317
1318 # description
1318 # description
1319 doc = i[0].__doc__
1319 doc = i[0].__doc__
1320 if not doc:
1320 if not doc:
1321 doc = _("(No help text available)")
1321 doc = _("(No help text available)")
1322 if ui.quiet:
1322 if ui.quiet:
1323 doc = doc.splitlines(0)[0]
1323 doc = doc.splitlines(0)[0]
1324 ui.write("%s\n" % doc.rstrip())
1324 ui.write("%s\n" % doc.rstrip())
1325
1325
1326 if not ui.quiet:
1326 if not ui.quiet:
1327 # aliases
1327 # aliases
1328 if len(aliases) > 1:
1328 if len(aliases) > 1:
1329 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1329 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1330
1330
1331 # options
1331 # options
1332 if i[1]:
1332 if i[1]:
1333 option_lists.append((_("options:\n"), i[1]))
1333 option_lists.append((_("options:\n"), i[1]))
1334
1334
1335 addglobalopts(False)
1335 addglobalopts(False)
1336
1336
1337 def helplist(header, select=None):
1337 def helplist(header, select=None):
1338 h = {}
1338 h = {}
1339 cmds = {}
1339 cmds = {}
1340 for c, e in table.items():
1340 for c, e in table.items():
1341 f = c.split("|", 1)[0]
1341 f = c.split("|", 1)[0]
1342 if select and not select(f):
1342 if select and not select(f):
1343 continue
1343 continue
1344 if name == "shortlist" and not f.startswith("^"):
1344 if name == "shortlist" and not f.startswith("^"):
1345 continue
1345 continue
1346 f = f.lstrip("^")
1346 f = f.lstrip("^")
1347 if not ui.debugflag and f.startswith("debug"):
1347 if not ui.debugflag and f.startswith("debug"):
1348 continue
1348 continue
1349 doc = e[0].__doc__
1349 doc = e[0].__doc__
1350 if not doc:
1350 if not doc:
1351 doc = _("(No help text available)")
1351 doc = _("(No help text available)")
1352 h[f] = doc.splitlines(0)[0].rstrip()
1352 h[f] = doc.splitlines(0)[0].rstrip()
1353 cmds[f] = c.lstrip("^")
1353 cmds[f] = c.lstrip("^")
1354
1354
1355 if not h:
1355 if not h:
1356 ui.status(_('no commands defined\n'))
1356 ui.status(_('no commands defined\n'))
1357 return
1357 return
1358
1358
1359 ui.status(header)
1359 ui.status(header)
1360 fns = h.keys()
1360 fns = h.keys()
1361 fns.sort()
1361 fns.sort()
1362 m = max(map(len, fns))
1362 m = max(map(len, fns))
1363 for f in fns:
1363 for f in fns:
1364 if ui.verbose:
1364 if ui.verbose:
1365 commands = cmds[f].replace("|",", ")
1365 commands = cmds[f].replace("|",", ")
1366 ui.write(" %s:\n %s\n"%(commands, h[f]))
1366 ui.write(" %s:\n %s\n"%(commands, h[f]))
1367 else:
1367 else:
1368 ui.write(' %-*s %s\n' % (m, f, h[f]))
1368 ui.write(' %-*s %s\n' % (m, f, h[f]))
1369
1369
1370 if not ui.quiet:
1370 if not ui.quiet:
1371 addglobalopts(True)
1371 addglobalopts(True)
1372
1372
1373 def helptopic(name):
1373 def helptopic(name):
1374 v = None
1374 v = None
1375 for i in help.helptable:
1375 for i in help.helptable:
1376 l = i.split('|')
1376 l = i.split('|')
1377 if name in l:
1377 if name in l:
1378 v = i
1378 v = i
1379 header = l[-1]
1379 header = l[-1]
1380 if not v:
1380 if not v:
1381 raise cmdutil.UnknownCommand(name)
1381 raise cmdutil.UnknownCommand(name)
1382
1382
1383 # description
1383 # description
1384 doc = help.helptable[v]
1384 doc = help.helptable[v]
1385 if not doc:
1385 if not doc:
1386 doc = _("(No help text available)")
1386 doc = _("(No help text available)")
1387 if callable(doc):
1387 if callable(doc):
1388 doc = doc()
1388 doc = doc()
1389
1389
1390 ui.write("%s\n" % header)
1390 ui.write("%s\n" % header)
1391 ui.write("%s\n" % doc.rstrip())
1391 ui.write("%s\n" % doc.rstrip())
1392
1392
1393 def helpext(name):
1393 def helpext(name):
1394 try:
1394 try:
1395 mod = extensions.find(name)
1395 mod = extensions.find(name)
1396 except KeyError:
1396 except KeyError:
1397 raise cmdutil.UnknownCommand(name)
1397 raise cmdutil.UnknownCommand(name)
1398
1398
1399 doc = (mod.__doc__ or _('No help text available')).splitlines(0)
1399 doc = (mod.__doc__ or _('No help text available')).splitlines(0)
1400 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
1400 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
1401 for d in doc[1:]:
1401 for d in doc[1:]:
1402 ui.write(d, '\n')
1402 ui.write(d, '\n')
1403
1403
1404 ui.status('\n')
1404 ui.status('\n')
1405
1405
1406 try:
1406 try:
1407 ct = mod.cmdtable
1407 ct = mod.cmdtable
1408 except AttributeError:
1408 except AttributeError:
1409 ct = {}
1409 ct = {}
1410
1410
1411 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in ct])
1411 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in ct])
1412 helplist(_('list of commands:\n\n'), modcmds.has_key)
1412 helplist(_('list of commands:\n\n'), modcmds.has_key)
1413
1413
1414 if name and name != 'shortlist':
1414 if name and name != 'shortlist':
1415 i = None
1415 i = None
1416 for f in (helpcmd, helptopic, helpext):
1416 for f in (helpcmd, helptopic, helpext):
1417 try:
1417 try:
1418 f(name)
1418 f(name)
1419 i = None
1419 i = None
1420 break
1420 break
1421 except cmdutil.UnknownCommand, inst:
1421 except cmdutil.UnknownCommand, inst:
1422 i = inst
1422 i = inst
1423 if i:
1423 if i:
1424 raise i
1424 raise i
1425
1425
1426 else:
1426 else:
1427 # program name
1427 # program name
1428 if ui.verbose or with_version:
1428 if ui.verbose or with_version:
1429 version_(ui)
1429 version_(ui)
1430 else:
1430 else:
1431 ui.status(_("Mercurial Distributed SCM\n"))
1431 ui.status(_("Mercurial Distributed SCM\n"))
1432 ui.status('\n')
1432 ui.status('\n')
1433
1433
1434 # list of commands
1434 # list of commands
1435 if name == "shortlist":
1435 if name == "shortlist":
1436 header = _('basic commands:\n\n')
1436 header = _('basic commands:\n\n')
1437 else:
1437 else:
1438 header = _('list of commands:\n\n')
1438 header = _('list of commands:\n\n')
1439
1439
1440 helplist(header)
1440 helplist(header)
1441
1441
1442 # list all option lists
1442 # list all option lists
1443 opt_output = []
1443 opt_output = []
1444 for title, options in option_lists:
1444 for title, options in option_lists:
1445 opt_output.append(("\n%s" % title, None))
1445 opt_output.append(("\n%s" % title, None))
1446 for shortopt, longopt, default, desc in options:
1446 for shortopt, longopt, default, desc in options:
1447 if "DEPRECATED" in desc and not ui.verbose: continue
1447 if "DEPRECATED" in desc and not ui.verbose: continue
1448 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1448 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1449 longopt and " --%s" % longopt),
1449 longopt and " --%s" % longopt),
1450 "%s%s" % (desc,
1450 "%s%s" % (desc,
1451 default
1451 default
1452 and _(" (default: %s)") % default
1452 and _(" (default: %s)") % default
1453 or "")))
1453 or "")))
1454
1454
1455 if opt_output:
1455 if opt_output:
1456 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1456 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1457 for first, second in opt_output:
1457 for first, second in opt_output:
1458 if second:
1458 if second:
1459 ui.write(" %-*s %s\n" % (opts_len, first, second))
1459 ui.write(" %-*s %s\n" % (opts_len, first, second))
1460 else:
1460 else:
1461 ui.write("%s\n" % first)
1461 ui.write("%s\n" % first)
1462
1462
1463 def identify(ui, repo, source=None,
1463 def identify(ui, repo, source=None,
1464 rev=None, num=None, id=None, branch=None, tags=None):
1464 rev=None, num=None, id=None, branch=None, tags=None):
1465 """identify the working copy or specified revision
1465 """identify the working copy or specified revision
1466
1466
1467 With no revision, print a summary of the current state of the repo.
1467 With no revision, print a summary of the current state of the repo.
1468
1468
1469 With a path, do a lookup in another repository.
1469 With a path, do a lookup in another repository.
1470
1470
1471 This summary identifies the repository state using one or two parent
1471 This summary identifies the repository state using one or two parent
1472 hash identifiers, followed by a "+" if there are uncommitted changes
1472 hash identifiers, followed by a "+" if there are uncommitted changes
1473 in the working directory, a list of tags for this revision and a branch
1473 in the working directory, a list of tags for this revision and a branch
1474 name for non-default branches.
1474 name for non-default branches.
1475 """
1475 """
1476
1476
1477 if not repo and not source:
1477 if not repo and not source:
1478 raise util.Abort(_("There is no Mercurial repository here "
1478 raise util.Abort(_("There is no Mercurial repository here "
1479 "(.hg not found)"))
1479 "(.hg not found)"))
1480
1480
1481 hexfunc = ui.debugflag and hex or short
1481 hexfunc = ui.debugflag and hex or short
1482 default = not (num or id or branch or tags)
1482 default = not (num or id or branch or tags)
1483 output = []
1483 output = []
1484
1484
1485 if source:
1485 if source:
1486 source, revs, checkout = hg.parseurl(ui.expandpath(source), [])
1486 source, revs, checkout = hg.parseurl(ui.expandpath(source), [])
1487 srepo = hg.repository(ui, source)
1487 srepo = hg.repository(ui, source)
1488 if not rev and revs:
1488 if not rev and revs:
1489 rev = revs[0]
1489 rev = revs[0]
1490 if not rev:
1490 if not rev:
1491 rev = "tip"
1491 rev = "tip"
1492 if num or branch or tags:
1492 if num or branch or tags:
1493 raise util.Abort(
1493 raise util.Abort(
1494 "can't query remote revision number, branch, or tags")
1494 "can't query remote revision number, branch, or tags")
1495 output = [hexfunc(srepo.lookup(rev))]
1495 output = [hexfunc(srepo.lookup(rev))]
1496 elif not rev:
1496 elif not rev:
1497 ctx = repo.workingctx()
1497 ctx = repo.workingctx()
1498 parents = ctx.parents()
1498 parents = ctx.parents()
1499 changed = False
1499 changed = False
1500 if default or id or num:
1500 if default or id or num:
1501 changed = ctx.files() + ctx.deleted()
1501 changed = ctx.files() + ctx.deleted()
1502 if default or id:
1502 if default or id:
1503 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1503 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1504 (changed) and "+" or "")]
1504 (changed) and "+" or "")]
1505 if num:
1505 if num:
1506 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1506 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1507 (changed) and "+" or ""))
1507 (changed) and "+" or ""))
1508 else:
1508 else:
1509 ctx = repo.changectx(rev)
1509 ctx = repo.changectx(rev)
1510 if default or id:
1510 if default or id:
1511 output = [hexfunc(ctx.node())]
1511 output = [hexfunc(ctx.node())]
1512 if num:
1512 if num:
1513 output.append(str(ctx.rev()))
1513 output.append(str(ctx.rev()))
1514
1514
1515 if not source and default and not ui.quiet:
1515 if not source and default and not ui.quiet:
1516 b = util.tolocal(ctx.branch())
1516 b = util.tolocal(ctx.branch())
1517 if b != 'default':
1517 if b != 'default':
1518 output.append("(%s)" % b)
1518 output.append("(%s)" % b)
1519
1519
1520 # multiple tags for a single parent separated by '/'
1520 # multiple tags for a single parent separated by '/'
1521 t = "/".join(ctx.tags())
1521 t = "/".join(ctx.tags())
1522 if t:
1522 if t:
1523 output.append(t)
1523 output.append(t)
1524
1524
1525 if branch:
1525 if branch:
1526 output.append(util.tolocal(ctx.branch()))
1526 output.append(util.tolocal(ctx.branch()))
1527
1527
1528 if tags:
1528 if tags:
1529 output.extend(ctx.tags())
1529 output.extend(ctx.tags())
1530
1530
1531 ui.write("%s\n" % ' '.join(output))
1531 ui.write("%s\n" % ' '.join(output))
1532
1532
1533 def import_(ui, repo, patch1, *patches, **opts):
1533 def import_(ui, repo, patch1, *patches, **opts):
1534 """import an ordered set of patches
1534 """import an ordered set of patches
1535
1535
1536 Import a list of patches and commit them individually.
1536 Import a list of patches and commit them individually.
1537
1537
1538 If there are outstanding changes in the working directory, import
1538 If there are outstanding changes in the working directory, import
1539 will abort unless given the -f flag.
1539 will abort unless given the -f flag.
1540
1540
1541 You can import a patch straight from a mail message. Even patches
1541 You can import a patch straight from a mail message. Even patches
1542 as attachments work (body part must be type text/plain or
1542 as attachments work (body part must be type text/plain or
1543 text/x-patch to be used). From and Subject headers of email
1543 text/x-patch to be used). From and Subject headers of email
1544 message are used as default committer and commit message. All
1544 message are used as default committer and commit message. All
1545 text/plain body parts before first diff are added to commit
1545 text/plain body parts before first diff are added to commit
1546 message.
1546 message.
1547
1547
1548 If the imported patch was generated by hg export, user and description
1548 If the imported patch was generated by hg export, user and description
1549 from patch override values from message headers and body. Values
1549 from patch override values from message headers and body. Values
1550 given on command line with -m and -u override these.
1550 given on command line with -m and -u override these.
1551
1551
1552 If --exact is specified, import will set the working directory
1552 If --exact is specified, import will set the working directory
1553 to the parent of each patch before applying it, and will abort
1553 to the parent of each patch before applying it, and will abort
1554 if the resulting changeset has a different ID than the one
1554 if the resulting changeset has a different ID than the one
1555 recorded in the patch. This may happen due to character set
1555 recorded in the patch. This may happen due to character set
1556 problems or other deficiencies in the text patch format.
1556 problems or other deficiencies in the text patch format.
1557
1557
1558 To read a patch from standard input, use patch name "-".
1558 To read a patch from standard input, use patch name "-".
1559 """
1559 """
1560 patches = (patch1,) + patches
1560 patches = (patch1,) + patches
1561
1561
1562 if opts.get('exact') or not opts['force']:
1562 if opts.get('exact') or not opts['force']:
1563 cmdutil.bail_if_changed(repo)
1563 cmdutil.bail_if_changed(repo)
1564
1564
1565 d = opts["base"]
1565 d = opts["base"]
1566 strip = opts["strip"]
1566 strip = opts["strip"]
1567 wlock = lock = None
1567 wlock = lock = None
1568 try:
1568 try:
1569 wlock = repo.wlock()
1569 wlock = repo.wlock()
1570 lock = repo.lock()
1570 lock = repo.lock()
1571 for p in patches:
1571 for p in patches:
1572 pf = os.path.join(d, p)
1572 pf = os.path.join(d, p)
1573
1573
1574 if pf == '-':
1574 if pf == '-':
1575 ui.status(_("applying patch from stdin\n"))
1575 ui.status(_("applying patch from stdin\n"))
1576 data = patch.extract(ui, sys.stdin)
1576 data = patch.extract(ui, sys.stdin)
1577 else:
1577 else:
1578 ui.status(_("applying %s\n") % p)
1578 ui.status(_("applying %s\n") % p)
1579 if os.path.exists(pf):
1579 if os.path.exists(pf):
1580 data = patch.extract(ui, file(pf, 'rb'))
1580 data = patch.extract(ui, file(pf, 'rb'))
1581 else:
1581 else:
1582 data = patch.extract(ui, urllib.urlopen(pf))
1582 data = patch.extract(ui, urllib.urlopen(pf))
1583 tmpname, message, user, date, branch, nodeid, p1, p2 = data
1583 tmpname, message, user, date, branch, nodeid, p1, p2 = data
1584
1584
1585 if tmpname is None:
1585 if tmpname is None:
1586 raise util.Abort(_('no diffs found'))
1586 raise util.Abort(_('no diffs found'))
1587
1587
1588 try:
1588 try:
1589 cmdline_message = cmdutil.logmessage(opts)
1589 cmdline_message = cmdutil.logmessage(opts)
1590 if cmdline_message:
1590 if cmdline_message:
1591 # pickup the cmdline msg
1591 # pickup the cmdline msg
1592 message = cmdline_message
1592 message = cmdline_message
1593 elif message:
1593 elif message:
1594 # pickup the patch msg
1594 # pickup the patch msg
1595 message = message.strip()
1595 message = message.strip()
1596 else:
1596 else:
1597 # launch the editor
1597 # launch the editor
1598 message = None
1598 message = None
1599 ui.debug(_('message:\n%s\n') % message)
1599 ui.debug(_('message:\n%s\n') % message)
1600
1600
1601 wp = repo.workingctx().parents()
1601 wp = repo.workingctx().parents()
1602 if opts.get('exact'):
1602 if opts.get('exact'):
1603 if not nodeid or not p1:
1603 if not nodeid or not p1:
1604 raise util.Abort(_('not a mercurial patch'))
1604 raise util.Abort(_('not a mercurial patch'))
1605 p1 = repo.lookup(p1)
1605 p1 = repo.lookup(p1)
1606 p2 = repo.lookup(p2 or hex(nullid))
1606 p2 = repo.lookup(p2 or hex(nullid))
1607
1607
1608 if p1 != wp[0].node():
1608 if p1 != wp[0].node():
1609 hg.clean(repo, p1)
1609 hg.clean(repo, p1)
1610 repo.dirstate.setparents(p1, p2)
1610 repo.dirstate.setparents(p1, p2)
1611 elif p2:
1611 elif p2:
1612 try:
1612 try:
1613 p1 = repo.lookup(p1)
1613 p1 = repo.lookup(p1)
1614 p2 = repo.lookup(p2)
1614 p2 = repo.lookup(p2)
1615 if p1 == wp[0].node():
1615 if p1 == wp[0].node():
1616 repo.dirstate.setparents(p1, p2)
1616 repo.dirstate.setparents(p1, p2)
1617 except hg.RepoError:
1617 except hg.RepoError:
1618 pass
1618 pass
1619 if opts.get('exact') or opts.get('import_branch'):
1619 if opts.get('exact') or opts.get('import_branch'):
1620 repo.dirstate.setbranch(branch or 'default')
1620 repo.dirstate.setbranch(branch or 'default')
1621
1621
1622 files = {}
1622 files = {}
1623 try:
1623 try:
1624 fuzz = patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1624 fuzz = patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1625 files=files)
1625 files=files)
1626 finally:
1626 finally:
1627 files = patch.updatedir(ui, repo, files)
1627 files = patch.updatedir(ui, repo, files)
1628 n = repo.commit(files, message, user, date)
1628 n = repo.commit(files, message, user, date)
1629 if opts.get('exact'):
1629 if opts.get('exact'):
1630 if hex(n) != nodeid:
1630 if hex(n) != nodeid:
1631 repo.rollback()
1631 repo.rollback()
1632 raise util.Abort(_('patch is damaged' +
1632 raise util.Abort(_('patch is damaged' +
1633 ' or loses information'))
1633 ' or loses information'))
1634 finally:
1634 finally:
1635 os.unlink(tmpname)
1635 os.unlink(tmpname)
1636 finally:
1636 finally:
1637 del lock, wlock
1637 del lock, wlock
1638
1638
1639 def incoming(ui, repo, source="default", **opts):
1639 def incoming(ui, repo, source="default", **opts):
1640 """show new changesets found in source
1640 """show new changesets found in source
1641
1641
1642 Show new changesets found in the specified path/URL or the default
1642 Show new changesets found in the specified path/URL or the default
1643 pull location. These are the changesets that would be pulled if a pull
1643 pull location. These are the changesets that would be pulled if a pull
1644 was requested.
1644 was requested.
1645
1645
1646 For remote repository, using --bundle avoids downloading the changesets
1646 For remote repository, using --bundle avoids downloading the changesets
1647 twice if the incoming is followed by a pull.
1647 twice if the incoming is followed by a pull.
1648
1648
1649 See pull for valid source format details.
1649 See pull for valid source format details.
1650 """
1650 """
1651 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
1651 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
1652 cmdutil.setremoteconfig(ui, opts)
1652 cmdutil.setremoteconfig(ui, opts)
1653
1653
1654 other = hg.repository(ui, source)
1654 other = hg.repository(ui, source)
1655 ui.status(_('comparing with %s\n') % source)
1655 ui.status(_('comparing with %s\n') % util.hidepassword(source))
1656 if revs:
1656 if revs:
1657 revs = [other.lookup(rev) for rev in revs]
1657 revs = [other.lookup(rev) for rev in revs]
1658 incoming = repo.findincoming(other, heads=revs, force=opts["force"])
1658 incoming = repo.findincoming(other, heads=revs, force=opts["force"])
1659 if not incoming:
1659 if not incoming:
1660 try:
1660 try:
1661 os.unlink(opts["bundle"])
1661 os.unlink(opts["bundle"])
1662 except:
1662 except:
1663 pass
1663 pass
1664 ui.status(_("no changes found\n"))
1664 ui.status(_("no changes found\n"))
1665 return 1
1665 return 1
1666
1666
1667 cleanup = None
1667 cleanup = None
1668 try:
1668 try:
1669 fname = opts["bundle"]
1669 fname = opts["bundle"]
1670 if fname or not other.local():
1670 if fname or not other.local():
1671 # create a bundle (uncompressed if other repo is not local)
1671 # create a bundle (uncompressed if other repo is not local)
1672 if revs is None:
1672 if revs is None:
1673 cg = other.changegroup(incoming, "incoming")
1673 cg = other.changegroup(incoming, "incoming")
1674 else:
1674 else:
1675 cg = other.changegroupsubset(incoming, revs, 'incoming')
1675 cg = other.changegroupsubset(incoming, revs, 'incoming')
1676 bundletype = other.local() and "HG10BZ" or "HG10UN"
1676 bundletype = other.local() and "HG10BZ" or "HG10UN"
1677 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
1677 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
1678 # keep written bundle?
1678 # keep written bundle?
1679 if opts["bundle"]:
1679 if opts["bundle"]:
1680 cleanup = None
1680 cleanup = None
1681 if not other.local():
1681 if not other.local():
1682 # use the created uncompressed bundlerepo
1682 # use the created uncompressed bundlerepo
1683 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1683 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1684
1684
1685 o = other.changelog.nodesbetween(incoming, revs)[0]
1685 o = other.changelog.nodesbetween(incoming, revs)[0]
1686 if opts['newest_first']:
1686 if opts['newest_first']:
1687 o.reverse()
1687 o.reverse()
1688 displayer = cmdutil.show_changeset(ui, other, opts)
1688 displayer = cmdutil.show_changeset(ui, other, opts)
1689 for n in o:
1689 for n in o:
1690 parents = [p for p in other.changelog.parents(n) if p != nullid]
1690 parents = [p for p in other.changelog.parents(n) if p != nullid]
1691 if opts['no_merges'] and len(parents) == 2:
1691 if opts['no_merges'] and len(parents) == 2:
1692 continue
1692 continue
1693 displayer.show(changenode=n)
1693 displayer.show(changenode=n)
1694 finally:
1694 finally:
1695 if hasattr(other, 'close'):
1695 if hasattr(other, 'close'):
1696 other.close()
1696 other.close()
1697 if cleanup:
1697 if cleanup:
1698 os.unlink(cleanup)
1698 os.unlink(cleanup)
1699
1699
1700 def init(ui, dest=".", **opts):
1700 def init(ui, dest=".", **opts):
1701 """create a new repository in the given directory
1701 """create a new repository in the given directory
1702
1702
1703 Initialize a new repository in the given directory. If the given
1703 Initialize a new repository in the given directory. If the given
1704 directory does not exist, it is created.
1704 directory does not exist, it is created.
1705
1705
1706 If no directory is given, the current directory is used.
1706 If no directory is given, the current directory is used.
1707
1707
1708 It is possible to specify an ssh:// URL as the destination.
1708 It is possible to specify an ssh:// URL as the destination.
1709 Look at the help text for the pull command for important details
1709 Look at the help text for the pull command for important details
1710 about ssh:// URLs.
1710 about ssh:// URLs.
1711 """
1711 """
1712 cmdutil.setremoteconfig(ui, opts)
1712 cmdutil.setremoteconfig(ui, opts)
1713 hg.repository(ui, dest, create=1)
1713 hg.repository(ui, dest, create=1)
1714
1714
1715 def locate(ui, repo, *pats, **opts):
1715 def locate(ui, repo, *pats, **opts):
1716 """locate files matching specific patterns
1716 """locate files matching specific patterns
1717
1717
1718 Print all files under Mercurial control whose names match the
1718 Print all files under Mercurial control whose names match the
1719 given patterns.
1719 given patterns.
1720
1720
1721 This command searches the entire repository by default. To search
1721 This command searches the entire repository by default. To search
1722 just the current directory and its subdirectories, use
1722 just the current directory and its subdirectories, use
1723 "--include .".
1723 "--include .".
1724
1724
1725 If no patterns are given to match, this command prints all file
1725 If no patterns are given to match, this command prints all file
1726 names.
1726 names.
1727
1727
1728 If you want to feed the output of this command into the "xargs"
1728 If you want to feed the output of this command into the "xargs"
1729 command, use the "-0" option to both this command and "xargs".
1729 command, use the "-0" option to both this command and "xargs".
1730 This will avoid the problem of "xargs" treating single filenames
1730 This will avoid the problem of "xargs" treating single filenames
1731 that contain white space as multiple filenames.
1731 that contain white space as multiple filenames.
1732 """
1732 """
1733 end = opts['print0'] and '\0' or '\n'
1733 end = opts['print0'] and '\0' or '\n'
1734 rev = opts['rev']
1734 rev = opts['rev']
1735 if rev:
1735 if rev:
1736 node = repo.lookup(rev)
1736 node = repo.lookup(rev)
1737 else:
1737 else:
1738 node = None
1738 node = None
1739
1739
1740 ret = 1
1740 ret = 1
1741 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
1741 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
1742 badmatch=util.always,
1742 badmatch=util.always,
1743 default='relglob'):
1743 default='relglob'):
1744 if src == 'b':
1744 if src == 'b':
1745 continue
1745 continue
1746 if not node and abs not in repo.dirstate:
1746 if not node and abs not in repo.dirstate:
1747 continue
1747 continue
1748 if opts['fullpath']:
1748 if opts['fullpath']:
1749 ui.write(os.path.join(repo.root, abs), end)
1749 ui.write(os.path.join(repo.root, abs), end)
1750 else:
1750 else:
1751 ui.write(((pats and rel) or abs), end)
1751 ui.write(((pats and rel) or abs), end)
1752 ret = 0
1752 ret = 0
1753
1753
1754 return ret
1754 return ret
1755
1755
1756 def log(ui, repo, *pats, **opts):
1756 def log(ui, repo, *pats, **opts):
1757 """show revision history of entire repository or files
1757 """show revision history of entire repository or files
1758
1758
1759 Print the revision history of the specified files or the entire
1759 Print the revision history of the specified files or the entire
1760 project.
1760 project.
1761
1761
1762 File history is shown without following rename or copy history of
1762 File history is shown without following rename or copy history of
1763 files. Use -f/--follow with a file name to follow history across
1763 files. Use -f/--follow with a file name to follow history across
1764 renames and copies. --follow without a file name will only show
1764 renames and copies. --follow without a file name will only show
1765 ancestors or descendants of the starting revision. --follow-first
1765 ancestors or descendants of the starting revision. --follow-first
1766 only follows the first parent of merge revisions.
1766 only follows the first parent of merge revisions.
1767
1767
1768 If no revision range is specified, the default is tip:0 unless
1768 If no revision range is specified, the default is tip:0 unless
1769 --follow is set, in which case the working directory parent is
1769 --follow is set, in which case the working directory parent is
1770 used as the starting revision.
1770 used as the starting revision.
1771
1771
1772 By default this command outputs: changeset id and hash, tags,
1772 By default this command outputs: changeset id and hash, tags,
1773 non-trivial parents, user, date and time, and a summary for each
1773 non-trivial parents, user, date and time, and a summary for each
1774 commit. When the -v/--verbose switch is used, the list of changed
1774 commit. When the -v/--verbose switch is used, the list of changed
1775 files and full commit message is shown.
1775 files and full commit message is shown.
1776
1776
1777 NOTE: log -p may generate unexpected diff output for merge
1777 NOTE: log -p may generate unexpected diff output for merge
1778 changesets, as it will compare the merge changeset against its
1778 changesets, as it will compare the merge changeset against its
1779 first parent only. Also, the files: list will only reflect files
1779 first parent only. Also, the files: list will only reflect files
1780 that are different from BOTH parents.
1780 that are different from BOTH parents.
1781
1781
1782 """
1782 """
1783
1783
1784 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1784 get = util.cachefunc(lambda r: repo.changectx(r).changeset())
1785 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1785 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1786
1786
1787 if opts['limit']:
1787 if opts['limit']:
1788 try:
1788 try:
1789 limit = int(opts['limit'])
1789 limit = int(opts['limit'])
1790 except ValueError:
1790 except ValueError:
1791 raise util.Abort(_('limit must be a positive integer'))
1791 raise util.Abort(_('limit must be a positive integer'))
1792 if limit <= 0: raise util.Abort(_('limit must be positive'))
1792 if limit <= 0: raise util.Abort(_('limit must be positive'))
1793 else:
1793 else:
1794 limit = sys.maxint
1794 limit = sys.maxint
1795 count = 0
1795 count = 0
1796
1796
1797 if opts['copies'] and opts['rev']:
1797 if opts['copies'] and opts['rev']:
1798 endrev = max(cmdutil.revrange(repo, opts['rev'])) + 1
1798 endrev = max(cmdutil.revrange(repo, opts['rev'])) + 1
1799 else:
1799 else:
1800 endrev = repo.changelog.count()
1800 endrev = repo.changelog.count()
1801 rcache = {}
1801 rcache = {}
1802 ncache = {}
1802 ncache = {}
1803 dcache = []
1803 dcache = []
1804 def getrenamed(fn, rev, man):
1804 def getrenamed(fn, rev, man):
1805 '''looks up all renames for a file (up to endrev) the first
1805 '''looks up all renames for a file (up to endrev) the first
1806 time the file is given. It indexes on the changerev and only
1806 time the file is given. It indexes on the changerev and only
1807 parses the manifest if linkrev != changerev.
1807 parses the manifest if linkrev != changerev.
1808 Returns rename info for fn at changerev rev.'''
1808 Returns rename info for fn at changerev rev.'''
1809 if fn not in rcache:
1809 if fn not in rcache:
1810 rcache[fn] = {}
1810 rcache[fn] = {}
1811 ncache[fn] = {}
1811 ncache[fn] = {}
1812 fl = repo.file(fn)
1812 fl = repo.file(fn)
1813 for i in xrange(fl.count()):
1813 for i in xrange(fl.count()):
1814 node = fl.node(i)
1814 node = fl.node(i)
1815 lr = fl.linkrev(node)
1815 lr = fl.linkrev(node)
1816 renamed = fl.renamed(node)
1816 renamed = fl.renamed(node)
1817 rcache[fn][lr] = renamed
1817 rcache[fn][lr] = renamed
1818 if renamed:
1818 if renamed:
1819 ncache[fn][node] = renamed
1819 ncache[fn][node] = renamed
1820 if lr >= endrev:
1820 if lr >= endrev:
1821 break
1821 break
1822 if rev in rcache[fn]:
1822 if rev in rcache[fn]:
1823 return rcache[fn][rev]
1823 return rcache[fn][rev]
1824 mr = repo.manifest.rev(man)
1824 mr = repo.manifest.rev(man)
1825 if repo.manifest.parentrevs(mr) != (mr - 1, nullrev):
1825 if repo.manifest.parentrevs(mr) != (mr - 1, nullrev):
1826 return ncache[fn].get(repo.manifest.find(man, fn)[0])
1826 return ncache[fn].get(repo.manifest.find(man, fn)[0])
1827 if not dcache or dcache[0] != man:
1827 if not dcache or dcache[0] != man:
1828 dcache[:] = [man, repo.manifest.readdelta(man)]
1828 dcache[:] = [man, repo.manifest.readdelta(man)]
1829 if fn in dcache[1]:
1829 if fn in dcache[1]:
1830 return ncache[fn].get(dcache[1][fn])
1830 return ncache[fn].get(dcache[1][fn])
1831 return None
1831 return None
1832
1832
1833 df = False
1833 df = False
1834 if opts["date"]:
1834 if opts["date"]:
1835 df = util.matchdate(opts["date"])
1835 df = util.matchdate(opts["date"])
1836
1836
1837 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
1837 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
1838 for st, rev, fns in changeiter:
1838 for st, rev, fns in changeiter:
1839 if st == 'add':
1839 if st == 'add':
1840 changenode = repo.changelog.node(rev)
1840 changenode = repo.changelog.node(rev)
1841 parents = [p for p in repo.changelog.parentrevs(rev)
1841 parents = [p for p in repo.changelog.parentrevs(rev)
1842 if p != nullrev]
1842 if p != nullrev]
1843 if opts['no_merges'] and len(parents) == 2:
1843 if opts['no_merges'] and len(parents) == 2:
1844 continue
1844 continue
1845 if opts['only_merges'] and len(parents) != 2:
1845 if opts['only_merges'] and len(parents) != 2:
1846 continue
1846 continue
1847
1847
1848 if df:
1848 if df:
1849 changes = get(rev)
1849 changes = get(rev)
1850 if not df(changes[2][0]):
1850 if not df(changes[2][0]):
1851 continue
1851 continue
1852
1852
1853 if opts['keyword']:
1853 if opts['keyword']:
1854 changes = get(rev)
1854 changes = get(rev)
1855 miss = 0
1855 miss = 0
1856 for k in [kw.lower() for kw in opts['keyword']]:
1856 for k in [kw.lower() for kw in opts['keyword']]:
1857 if not (k in changes[1].lower() or
1857 if not (k in changes[1].lower() or
1858 k in changes[4].lower() or
1858 k in changes[4].lower() or
1859 k in " ".join(changes[3]).lower()):
1859 k in " ".join(changes[3]).lower()):
1860 miss = 1
1860 miss = 1
1861 break
1861 break
1862 if miss:
1862 if miss:
1863 continue
1863 continue
1864
1864
1865 copies = []
1865 copies = []
1866 if opts.get('copies') and rev:
1866 if opts.get('copies') and rev:
1867 mf = get(rev)[0]
1867 mf = get(rev)[0]
1868 for fn in get(rev)[3]:
1868 for fn in get(rev)[3]:
1869 rename = getrenamed(fn, rev, mf)
1869 rename = getrenamed(fn, rev, mf)
1870 if rename:
1870 if rename:
1871 copies.append((fn, rename[0]))
1871 copies.append((fn, rename[0]))
1872 displayer.show(rev, changenode, copies=copies)
1872 displayer.show(rev, changenode, copies=copies)
1873 elif st == 'iter':
1873 elif st == 'iter':
1874 if count == limit: break
1874 if count == limit: break
1875 if displayer.flush(rev):
1875 if displayer.flush(rev):
1876 count += 1
1876 count += 1
1877
1877
1878 def manifest(ui, repo, node=None, rev=None):
1878 def manifest(ui, repo, node=None, rev=None):
1879 """output the current or given revision of the project manifest
1879 """output the current or given revision of the project manifest
1880
1880
1881 Print a list of version controlled files for the given revision.
1881 Print a list of version controlled files for the given revision.
1882 If no revision is given, the parent of the working directory is used,
1882 If no revision is given, the parent of the working directory is used,
1883 or tip if no revision is checked out.
1883 or tip if no revision is checked out.
1884
1884
1885 The manifest is the list of files being version controlled. If no revision
1885 The manifest is the list of files being version controlled. If no revision
1886 is given then the first parent of the working directory is used.
1886 is given then the first parent of the working directory is used.
1887
1887
1888 With -v flag, print file permissions, symlink and executable bits. With
1888 With -v flag, print file permissions, symlink and executable bits. With
1889 --debug flag, print file revision hashes.
1889 --debug flag, print file revision hashes.
1890 """
1890 """
1891
1891
1892 if rev and node:
1892 if rev and node:
1893 raise util.Abort(_("please specify just one revision"))
1893 raise util.Abort(_("please specify just one revision"))
1894
1894
1895 if not node:
1895 if not node:
1896 node = rev
1896 node = rev
1897
1897
1898 m = repo.changectx(node).manifest()
1898 m = repo.changectx(node).manifest()
1899 files = m.keys()
1899 files = m.keys()
1900 files.sort()
1900 files.sort()
1901
1901
1902 for f in files:
1902 for f in files:
1903 if ui.debugflag:
1903 if ui.debugflag:
1904 ui.write("%40s " % hex(m[f]))
1904 ui.write("%40s " % hex(m[f]))
1905 if ui.verbose:
1905 if ui.verbose:
1906 type = m.execf(f) and "*" or m.linkf(f) and "@" or " "
1906 type = m.execf(f) and "*" or m.linkf(f) and "@" or " "
1907 perm = m.execf(f) and "755" or "644"
1907 perm = m.execf(f) and "755" or "644"
1908 ui.write("%3s %1s " % (perm, type))
1908 ui.write("%3s %1s " % (perm, type))
1909 ui.write("%s\n" % f)
1909 ui.write("%s\n" % f)
1910
1910
1911 def merge(ui, repo, node=None, force=None, rev=None):
1911 def merge(ui, repo, node=None, force=None, rev=None):
1912 """merge working directory with another revision
1912 """merge working directory with another revision
1913
1913
1914 Merge the contents of the current working directory and the
1914 Merge the contents of the current working directory and the
1915 requested revision. Files that changed between either parent are
1915 requested revision. Files that changed between either parent are
1916 marked as changed for the next commit and a commit must be
1916 marked as changed for the next commit and a commit must be
1917 performed before any further updates are allowed.
1917 performed before any further updates are allowed.
1918
1918
1919 If no revision is specified, the working directory's parent is a
1919 If no revision is specified, the working directory's parent is a
1920 head revision, and the repository contains exactly one other head,
1920 head revision, and the repository contains exactly one other head,
1921 the other head is merged with by default. Otherwise, an explicit
1921 the other head is merged with by default. Otherwise, an explicit
1922 revision to merge with must be provided.
1922 revision to merge with must be provided.
1923 """
1923 """
1924
1924
1925 if rev and node:
1925 if rev and node:
1926 raise util.Abort(_("please specify just one revision"))
1926 raise util.Abort(_("please specify just one revision"))
1927 if not node:
1927 if not node:
1928 node = rev
1928 node = rev
1929
1929
1930 if not node:
1930 if not node:
1931 heads = repo.heads()
1931 heads = repo.heads()
1932 if len(heads) > 2:
1932 if len(heads) > 2:
1933 raise util.Abort(_('repo has %d heads - '
1933 raise util.Abort(_('repo has %d heads - '
1934 'please merge with an explicit rev') %
1934 'please merge with an explicit rev') %
1935 len(heads))
1935 len(heads))
1936 parent = repo.dirstate.parents()[0]
1936 parent = repo.dirstate.parents()[0]
1937 if len(heads) == 1:
1937 if len(heads) == 1:
1938 msg = _('there is nothing to merge')
1938 msg = _('there is nothing to merge')
1939 if parent != repo.lookup(repo.workingctx().branch()):
1939 if parent != repo.lookup(repo.workingctx().branch()):
1940 msg = _('%s - use "hg update" instead' % msg)
1940 msg = _('%s - use "hg update" instead' % msg)
1941 raise util.Abort(msg)
1941 raise util.Abort(msg)
1942
1942
1943 if parent not in heads:
1943 if parent not in heads:
1944 raise util.Abort(_('working dir not at a head rev - '
1944 raise util.Abort(_('working dir not at a head rev - '
1945 'use "hg update" or merge with an explicit rev'))
1945 'use "hg update" or merge with an explicit rev'))
1946 node = parent == heads[0] and heads[-1] or heads[0]
1946 node = parent == heads[0] and heads[-1] or heads[0]
1947 return hg.merge(repo, node, force=force)
1947 return hg.merge(repo, node, force=force)
1948
1948
1949 def outgoing(ui, repo, dest=None, **opts):
1949 def outgoing(ui, repo, dest=None, **opts):
1950 """show changesets not found in destination
1950 """show changesets not found in destination
1951
1951
1952 Show changesets not found in the specified destination repository or
1952 Show changesets not found in the specified destination repository or
1953 the default push location. These are the changesets that would be pushed
1953 the default push location. These are the changesets that would be pushed
1954 if a push was requested.
1954 if a push was requested.
1955
1955
1956 See pull for valid destination format details.
1956 See pull for valid destination format details.
1957 """
1957 """
1958 dest, revs, checkout = hg.parseurl(
1958 dest, revs, checkout = hg.parseurl(
1959 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
1959 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
1960 cmdutil.setremoteconfig(ui, opts)
1960 cmdutil.setremoteconfig(ui, opts)
1961 if revs:
1961 if revs:
1962 revs = [repo.lookup(rev) for rev in revs]
1962 revs = [repo.lookup(rev) for rev in revs]
1963
1963
1964 other = hg.repository(ui, dest)
1964 other = hg.repository(ui, dest)
1965 ui.status(_('comparing with %s\n') % dest)
1965 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
1966 o = repo.findoutgoing(other, force=opts['force'])
1966 o = repo.findoutgoing(other, force=opts['force'])
1967 if not o:
1967 if not o:
1968 ui.status(_("no changes found\n"))
1968 ui.status(_("no changes found\n"))
1969 return 1
1969 return 1
1970 o = repo.changelog.nodesbetween(o, revs)[0]
1970 o = repo.changelog.nodesbetween(o, revs)[0]
1971 if opts['newest_first']:
1971 if opts['newest_first']:
1972 o.reverse()
1972 o.reverse()
1973 displayer = cmdutil.show_changeset(ui, repo, opts)
1973 displayer = cmdutil.show_changeset(ui, repo, opts)
1974 for n in o:
1974 for n in o:
1975 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1975 parents = [p for p in repo.changelog.parents(n) if p != nullid]
1976 if opts['no_merges'] and len(parents) == 2:
1976 if opts['no_merges'] and len(parents) == 2:
1977 continue
1977 continue
1978 displayer.show(changenode=n)
1978 displayer.show(changenode=n)
1979
1979
1980 def parents(ui, repo, file_=None, **opts):
1980 def parents(ui, repo, file_=None, **opts):
1981 """show the parents of the working dir or revision
1981 """show the parents of the working dir or revision
1982
1982
1983 Print the working directory's parent revisions. If a
1983 Print the working directory's parent revisions. If a
1984 revision is given via --rev, the parent of that revision
1984 revision is given via --rev, the parent of that revision
1985 will be printed. If a file argument is given, revision in
1985 will be printed. If a file argument is given, revision in
1986 which the file was last changed (before the working directory
1986 which the file was last changed (before the working directory
1987 revision or the argument to --rev if given) is printed.
1987 revision or the argument to --rev if given) is printed.
1988 """
1988 """
1989 rev = opts.get('rev')
1989 rev = opts.get('rev')
1990 if rev:
1990 if rev:
1991 ctx = repo.changectx(rev)
1991 ctx = repo.changectx(rev)
1992 else:
1992 else:
1993 ctx = repo.workingctx()
1993 ctx = repo.workingctx()
1994
1994
1995 if file_:
1995 if file_:
1996 files, match, anypats = cmdutil.matchpats(repo, (file_,), opts)
1996 files, match, anypats = cmdutil.matchpats(repo, (file_,), opts)
1997 if anypats or len(files) != 1:
1997 if anypats or len(files) != 1:
1998 raise util.Abort(_('can only specify an explicit file name'))
1998 raise util.Abort(_('can only specify an explicit file name'))
1999 file_ = files[0]
1999 file_ = files[0]
2000 filenodes = []
2000 filenodes = []
2001 for cp in ctx.parents():
2001 for cp in ctx.parents():
2002 if not cp:
2002 if not cp:
2003 continue
2003 continue
2004 try:
2004 try:
2005 filenodes.append(cp.filenode(file_))
2005 filenodes.append(cp.filenode(file_))
2006 except revlog.LookupError:
2006 except revlog.LookupError:
2007 pass
2007 pass
2008 if not filenodes:
2008 if not filenodes:
2009 raise util.Abort(_("'%s' not found in manifest!") % file_)
2009 raise util.Abort(_("'%s' not found in manifest!") % file_)
2010 fl = repo.file(file_)
2010 fl = repo.file(file_)
2011 p = [repo.lookup(fl.linkrev(fn)) for fn in filenodes]
2011 p = [repo.lookup(fl.linkrev(fn)) for fn in filenodes]
2012 else:
2012 else:
2013 p = [cp.node() for cp in ctx.parents()]
2013 p = [cp.node() for cp in ctx.parents()]
2014
2014
2015 displayer = cmdutil.show_changeset(ui, repo, opts)
2015 displayer = cmdutil.show_changeset(ui, repo, opts)
2016 for n in p:
2016 for n in p:
2017 if n != nullid:
2017 if n != nullid:
2018 displayer.show(changenode=n)
2018 displayer.show(changenode=n)
2019
2019
2020 def paths(ui, repo, search=None):
2020 def paths(ui, repo, search=None):
2021 """show definition of symbolic path names
2021 """show definition of symbolic path names
2022
2022
2023 Show definition of symbolic path name NAME. If no name is given, show
2023 Show definition of symbolic path name NAME. If no name is given, show
2024 definition of available names.
2024 definition of available names.
2025
2025
2026 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2026 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2027 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2027 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2028 """
2028 """
2029 if search:
2029 if search:
2030 for name, path in ui.configitems("paths"):
2030 for name, path in ui.configitems("paths"):
2031 if name == search:
2031 if name == search:
2032 ui.write("%s\n" % path)
2032 ui.write("%s\n" % path)
2033 return
2033 return
2034 ui.warn(_("not found!\n"))
2034 ui.warn(_("not found!\n"))
2035 return 1
2035 return 1
2036 else:
2036 else:
2037 for name, path in ui.configitems("paths"):
2037 for name, path in ui.configitems("paths"):
2038 ui.write("%s = %s\n" % (name, path))
2038 ui.write("%s = %s\n" % (name, path))
2039
2039
2040 def postincoming(ui, repo, modheads, optupdate, checkout):
2040 def postincoming(ui, repo, modheads, optupdate, checkout):
2041 if modheads == 0:
2041 if modheads == 0:
2042 return
2042 return
2043 if optupdate:
2043 if optupdate:
2044 if modheads <= 1 or checkout:
2044 if modheads <= 1 or checkout:
2045 return hg.update(repo, checkout)
2045 return hg.update(repo, checkout)
2046 else:
2046 else:
2047 ui.status(_("not updating, since new heads added\n"))
2047 ui.status(_("not updating, since new heads added\n"))
2048 if modheads > 1:
2048 if modheads > 1:
2049 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2049 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2050 else:
2050 else:
2051 ui.status(_("(run 'hg update' to get a working copy)\n"))
2051 ui.status(_("(run 'hg update' to get a working copy)\n"))
2052
2052
2053 def pull(ui, repo, source="default", **opts):
2053 def pull(ui, repo, source="default", **opts):
2054 """pull changes from the specified source
2054 """pull changes from the specified source
2055
2055
2056 Pull changes from a remote repository to a local one.
2056 Pull changes from a remote repository to a local one.
2057
2057
2058 This finds all changes from the repository at the specified path
2058 This finds all changes from the repository at the specified path
2059 or URL and adds them to the local repository. By default, this
2059 or URL and adds them to the local repository. By default, this
2060 does not update the copy of the project in the working directory.
2060 does not update the copy of the project in the working directory.
2061
2061
2062 Valid URLs are of the form:
2062 Valid URLs are of the form:
2063
2063
2064 local/filesystem/path (or file://local/filesystem/path)
2064 local/filesystem/path (or file://local/filesystem/path)
2065 http://[user@]host[:port]/[path]
2065 http://[user@]host[:port]/[path]
2066 https://[user@]host[:port]/[path]
2066 https://[user@]host[:port]/[path]
2067 ssh://[user@]host[:port]/[path]
2067 ssh://[user@]host[:port]/[path]
2068 static-http://host[:port]/[path]
2068 static-http://host[:port]/[path]
2069
2069
2070 Paths in the local filesystem can either point to Mercurial
2070 Paths in the local filesystem can either point to Mercurial
2071 repositories or to bundle files (as created by 'hg bundle' or
2071 repositories or to bundle files (as created by 'hg bundle' or
2072 'hg incoming --bundle'). The static-http:// protocol, albeit slow,
2072 'hg incoming --bundle'). The static-http:// protocol, albeit slow,
2073 allows access to a Mercurial repository where you simply use a web
2073 allows access to a Mercurial repository where you simply use a web
2074 server to publish the .hg directory as static content.
2074 server to publish the .hg directory as static content.
2075
2075
2076 An optional identifier after # indicates a particular branch, tag,
2076 An optional identifier after # indicates a particular branch, tag,
2077 or changeset to pull.
2077 or changeset to pull.
2078
2078
2079 Some notes about using SSH with Mercurial:
2079 Some notes about using SSH with Mercurial:
2080 - SSH requires an accessible shell account on the destination machine
2080 - SSH requires an accessible shell account on the destination machine
2081 and a copy of hg in the remote path or specified with as remotecmd.
2081 and a copy of hg in the remote path or specified with as remotecmd.
2082 - path is relative to the remote user's home directory by default.
2082 - path is relative to the remote user's home directory by default.
2083 Use an extra slash at the start of a path to specify an absolute path:
2083 Use an extra slash at the start of a path to specify an absolute path:
2084 ssh://example.com//tmp/repository
2084 ssh://example.com//tmp/repository
2085 - Mercurial doesn't use its own compression via SSH; the right thing
2085 - Mercurial doesn't use its own compression via SSH; the right thing
2086 to do is to configure it in your ~/.ssh/config, e.g.:
2086 to do is to configure it in your ~/.ssh/config, e.g.:
2087 Host *.mylocalnetwork.example.com
2087 Host *.mylocalnetwork.example.com
2088 Compression no
2088 Compression no
2089 Host *
2089 Host *
2090 Compression yes
2090 Compression yes
2091 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2091 Alternatively specify "ssh -C" as your ssh command in your hgrc or
2092 with the --ssh command line option.
2092 with the --ssh command line option.
2093 """
2093 """
2094 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
2094 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts['rev'])
2095 cmdutil.setremoteconfig(ui, opts)
2095 cmdutil.setremoteconfig(ui, opts)
2096
2096
2097 other = hg.repository(ui, source)
2097 other = hg.repository(ui, source)
2098 ui.status(_('pulling from %s\n') % (source))
2098 ui.status(_('pulling from %s\n') % util.hidepassword(source))
2099 if revs:
2099 if revs:
2100 try:
2100 try:
2101 revs = [other.lookup(rev) for rev in revs]
2101 revs = [other.lookup(rev) for rev in revs]
2102 except repo.NoCapability:
2102 except repo.NoCapability:
2103 error = _("Other repository doesn't support revision lookup, "
2103 error = _("Other repository doesn't support revision lookup, "
2104 "so a rev cannot be specified.")
2104 "so a rev cannot be specified.")
2105 raise util.Abort(error)
2105 raise util.Abort(error)
2106
2106
2107 modheads = repo.pull(other, heads=revs, force=opts['force'])
2107 modheads = repo.pull(other, heads=revs, force=opts['force'])
2108 return postincoming(ui, repo, modheads, opts['update'], checkout)
2108 return postincoming(ui, repo, modheads, opts['update'], checkout)
2109
2109
2110 def push(ui, repo, dest=None, **opts):
2110 def push(ui, repo, dest=None, **opts):
2111 """push changes to the specified destination
2111 """push changes to the specified destination
2112
2112
2113 Push changes from the local repository to the given destination.
2113 Push changes from the local repository to the given destination.
2114
2114
2115 This is the symmetrical operation for pull. It helps to move
2115 This is the symmetrical operation for pull. It helps to move
2116 changes from the current repository to a different one. If the
2116 changes from the current repository to a different one. If the
2117 destination is local this is identical to a pull in that directory
2117 destination is local this is identical to a pull in that directory
2118 from the current one.
2118 from the current one.
2119
2119
2120 By default, push will refuse to run if it detects the result would
2120 By default, push will refuse to run if it detects the result would
2121 increase the number of remote heads. This generally indicates the
2121 increase the number of remote heads. This generally indicates the
2122 the client has forgotten to sync and merge before pushing.
2122 the client has forgotten to sync and merge before pushing.
2123
2123
2124 Valid URLs are of the form:
2124 Valid URLs are of the form:
2125
2125
2126 local/filesystem/path (or file://local/filesystem/path)
2126 local/filesystem/path (or file://local/filesystem/path)
2127 ssh://[user@]host[:port]/[path]
2127 ssh://[user@]host[:port]/[path]
2128 http://[user@]host[:port]/[path]
2128 http://[user@]host[:port]/[path]
2129 https://[user@]host[:port]/[path]
2129 https://[user@]host[:port]/[path]
2130
2130
2131 An optional identifier after # indicates a particular branch, tag,
2131 An optional identifier after # indicates a particular branch, tag,
2132 or changeset to push.
2132 or changeset to push.
2133
2133
2134 Look at the help text for the pull command for important details
2134 Look at the help text for the pull command for important details
2135 about ssh:// URLs.
2135 about ssh:// URLs.
2136
2136
2137 Pushing to http:// and https:// URLs is only possible, if this
2137 Pushing to http:// and https:// URLs is only possible, if this
2138 feature is explicitly enabled on the remote Mercurial server.
2138 feature is explicitly enabled on the remote Mercurial server.
2139 """
2139 """
2140 dest, revs, checkout = hg.parseurl(
2140 dest, revs, checkout = hg.parseurl(
2141 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
2141 ui.expandpath(dest or 'default-push', dest or 'default'), opts['rev'])
2142 cmdutil.setremoteconfig(ui, opts)
2142 cmdutil.setremoteconfig(ui, opts)
2143
2143
2144 other = hg.repository(ui, dest)
2144 other = hg.repository(ui, dest)
2145 ui.status('pushing to %s\n' % (dest))
2145 ui.status('pushing to %s\n' % util.hidepassword(dest))
2146 if revs:
2146 if revs:
2147 revs = [repo.lookup(rev) for rev in revs]
2147 revs = [repo.lookup(rev) for rev in revs]
2148 r = repo.push(other, opts['force'], revs=revs)
2148 r = repo.push(other, opts['force'], revs=revs)
2149 return r == 0
2149 return r == 0
2150
2150
2151 def rawcommit(ui, repo, *pats, **opts):
2151 def rawcommit(ui, repo, *pats, **opts):
2152 """raw commit interface (DEPRECATED)
2152 """raw commit interface (DEPRECATED)
2153
2153
2154 (DEPRECATED)
2154 (DEPRECATED)
2155 Lowlevel commit, for use in helper scripts.
2155 Lowlevel commit, for use in helper scripts.
2156
2156
2157 This command is not intended to be used by normal users, as it is
2157 This command is not intended to be used by normal users, as it is
2158 primarily useful for importing from other SCMs.
2158 primarily useful for importing from other SCMs.
2159
2159
2160 This command is now deprecated and will be removed in a future
2160 This command is now deprecated and will be removed in a future
2161 release, please use debugsetparents and commit instead.
2161 release, please use debugsetparents and commit instead.
2162 """
2162 """
2163
2163
2164 ui.warn(_("(the rawcommit command is deprecated)\n"))
2164 ui.warn(_("(the rawcommit command is deprecated)\n"))
2165
2165
2166 message = cmdutil.logmessage(opts)
2166 message = cmdutil.logmessage(opts)
2167
2167
2168 files, match, anypats = cmdutil.matchpats(repo, pats, opts)
2168 files, match, anypats = cmdutil.matchpats(repo, pats, opts)
2169 if opts['files']:
2169 if opts['files']:
2170 files += open(opts['files']).read().splitlines()
2170 files += open(opts['files']).read().splitlines()
2171
2171
2172 parents = [repo.lookup(p) for p in opts['parent']]
2172 parents = [repo.lookup(p) for p in opts['parent']]
2173
2173
2174 try:
2174 try:
2175 repo.rawcommit(files, message, opts['user'], opts['date'], *parents)
2175 repo.rawcommit(files, message, opts['user'], opts['date'], *parents)
2176 except ValueError, inst:
2176 except ValueError, inst:
2177 raise util.Abort(str(inst))
2177 raise util.Abort(str(inst))
2178
2178
2179 def recover(ui, repo):
2179 def recover(ui, repo):
2180 """roll back an interrupted transaction
2180 """roll back an interrupted transaction
2181
2181
2182 Recover from an interrupted commit or pull.
2182 Recover from an interrupted commit or pull.
2183
2183
2184 This command tries to fix the repository status after an interrupted
2184 This command tries to fix the repository status after an interrupted
2185 operation. It should only be necessary when Mercurial suggests it.
2185 operation. It should only be necessary when Mercurial suggests it.
2186 """
2186 """
2187 if repo.recover():
2187 if repo.recover():
2188 return hg.verify(repo)
2188 return hg.verify(repo)
2189 return 1
2189 return 1
2190
2190
2191 def remove(ui, repo, *pats, **opts):
2191 def remove(ui, repo, *pats, **opts):
2192 """remove the specified files on the next commit
2192 """remove the specified files on the next commit
2193
2193
2194 Schedule the indicated files for removal from the repository.
2194 Schedule the indicated files for removal from the repository.
2195
2195
2196 This only removes files from the current branch, not from the
2196 This only removes files from the current branch, not from the
2197 entire project history. If the files still exist in the working
2197 entire project history. If the files still exist in the working
2198 directory, they will be deleted from it. If invoked with --after,
2198 directory, they will be deleted from it. If invoked with --after,
2199 files are marked as removed, but not actually unlinked unless --force
2199 files are marked as removed, but not actually unlinked unless --force
2200 is also given. Without exact file names, --after will only mark
2200 is also given. Without exact file names, --after will only mark
2201 files as removed if they are no longer in the working directory.
2201 files as removed if they are no longer in the working directory.
2202
2202
2203 This command schedules the files to be removed at the next commit.
2203 This command schedules the files to be removed at the next commit.
2204 To undo a remove before that, see hg revert.
2204 To undo a remove before that, see hg revert.
2205
2205
2206 Modified files and added files are not removed by default. To
2206 Modified files and added files are not removed by default. To
2207 remove them, use the -f/--force option.
2207 remove them, use the -f/--force option.
2208 """
2208 """
2209 if not opts['after'] and not pats:
2209 if not opts['after'] and not pats:
2210 raise util.Abort(_('no files specified'))
2210 raise util.Abort(_('no files specified'))
2211 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2211 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2212 exact = dict.fromkeys(files)
2212 exact = dict.fromkeys(files)
2213 mardu = map(dict.fromkeys, repo.status(files=files, match=matchfn))[:5]
2213 mardu = map(dict.fromkeys, repo.status(files=files, match=matchfn))[:5]
2214 modified, added, removed, deleted, unknown = mardu
2214 modified, added, removed, deleted, unknown = mardu
2215 remove, forget = [], []
2215 remove, forget = [], []
2216 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
2216 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts):
2217 reason = None
2217 reason = None
2218 if abs in modified and not opts['force']:
2218 if abs in modified and not opts['force']:
2219 reason = _('is modified (use -f to force removal)')
2219 reason = _('is modified (use -f to force removal)')
2220 elif abs in added:
2220 elif abs in added:
2221 if opts['force']:
2221 if opts['force']:
2222 forget.append(abs)
2222 forget.append(abs)
2223 continue
2223 continue
2224 reason = _('has been marked for add (use -f to force removal)')
2224 reason = _('has been marked for add (use -f to force removal)')
2225 elif abs not in repo.dirstate:
2225 elif abs not in repo.dirstate:
2226 reason = _('is not managed')
2226 reason = _('is not managed')
2227 elif opts['after'] and not exact and abs not in deleted:
2227 elif opts['after'] and not exact and abs not in deleted:
2228 continue
2228 continue
2229 elif abs in removed:
2229 elif abs in removed:
2230 continue
2230 continue
2231 if reason:
2231 if reason:
2232 if exact:
2232 if exact:
2233 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2233 ui.warn(_('not removing %s: file %s\n') % (rel, reason))
2234 else:
2234 else:
2235 if ui.verbose or not exact:
2235 if ui.verbose or not exact:
2236 ui.status(_('removing %s\n') % rel)
2236 ui.status(_('removing %s\n') % rel)
2237 remove.append(abs)
2237 remove.append(abs)
2238 repo.forget(forget)
2238 repo.forget(forget)
2239 repo.remove(remove, unlink=opts['force'] or not opts['after'])
2239 repo.remove(remove, unlink=opts['force'] or not opts['after'])
2240
2240
2241 def rename(ui, repo, *pats, **opts):
2241 def rename(ui, repo, *pats, **opts):
2242 """rename files; equivalent of copy + remove
2242 """rename files; equivalent of copy + remove
2243
2243
2244 Mark dest as copies of sources; mark sources for deletion. If
2244 Mark dest as copies of sources; mark sources for deletion. If
2245 dest is a directory, copies are put in that directory. If dest is
2245 dest is a directory, copies are put in that directory. If dest is
2246 a file, there can only be one source.
2246 a file, there can only be one source.
2247
2247
2248 By default, this command copies the contents of files as they
2248 By default, this command copies the contents of files as they
2249 stand in the working directory. If invoked with --after, the
2249 stand in the working directory. If invoked with --after, the
2250 operation is recorded, but no copying is performed.
2250 operation is recorded, but no copying is performed.
2251
2251
2252 This command takes effect in the next commit. To undo a rename
2252 This command takes effect in the next commit. To undo a rename
2253 before that, see hg revert.
2253 before that, see hg revert.
2254 """
2254 """
2255 wlock = repo.wlock(False)
2255 wlock = repo.wlock(False)
2256 try:
2256 try:
2257 errs, copied = docopy(ui, repo, pats, opts)
2257 errs, copied = docopy(ui, repo, pats, opts)
2258 names = []
2258 names = []
2259 for abs, rel, exact in copied:
2259 for abs, rel, exact in copied:
2260 if ui.verbose or not exact:
2260 if ui.verbose or not exact:
2261 ui.status(_('removing %s\n') % rel)
2261 ui.status(_('removing %s\n') % rel)
2262 names.append(abs)
2262 names.append(abs)
2263 if not opts.get('dry_run'):
2263 if not opts.get('dry_run'):
2264 repo.remove(names, True)
2264 repo.remove(names, True)
2265 return errs
2265 return errs
2266 finally:
2266 finally:
2267 del wlock
2267 del wlock
2268
2268
2269 def revert(ui, repo, *pats, **opts):
2269 def revert(ui, repo, *pats, **opts):
2270 """revert files or dirs to their states as of some revision
2270 """revert files or dirs to their states as of some revision
2271
2271
2272 With no revision specified, revert the named files or directories
2272 With no revision specified, revert the named files or directories
2273 to the contents they had in the parent of the working directory.
2273 to the contents they had in the parent of the working directory.
2274 This restores the contents of the affected files to an unmodified
2274 This restores the contents of the affected files to an unmodified
2275 state and unschedules adds, removes, copies, and renames. If the
2275 state and unschedules adds, removes, copies, and renames. If the
2276 working directory has two parents, you must explicitly specify the
2276 working directory has two parents, you must explicitly specify the
2277 revision to revert to.
2277 revision to revert to.
2278
2278
2279 Modified files are saved with a .orig suffix before reverting.
2279 Modified files are saved with a .orig suffix before reverting.
2280 To disable these backups, use --no-backup.
2280 To disable these backups, use --no-backup.
2281
2281
2282 Using the -r option, revert the given files or directories to their
2282 Using the -r option, revert the given files or directories to their
2283 contents as of a specific revision. This can be helpful to "roll
2283 contents as of a specific revision. This can be helpful to "roll
2284 back" some or all of a change that should not have been committed.
2284 back" some or all of a change that should not have been committed.
2285
2285
2286 Revert modifies the working directory. It does not commit any
2286 Revert modifies the working directory. It does not commit any
2287 changes, or change the parent of the working directory. If you
2287 changes, or change the parent of the working directory. If you
2288 revert to a revision other than the parent of the working
2288 revert to a revision other than the parent of the working
2289 directory, the reverted files will thus appear modified
2289 directory, the reverted files will thus appear modified
2290 afterwards.
2290 afterwards.
2291
2291
2292 If a file has been deleted, it is restored. If the executable
2292 If a file has been deleted, it is restored. If the executable
2293 mode of a file was changed, it is reset.
2293 mode of a file was changed, it is reset.
2294
2294
2295 If names are given, all files matching the names are reverted.
2295 If names are given, all files matching the names are reverted.
2296
2296
2297 If no arguments are given, no files are reverted.
2297 If no arguments are given, no files are reverted.
2298 """
2298 """
2299
2299
2300 if opts["date"]:
2300 if opts["date"]:
2301 if opts["rev"]:
2301 if opts["rev"]:
2302 raise util.Abort(_("you can't specify a revision and a date"))
2302 raise util.Abort(_("you can't specify a revision and a date"))
2303 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2303 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2304
2304
2305 if not pats and not opts['all']:
2305 if not pats and not opts['all']:
2306 raise util.Abort(_('no files or directories specified; '
2306 raise util.Abort(_('no files or directories specified; '
2307 'use --all to revert the whole repo'))
2307 'use --all to revert the whole repo'))
2308
2308
2309 parent, p2 = repo.dirstate.parents()
2309 parent, p2 = repo.dirstate.parents()
2310 if not opts['rev'] and p2 != nullid:
2310 if not opts['rev'] and p2 != nullid:
2311 raise util.Abort(_('uncommitted merge - please provide a '
2311 raise util.Abort(_('uncommitted merge - please provide a '
2312 'specific revision'))
2312 'specific revision'))
2313 ctx = repo.changectx(opts['rev'])
2313 ctx = repo.changectx(opts['rev'])
2314 node = ctx.node()
2314 node = ctx.node()
2315 mf = ctx.manifest()
2315 mf = ctx.manifest()
2316 if node == parent:
2316 if node == parent:
2317 pmf = mf
2317 pmf = mf
2318 else:
2318 else:
2319 pmf = None
2319 pmf = None
2320
2320
2321 # need all matching names in dirstate and manifest of target rev,
2321 # need all matching names in dirstate and manifest of target rev,
2322 # so have to walk both. do not print errors if files exist in one
2322 # so have to walk both. do not print errors if files exist in one
2323 # but not other.
2323 # but not other.
2324
2324
2325 names = {}
2325 names = {}
2326 target_only = {}
2326 target_only = {}
2327
2327
2328 wlock = repo.wlock()
2328 wlock = repo.wlock()
2329 try:
2329 try:
2330 # walk dirstate.
2330 # walk dirstate.
2331 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
2331 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts,
2332 badmatch=mf.has_key):
2332 badmatch=mf.has_key):
2333 names[abs] = (rel, exact)
2333 names[abs] = (rel, exact)
2334 if src == 'b':
2334 if src == 'b':
2335 target_only[abs] = True
2335 target_only[abs] = True
2336
2336
2337 # walk target manifest.
2337 # walk target manifest.
2338
2338
2339 def badmatch(path):
2339 def badmatch(path):
2340 if path in names:
2340 if path in names:
2341 return True
2341 return True
2342 path_ = path + '/'
2342 path_ = path + '/'
2343 for f in names:
2343 for f in names:
2344 if f.startswith(path_):
2344 if f.startswith(path_):
2345 return True
2345 return True
2346 return False
2346 return False
2347
2347
2348 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
2348 for src, abs, rel, exact in cmdutil.walk(repo, pats, opts, node=node,
2349 badmatch=badmatch):
2349 badmatch=badmatch):
2350 if abs in names or src == 'b':
2350 if abs in names or src == 'b':
2351 continue
2351 continue
2352 names[abs] = (rel, exact)
2352 names[abs] = (rel, exact)
2353 target_only[abs] = True
2353 target_only[abs] = True
2354
2354
2355 changes = repo.status(match=names.has_key)[:5]
2355 changes = repo.status(match=names.has_key)[:5]
2356 modified, added, removed, deleted, unknown = map(dict.fromkeys, changes)
2356 modified, added, removed, deleted, unknown = map(dict.fromkeys, changes)
2357
2357
2358 # if f is a rename, also revert the source
2358 # if f is a rename, also revert the source
2359 cwd = repo.getcwd()
2359 cwd = repo.getcwd()
2360 for f in added:
2360 for f in added:
2361 src = repo.dirstate.copied(f)
2361 src = repo.dirstate.copied(f)
2362 if src and src not in names and repo.dirstate[src] == 'r':
2362 if src and src not in names and repo.dirstate[src] == 'r':
2363 removed[src] = None
2363 removed[src] = None
2364 names[src] = (repo.pathto(src, cwd), True)
2364 names[src] = (repo.pathto(src, cwd), True)
2365
2365
2366 revert = ([], _('reverting %s\n'))
2366 revert = ([], _('reverting %s\n'))
2367 add = ([], _('adding %s\n'))
2367 add = ([], _('adding %s\n'))
2368 remove = ([], _('removing %s\n'))
2368 remove = ([], _('removing %s\n'))
2369 forget = ([], _('forgetting %s\n'))
2369 forget = ([], _('forgetting %s\n'))
2370 undelete = ([], _('undeleting %s\n'))
2370 undelete = ([], _('undeleting %s\n'))
2371 update = {}
2371 update = {}
2372
2372
2373 disptable = (
2373 disptable = (
2374 # dispatch table:
2374 # dispatch table:
2375 # file state
2375 # file state
2376 # action if in target manifest
2376 # action if in target manifest
2377 # action if not in target manifest
2377 # action if not in target manifest
2378 # make backup if in target manifest
2378 # make backup if in target manifest
2379 # make backup if not in target manifest
2379 # make backup if not in target manifest
2380 (modified, revert, remove, True, True),
2380 (modified, revert, remove, True, True),
2381 (added, revert, forget, True, False),
2381 (added, revert, forget, True, False),
2382 (removed, undelete, None, False, False),
2382 (removed, undelete, None, False, False),
2383 (deleted, revert, remove, False, False),
2383 (deleted, revert, remove, False, False),
2384 (unknown, add, None, True, False),
2384 (unknown, add, None, True, False),
2385 (target_only, add, None, False, False),
2385 (target_only, add, None, False, False),
2386 )
2386 )
2387
2387
2388 entries = names.items()
2388 entries = names.items()
2389 entries.sort()
2389 entries.sort()
2390
2390
2391 for abs, (rel, exact) in entries:
2391 for abs, (rel, exact) in entries:
2392 mfentry = mf.get(abs)
2392 mfentry = mf.get(abs)
2393 target = repo.wjoin(abs)
2393 target = repo.wjoin(abs)
2394 def handle(xlist, dobackup):
2394 def handle(xlist, dobackup):
2395 xlist[0].append(abs)
2395 xlist[0].append(abs)
2396 update[abs] = 1
2396 update[abs] = 1
2397 if dobackup and not opts['no_backup'] and util.lexists(target):
2397 if dobackup and not opts['no_backup'] and util.lexists(target):
2398 bakname = "%s.orig" % rel
2398 bakname = "%s.orig" % rel
2399 ui.note(_('saving current version of %s as %s\n') %
2399 ui.note(_('saving current version of %s as %s\n') %
2400 (rel, bakname))
2400 (rel, bakname))
2401 if not opts.get('dry_run'):
2401 if not opts.get('dry_run'):
2402 util.copyfile(target, bakname)
2402 util.copyfile(target, bakname)
2403 if ui.verbose or not exact:
2403 if ui.verbose or not exact:
2404 ui.status(xlist[1] % rel)
2404 ui.status(xlist[1] % rel)
2405 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2405 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2406 if abs not in table: continue
2406 if abs not in table: continue
2407 # file has changed in dirstate
2407 # file has changed in dirstate
2408 if mfentry:
2408 if mfentry:
2409 handle(hitlist, backuphit)
2409 handle(hitlist, backuphit)
2410 elif misslist is not None:
2410 elif misslist is not None:
2411 handle(misslist, backupmiss)
2411 handle(misslist, backupmiss)
2412 else:
2412 else:
2413 if exact: ui.warn(_('file not managed: %s\n') % rel)
2413 if exact: ui.warn(_('file not managed: %s\n') % rel)
2414 break
2414 break
2415 else:
2415 else:
2416 # file has not changed in dirstate
2416 # file has not changed in dirstate
2417 if node == parent:
2417 if node == parent:
2418 if exact: ui.warn(_('no changes needed to %s\n') % rel)
2418 if exact: ui.warn(_('no changes needed to %s\n') % rel)
2419 continue
2419 continue
2420 if pmf is None:
2420 if pmf is None:
2421 # only need parent manifest in this unlikely case,
2421 # only need parent manifest in this unlikely case,
2422 # so do not read by default
2422 # so do not read by default
2423 pmf = repo.changectx(parent).manifest()
2423 pmf = repo.changectx(parent).manifest()
2424 if abs in pmf:
2424 if abs in pmf:
2425 if mfentry:
2425 if mfentry:
2426 # if version of file is same in parent and target
2426 # if version of file is same in parent and target
2427 # manifests, do nothing
2427 # manifests, do nothing
2428 if pmf[abs] != mfentry:
2428 if pmf[abs] != mfentry:
2429 handle(revert, False)
2429 handle(revert, False)
2430 else:
2430 else:
2431 handle(remove, False)
2431 handle(remove, False)
2432
2432
2433 if not opts.get('dry_run'):
2433 if not opts.get('dry_run'):
2434 for f in forget[0]:
2434 for f in forget[0]:
2435 repo.dirstate.forget(f)
2435 repo.dirstate.forget(f)
2436 r = hg.revert(repo, node, update.has_key)
2436 r = hg.revert(repo, node, update.has_key)
2437 for f in add[0]:
2437 for f in add[0]:
2438 repo.dirstate.add(f)
2438 repo.dirstate.add(f)
2439 for f in undelete[0]:
2439 for f in undelete[0]:
2440 repo.dirstate.normal(f)
2440 repo.dirstate.normal(f)
2441 for f in remove[0]:
2441 for f in remove[0]:
2442 repo.dirstate.remove(f)
2442 repo.dirstate.remove(f)
2443 return r
2443 return r
2444 finally:
2444 finally:
2445 del wlock
2445 del wlock
2446
2446
2447 def rollback(ui, repo):
2447 def rollback(ui, repo):
2448 """roll back the last transaction in this repository
2448 """roll back the last transaction in this repository
2449
2449
2450 Roll back the last transaction in this repository, restoring the
2450 Roll back the last transaction in this repository, restoring the
2451 project to its state prior to the transaction.
2451 project to its state prior to the transaction.
2452
2452
2453 Transactions are used to encapsulate the effects of all commands
2453 Transactions are used to encapsulate the effects of all commands
2454 that create new changesets or propagate existing changesets into a
2454 that create new changesets or propagate existing changesets into a
2455 repository. For example, the following commands are transactional,
2455 repository. For example, the following commands are transactional,
2456 and their effects can be rolled back:
2456 and their effects can be rolled back:
2457
2457
2458 commit
2458 commit
2459 import
2459 import
2460 pull
2460 pull
2461 push (with this repository as destination)
2461 push (with this repository as destination)
2462 unbundle
2462 unbundle
2463
2463
2464 This command should be used with care. There is only one level of
2464 This command should be used with care. There is only one level of
2465 rollback, and there is no way to undo a rollback. It will also
2465 rollback, and there is no way to undo a rollback. It will also
2466 restore the dirstate at the time of the last transaction, which
2466 restore the dirstate at the time of the last transaction, which
2467 may lose subsequent dirstate changes.
2467 may lose subsequent dirstate changes.
2468
2468
2469 This command is not intended for use on public repositories. Once
2469 This command is not intended for use on public repositories. Once
2470 changes are visible for pull by other users, rolling a transaction
2470 changes are visible for pull by other users, rolling a transaction
2471 back locally is ineffective (someone else may already have pulled
2471 back locally is ineffective (someone else may already have pulled
2472 the changes). Furthermore, a race is possible with readers of the
2472 the changes). Furthermore, a race is possible with readers of the
2473 repository; for example an in-progress pull from the repository
2473 repository; for example an in-progress pull from the repository
2474 may fail if a rollback is performed.
2474 may fail if a rollback is performed.
2475 """
2475 """
2476 repo.rollback()
2476 repo.rollback()
2477
2477
2478 def root(ui, repo):
2478 def root(ui, repo):
2479 """print the root (top) of the current working dir
2479 """print the root (top) of the current working dir
2480
2480
2481 Print the root directory of the current repository.
2481 Print the root directory of the current repository.
2482 """
2482 """
2483 ui.write(repo.root + "\n")
2483 ui.write(repo.root + "\n")
2484
2484
2485 def serve(ui, repo, **opts):
2485 def serve(ui, repo, **opts):
2486 """export the repository via HTTP
2486 """export the repository via HTTP
2487
2487
2488 Start a local HTTP repository browser and pull server.
2488 Start a local HTTP repository browser and pull server.
2489
2489
2490 By default, the server logs accesses to stdout and errors to
2490 By default, the server logs accesses to stdout and errors to
2491 stderr. Use the "-A" and "-E" options to log to files.
2491 stderr. Use the "-A" and "-E" options to log to files.
2492 """
2492 """
2493
2493
2494 if opts["stdio"]:
2494 if opts["stdio"]:
2495 if repo is None:
2495 if repo is None:
2496 raise hg.RepoError(_("There is no Mercurial repository here"
2496 raise hg.RepoError(_("There is no Mercurial repository here"
2497 " (.hg not found)"))
2497 " (.hg not found)"))
2498 s = sshserver.sshserver(ui, repo)
2498 s = sshserver.sshserver(ui, repo)
2499 s.serve_forever()
2499 s.serve_forever()
2500
2500
2501 parentui = ui.parentui or ui
2501 parentui = ui.parentui or ui
2502 optlist = ("name templates style address port ipv6"
2502 optlist = ("name templates style address port ipv6"
2503 " accesslog errorlog webdir_conf certificate")
2503 " accesslog errorlog webdir_conf certificate")
2504 for o in optlist.split():
2504 for o in optlist.split():
2505 if opts[o]:
2505 if opts[o]:
2506 parentui.setconfig("web", o, str(opts[o]))
2506 parentui.setconfig("web", o, str(opts[o]))
2507 if (repo is not None) and (repo.ui != parentui):
2507 if (repo is not None) and (repo.ui != parentui):
2508 repo.ui.setconfig("web", o, str(opts[o]))
2508 repo.ui.setconfig("web", o, str(opts[o]))
2509
2509
2510 if repo is None and not ui.config("web", "webdir_conf"):
2510 if repo is None and not ui.config("web", "webdir_conf"):
2511 raise hg.RepoError(_("There is no Mercurial repository here"
2511 raise hg.RepoError(_("There is no Mercurial repository here"
2512 " (.hg not found)"))
2512 " (.hg not found)"))
2513
2513
2514 class service:
2514 class service:
2515 def init(self):
2515 def init(self):
2516 util.set_signal_handler()
2516 util.set_signal_handler()
2517 try:
2517 try:
2518 self.httpd = hgweb.server.create_server(parentui, repo)
2518 self.httpd = hgweb.server.create_server(parentui, repo)
2519 except socket.error, inst:
2519 except socket.error, inst:
2520 raise util.Abort(_('cannot start server: ') + inst.args[1])
2520 raise util.Abort(_('cannot start server: ') + inst.args[1])
2521
2521
2522 if not ui.verbose: return
2522 if not ui.verbose: return
2523
2523
2524 if self.httpd.port != 80:
2524 if self.httpd.port != 80:
2525 ui.status(_('listening at http://%s:%d/\n') %
2525 ui.status(_('listening at http://%s:%d/\n') %
2526 (self.httpd.addr, self.httpd.port))
2526 (self.httpd.addr, self.httpd.port))
2527 else:
2527 else:
2528 ui.status(_('listening at http://%s/\n') % self.httpd.addr)
2528 ui.status(_('listening at http://%s/\n') % self.httpd.addr)
2529
2529
2530 def run(self):
2530 def run(self):
2531 self.httpd.serve_forever()
2531 self.httpd.serve_forever()
2532
2532
2533 service = service()
2533 service = service()
2534
2534
2535 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2535 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2536
2536
2537 def status(ui, repo, *pats, **opts):
2537 def status(ui, repo, *pats, **opts):
2538 """show changed files in the working directory
2538 """show changed files in the working directory
2539
2539
2540 Show status of files in the repository. If names are given, only
2540 Show status of files in the repository. If names are given, only
2541 files that match are shown. Files that are clean or ignored, are
2541 files that match are shown. Files that are clean or ignored, are
2542 not listed unless -c (clean), -i (ignored) or -A is given.
2542 not listed unless -c (clean), -i (ignored) or -A is given.
2543
2543
2544 NOTE: status may appear to disagree with diff if permissions have
2544 NOTE: status may appear to disagree with diff if permissions have
2545 changed or a merge has occurred. The standard diff format does not
2545 changed or a merge has occurred. The standard diff format does not
2546 report permission changes and diff only reports changes relative
2546 report permission changes and diff only reports changes relative
2547 to one merge parent.
2547 to one merge parent.
2548
2548
2549 If one revision is given, it is used as the base revision.
2549 If one revision is given, it is used as the base revision.
2550 If two revisions are given, the difference between them is shown.
2550 If two revisions are given, the difference between them is shown.
2551
2551
2552 The codes used to show the status of files are:
2552 The codes used to show the status of files are:
2553 M = modified
2553 M = modified
2554 A = added
2554 A = added
2555 R = removed
2555 R = removed
2556 C = clean
2556 C = clean
2557 ! = deleted, but still tracked
2557 ! = deleted, but still tracked
2558 ? = not tracked
2558 ? = not tracked
2559 I = ignored (not shown by default)
2559 I = ignored (not shown by default)
2560 = the previous added file was copied from here
2560 = the previous added file was copied from here
2561 """
2561 """
2562
2562
2563 all = opts['all']
2563 all = opts['all']
2564 node1, node2 = cmdutil.revpair(repo, opts.get('rev'))
2564 node1, node2 = cmdutil.revpair(repo, opts.get('rev'))
2565
2565
2566 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2566 files, matchfn, anypats = cmdutil.matchpats(repo, pats, opts)
2567 cwd = (pats and repo.getcwd()) or ''
2567 cwd = (pats and repo.getcwd()) or ''
2568 modified, added, removed, deleted, unknown, ignored, clean = [
2568 modified, added, removed, deleted, unknown, ignored, clean = [
2569 n for n in repo.status(node1=node1, node2=node2, files=files,
2569 n for n in repo.status(node1=node1, node2=node2, files=files,
2570 match=matchfn,
2570 match=matchfn,
2571 list_ignored=all or opts['ignored'],
2571 list_ignored=all or opts['ignored'],
2572 list_clean=all or opts['clean'])]
2572 list_clean=all or opts['clean'])]
2573
2573
2574 changetypes = (('modified', 'M', modified),
2574 changetypes = (('modified', 'M', modified),
2575 ('added', 'A', added),
2575 ('added', 'A', added),
2576 ('removed', 'R', removed),
2576 ('removed', 'R', removed),
2577 ('deleted', '!', deleted),
2577 ('deleted', '!', deleted),
2578 ('unknown', '?', unknown),
2578 ('unknown', '?', unknown),
2579 ('ignored', 'I', ignored))
2579 ('ignored', 'I', ignored))
2580
2580
2581 explicit_changetypes = changetypes + (('clean', 'C', clean),)
2581 explicit_changetypes = changetypes + (('clean', 'C', clean),)
2582
2582
2583 end = opts['print0'] and '\0' or '\n'
2583 end = opts['print0'] and '\0' or '\n'
2584
2584
2585 for opt, char, changes in ([ct for ct in explicit_changetypes
2585 for opt, char, changes in ([ct for ct in explicit_changetypes
2586 if all or opts[ct[0]]]
2586 if all or opts[ct[0]]]
2587 or changetypes):
2587 or changetypes):
2588 if opts['no_status']:
2588 if opts['no_status']:
2589 format = "%%s%s" % end
2589 format = "%%s%s" % end
2590 else:
2590 else:
2591 format = "%s %%s%s" % (char, end)
2591 format = "%s %%s%s" % (char, end)
2592
2592
2593 for f in changes:
2593 for f in changes:
2594 ui.write(format % repo.pathto(f, cwd))
2594 ui.write(format % repo.pathto(f, cwd))
2595 if ((all or opts.get('copies')) and not opts.get('no_status')):
2595 if ((all or opts.get('copies')) and not opts.get('no_status')):
2596 copied = repo.dirstate.copied(f)
2596 copied = repo.dirstate.copied(f)
2597 if copied:
2597 if copied:
2598 ui.write(' %s%s' % (repo.pathto(copied, cwd), end))
2598 ui.write(' %s%s' % (repo.pathto(copied, cwd), end))
2599
2599
2600 def tag(ui, repo, name, rev_=None, **opts):
2600 def tag(ui, repo, name, rev_=None, **opts):
2601 """add a tag for the current or given revision
2601 """add a tag for the current or given revision
2602
2602
2603 Name a particular revision using <name>.
2603 Name a particular revision using <name>.
2604
2604
2605 Tags are used to name particular revisions of the repository and are
2605 Tags are used to name particular revisions of the repository and are
2606 very useful to compare different revision, to go back to significant
2606 very useful to compare different revision, to go back to significant
2607 earlier versions or to mark branch points as releases, etc.
2607 earlier versions or to mark branch points as releases, etc.
2608
2608
2609 If no revision is given, the parent of the working directory is used,
2609 If no revision is given, the parent of the working directory is used,
2610 or tip if no revision is checked out.
2610 or tip if no revision is checked out.
2611
2611
2612 To facilitate version control, distribution, and merging of tags,
2612 To facilitate version control, distribution, and merging of tags,
2613 they are stored as a file named ".hgtags" which is managed
2613 they are stored as a file named ".hgtags" which is managed
2614 similarly to other project files and can be hand-edited if
2614 similarly to other project files and can be hand-edited if
2615 necessary. The file '.hg/localtags' is used for local tags (not
2615 necessary. The file '.hg/localtags' is used for local tags (not
2616 shared among repositories).
2616 shared among repositories).
2617 """
2617 """
2618 if name in ['tip', '.', 'null']:
2618 if name in ['tip', '.', 'null']:
2619 raise util.Abort(_("the name '%s' is reserved") % name)
2619 raise util.Abort(_("the name '%s' is reserved") % name)
2620 if rev_ is not None:
2620 if rev_ is not None:
2621 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2621 ui.warn(_("use of 'hg tag NAME [REV]' is deprecated, "
2622 "please use 'hg tag [-r REV] NAME' instead\n"))
2622 "please use 'hg tag [-r REV] NAME' instead\n"))
2623 if opts['rev']:
2623 if opts['rev']:
2624 raise util.Abort(_("use only one form to specify the revision"))
2624 raise util.Abort(_("use only one form to specify the revision"))
2625 if opts['rev'] and opts['remove']:
2625 if opts['rev'] and opts['remove']:
2626 raise util.Abort(_("--rev and --remove are incompatible"))
2626 raise util.Abort(_("--rev and --remove are incompatible"))
2627 if opts['rev']:
2627 if opts['rev']:
2628 rev_ = opts['rev']
2628 rev_ = opts['rev']
2629 message = opts['message']
2629 message = opts['message']
2630 if opts['remove']:
2630 if opts['remove']:
2631 if not name in repo.tags():
2631 if not name in repo.tags():
2632 raise util.Abort(_('tag %s does not exist') % name)
2632 raise util.Abort(_('tag %s does not exist') % name)
2633 rev_ = nullid
2633 rev_ = nullid
2634 if not message:
2634 if not message:
2635 message = _('Removed tag %s') % name
2635 message = _('Removed tag %s') % name
2636 elif name in repo.tags() and not opts['force']:
2636 elif name in repo.tags() and not opts['force']:
2637 raise util.Abort(_('a tag named %s already exists (use -f to force)')
2637 raise util.Abort(_('a tag named %s already exists (use -f to force)')
2638 % name)
2638 % name)
2639 if not rev_ and repo.dirstate.parents()[1] != nullid:
2639 if not rev_ and repo.dirstate.parents()[1] != nullid:
2640 raise util.Abort(_('uncommitted merge - please provide a '
2640 raise util.Abort(_('uncommitted merge - please provide a '
2641 'specific revision'))
2641 'specific revision'))
2642 r = repo.changectx(rev_).node()
2642 r = repo.changectx(rev_).node()
2643
2643
2644 if not message:
2644 if not message:
2645 message = _('Added tag %s for changeset %s') % (name, short(r))
2645 message = _('Added tag %s for changeset %s') % (name, short(r))
2646
2646
2647 repo.tag(name, r, message, opts['local'], opts['user'], opts['date'])
2647 repo.tag(name, r, message, opts['local'], opts['user'], opts['date'])
2648
2648
2649 def tags(ui, repo):
2649 def tags(ui, repo):
2650 """list repository tags
2650 """list repository tags
2651
2651
2652 List the repository tags.
2652 List the repository tags.
2653
2653
2654 This lists both regular and local tags.
2654 This lists both regular and local tags.
2655 """
2655 """
2656
2656
2657 l = repo.tagslist()
2657 l = repo.tagslist()
2658 l.reverse()
2658 l.reverse()
2659 hexfunc = ui.debugflag and hex or short
2659 hexfunc = ui.debugflag and hex or short
2660 for t, n in l:
2660 for t, n in l:
2661 try:
2661 try:
2662 hn = hexfunc(n)
2662 hn = hexfunc(n)
2663 r = "%5d:%s" % (repo.changelog.rev(n), hexfunc(n))
2663 r = "%5d:%s" % (repo.changelog.rev(n), hexfunc(n))
2664 except revlog.LookupError:
2664 except revlog.LookupError:
2665 r = " ?:%s" % hn
2665 r = " ?:%s" % hn
2666 if ui.quiet:
2666 if ui.quiet:
2667 ui.write("%s\n" % t)
2667 ui.write("%s\n" % t)
2668 else:
2668 else:
2669 spaces = " " * (30 - util.locallen(t))
2669 spaces = " " * (30 - util.locallen(t))
2670 ui.write("%s%s %s\n" % (t, spaces, r))
2670 ui.write("%s%s %s\n" % (t, spaces, r))
2671
2671
2672 def tip(ui, repo, **opts):
2672 def tip(ui, repo, **opts):
2673 """show the tip revision
2673 """show the tip revision
2674
2674
2675 Show the tip revision.
2675 Show the tip revision.
2676 """
2676 """
2677 cmdutil.show_changeset(ui, repo, opts).show(nullrev+repo.changelog.count())
2677 cmdutil.show_changeset(ui, repo, opts).show(nullrev+repo.changelog.count())
2678
2678
2679 def unbundle(ui, repo, fname1, *fnames, **opts):
2679 def unbundle(ui, repo, fname1, *fnames, **opts):
2680 """apply one or more changegroup files
2680 """apply one or more changegroup files
2681
2681
2682 Apply one or more compressed changegroup files generated by the
2682 Apply one or more compressed changegroup files generated by the
2683 bundle command.
2683 bundle command.
2684 """
2684 """
2685 fnames = (fname1,) + fnames
2685 fnames = (fname1,) + fnames
2686 for fname in fnames:
2686 for fname in fnames:
2687 if os.path.exists(fname):
2687 if os.path.exists(fname):
2688 f = open(fname, "rb")
2688 f = open(fname, "rb")
2689 else:
2689 else:
2690 f = urllib.urlopen(fname)
2690 f = urllib.urlopen(fname)
2691 gen = changegroup.readbundle(f, fname)
2691 gen = changegroup.readbundle(f, fname)
2692 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
2692 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
2693
2693
2694 return postincoming(ui, repo, modheads, opts['update'], None)
2694 return postincoming(ui, repo, modheads, opts['update'], None)
2695
2695
2696 def update(ui, repo, node=None, rev=None, clean=False, date=None):
2696 def update(ui, repo, node=None, rev=None, clean=False, date=None):
2697 """update working directory
2697 """update working directory
2698
2698
2699 Update the working directory to the specified revision, or the
2699 Update the working directory to the specified revision, or the
2700 tip of the current branch if none is specified.
2700 tip of the current branch if none is specified.
2701
2701
2702 If there are no outstanding changes in the working directory and
2702 If there are no outstanding changes in the working directory and
2703 there is a linear relationship between the current version and the
2703 there is a linear relationship between the current version and the
2704 requested version, the result is the requested version.
2704 requested version, the result is the requested version.
2705
2705
2706 To merge the working directory with another revision, use the
2706 To merge the working directory with another revision, use the
2707 merge command.
2707 merge command.
2708
2708
2709 By default, update will refuse to run if doing so would require
2709 By default, update will refuse to run if doing so would require
2710 discarding local changes.
2710 discarding local changes.
2711 """
2711 """
2712 if rev and node:
2712 if rev and node:
2713 raise util.Abort(_("please specify just one revision"))
2713 raise util.Abort(_("please specify just one revision"))
2714
2714
2715 if not rev:
2715 if not rev:
2716 rev = node
2716 rev = node
2717
2717
2718 if date:
2718 if date:
2719 if rev:
2719 if rev:
2720 raise util.Abort(_("you can't specify a revision and a date"))
2720 raise util.Abort(_("you can't specify a revision and a date"))
2721 rev = cmdutil.finddate(ui, repo, date)
2721 rev = cmdutil.finddate(ui, repo, date)
2722
2722
2723 if clean:
2723 if clean:
2724 return hg.clean(repo, rev)
2724 return hg.clean(repo, rev)
2725 else:
2725 else:
2726 return hg.update(repo, rev)
2726 return hg.update(repo, rev)
2727
2727
2728 def verify(ui, repo):
2728 def verify(ui, repo):
2729 """verify the integrity of the repository
2729 """verify the integrity of the repository
2730
2730
2731 Verify the integrity of the current repository.
2731 Verify the integrity of the current repository.
2732
2732
2733 This will perform an extensive check of the repository's
2733 This will perform an extensive check of the repository's
2734 integrity, validating the hashes and checksums of each entry in
2734 integrity, validating the hashes and checksums of each entry in
2735 the changelog, manifest, and tracked files, as well as the
2735 the changelog, manifest, and tracked files, as well as the
2736 integrity of their crosslinks and indices.
2736 integrity of their crosslinks and indices.
2737 """
2737 """
2738 return hg.verify(repo)
2738 return hg.verify(repo)
2739
2739
2740 def version_(ui):
2740 def version_(ui):
2741 """output version and copyright information"""
2741 """output version and copyright information"""
2742 ui.write(_("Mercurial Distributed SCM (version %s)\n")
2742 ui.write(_("Mercurial Distributed SCM (version %s)\n")
2743 % version.get_version())
2743 % version.get_version())
2744 ui.status(_(
2744 ui.status(_(
2745 "\nCopyright (C) 2005-2007 Matt Mackall <mpm@selenic.com> and others\n"
2745 "\nCopyright (C) 2005-2007 Matt Mackall <mpm@selenic.com> and others\n"
2746 "This is free software; see the source for copying conditions. "
2746 "This is free software; see the source for copying conditions. "
2747 "There is NO\nwarranty; "
2747 "There is NO\nwarranty; "
2748 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
2748 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
2749 ))
2749 ))
2750
2750
2751 # Command options and aliases are listed here, alphabetically
2751 # Command options and aliases are listed here, alphabetically
2752
2752
2753 globalopts = [
2753 globalopts = [
2754 ('R', 'repository', '',
2754 ('R', 'repository', '',
2755 _('repository root directory or symbolic path name')),
2755 _('repository root directory or symbolic path name')),
2756 ('', 'cwd', '', _('change working directory')),
2756 ('', 'cwd', '', _('change working directory')),
2757 ('y', 'noninteractive', None,
2757 ('y', 'noninteractive', None,
2758 _('do not prompt, assume \'yes\' for any required answers')),
2758 _('do not prompt, assume \'yes\' for any required answers')),
2759 ('q', 'quiet', None, _('suppress output')),
2759 ('q', 'quiet', None, _('suppress output')),
2760 ('v', 'verbose', None, _('enable additional output')),
2760 ('v', 'verbose', None, _('enable additional output')),
2761 ('', 'config', [], _('set/override config option')),
2761 ('', 'config', [], _('set/override config option')),
2762 ('', 'debug', None, _('enable debugging output')),
2762 ('', 'debug', None, _('enable debugging output')),
2763 ('', 'debugger', None, _('start debugger')),
2763 ('', 'debugger', None, _('start debugger')),
2764 ('', 'encoding', util._encoding, _('set the charset encoding')),
2764 ('', 'encoding', util._encoding, _('set the charset encoding')),
2765 ('', 'encodingmode', util._encodingmode, _('set the charset encoding mode')),
2765 ('', 'encodingmode', util._encodingmode, _('set the charset encoding mode')),
2766 ('', 'lsprof', None, _('print improved command execution profile')),
2766 ('', 'lsprof', None, _('print improved command execution profile')),
2767 ('', 'traceback', None, _('print traceback on exception')),
2767 ('', 'traceback', None, _('print traceback on exception')),
2768 ('', 'time', None, _('time how long the command takes')),
2768 ('', 'time', None, _('time how long the command takes')),
2769 ('', 'profile', None, _('print command execution profile')),
2769 ('', 'profile', None, _('print command execution profile')),
2770 ('', 'version', None, _('output version information and exit')),
2770 ('', 'version', None, _('output version information and exit')),
2771 ('h', 'help', None, _('display help and exit')),
2771 ('h', 'help', None, _('display help and exit')),
2772 ]
2772 ]
2773
2773
2774 dryrunopts = [('n', 'dry-run', None,
2774 dryrunopts = [('n', 'dry-run', None,
2775 _('do not perform actions, just print output'))]
2775 _('do not perform actions, just print output'))]
2776
2776
2777 remoteopts = [
2777 remoteopts = [
2778 ('e', 'ssh', '', _('specify ssh command to use')),
2778 ('e', 'ssh', '', _('specify ssh command to use')),
2779 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
2779 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
2780 ]
2780 ]
2781
2781
2782 walkopts = [
2782 walkopts = [
2783 ('I', 'include', [], _('include names matching the given patterns')),
2783 ('I', 'include', [], _('include names matching the given patterns')),
2784 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2784 ('X', 'exclude', [], _('exclude names matching the given patterns')),
2785 ]
2785 ]
2786
2786
2787 commitopts = [
2787 commitopts = [
2788 ('m', 'message', '', _('use <text> as commit message')),
2788 ('m', 'message', '', _('use <text> as commit message')),
2789 ('l', 'logfile', '', _('read commit message from <file>')),
2789 ('l', 'logfile', '', _('read commit message from <file>')),
2790 ]
2790 ]
2791
2791
2792 commitopts2 = [
2792 commitopts2 = [
2793 ('d', 'date', '', _('record datecode as commit date')),
2793 ('d', 'date', '', _('record datecode as commit date')),
2794 ('u', 'user', '', _('record user as committer')),
2794 ('u', 'user', '', _('record user as committer')),
2795 ]
2795 ]
2796
2796
2797 table = {
2797 table = {
2798 "^add": (add, walkopts + dryrunopts, _('hg add [OPTION]... [FILE]...')),
2798 "^add": (add, walkopts + dryrunopts, _('hg add [OPTION]... [FILE]...')),
2799 "addremove":
2799 "addremove":
2800 (addremove,
2800 (addremove,
2801 [('s', 'similarity', '',
2801 [('s', 'similarity', '',
2802 _('guess renamed files by similarity (0<=s<=100)')),
2802 _('guess renamed files by similarity (0<=s<=100)')),
2803 ] + walkopts + dryrunopts,
2803 ] + walkopts + dryrunopts,
2804 _('hg addremove [OPTION]... [FILE]...')),
2804 _('hg addremove [OPTION]... [FILE]...')),
2805 "^annotate":
2805 "^annotate":
2806 (annotate,
2806 (annotate,
2807 [('r', 'rev', '', _('annotate the specified revision')),
2807 [('r', 'rev', '', _('annotate the specified revision')),
2808 ('f', 'follow', None, _('follow file copies and renames')),
2808 ('f', 'follow', None, _('follow file copies and renames')),
2809 ('a', 'text', None, _('treat all files as text')),
2809 ('a', 'text', None, _('treat all files as text')),
2810 ('u', 'user', None, _('list the author')),
2810 ('u', 'user', None, _('list the author')),
2811 ('d', 'date', None, _('list the date')),
2811 ('d', 'date', None, _('list the date')),
2812 ('n', 'number', None, _('list the revision number (default)')),
2812 ('n', 'number', None, _('list the revision number (default)')),
2813 ('c', 'changeset', None, _('list the changeset')),
2813 ('c', 'changeset', None, _('list the changeset')),
2814 ('l', 'line-number', None,
2814 ('l', 'line-number', None,
2815 _('show line number at the first appearance'))
2815 _('show line number at the first appearance'))
2816 ] + walkopts,
2816 ] + walkopts,
2817 _('hg annotate [-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
2817 _('hg annotate [-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
2818 "archive":
2818 "archive":
2819 (archive,
2819 (archive,
2820 [('', 'no-decode', None, _('do not pass files through decoders')),
2820 [('', 'no-decode', None, _('do not pass files through decoders')),
2821 ('p', 'prefix', '', _('directory prefix for files in archive')),
2821 ('p', 'prefix', '', _('directory prefix for files in archive')),
2822 ('r', 'rev', '', _('revision to distribute')),
2822 ('r', 'rev', '', _('revision to distribute')),
2823 ('t', 'type', '', _('type of distribution to create')),
2823 ('t', 'type', '', _('type of distribution to create')),
2824 ] + walkopts,
2824 ] + walkopts,
2825 _('hg archive [OPTION]... DEST')),
2825 _('hg archive [OPTION]... DEST')),
2826 "backout":
2826 "backout":
2827 (backout,
2827 (backout,
2828 [('', 'merge', None,
2828 [('', 'merge', None,
2829 _('merge with old dirstate parent after backout')),
2829 _('merge with old dirstate parent after backout')),
2830 ('', 'parent', '', _('parent to choose when backing out merge')),
2830 ('', 'parent', '', _('parent to choose when backing out merge')),
2831 ('r', 'rev', '', _('revision to backout')),
2831 ('r', 'rev', '', _('revision to backout')),
2832 ] + walkopts + commitopts + commitopts2,
2832 ] + walkopts + commitopts + commitopts2,
2833 _('hg backout [OPTION]... [-r] REV')),
2833 _('hg backout [OPTION]... [-r] REV')),
2834 "branch":
2834 "branch":
2835 (branch,
2835 (branch,
2836 [('f', 'force', None,
2836 [('f', 'force', None,
2837 _('set branch name even if it shadows an existing branch'))],
2837 _('set branch name even if it shadows an existing branch'))],
2838 _('hg branch [NAME]')),
2838 _('hg branch [NAME]')),
2839 "branches":
2839 "branches":
2840 (branches,
2840 (branches,
2841 [('a', 'active', False,
2841 [('a', 'active', False,
2842 _('show only branches that have unmerged heads'))],
2842 _('show only branches that have unmerged heads'))],
2843 _('hg branches [-a]')),
2843 _('hg branches [-a]')),
2844 "bundle":
2844 "bundle":
2845 (bundle,
2845 (bundle,
2846 [('f', 'force', None,
2846 [('f', 'force', None,
2847 _('run even when remote repository is unrelated')),
2847 _('run even when remote repository is unrelated')),
2848 ('r', 'rev', [],
2848 ('r', 'rev', [],
2849 _('a changeset you would like to bundle')),
2849 _('a changeset you would like to bundle')),
2850 ('', 'base', [],
2850 ('', 'base', [],
2851 _('a base changeset to specify instead of a destination')),
2851 _('a base changeset to specify instead of a destination')),
2852 ] + remoteopts,
2852 ] + remoteopts,
2853 _('hg bundle [-f] [-r REV]... [--base REV]... FILE [DEST]')),
2853 _('hg bundle [-f] [-r REV]... [--base REV]... FILE [DEST]')),
2854 "cat":
2854 "cat":
2855 (cat,
2855 (cat,
2856 [('o', 'output', '', _('print output to file with formatted name')),
2856 [('o', 'output', '', _('print output to file with formatted name')),
2857 ('r', 'rev', '', _('print the given revision')),
2857 ('r', 'rev', '', _('print the given revision')),
2858 ] + walkopts,
2858 ] + walkopts,
2859 _('hg cat [OPTION]... FILE...')),
2859 _('hg cat [OPTION]... FILE...')),
2860 "^clone":
2860 "^clone":
2861 (clone,
2861 (clone,
2862 [('U', 'noupdate', None, _('do not update the new working directory')),
2862 [('U', 'noupdate', None, _('do not update the new working directory')),
2863 ('r', 'rev', [],
2863 ('r', 'rev', [],
2864 _('a changeset you would like to have after cloning')),
2864 _('a changeset you would like to have after cloning')),
2865 ('', 'pull', None, _('use pull protocol to copy metadata')),
2865 ('', 'pull', None, _('use pull protocol to copy metadata')),
2866 ('', 'uncompressed', None,
2866 ('', 'uncompressed', None,
2867 _('use uncompressed transfer (fast over LAN)')),
2867 _('use uncompressed transfer (fast over LAN)')),
2868 ] + remoteopts,
2868 ] + remoteopts,
2869 _('hg clone [OPTION]... SOURCE [DEST]')),
2869 _('hg clone [OPTION]... SOURCE [DEST]')),
2870 "^commit|ci":
2870 "^commit|ci":
2871 (commit,
2871 (commit,
2872 [('A', 'addremove', None,
2872 [('A', 'addremove', None,
2873 _('mark new/missing files as added/removed before committing')),
2873 _('mark new/missing files as added/removed before committing')),
2874 ] + walkopts + commitopts + commitopts2,
2874 ] + walkopts + commitopts + commitopts2,
2875 _('hg commit [OPTION]... [FILE]...')),
2875 _('hg commit [OPTION]... [FILE]...')),
2876 "copy|cp":
2876 "copy|cp":
2877 (copy,
2877 (copy,
2878 [('A', 'after', None, _('record a copy that has already occurred')),
2878 [('A', 'after', None, _('record a copy that has already occurred')),
2879 ('f', 'force', None,
2879 ('f', 'force', None,
2880 _('forcibly copy over an existing managed file')),
2880 _('forcibly copy over an existing managed file')),
2881 ] + walkopts + dryrunopts,
2881 ] + walkopts + dryrunopts,
2882 _('hg copy [OPTION]... [SOURCE]... DEST')),
2882 _('hg copy [OPTION]... [SOURCE]... DEST')),
2883 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2883 "debugancestor": (debugancestor, [], _('debugancestor INDEX REV1 REV2')),
2884 "debugcomplete":
2884 "debugcomplete":
2885 (debugcomplete,
2885 (debugcomplete,
2886 [('o', 'options', None, _('show the command options'))],
2886 [('o', 'options', None, _('show the command options'))],
2887 _('debugcomplete [-o] CMD')),
2887 _('debugcomplete [-o] CMD')),
2888 "debuginstall": (debuginstall, [], _('debuginstall')),
2888 "debuginstall": (debuginstall, [], _('debuginstall')),
2889 "debugrebuildstate":
2889 "debugrebuildstate":
2890 (debugrebuildstate,
2890 (debugrebuildstate,
2891 [('r', 'rev', '', _('revision to rebuild to'))],
2891 [('r', 'rev', '', _('revision to rebuild to'))],
2892 _('debugrebuildstate [-r REV] [REV]')),
2892 _('debugrebuildstate [-r REV] [REV]')),
2893 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2893 "debugcheckstate": (debugcheckstate, [], _('debugcheckstate')),
2894 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2894 "debugsetparents": (debugsetparents, [], _('debugsetparents REV1 [REV2]')),
2895 "debugstate": (debugstate, [], _('debugstate')),
2895 "debugstate": (debugstate, [], _('debugstate')),
2896 "debugdate":
2896 "debugdate":
2897 (debugdate,
2897 (debugdate,
2898 [('e', 'extended', None, _('try extended date formats'))],
2898 [('e', 'extended', None, _('try extended date formats'))],
2899 _('debugdate [-e] DATE [RANGE]')),
2899 _('debugdate [-e] DATE [RANGE]')),
2900 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2900 "debugdata": (debugdata, [], _('debugdata FILE REV')),
2901 "debugindex": (debugindex, [], _('debugindex FILE')),
2901 "debugindex": (debugindex, [], _('debugindex FILE')),
2902 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2902 "debugindexdot": (debugindexdot, [], _('debugindexdot FILE')),
2903 "debugrename":
2903 "debugrename":
2904 (debugrename,
2904 (debugrename,
2905 [('r', 'rev', '', _('revision to debug'))],
2905 [('r', 'rev', '', _('revision to debug'))],
2906 _('debugrename [-r REV] FILE')),
2906 _('debugrename [-r REV] FILE')),
2907 "debugwalk": (debugwalk, walkopts, _('debugwalk [OPTION]... [FILE]...')),
2907 "debugwalk": (debugwalk, walkopts, _('debugwalk [OPTION]... [FILE]...')),
2908 "^diff":
2908 "^diff":
2909 (diff,
2909 (diff,
2910 [('r', 'rev', [], _('revision')),
2910 [('r', 'rev', [], _('revision')),
2911 ('a', 'text', None, _('treat all files as text')),
2911 ('a', 'text', None, _('treat all files as text')),
2912 ('p', 'show-function', None,
2912 ('p', 'show-function', None,
2913 _('show which function each change is in')),
2913 _('show which function each change is in')),
2914 ('g', 'git', None, _('use git extended diff format')),
2914 ('g', 'git', None, _('use git extended diff format')),
2915 ('', 'nodates', None, _("don't include dates in diff headers")),
2915 ('', 'nodates', None, _("don't include dates in diff headers")),
2916 ('w', 'ignore-all-space', None,
2916 ('w', 'ignore-all-space', None,
2917 _('ignore white space when comparing lines')),
2917 _('ignore white space when comparing lines')),
2918 ('b', 'ignore-space-change', None,
2918 ('b', 'ignore-space-change', None,
2919 _('ignore changes in the amount of white space')),
2919 _('ignore changes in the amount of white space')),
2920 ('B', 'ignore-blank-lines', None,
2920 ('B', 'ignore-blank-lines', None,
2921 _('ignore changes whose lines are all blank')),
2921 _('ignore changes whose lines are all blank')),
2922 ] + walkopts,
2922 ] + walkopts,
2923 _('hg diff [OPTION]... [-r REV1 [-r REV2]] [FILE]...')),
2923 _('hg diff [OPTION]... [-r REV1 [-r REV2]] [FILE]...')),
2924 "^export":
2924 "^export":
2925 (export,
2925 (export,
2926 [('o', 'output', '', _('print output to file with formatted name')),
2926 [('o', 'output', '', _('print output to file with formatted name')),
2927 ('a', 'text', None, _('treat all files as text')),
2927 ('a', 'text', None, _('treat all files as text')),
2928 ('g', 'git', None, _('use git extended diff format')),
2928 ('g', 'git', None, _('use git extended diff format')),
2929 ('', 'nodates', None, _("don't include dates in diff headers")),
2929 ('', 'nodates', None, _("don't include dates in diff headers")),
2930 ('', 'switch-parent', None, _('diff against the second parent'))],
2930 ('', 'switch-parent', None, _('diff against the second parent'))],
2931 _('hg export [OPTION]... [-o OUTFILESPEC] REV...')),
2931 _('hg export [OPTION]... [-o OUTFILESPEC] REV...')),
2932 "grep":
2932 "grep":
2933 (grep,
2933 (grep,
2934 [('0', 'print0', None, _('end fields with NUL')),
2934 [('0', 'print0', None, _('end fields with NUL')),
2935 ('', 'all', None, _('print all revisions that match')),
2935 ('', 'all', None, _('print all revisions that match')),
2936 ('f', 'follow', None,
2936 ('f', 'follow', None,
2937 _('follow changeset history, or file history across copies and renames')),
2937 _('follow changeset history, or file history across copies and renames')),
2938 ('i', 'ignore-case', None, _('ignore case when matching')),
2938 ('i', 'ignore-case', None, _('ignore case when matching')),
2939 ('l', 'files-with-matches', None,
2939 ('l', 'files-with-matches', None,
2940 _('print only filenames and revs that match')),
2940 _('print only filenames and revs that match')),
2941 ('n', 'line-number', None, _('print matching line numbers')),
2941 ('n', 'line-number', None, _('print matching line numbers')),
2942 ('r', 'rev', [], _('search in given revision range')),
2942 ('r', 'rev', [], _('search in given revision range')),
2943 ('u', 'user', None, _('print user who committed change')),
2943 ('u', 'user', None, _('print user who committed change')),
2944 ] + walkopts,
2944 ] + walkopts,
2945 _('hg grep [OPTION]... PATTERN [FILE]...')),
2945 _('hg grep [OPTION]... PATTERN [FILE]...')),
2946 "heads":
2946 "heads":
2947 (heads,
2947 (heads,
2948 [('', 'style', '', _('display using template map file')),
2948 [('', 'style', '', _('display using template map file')),
2949 ('r', 'rev', '', _('show only heads which are descendants of rev')),
2949 ('r', 'rev', '', _('show only heads which are descendants of rev')),
2950 ('', 'template', '', _('display with template'))],
2950 ('', 'template', '', _('display with template'))],
2951 _('hg heads [-r REV] [REV]...')),
2951 _('hg heads [-r REV] [REV]...')),
2952 "help": (help_, [], _('hg help [COMMAND]')),
2952 "help": (help_, [], _('hg help [COMMAND]')),
2953 "identify|id":
2953 "identify|id":
2954 (identify,
2954 (identify,
2955 [('r', 'rev', '', _('identify the specified rev')),
2955 [('r', 'rev', '', _('identify the specified rev')),
2956 ('n', 'num', None, _('show local revision number')),
2956 ('n', 'num', None, _('show local revision number')),
2957 ('i', 'id', None, _('show global revision id')),
2957 ('i', 'id', None, _('show global revision id')),
2958 ('b', 'branch', None, _('show branch')),
2958 ('b', 'branch', None, _('show branch')),
2959 ('t', 'tags', None, _('show tags'))],
2959 ('t', 'tags', None, _('show tags'))],
2960 _('hg identify [-nibt] [-r REV] [SOURCE]')),
2960 _('hg identify [-nibt] [-r REV] [SOURCE]')),
2961 "import|patch":
2961 "import|patch":
2962 (import_,
2962 (import_,
2963 [('p', 'strip', 1,
2963 [('p', 'strip', 1,
2964 _('directory strip option for patch. This has the same\n'
2964 _('directory strip option for patch. This has the same\n'
2965 'meaning as the corresponding patch option')),
2965 'meaning as the corresponding patch option')),
2966 ('b', 'base', '', _('base path')),
2966 ('b', 'base', '', _('base path')),
2967 ('f', 'force', None,
2967 ('f', 'force', None,
2968 _('skip check for outstanding uncommitted changes')),
2968 _('skip check for outstanding uncommitted changes')),
2969 ('', 'exact', None,
2969 ('', 'exact', None,
2970 _('apply patch to the nodes from which it was generated')),
2970 _('apply patch to the nodes from which it was generated')),
2971 ('', 'import-branch', None,
2971 ('', 'import-branch', None,
2972 _('Use any branch information in patch (implied by --exact)'))] + commitopts,
2972 _('Use any branch information in patch (implied by --exact)'))] + commitopts,
2973 _('hg import [-p NUM] [-m MESSAGE] [-f] PATCH...')),
2973 _('hg import [-p NUM] [-m MESSAGE] [-f] PATCH...')),
2974 "incoming|in": (incoming,
2974 "incoming|in": (incoming,
2975 [('M', 'no-merges', None, _('do not show merges')),
2975 [('M', 'no-merges', None, _('do not show merges')),
2976 ('f', 'force', None,
2976 ('f', 'force', None,
2977 _('run even when remote repository is unrelated')),
2977 _('run even when remote repository is unrelated')),
2978 ('', 'style', '', _('display using template map file')),
2978 ('', 'style', '', _('display using template map file')),
2979 ('n', 'newest-first', None, _('show newest record first')),
2979 ('n', 'newest-first', None, _('show newest record first')),
2980 ('', 'bundle', '', _('file to store the bundles into')),
2980 ('', 'bundle', '', _('file to store the bundles into')),
2981 ('p', 'patch', None, _('show patch')),
2981 ('p', 'patch', None, _('show patch')),
2982 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
2982 ('r', 'rev', [], _('a specific revision up to which you would like to pull')),
2983 ('', 'template', '', _('display with template')),
2983 ('', 'template', '', _('display with template')),
2984 ] + remoteopts,
2984 ] + remoteopts,
2985 _('hg incoming [-p] [-n] [-M] [-f] [-r REV]...'
2985 _('hg incoming [-p] [-n] [-M] [-f] [-r REV]...'
2986 ' [--bundle FILENAME] [SOURCE]')),
2986 ' [--bundle FILENAME] [SOURCE]')),
2987 "^init":
2987 "^init":
2988 (init,
2988 (init,
2989 remoteopts,
2989 remoteopts,
2990 _('hg init [-e CMD] [--remotecmd CMD] [DEST]')),
2990 _('hg init [-e CMD] [--remotecmd CMD] [DEST]')),
2991 "locate":
2991 "locate":
2992 (locate,
2992 (locate,
2993 [('r', 'rev', '', _('search the repository as it stood at rev')),
2993 [('r', 'rev', '', _('search the repository as it stood at rev')),
2994 ('0', 'print0', None,
2994 ('0', 'print0', None,
2995 _('end filenames with NUL, for use with xargs')),
2995 _('end filenames with NUL, for use with xargs')),
2996 ('f', 'fullpath', None,
2996 ('f', 'fullpath', None,
2997 _('print complete paths from the filesystem root')),
2997 _('print complete paths from the filesystem root')),
2998 ] + walkopts,
2998 ] + walkopts,
2999 _('hg locate [OPTION]... [PATTERN]...')),
2999 _('hg locate [OPTION]... [PATTERN]...')),
3000 "^log|history":
3000 "^log|history":
3001 (log,
3001 (log,
3002 [('f', 'follow', None,
3002 [('f', 'follow', None,
3003 _('follow changeset history, or file history across copies and renames')),
3003 _('follow changeset history, or file history across copies and renames')),
3004 ('', 'follow-first', None,
3004 ('', 'follow-first', None,
3005 _('only follow the first parent of merge changesets')),
3005 _('only follow the first parent of merge changesets')),
3006 ('d', 'date', '', _('show revs matching date spec')),
3006 ('d', 'date', '', _('show revs matching date spec')),
3007 ('C', 'copies', None, _('show copied files')),
3007 ('C', 'copies', None, _('show copied files')),
3008 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3008 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3009 ('l', 'limit', '', _('limit number of changes displayed')),
3009 ('l', 'limit', '', _('limit number of changes displayed')),
3010 ('r', 'rev', [], _('show the specified revision or range')),
3010 ('r', 'rev', [], _('show the specified revision or range')),
3011 ('', 'removed', None, _('include revs where files were removed')),
3011 ('', 'removed', None, _('include revs where files were removed')),
3012 ('M', 'no-merges', None, _('do not show merges')),
3012 ('M', 'no-merges', None, _('do not show merges')),
3013 ('', 'style', '', _('display using template map file')),
3013 ('', 'style', '', _('display using template map file')),
3014 ('m', 'only-merges', None, _('show only merges')),
3014 ('m', 'only-merges', None, _('show only merges')),
3015 ('p', 'patch', None, _('show patch')),
3015 ('p', 'patch', None, _('show patch')),
3016 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3016 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3017 ('', 'template', '', _('display with template')),
3017 ('', 'template', '', _('display with template')),
3018 ] + walkopts,
3018 ] + walkopts,
3019 _('hg log [OPTION]... [FILE]')),
3019 _('hg log [OPTION]... [FILE]')),
3020 "manifest": (manifest, [('r', 'rev', '', _('revision to display'))],
3020 "manifest": (manifest, [('r', 'rev', '', _('revision to display'))],
3021 _('hg manifest [-r REV]')),
3021 _('hg manifest [-r REV]')),
3022 "^merge":
3022 "^merge":
3023 (merge,
3023 (merge,
3024 [('f', 'force', None, _('force a merge with outstanding changes')),
3024 [('f', 'force', None, _('force a merge with outstanding changes')),
3025 ('r', 'rev', '', _('revision to merge')),
3025 ('r', 'rev', '', _('revision to merge')),
3026 ],
3026 ],
3027 _('hg merge [-f] [[-r] REV]')),
3027 _('hg merge [-f] [[-r] REV]')),
3028 "outgoing|out": (outgoing,
3028 "outgoing|out": (outgoing,
3029 [('M', 'no-merges', None, _('do not show merges')),
3029 [('M', 'no-merges', None, _('do not show merges')),
3030 ('f', 'force', None,
3030 ('f', 'force', None,
3031 _('run even when remote repository is unrelated')),
3031 _('run even when remote repository is unrelated')),
3032 ('p', 'patch', None, _('show patch')),
3032 ('p', 'patch', None, _('show patch')),
3033 ('', 'style', '', _('display using template map file')),
3033 ('', 'style', '', _('display using template map file')),
3034 ('r', 'rev', [], _('a specific revision you would like to push')),
3034 ('r', 'rev', [], _('a specific revision you would like to push')),
3035 ('n', 'newest-first', None, _('show newest record first')),
3035 ('n', 'newest-first', None, _('show newest record first')),
3036 ('', 'template', '', _('display with template')),
3036 ('', 'template', '', _('display with template')),
3037 ] + remoteopts,
3037 ] + remoteopts,
3038 _('hg outgoing [-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3038 _('hg outgoing [-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3039 "^parents":
3039 "^parents":
3040 (parents,
3040 (parents,
3041 [('r', 'rev', '', _('show parents from the specified rev')),
3041 [('r', 'rev', '', _('show parents from the specified rev')),
3042 ('', 'style', '', _('display using template map file')),
3042 ('', 'style', '', _('display using template map file')),
3043 ('', 'template', '', _('display with template'))],
3043 ('', 'template', '', _('display with template'))],
3044 _('hg parents [-r REV] [FILE]')),
3044 _('hg parents [-r REV] [FILE]')),
3045 "paths": (paths, [], _('hg paths [NAME]')),
3045 "paths": (paths, [], _('hg paths [NAME]')),
3046 "^pull":
3046 "^pull":
3047 (pull,
3047 (pull,
3048 [('u', 'update', None,
3048 [('u', 'update', None,
3049 _('update to new tip if changesets were pulled')),
3049 _('update to new tip if changesets were pulled')),
3050 ('f', 'force', None,
3050 ('f', 'force', None,
3051 _('run even when remote repository is unrelated')),
3051 _('run even when remote repository is unrelated')),
3052 ('r', 'rev', [],
3052 ('r', 'rev', [],
3053 _('a specific revision up to which you would like to pull')),
3053 _('a specific revision up to which you would like to pull')),
3054 ] + remoteopts,
3054 ] + remoteopts,
3055 _('hg pull [-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3055 _('hg pull [-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3056 "^push":
3056 "^push":
3057 (push,
3057 (push,
3058 [('f', 'force', None, _('force push')),
3058 [('f', 'force', None, _('force push')),
3059 ('r', 'rev', [], _('a specific revision you would like to push')),
3059 ('r', 'rev', [], _('a specific revision you would like to push')),
3060 ] + remoteopts,
3060 ] + remoteopts,
3061 _('hg push [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3061 _('hg push [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3062 "debugrawcommit|rawcommit":
3062 "debugrawcommit|rawcommit":
3063 (rawcommit,
3063 (rawcommit,
3064 [('p', 'parent', [], _('parent')),
3064 [('p', 'parent', [], _('parent')),
3065 ('F', 'files', '', _('file list'))
3065 ('F', 'files', '', _('file list'))
3066 ] + commitopts + commitopts2,
3066 ] + commitopts + commitopts2,
3067 _('hg debugrawcommit [OPTION]... [FILE]...')),
3067 _('hg debugrawcommit [OPTION]... [FILE]...')),
3068 "recover": (recover, [], _('hg recover')),
3068 "recover": (recover, [], _('hg recover')),
3069 "^remove|rm":
3069 "^remove|rm":
3070 (remove,
3070 (remove,
3071 [('A', 'after', None, _('record remove that has already occurred')),
3071 [('A', 'after', None, _('record remove that has already occurred')),
3072 ('f', 'force', None, _('remove file even if modified')),
3072 ('f', 'force', None, _('remove file even if modified')),
3073 ] + walkopts,
3073 ] + walkopts,
3074 _('hg remove [OPTION]... FILE...')),
3074 _('hg remove [OPTION]... FILE...')),
3075 "rename|mv":
3075 "rename|mv":
3076 (rename,
3076 (rename,
3077 [('A', 'after', None, _('record a rename that has already occurred')),
3077 [('A', 'after', None, _('record a rename that has already occurred')),
3078 ('f', 'force', None,
3078 ('f', 'force', None,
3079 _('forcibly copy over an existing managed file')),
3079 _('forcibly copy over an existing managed file')),
3080 ] + walkopts + dryrunopts,
3080 ] + walkopts + dryrunopts,
3081 _('hg rename [OPTION]... SOURCE... DEST')),
3081 _('hg rename [OPTION]... SOURCE... DEST')),
3082 "^revert":
3082 "^revert":
3083 (revert,
3083 (revert,
3084 [('a', 'all', None, _('revert all changes when no arguments given')),
3084 [('a', 'all', None, _('revert all changes when no arguments given')),
3085 ('d', 'date', '', _('tipmost revision matching date')),
3085 ('d', 'date', '', _('tipmost revision matching date')),
3086 ('r', 'rev', '', _('revision to revert to')),
3086 ('r', 'rev', '', _('revision to revert to')),
3087 ('', 'no-backup', None, _('do not save backup copies of files')),
3087 ('', 'no-backup', None, _('do not save backup copies of files')),
3088 ] + walkopts + dryrunopts,
3088 ] + walkopts + dryrunopts,
3089 _('hg revert [OPTION]... [-r REV] [NAME]...')),
3089 _('hg revert [OPTION]... [-r REV] [NAME]...')),
3090 "rollback": (rollback, [], _('hg rollback')),
3090 "rollback": (rollback, [], _('hg rollback')),
3091 "root": (root, [], _('hg root')),
3091 "root": (root, [], _('hg root')),
3092 "showconfig|debugconfig":
3092 "showconfig|debugconfig":
3093 (showconfig,
3093 (showconfig,
3094 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3094 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3095 _('showconfig [-u] [NAME]...')),
3095 _('showconfig [-u] [NAME]...')),
3096 "^serve":
3096 "^serve":
3097 (serve,
3097 (serve,
3098 [('A', 'accesslog', '', _('name of access log file to write to')),
3098 [('A', 'accesslog', '', _('name of access log file to write to')),
3099 ('d', 'daemon', None, _('run server in background')),
3099 ('d', 'daemon', None, _('run server in background')),
3100 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3100 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3101 ('E', 'errorlog', '', _('name of error log file to write to')),
3101 ('E', 'errorlog', '', _('name of error log file to write to')),
3102 ('p', 'port', 0, _('port to use (default: 8000)')),
3102 ('p', 'port', 0, _('port to use (default: 8000)')),
3103 ('a', 'address', '', _('address to use')),
3103 ('a', 'address', '', _('address to use')),
3104 ('n', 'name', '',
3104 ('n', 'name', '',
3105 _('name to show in web pages (default: working dir)')),
3105 _('name to show in web pages (default: working dir)')),
3106 ('', 'webdir-conf', '', _('name of the webdir config file'
3106 ('', 'webdir-conf', '', _('name of the webdir config file'
3107 ' (serve more than one repo)')),
3107 ' (serve more than one repo)')),
3108 ('', 'pid-file', '', _('name of file to write process ID to')),
3108 ('', 'pid-file', '', _('name of file to write process ID to')),
3109 ('', 'stdio', None, _('for remote clients')),
3109 ('', 'stdio', None, _('for remote clients')),
3110 ('t', 'templates', '', _('web templates to use')),
3110 ('t', 'templates', '', _('web templates to use')),
3111 ('', 'style', '', _('template style to use')),
3111 ('', 'style', '', _('template style to use')),
3112 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3112 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3113 ('', 'certificate', '', _('SSL certificate file'))],
3113 ('', 'certificate', '', _('SSL certificate file'))],
3114 _('hg serve [OPTION]...')),
3114 _('hg serve [OPTION]...')),
3115 "^status|st":
3115 "^status|st":
3116 (status,
3116 (status,
3117 [('A', 'all', None, _('show status of all files')),
3117 [('A', 'all', None, _('show status of all files')),
3118 ('m', 'modified', None, _('show only modified files')),
3118 ('m', 'modified', None, _('show only modified files')),
3119 ('a', 'added', None, _('show only added files')),
3119 ('a', 'added', None, _('show only added files')),
3120 ('r', 'removed', None, _('show only removed files')),
3120 ('r', 'removed', None, _('show only removed files')),
3121 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3121 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3122 ('c', 'clean', None, _('show only files without changes')),
3122 ('c', 'clean', None, _('show only files without changes')),
3123 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3123 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3124 ('i', 'ignored', None, _('show only ignored files')),
3124 ('i', 'ignored', None, _('show only ignored files')),
3125 ('n', 'no-status', None, _('hide status prefix')),
3125 ('n', 'no-status', None, _('hide status prefix')),
3126 ('C', 'copies', None, _('show source of copied files')),
3126 ('C', 'copies', None, _('show source of copied files')),
3127 ('0', 'print0', None,
3127 ('0', 'print0', None,
3128 _('end filenames with NUL, for use with xargs')),
3128 _('end filenames with NUL, for use with xargs')),
3129 ('', 'rev', [], _('show difference from revision')),
3129 ('', 'rev', [], _('show difference from revision')),
3130 ] + walkopts,
3130 ] + walkopts,
3131 _('hg status [OPTION]... [FILE]...')),
3131 _('hg status [OPTION]... [FILE]...')),
3132 "tag":
3132 "tag":
3133 (tag,
3133 (tag,
3134 [('f', 'force', None, _('replace existing tag')),
3134 [('f', 'force', None, _('replace existing tag')),
3135 ('l', 'local', None, _('make the tag local')),
3135 ('l', 'local', None, _('make the tag local')),
3136 ('r', 'rev', '', _('revision to tag')),
3136 ('r', 'rev', '', _('revision to tag')),
3137 ('', 'remove', None, _('remove a tag')),
3137 ('', 'remove', None, _('remove a tag')),
3138 # -l/--local is already there, commitopts cannot be used
3138 # -l/--local is already there, commitopts cannot be used
3139 ('m', 'message', '', _('use <text> as commit message')),
3139 ('m', 'message', '', _('use <text> as commit message')),
3140 ] + commitopts2,
3140 ] + commitopts2,
3141 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3141 _('hg tag [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME')),
3142 "tags": (tags, [], _('hg tags')),
3142 "tags": (tags, [], _('hg tags')),
3143 "tip":
3143 "tip":
3144 (tip,
3144 (tip,
3145 [('', 'style', '', _('display using template map file')),
3145 [('', 'style', '', _('display using template map file')),
3146 ('p', 'patch', None, _('show patch')),
3146 ('p', 'patch', None, _('show patch')),
3147 ('', 'template', '', _('display with template'))],
3147 ('', 'template', '', _('display with template'))],
3148 _('hg tip [-p]')),
3148 _('hg tip [-p]')),
3149 "unbundle":
3149 "unbundle":
3150 (unbundle,
3150 (unbundle,
3151 [('u', 'update', None,
3151 [('u', 'update', None,
3152 _('update to new tip if changesets were unbundled'))],
3152 _('update to new tip if changesets were unbundled'))],
3153 _('hg unbundle [-u] FILE...')),
3153 _('hg unbundle [-u] FILE...')),
3154 "^update|up|checkout|co":
3154 "^update|up|checkout|co":
3155 (update,
3155 (update,
3156 [('C', 'clean', None, _('overwrite locally modified files')),
3156 [('C', 'clean', None, _('overwrite locally modified files')),
3157 ('d', 'date', '', _('tipmost revision matching date')),
3157 ('d', 'date', '', _('tipmost revision matching date')),
3158 ('r', 'rev', '', _('revision'))],
3158 ('r', 'rev', '', _('revision'))],
3159 _('hg update [-C] [-d DATE] [[-r] REV]')),
3159 _('hg update [-C] [-d DATE] [[-r] REV]')),
3160 "verify": (verify, [], _('hg verify')),
3160 "verify": (verify, [], _('hg verify')),
3161 "version": (version_, [], _('hg version')),
3161 "version": (version_, [], _('hg version')),
3162 }
3162 }
3163
3163
3164 norepo = ("clone init version help debugancestor debugcomplete debugdata"
3164 norepo = ("clone init version help debugancestor debugcomplete debugdata"
3165 " debugindex debugindexdot debugdate debuginstall")
3165 " debugindex debugindexdot debugdate debuginstall")
3166 optionalrepo = ("identify paths serve showconfig")
3166 optionalrepo = ("identify paths serve showconfig")
@@ -1,1700 +1,1731 b''
1 """
1 """
2 util.py - Mercurial utility functions and platform specfic implementations
2 util.py - Mercurial utility functions and platform specfic implementations
3
3
4 Copyright 2005 K. Thananchayan <thananck@yahoo.com>
4 Copyright 2005 K. Thananchayan <thananck@yahoo.com>
5 Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
5 Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
6 Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
6 Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
7
7
8 This software may be used and distributed according to the terms
8 This software may be used and distributed according to the terms
9 of the GNU General Public License, incorporated herein by reference.
9 of the GNU General Public License, incorporated herein by reference.
10
10
11 This contains helper routines that are independent of the SCM core and hide
11 This contains helper routines that are independent of the SCM core and hide
12 platform-specific details from the core.
12 platform-specific details from the core.
13 """
13 """
14
14
15 from i18n import _
15 from i18n import _
16 import cStringIO, errno, getpass, popen2, re, shutil, sys, tempfile, strutil
16 import cStringIO, errno, getpass, popen2, re, shutil, sys, tempfile, strutil
17 import os, stat, threading, time, calendar, ConfigParser, locale, glob, osutil
17 import os, stat, threading, time, calendar, ConfigParser, locale, glob, osutil
18 import re, urlparse
18
19
19 try:
20 try:
20 set = set
21 set = set
21 frozenset = frozenset
22 frozenset = frozenset
22 except NameError:
23 except NameError:
23 from sets import Set as set, ImmutableSet as frozenset
24 from sets import Set as set, ImmutableSet as frozenset
24
25
25 try:
26 try:
26 _encoding = os.environ.get("HGENCODING")
27 _encoding = os.environ.get("HGENCODING")
27 if sys.platform == 'darwin' and not _encoding:
28 if sys.platform == 'darwin' and not _encoding:
28 # On darwin, getpreferredencoding ignores the locale environment and
29 # On darwin, getpreferredencoding ignores the locale environment and
29 # always returns mac-roman. We override this if the environment is
30 # always returns mac-roman. We override this if the environment is
30 # not C (has been customized by the user).
31 # not C (has been customized by the user).
31 locale.setlocale(locale.LC_CTYPE, '')
32 locale.setlocale(locale.LC_CTYPE, '')
32 _encoding = locale.getlocale()[1]
33 _encoding = locale.getlocale()[1]
33 if not _encoding:
34 if not _encoding:
34 _encoding = locale.getpreferredencoding() or 'ascii'
35 _encoding = locale.getpreferredencoding() or 'ascii'
35 except locale.Error:
36 except locale.Error:
36 _encoding = 'ascii'
37 _encoding = 'ascii'
37 _encodingmode = os.environ.get("HGENCODINGMODE", "strict")
38 _encodingmode = os.environ.get("HGENCODINGMODE", "strict")
38 _fallbackencoding = 'ISO-8859-1'
39 _fallbackencoding = 'ISO-8859-1'
39
40
40 def tolocal(s):
41 def tolocal(s):
41 """
42 """
42 Convert a string from internal UTF-8 to local encoding
43 Convert a string from internal UTF-8 to local encoding
43
44
44 All internal strings should be UTF-8 but some repos before the
45 All internal strings should be UTF-8 but some repos before the
45 implementation of locale support may contain latin1 or possibly
46 implementation of locale support may contain latin1 or possibly
46 other character sets. We attempt to decode everything strictly
47 other character sets. We attempt to decode everything strictly
47 using UTF-8, then Latin-1, and failing that, we use UTF-8 and
48 using UTF-8, then Latin-1, and failing that, we use UTF-8 and
48 replace unknown characters.
49 replace unknown characters.
49 """
50 """
50 for e in ('UTF-8', _fallbackencoding):
51 for e in ('UTF-8', _fallbackencoding):
51 try:
52 try:
52 u = s.decode(e) # attempt strict decoding
53 u = s.decode(e) # attempt strict decoding
53 return u.encode(_encoding, "replace")
54 return u.encode(_encoding, "replace")
54 except LookupError, k:
55 except LookupError, k:
55 raise Abort(_("%s, please check your locale settings") % k)
56 raise Abort(_("%s, please check your locale settings") % k)
56 except UnicodeDecodeError:
57 except UnicodeDecodeError:
57 pass
58 pass
58 u = s.decode("utf-8", "replace") # last ditch
59 u = s.decode("utf-8", "replace") # last ditch
59 return u.encode(_encoding, "replace")
60 return u.encode(_encoding, "replace")
60
61
61 def fromlocal(s):
62 def fromlocal(s):
62 """
63 """
63 Convert a string from the local character encoding to UTF-8
64 Convert a string from the local character encoding to UTF-8
64
65
65 We attempt to decode strings using the encoding mode set by
66 We attempt to decode strings using the encoding mode set by
66 HGENCODINGMODE, which defaults to 'strict'. In this mode, unknown
67 HGENCODINGMODE, which defaults to 'strict'. In this mode, unknown
67 characters will cause an error message. Other modes include
68 characters will cause an error message. Other modes include
68 'replace', which replaces unknown characters with a special
69 'replace', which replaces unknown characters with a special
69 Unicode character, and 'ignore', which drops the character.
70 Unicode character, and 'ignore', which drops the character.
70 """
71 """
71 try:
72 try:
72 return s.decode(_encoding, _encodingmode).encode("utf-8")
73 return s.decode(_encoding, _encodingmode).encode("utf-8")
73 except UnicodeDecodeError, inst:
74 except UnicodeDecodeError, inst:
74 sub = s[max(0, inst.start-10):inst.start+10]
75 sub = s[max(0, inst.start-10):inst.start+10]
75 raise Abort("decoding near '%s': %s!" % (sub, inst))
76 raise Abort("decoding near '%s': %s!" % (sub, inst))
76 except LookupError, k:
77 except LookupError, k:
77 raise Abort(_("%s, please check your locale settings") % k)
78 raise Abort(_("%s, please check your locale settings") % k)
78
79
79 def locallen(s):
80 def locallen(s):
80 """Find the length in characters of a local string"""
81 """Find the length in characters of a local string"""
81 return len(s.decode(_encoding, "replace"))
82 return len(s.decode(_encoding, "replace"))
82
83
83 def localsub(s, a, b=None):
84 def localsub(s, a, b=None):
84 try:
85 try:
85 u = s.decode(_encoding, _encodingmode)
86 u = s.decode(_encoding, _encodingmode)
86 if b is not None:
87 if b is not None:
87 u = u[a:b]
88 u = u[a:b]
88 else:
89 else:
89 u = u[:a]
90 u = u[:a]
90 return u.encode(_encoding, _encodingmode)
91 return u.encode(_encoding, _encodingmode)
91 except UnicodeDecodeError, inst:
92 except UnicodeDecodeError, inst:
92 sub = s[max(0, inst.start-10), inst.start+10]
93 sub = s[max(0, inst.start-10), inst.start+10]
93 raise Abort(_("decoding near '%s': %s!") % (sub, inst))
94 raise Abort(_("decoding near '%s': %s!") % (sub, inst))
94
95
95 # used by parsedate
96 # used by parsedate
96 defaultdateformats = (
97 defaultdateformats = (
97 '%Y-%m-%d %H:%M:%S',
98 '%Y-%m-%d %H:%M:%S',
98 '%Y-%m-%d %I:%M:%S%p',
99 '%Y-%m-%d %I:%M:%S%p',
99 '%Y-%m-%d %H:%M',
100 '%Y-%m-%d %H:%M',
100 '%Y-%m-%d %I:%M%p',
101 '%Y-%m-%d %I:%M%p',
101 '%Y-%m-%d',
102 '%Y-%m-%d',
102 '%m-%d',
103 '%m-%d',
103 '%m/%d',
104 '%m/%d',
104 '%m/%d/%y',
105 '%m/%d/%y',
105 '%m/%d/%Y',
106 '%m/%d/%Y',
106 '%a %b %d %H:%M:%S %Y',
107 '%a %b %d %H:%M:%S %Y',
107 '%a %b %d %I:%M:%S%p %Y',
108 '%a %b %d %I:%M:%S%p %Y',
108 '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
109 '%a, %d %b %Y %H:%M:%S', # GNU coreutils "/bin/date --rfc-2822"
109 '%b %d %H:%M:%S %Y',
110 '%b %d %H:%M:%S %Y',
110 '%b %d %I:%M:%S%p %Y',
111 '%b %d %I:%M:%S%p %Y',
111 '%b %d %H:%M:%S',
112 '%b %d %H:%M:%S',
112 '%b %d %I:%M:%S%p',
113 '%b %d %I:%M:%S%p',
113 '%b %d %H:%M',
114 '%b %d %H:%M',
114 '%b %d %I:%M%p',
115 '%b %d %I:%M%p',
115 '%b %d %Y',
116 '%b %d %Y',
116 '%b %d',
117 '%b %d',
117 '%H:%M:%S',
118 '%H:%M:%S',
118 '%I:%M:%SP',
119 '%I:%M:%SP',
119 '%H:%M',
120 '%H:%M',
120 '%I:%M%p',
121 '%I:%M%p',
121 )
122 )
122
123
123 extendeddateformats = defaultdateformats + (
124 extendeddateformats = defaultdateformats + (
124 "%Y",
125 "%Y",
125 "%Y-%m",
126 "%Y-%m",
126 "%b",
127 "%b",
127 "%b %Y",
128 "%b %Y",
128 )
129 )
129
130
130 class SignalInterrupt(Exception):
131 class SignalInterrupt(Exception):
131 """Exception raised on SIGTERM and SIGHUP."""
132 """Exception raised on SIGTERM and SIGHUP."""
132
133
133 # differences from SafeConfigParser:
134 # differences from SafeConfigParser:
134 # - case-sensitive keys
135 # - case-sensitive keys
135 # - allows values that are not strings (this means that you may not
136 # - allows values that are not strings (this means that you may not
136 # be able to save the configuration to a file)
137 # be able to save the configuration to a file)
137 class configparser(ConfigParser.SafeConfigParser):
138 class configparser(ConfigParser.SafeConfigParser):
138 def optionxform(self, optionstr):
139 def optionxform(self, optionstr):
139 return optionstr
140 return optionstr
140
141
141 def set(self, section, option, value):
142 def set(self, section, option, value):
142 return ConfigParser.ConfigParser.set(self, section, option, value)
143 return ConfigParser.ConfigParser.set(self, section, option, value)
143
144
144 def _interpolate(self, section, option, rawval, vars):
145 def _interpolate(self, section, option, rawval, vars):
145 if not isinstance(rawval, basestring):
146 if not isinstance(rawval, basestring):
146 return rawval
147 return rawval
147 return ConfigParser.SafeConfigParser._interpolate(self, section,
148 return ConfigParser.SafeConfigParser._interpolate(self, section,
148 option, rawval, vars)
149 option, rawval, vars)
149
150
150 def cachefunc(func):
151 def cachefunc(func):
151 '''cache the result of function calls'''
152 '''cache the result of function calls'''
152 # XXX doesn't handle keywords args
153 # XXX doesn't handle keywords args
153 cache = {}
154 cache = {}
154 if func.func_code.co_argcount == 1:
155 if func.func_code.co_argcount == 1:
155 # we gain a small amount of time because
156 # we gain a small amount of time because
156 # we don't need to pack/unpack the list
157 # we don't need to pack/unpack the list
157 def f(arg):
158 def f(arg):
158 if arg not in cache:
159 if arg not in cache:
159 cache[arg] = func(arg)
160 cache[arg] = func(arg)
160 return cache[arg]
161 return cache[arg]
161 else:
162 else:
162 def f(*args):
163 def f(*args):
163 if args not in cache:
164 if args not in cache:
164 cache[args] = func(*args)
165 cache[args] = func(*args)
165 return cache[args]
166 return cache[args]
166
167
167 return f
168 return f
168
169
169 def pipefilter(s, cmd):
170 def pipefilter(s, cmd):
170 '''filter string S through command CMD, returning its output'''
171 '''filter string S through command CMD, returning its output'''
171 (pin, pout) = os.popen2(cmd, 'b')
172 (pin, pout) = os.popen2(cmd, 'b')
172 def writer():
173 def writer():
173 try:
174 try:
174 pin.write(s)
175 pin.write(s)
175 pin.close()
176 pin.close()
176 except IOError, inst:
177 except IOError, inst:
177 if inst.errno != errno.EPIPE:
178 if inst.errno != errno.EPIPE:
178 raise
179 raise
179
180
180 # we should use select instead on UNIX, but this will work on most
181 # we should use select instead on UNIX, but this will work on most
181 # systems, including Windows
182 # systems, including Windows
182 w = threading.Thread(target=writer)
183 w = threading.Thread(target=writer)
183 w.start()
184 w.start()
184 f = pout.read()
185 f = pout.read()
185 pout.close()
186 pout.close()
186 w.join()
187 w.join()
187 return f
188 return f
188
189
189 def tempfilter(s, cmd):
190 def tempfilter(s, cmd):
190 '''filter string S through a pair of temporary files with CMD.
191 '''filter string S through a pair of temporary files with CMD.
191 CMD is used as a template to create the real command to be run,
192 CMD is used as a template to create the real command to be run,
192 with the strings INFILE and OUTFILE replaced by the real names of
193 with the strings INFILE and OUTFILE replaced by the real names of
193 the temporary files generated.'''
194 the temporary files generated.'''
194 inname, outname = None, None
195 inname, outname = None, None
195 try:
196 try:
196 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
197 infd, inname = tempfile.mkstemp(prefix='hg-filter-in-')
197 fp = os.fdopen(infd, 'wb')
198 fp = os.fdopen(infd, 'wb')
198 fp.write(s)
199 fp.write(s)
199 fp.close()
200 fp.close()
200 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
201 outfd, outname = tempfile.mkstemp(prefix='hg-filter-out-')
201 os.close(outfd)
202 os.close(outfd)
202 cmd = cmd.replace('INFILE', inname)
203 cmd = cmd.replace('INFILE', inname)
203 cmd = cmd.replace('OUTFILE', outname)
204 cmd = cmd.replace('OUTFILE', outname)
204 code = os.system(cmd)
205 code = os.system(cmd)
205 if sys.platform == 'OpenVMS' and code & 1:
206 if sys.platform == 'OpenVMS' and code & 1:
206 code = 0
207 code = 0
207 if code: raise Abort(_("command '%s' failed: %s") %
208 if code: raise Abort(_("command '%s' failed: %s") %
208 (cmd, explain_exit(code)))
209 (cmd, explain_exit(code)))
209 return open(outname, 'rb').read()
210 return open(outname, 'rb').read()
210 finally:
211 finally:
211 try:
212 try:
212 if inname: os.unlink(inname)
213 if inname: os.unlink(inname)
213 except: pass
214 except: pass
214 try:
215 try:
215 if outname: os.unlink(outname)
216 if outname: os.unlink(outname)
216 except: pass
217 except: pass
217
218
218 filtertable = {
219 filtertable = {
219 'tempfile:': tempfilter,
220 'tempfile:': tempfilter,
220 'pipe:': pipefilter,
221 'pipe:': pipefilter,
221 }
222 }
222
223
223 def filter(s, cmd):
224 def filter(s, cmd):
224 "filter a string through a command that transforms its input to its output"
225 "filter a string through a command that transforms its input to its output"
225 for name, fn in filtertable.iteritems():
226 for name, fn in filtertable.iteritems():
226 if cmd.startswith(name):
227 if cmd.startswith(name):
227 return fn(s, cmd[len(name):].lstrip())
228 return fn(s, cmd[len(name):].lstrip())
228 return pipefilter(s, cmd)
229 return pipefilter(s, cmd)
229
230
230 def binary(s):
231 def binary(s):
231 """return true if a string is binary data using diff's heuristic"""
232 """return true if a string is binary data using diff's heuristic"""
232 if s and '\0' in s[:4096]:
233 if s and '\0' in s[:4096]:
233 return True
234 return True
234 return False
235 return False
235
236
236 def unique(g):
237 def unique(g):
237 """return the uniq elements of iterable g"""
238 """return the uniq elements of iterable g"""
238 seen = {}
239 seen = {}
239 l = []
240 l = []
240 for f in g:
241 for f in g:
241 if f not in seen:
242 if f not in seen:
242 seen[f] = 1
243 seen[f] = 1
243 l.append(f)
244 l.append(f)
244 return l
245 return l
245
246
246 class Abort(Exception):
247 class Abort(Exception):
247 """Raised if a command needs to print an error and exit."""
248 """Raised if a command needs to print an error and exit."""
248
249
249 class UnexpectedOutput(Abort):
250 class UnexpectedOutput(Abort):
250 """Raised to print an error with part of output and exit."""
251 """Raised to print an error with part of output and exit."""
251
252
252 def always(fn): return True
253 def always(fn): return True
253 def never(fn): return False
254 def never(fn): return False
254
255
255 def expand_glob(pats):
256 def expand_glob(pats):
256 '''On Windows, expand the implicit globs in a list of patterns'''
257 '''On Windows, expand the implicit globs in a list of patterns'''
257 if os.name != 'nt':
258 if os.name != 'nt':
258 return list(pats)
259 return list(pats)
259 ret = []
260 ret = []
260 for p in pats:
261 for p in pats:
261 kind, name = patkind(p, None)
262 kind, name = patkind(p, None)
262 if kind is None:
263 if kind is None:
263 globbed = glob.glob(name)
264 globbed = glob.glob(name)
264 if globbed:
265 if globbed:
265 ret.extend(globbed)
266 ret.extend(globbed)
266 continue
267 continue
267 # if we couldn't expand the glob, just keep it around
268 # if we couldn't expand the glob, just keep it around
268 ret.append(p)
269 ret.append(p)
269 return ret
270 return ret
270
271
271 def patkind(name, dflt_pat='glob'):
272 def patkind(name, dflt_pat='glob'):
272 """Split a string into an optional pattern kind prefix and the
273 """Split a string into an optional pattern kind prefix and the
273 actual pattern."""
274 actual pattern."""
274 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
275 for prefix in 're', 'glob', 'path', 'relglob', 'relpath', 'relre':
275 if name.startswith(prefix + ':'): return name.split(':', 1)
276 if name.startswith(prefix + ':'): return name.split(':', 1)
276 return dflt_pat, name
277 return dflt_pat, name
277
278
278 def globre(pat, head='^', tail='$'):
279 def globre(pat, head='^', tail='$'):
279 "convert a glob pattern into a regexp"
280 "convert a glob pattern into a regexp"
280 i, n = 0, len(pat)
281 i, n = 0, len(pat)
281 res = ''
282 res = ''
282 group = False
283 group = False
283 def peek(): return i < n and pat[i]
284 def peek(): return i < n and pat[i]
284 while i < n:
285 while i < n:
285 c = pat[i]
286 c = pat[i]
286 i = i+1
287 i = i+1
287 if c == '*':
288 if c == '*':
288 if peek() == '*':
289 if peek() == '*':
289 i += 1
290 i += 1
290 res += '.*'
291 res += '.*'
291 else:
292 else:
292 res += '[^/]*'
293 res += '[^/]*'
293 elif c == '?':
294 elif c == '?':
294 res += '.'
295 res += '.'
295 elif c == '[':
296 elif c == '[':
296 j = i
297 j = i
297 if j < n and pat[j] in '!]':
298 if j < n and pat[j] in '!]':
298 j += 1
299 j += 1
299 while j < n and pat[j] != ']':
300 while j < n and pat[j] != ']':
300 j += 1
301 j += 1
301 if j >= n:
302 if j >= n:
302 res += '\\['
303 res += '\\['
303 else:
304 else:
304 stuff = pat[i:j].replace('\\','\\\\')
305 stuff = pat[i:j].replace('\\','\\\\')
305 i = j + 1
306 i = j + 1
306 if stuff[0] == '!':
307 if stuff[0] == '!':
307 stuff = '^' + stuff[1:]
308 stuff = '^' + stuff[1:]
308 elif stuff[0] == '^':
309 elif stuff[0] == '^':
309 stuff = '\\' + stuff
310 stuff = '\\' + stuff
310 res = '%s[%s]' % (res, stuff)
311 res = '%s[%s]' % (res, stuff)
311 elif c == '{':
312 elif c == '{':
312 group = True
313 group = True
313 res += '(?:'
314 res += '(?:'
314 elif c == '}' and group:
315 elif c == '}' and group:
315 res += ')'
316 res += ')'
316 group = False
317 group = False
317 elif c == ',' and group:
318 elif c == ',' and group:
318 res += '|'
319 res += '|'
319 elif c == '\\':
320 elif c == '\\':
320 p = peek()
321 p = peek()
321 if p:
322 if p:
322 i += 1
323 i += 1
323 res += re.escape(p)
324 res += re.escape(p)
324 else:
325 else:
325 res += re.escape(c)
326 res += re.escape(c)
326 else:
327 else:
327 res += re.escape(c)
328 res += re.escape(c)
328 return head + res + tail
329 return head + res + tail
329
330
330 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
331 _globchars = {'[': 1, '{': 1, '*': 1, '?': 1}
331
332
332 def pathto(root, n1, n2):
333 def pathto(root, n1, n2):
333 '''return the relative path from one place to another.
334 '''return the relative path from one place to another.
334 root should use os.sep to separate directories
335 root should use os.sep to separate directories
335 n1 should use os.sep to separate directories
336 n1 should use os.sep to separate directories
336 n2 should use "/" to separate directories
337 n2 should use "/" to separate directories
337 returns an os.sep-separated path.
338 returns an os.sep-separated path.
338
339
339 If n1 is a relative path, it's assumed it's
340 If n1 is a relative path, it's assumed it's
340 relative to root.
341 relative to root.
341 n2 should always be relative to root.
342 n2 should always be relative to root.
342 '''
343 '''
343 if not n1: return localpath(n2)
344 if not n1: return localpath(n2)
344 if os.path.isabs(n1):
345 if os.path.isabs(n1):
345 if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
346 if os.path.splitdrive(root)[0] != os.path.splitdrive(n1)[0]:
346 return os.path.join(root, localpath(n2))
347 return os.path.join(root, localpath(n2))
347 n2 = '/'.join((pconvert(root), n2))
348 n2 = '/'.join((pconvert(root), n2))
348 a, b = n1.split(os.sep), n2.split('/')
349 a, b = n1.split(os.sep), n2.split('/')
349 a.reverse()
350 a.reverse()
350 b.reverse()
351 b.reverse()
351 while a and b and a[-1] == b[-1]:
352 while a and b and a[-1] == b[-1]:
352 a.pop()
353 a.pop()
353 b.pop()
354 b.pop()
354 b.reverse()
355 b.reverse()
355 return os.sep.join((['..'] * len(a)) + b)
356 return os.sep.join((['..'] * len(a)) + b)
356
357
357 def canonpath(root, cwd, myname):
358 def canonpath(root, cwd, myname):
358 """return the canonical path of myname, given cwd and root"""
359 """return the canonical path of myname, given cwd and root"""
359 if root == os.sep:
360 if root == os.sep:
360 rootsep = os.sep
361 rootsep = os.sep
361 elif root.endswith(os.sep):
362 elif root.endswith(os.sep):
362 rootsep = root
363 rootsep = root
363 else:
364 else:
364 rootsep = root + os.sep
365 rootsep = root + os.sep
365 name = myname
366 name = myname
366 if not os.path.isabs(name):
367 if not os.path.isabs(name):
367 name = os.path.join(root, cwd, name)
368 name = os.path.join(root, cwd, name)
368 name = os.path.normpath(name)
369 name = os.path.normpath(name)
369 audit_path = path_auditor(root)
370 audit_path = path_auditor(root)
370 if name != rootsep and name.startswith(rootsep):
371 if name != rootsep and name.startswith(rootsep):
371 name = name[len(rootsep):]
372 name = name[len(rootsep):]
372 audit_path(name)
373 audit_path(name)
373 return pconvert(name)
374 return pconvert(name)
374 elif name == root:
375 elif name == root:
375 return ''
376 return ''
376 else:
377 else:
377 # Determine whether `name' is in the hierarchy at or beneath `root',
378 # Determine whether `name' is in the hierarchy at or beneath `root',
378 # by iterating name=dirname(name) until that causes no change (can't
379 # by iterating name=dirname(name) until that causes no change (can't
379 # check name == '/', because that doesn't work on windows). For each
380 # check name == '/', because that doesn't work on windows). For each
380 # `name', compare dev/inode numbers. If they match, the list `rel'
381 # `name', compare dev/inode numbers. If they match, the list `rel'
381 # holds the reversed list of components making up the relative file
382 # holds the reversed list of components making up the relative file
382 # name we want.
383 # name we want.
383 root_st = os.stat(root)
384 root_st = os.stat(root)
384 rel = []
385 rel = []
385 while True:
386 while True:
386 try:
387 try:
387 name_st = os.stat(name)
388 name_st = os.stat(name)
388 except OSError:
389 except OSError:
389 break
390 break
390 if samestat(name_st, root_st):
391 if samestat(name_st, root_st):
391 if not rel:
392 if not rel:
392 # name was actually the same as root (maybe a symlink)
393 # name was actually the same as root (maybe a symlink)
393 return ''
394 return ''
394 rel.reverse()
395 rel.reverse()
395 name = os.path.join(*rel)
396 name = os.path.join(*rel)
396 audit_path(name)
397 audit_path(name)
397 return pconvert(name)
398 return pconvert(name)
398 dirname, basename = os.path.split(name)
399 dirname, basename = os.path.split(name)
399 rel.append(basename)
400 rel.append(basename)
400 if dirname == name:
401 if dirname == name:
401 break
402 break
402 name = dirname
403 name = dirname
403
404
404 raise Abort('%s not under root' % myname)
405 raise Abort('%s not under root' % myname)
405
406
406 def matcher(canonroot, cwd='', names=[], inc=[], exc=[], src=None):
407 def matcher(canonroot, cwd='', names=[], inc=[], exc=[], src=None):
407 return _matcher(canonroot, cwd, names, inc, exc, 'glob', src)
408 return _matcher(canonroot, cwd, names, inc, exc, 'glob', src)
408
409
409 def cmdmatcher(canonroot, cwd='', names=[], inc=[], exc=[], src=None,
410 def cmdmatcher(canonroot, cwd='', names=[], inc=[], exc=[], src=None,
410 globbed=False, default=None):
411 globbed=False, default=None):
411 default = default or 'relpath'
412 default = default or 'relpath'
412 if default == 'relpath' and not globbed:
413 if default == 'relpath' and not globbed:
413 names = expand_glob(names)
414 names = expand_glob(names)
414 return _matcher(canonroot, cwd, names, inc, exc, default, src)
415 return _matcher(canonroot, cwd, names, inc, exc, default, src)
415
416
416 def _matcher(canonroot, cwd, names, inc, exc, dflt_pat, src):
417 def _matcher(canonroot, cwd, names, inc, exc, dflt_pat, src):
417 """build a function to match a set of file patterns
418 """build a function to match a set of file patterns
418
419
419 arguments:
420 arguments:
420 canonroot - the canonical root of the tree you're matching against
421 canonroot - the canonical root of the tree you're matching against
421 cwd - the current working directory, if relevant
422 cwd - the current working directory, if relevant
422 names - patterns to find
423 names - patterns to find
423 inc - patterns to include
424 inc - patterns to include
424 exc - patterns to exclude
425 exc - patterns to exclude
425 dflt_pat - if a pattern in names has no explicit type, assume this one
426 dflt_pat - if a pattern in names has no explicit type, assume this one
426 src - where these patterns came from (e.g. .hgignore)
427 src - where these patterns came from (e.g. .hgignore)
427
428
428 a pattern is one of:
429 a pattern is one of:
429 'glob:<glob>' - a glob relative to cwd
430 'glob:<glob>' - a glob relative to cwd
430 're:<regexp>' - a regular expression
431 're:<regexp>' - a regular expression
431 'path:<path>' - a path relative to canonroot
432 'path:<path>' - a path relative to canonroot
432 'relglob:<glob>' - an unrooted glob (*.c matches C files in all dirs)
433 'relglob:<glob>' - an unrooted glob (*.c matches C files in all dirs)
433 'relpath:<path>' - a path relative to cwd
434 'relpath:<path>' - a path relative to cwd
434 'relre:<regexp>' - a regexp that doesn't have to match the start of a name
435 'relre:<regexp>' - a regexp that doesn't have to match the start of a name
435 '<something>' - one of the cases above, selected by the dflt_pat argument
436 '<something>' - one of the cases above, selected by the dflt_pat argument
436
437
437 returns:
438 returns:
438 a 3-tuple containing
439 a 3-tuple containing
439 - list of roots (places where one should start a recursive walk of the fs);
440 - list of roots (places where one should start a recursive walk of the fs);
440 this often matches the explicit non-pattern names passed in, but also
441 this often matches the explicit non-pattern names passed in, but also
441 includes the initial part of glob: patterns that has no glob characters
442 includes the initial part of glob: patterns that has no glob characters
442 - a bool match(filename) function
443 - a bool match(filename) function
443 - a bool indicating if any patterns were passed in
444 - a bool indicating if any patterns were passed in
444 """
445 """
445
446
446 # a common case: no patterns at all
447 # a common case: no patterns at all
447 if not names and not inc and not exc:
448 if not names and not inc and not exc:
448 return [], always, False
449 return [], always, False
449
450
450 def contains_glob(name):
451 def contains_glob(name):
451 for c in name:
452 for c in name:
452 if c in _globchars: return True
453 if c in _globchars: return True
453 return False
454 return False
454
455
455 def regex(kind, name, tail):
456 def regex(kind, name, tail):
456 '''convert a pattern into a regular expression'''
457 '''convert a pattern into a regular expression'''
457 if not name:
458 if not name:
458 return ''
459 return ''
459 if kind == 're':
460 if kind == 're':
460 return name
461 return name
461 elif kind == 'path':
462 elif kind == 'path':
462 return '^' + re.escape(name) + '(?:/|$)'
463 return '^' + re.escape(name) + '(?:/|$)'
463 elif kind == 'relglob':
464 elif kind == 'relglob':
464 return globre(name, '(?:|.*/)', tail)
465 return globre(name, '(?:|.*/)', tail)
465 elif kind == 'relpath':
466 elif kind == 'relpath':
466 return re.escape(name) + '(?:/|$)'
467 return re.escape(name) + '(?:/|$)'
467 elif kind == 'relre':
468 elif kind == 'relre':
468 if name.startswith('^'):
469 if name.startswith('^'):
469 return name
470 return name
470 return '.*' + name
471 return '.*' + name
471 return globre(name, '', tail)
472 return globre(name, '', tail)
472
473
473 def matchfn(pats, tail):
474 def matchfn(pats, tail):
474 """build a matching function from a set of patterns"""
475 """build a matching function from a set of patterns"""
475 if not pats:
476 if not pats:
476 return
477 return
477 try:
478 try:
478 pat = '(?:%s)' % '|'.join([regex(k, p, tail) for (k, p) in pats])
479 pat = '(?:%s)' % '|'.join([regex(k, p, tail) for (k, p) in pats])
479 return re.compile(pat).match
480 return re.compile(pat).match
480 except OverflowError:
481 except OverflowError:
481 # We're using a Python with a tiny regex engine and we
482 # We're using a Python with a tiny regex engine and we
482 # made it explode, so we'll divide the pattern list in two
483 # made it explode, so we'll divide the pattern list in two
483 # until it works
484 # until it works
484 l = len(pats)
485 l = len(pats)
485 if l < 2:
486 if l < 2:
486 raise
487 raise
487 a, b = matchfn(pats[:l//2], tail), matchfn(pats[l//2:], tail)
488 a, b = matchfn(pats[:l//2], tail), matchfn(pats[l//2:], tail)
488 return lambda s: a(s) or b(s)
489 return lambda s: a(s) or b(s)
489 except re.error:
490 except re.error:
490 for k, p in pats:
491 for k, p in pats:
491 try:
492 try:
492 re.compile('(?:%s)' % regex(k, p, tail))
493 re.compile('(?:%s)' % regex(k, p, tail))
493 except re.error:
494 except re.error:
494 if src:
495 if src:
495 raise Abort("%s: invalid pattern (%s): %s" %
496 raise Abort("%s: invalid pattern (%s): %s" %
496 (src, k, p))
497 (src, k, p))
497 else:
498 else:
498 raise Abort("invalid pattern (%s): %s" % (k, p))
499 raise Abort("invalid pattern (%s): %s" % (k, p))
499 raise Abort("invalid pattern")
500 raise Abort("invalid pattern")
500
501
501 def globprefix(pat):
502 def globprefix(pat):
502 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
503 '''return the non-glob prefix of a path, e.g. foo/* -> foo'''
503 root = []
504 root = []
504 for p in pat.split('/'):
505 for p in pat.split('/'):
505 if contains_glob(p): break
506 if contains_glob(p): break
506 root.append(p)
507 root.append(p)
507 return '/'.join(root) or '.'
508 return '/'.join(root) or '.'
508
509
509 def normalizepats(names, default):
510 def normalizepats(names, default):
510 pats = []
511 pats = []
511 roots = []
512 roots = []
512 anypats = False
513 anypats = False
513 for kind, name in [patkind(p, default) for p in names]:
514 for kind, name in [patkind(p, default) for p in names]:
514 if kind in ('glob', 'relpath'):
515 if kind in ('glob', 'relpath'):
515 name = canonpath(canonroot, cwd, name)
516 name = canonpath(canonroot, cwd, name)
516 elif kind in ('relglob', 'path'):
517 elif kind in ('relglob', 'path'):
517 name = normpath(name)
518 name = normpath(name)
518
519
519 pats.append((kind, name))
520 pats.append((kind, name))
520
521
521 if kind in ('glob', 're', 'relglob', 'relre'):
522 if kind in ('glob', 're', 'relglob', 'relre'):
522 anypats = True
523 anypats = True
523
524
524 if kind == 'glob':
525 if kind == 'glob':
525 root = globprefix(name)
526 root = globprefix(name)
526 roots.append(root)
527 roots.append(root)
527 elif kind in ('relpath', 'path'):
528 elif kind in ('relpath', 'path'):
528 roots.append(name or '.')
529 roots.append(name or '.')
529 elif kind == 'relglob':
530 elif kind == 'relglob':
530 roots.append('.')
531 roots.append('.')
531 return roots, pats, anypats
532 return roots, pats, anypats
532
533
533 roots, pats, anypats = normalizepats(names, dflt_pat)
534 roots, pats, anypats = normalizepats(names, dflt_pat)
534
535
535 patmatch = matchfn(pats, '$') or always
536 patmatch = matchfn(pats, '$') or always
536 incmatch = always
537 incmatch = always
537 if inc:
538 if inc:
538 dummy, inckinds, dummy = normalizepats(inc, 'glob')
539 dummy, inckinds, dummy = normalizepats(inc, 'glob')
539 incmatch = matchfn(inckinds, '(?:/|$)')
540 incmatch = matchfn(inckinds, '(?:/|$)')
540 excmatch = lambda fn: False
541 excmatch = lambda fn: False
541 if exc:
542 if exc:
542 dummy, exckinds, dummy = normalizepats(exc, 'glob')
543 dummy, exckinds, dummy = normalizepats(exc, 'glob')
543 excmatch = matchfn(exckinds, '(?:/|$)')
544 excmatch = matchfn(exckinds, '(?:/|$)')
544
545
545 if not names and inc and not exc:
546 if not names and inc and not exc:
546 # common case: hgignore patterns
547 # common case: hgignore patterns
547 match = incmatch
548 match = incmatch
548 else:
549 else:
549 match = lambda fn: incmatch(fn) and not excmatch(fn) and patmatch(fn)
550 match = lambda fn: incmatch(fn) and not excmatch(fn) and patmatch(fn)
550
551
551 return (roots, match, (inc or exc or anypats) and True)
552 return (roots, match, (inc or exc or anypats) and True)
552
553
553 _hgexecutable = None
554 _hgexecutable = None
554
555
555 def hgexecutable():
556 def hgexecutable():
556 """return location of the 'hg' executable.
557 """return location of the 'hg' executable.
557
558
558 Defaults to $HG or 'hg' in the search path.
559 Defaults to $HG or 'hg' in the search path.
559 """
560 """
560 if _hgexecutable is None:
561 if _hgexecutable is None:
561 set_hgexecutable(os.environ.get('HG') or find_exe('hg', 'hg'))
562 set_hgexecutable(os.environ.get('HG') or find_exe('hg', 'hg'))
562 return _hgexecutable
563 return _hgexecutable
563
564
564 def set_hgexecutable(path):
565 def set_hgexecutable(path):
565 """set location of the 'hg' executable"""
566 """set location of the 'hg' executable"""
566 global _hgexecutable
567 global _hgexecutable
567 _hgexecutable = path
568 _hgexecutable = path
568
569
569 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
570 def system(cmd, environ={}, cwd=None, onerr=None, errprefix=None):
570 '''enhanced shell command execution.
571 '''enhanced shell command execution.
571 run with environment maybe modified, maybe in different dir.
572 run with environment maybe modified, maybe in different dir.
572
573
573 if command fails and onerr is None, return status. if ui object,
574 if command fails and onerr is None, return status. if ui object,
574 print error message and return status, else raise onerr object as
575 print error message and return status, else raise onerr object as
575 exception.'''
576 exception.'''
576 def py2shell(val):
577 def py2shell(val):
577 'convert python object into string that is useful to shell'
578 'convert python object into string that is useful to shell'
578 if val in (None, False):
579 if val in (None, False):
579 return '0'
580 return '0'
580 if val == True:
581 if val == True:
581 return '1'
582 return '1'
582 return str(val)
583 return str(val)
583 oldenv = {}
584 oldenv = {}
584 for k in environ:
585 for k in environ:
585 oldenv[k] = os.environ.get(k)
586 oldenv[k] = os.environ.get(k)
586 if cwd is not None:
587 if cwd is not None:
587 oldcwd = os.getcwd()
588 oldcwd = os.getcwd()
588 origcmd = cmd
589 origcmd = cmd
589 if os.name == 'nt':
590 if os.name == 'nt':
590 cmd = '"%s"' % cmd
591 cmd = '"%s"' % cmd
591 try:
592 try:
592 for k, v in environ.iteritems():
593 for k, v in environ.iteritems():
593 os.environ[k] = py2shell(v)
594 os.environ[k] = py2shell(v)
594 os.environ['HG'] = hgexecutable()
595 os.environ['HG'] = hgexecutable()
595 if cwd is not None and oldcwd != cwd:
596 if cwd is not None and oldcwd != cwd:
596 os.chdir(cwd)
597 os.chdir(cwd)
597 rc = os.system(cmd)
598 rc = os.system(cmd)
598 if sys.platform == 'OpenVMS' and rc & 1:
599 if sys.platform == 'OpenVMS' and rc & 1:
599 rc = 0
600 rc = 0
600 if rc and onerr:
601 if rc and onerr:
601 errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
602 errmsg = '%s %s' % (os.path.basename(origcmd.split(None, 1)[0]),
602 explain_exit(rc)[0])
603 explain_exit(rc)[0])
603 if errprefix:
604 if errprefix:
604 errmsg = '%s: %s' % (errprefix, errmsg)
605 errmsg = '%s: %s' % (errprefix, errmsg)
605 try:
606 try:
606 onerr.warn(errmsg + '\n')
607 onerr.warn(errmsg + '\n')
607 except AttributeError:
608 except AttributeError:
608 raise onerr(errmsg)
609 raise onerr(errmsg)
609 return rc
610 return rc
610 finally:
611 finally:
611 for k, v in oldenv.iteritems():
612 for k, v in oldenv.iteritems():
612 if v is None:
613 if v is None:
613 del os.environ[k]
614 del os.environ[k]
614 else:
615 else:
615 os.environ[k] = v
616 os.environ[k] = v
616 if cwd is not None and oldcwd != cwd:
617 if cwd is not None and oldcwd != cwd:
617 os.chdir(oldcwd)
618 os.chdir(oldcwd)
618
619
619 # os.path.lexists is not available on python2.3
620 # os.path.lexists is not available on python2.3
620 def lexists(filename):
621 def lexists(filename):
621 "test whether a file with this name exists. does not follow symlinks"
622 "test whether a file with this name exists. does not follow symlinks"
622 try:
623 try:
623 os.lstat(filename)
624 os.lstat(filename)
624 except:
625 except:
625 return False
626 return False
626 return True
627 return True
627
628
628 def rename(src, dst):
629 def rename(src, dst):
629 """forcibly rename a file"""
630 """forcibly rename a file"""
630 try:
631 try:
631 os.rename(src, dst)
632 os.rename(src, dst)
632 except OSError, err: # FIXME: check err (EEXIST ?)
633 except OSError, err: # FIXME: check err (EEXIST ?)
633 # on windows, rename to existing file is not allowed, so we
634 # on windows, rename to existing file is not allowed, so we
634 # must delete destination first. but if file is open, unlink
635 # must delete destination first. but if file is open, unlink
635 # schedules it for delete but does not delete it. rename
636 # schedules it for delete but does not delete it. rename
636 # happens immediately even for open files, so we create
637 # happens immediately even for open files, so we create
637 # temporary file, delete it, rename destination to that name,
638 # temporary file, delete it, rename destination to that name,
638 # then delete that. then rename is safe to do.
639 # then delete that. then rename is safe to do.
639 fd, temp = tempfile.mkstemp(dir=os.path.dirname(dst) or '.')
640 fd, temp = tempfile.mkstemp(dir=os.path.dirname(dst) or '.')
640 os.close(fd)
641 os.close(fd)
641 os.unlink(temp)
642 os.unlink(temp)
642 os.rename(dst, temp)
643 os.rename(dst, temp)
643 os.unlink(temp)
644 os.unlink(temp)
644 os.rename(src, dst)
645 os.rename(src, dst)
645
646
646 def unlink(f):
647 def unlink(f):
647 """unlink and remove the directory if it is empty"""
648 """unlink and remove the directory if it is empty"""
648 os.unlink(f)
649 os.unlink(f)
649 # try removing directories that might now be empty
650 # try removing directories that might now be empty
650 try:
651 try:
651 os.removedirs(os.path.dirname(f))
652 os.removedirs(os.path.dirname(f))
652 except OSError:
653 except OSError:
653 pass
654 pass
654
655
655 def copyfile(src, dest):
656 def copyfile(src, dest):
656 "copy a file, preserving mode"
657 "copy a file, preserving mode"
657 if os.path.islink(src):
658 if os.path.islink(src):
658 try:
659 try:
659 os.unlink(dest)
660 os.unlink(dest)
660 except:
661 except:
661 pass
662 pass
662 os.symlink(os.readlink(src), dest)
663 os.symlink(os.readlink(src), dest)
663 else:
664 else:
664 try:
665 try:
665 shutil.copyfile(src, dest)
666 shutil.copyfile(src, dest)
666 shutil.copymode(src, dest)
667 shutil.copymode(src, dest)
667 except shutil.Error, inst:
668 except shutil.Error, inst:
668 raise Abort(str(inst))
669 raise Abort(str(inst))
669
670
670 def copyfiles(src, dst, hardlink=None):
671 def copyfiles(src, dst, hardlink=None):
671 """Copy a directory tree using hardlinks if possible"""
672 """Copy a directory tree using hardlinks if possible"""
672
673
673 if hardlink is None:
674 if hardlink is None:
674 hardlink = (os.stat(src).st_dev ==
675 hardlink = (os.stat(src).st_dev ==
675 os.stat(os.path.dirname(dst)).st_dev)
676 os.stat(os.path.dirname(dst)).st_dev)
676
677
677 if os.path.isdir(src):
678 if os.path.isdir(src):
678 os.mkdir(dst)
679 os.mkdir(dst)
679 for name, kind in osutil.listdir(src):
680 for name, kind in osutil.listdir(src):
680 srcname = os.path.join(src, name)
681 srcname = os.path.join(src, name)
681 dstname = os.path.join(dst, name)
682 dstname = os.path.join(dst, name)
682 copyfiles(srcname, dstname, hardlink)
683 copyfiles(srcname, dstname, hardlink)
683 else:
684 else:
684 if hardlink:
685 if hardlink:
685 try:
686 try:
686 os_link(src, dst)
687 os_link(src, dst)
687 except (IOError, OSError):
688 except (IOError, OSError):
688 hardlink = False
689 hardlink = False
689 shutil.copy(src, dst)
690 shutil.copy(src, dst)
690 else:
691 else:
691 shutil.copy(src, dst)
692 shutil.copy(src, dst)
692
693
693 class path_auditor(object):
694 class path_auditor(object):
694 '''ensure that a filesystem path contains no banned components.
695 '''ensure that a filesystem path contains no banned components.
695 the following properties of a path are checked:
696 the following properties of a path are checked:
696
697
697 - under top-level .hg
698 - under top-level .hg
698 - starts at the root of a windows drive
699 - starts at the root of a windows drive
699 - contains ".."
700 - contains ".."
700 - traverses a symlink (e.g. a/symlink_here/b)
701 - traverses a symlink (e.g. a/symlink_here/b)
701 - inside a nested repository'''
702 - inside a nested repository'''
702
703
703 def __init__(self, root):
704 def __init__(self, root):
704 self.audited = set()
705 self.audited = set()
705 self.auditeddir = set()
706 self.auditeddir = set()
706 self.root = root
707 self.root = root
707
708
708 def __call__(self, path):
709 def __call__(self, path):
709 if path in self.audited:
710 if path in self.audited:
710 return
711 return
711 normpath = os.path.normcase(path)
712 normpath = os.path.normcase(path)
712 parts = normpath.split(os.sep)
713 parts = normpath.split(os.sep)
713 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
714 if (os.path.splitdrive(path)[0] or parts[0] in ('.hg', '')
714 or os.pardir in parts):
715 or os.pardir in parts):
715 raise Abort(_("path contains illegal component: %s") % path)
716 raise Abort(_("path contains illegal component: %s") % path)
716 def check(prefix):
717 def check(prefix):
717 curpath = os.path.join(self.root, prefix)
718 curpath = os.path.join(self.root, prefix)
718 try:
719 try:
719 st = os.lstat(curpath)
720 st = os.lstat(curpath)
720 except OSError, err:
721 except OSError, err:
721 # EINVAL can be raised as invalid path syntax under win32.
722 # EINVAL can be raised as invalid path syntax under win32.
722 # They must be ignored for patterns can be checked too.
723 # They must be ignored for patterns can be checked too.
723 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
724 if err.errno not in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
724 raise
725 raise
725 else:
726 else:
726 if stat.S_ISLNK(st.st_mode):
727 if stat.S_ISLNK(st.st_mode):
727 raise Abort(_('path %r traverses symbolic link %r') %
728 raise Abort(_('path %r traverses symbolic link %r') %
728 (path, prefix))
729 (path, prefix))
729 elif (stat.S_ISDIR(st.st_mode) and
730 elif (stat.S_ISDIR(st.st_mode) and
730 os.path.isdir(os.path.join(curpath, '.hg'))):
731 os.path.isdir(os.path.join(curpath, '.hg'))):
731 raise Abort(_('path %r is inside repo %r') %
732 raise Abort(_('path %r is inside repo %r') %
732 (path, prefix))
733 (path, prefix))
733
734
734 prefixes = []
735 prefixes = []
735 for c in strutil.rfindall(normpath, os.sep):
736 for c in strutil.rfindall(normpath, os.sep):
736 prefix = normpath[:c]
737 prefix = normpath[:c]
737 if prefix in self.auditeddir:
738 if prefix in self.auditeddir:
738 break
739 break
739 check(prefix)
740 check(prefix)
740 prefixes.append(prefix)
741 prefixes.append(prefix)
741
742
742 self.audited.add(path)
743 self.audited.add(path)
743 # only add prefixes to the cache after checking everything: we don't
744 # only add prefixes to the cache after checking everything: we don't
744 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
745 # want to add "foo/bar/baz" before checking if there's a "foo/.hg"
745 self.auditeddir.update(prefixes)
746 self.auditeddir.update(prefixes)
746
747
747 def _makelock_file(info, pathname):
748 def _makelock_file(info, pathname):
748 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
749 ld = os.open(pathname, os.O_CREAT | os.O_WRONLY | os.O_EXCL)
749 os.write(ld, info)
750 os.write(ld, info)
750 os.close(ld)
751 os.close(ld)
751
752
752 def _readlock_file(pathname):
753 def _readlock_file(pathname):
753 return posixfile(pathname).read()
754 return posixfile(pathname).read()
754
755
755 def nlinks(pathname):
756 def nlinks(pathname):
756 """Return number of hardlinks for the given file."""
757 """Return number of hardlinks for the given file."""
757 return os.lstat(pathname).st_nlink
758 return os.lstat(pathname).st_nlink
758
759
759 if hasattr(os, 'link'):
760 if hasattr(os, 'link'):
760 os_link = os.link
761 os_link = os.link
761 else:
762 else:
762 def os_link(src, dst):
763 def os_link(src, dst):
763 raise OSError(0, _("Hardlinks not supported"))
764 raise OSError(0, _("Hardlinks not supported"))
764
765
765 def fstat(fp):
766 def fstat(fp):
766 '''stat file object that may not have fileno method.'''
767 '''stat file object that may not have fileno method.'''
767 try:
768 try:
768 return os.fstat(fp.fileno())
769 return os.fstat(fp.fileno())
769 except AttributeError:
770 except AttributeError:
770 return os.stat(fp.name)
771 return os.stat(fp.name)
771
772
772 posixfile = file
773 posixfile = file
773
774
774 def is_win_9x():
775 def is_win_9x():
775 '''return true if run on windows 95, 98 or me.'''
776 '''return true if run on windows 95, 98 or me.'''
776 try:
777 try:
777 return sys.getwindowsversion()[3] == 1
778 return sys.getwindowsversion()[3] == 1
778 except AttributeError:
779 except AttributeError:
779 return os.name == 'nt' and 'command' in os.environ.get('comspec', '')
780 return os.name == 'nt' and 'command' in os.environ.get('comspec', '')
780
781
781 getuser_fallback = None
782 getuser_fallback = None
782
783
783 def getuser():
784 def getuser():
784 '''return name of current user'''
785 '''return name of current user'''
785 try:
786 try:
786 return getpass.getuser()
787 return getpass.getuser()
787 except ImportError:
788 except ImportError:
788 # import of pwd will fail on windows - try fallback
789 # import of pwd will fail on windows - try fallback
789 if getuser_fallback:
790 if getuser_fallback:
790 return getuser_fallback()
791 return getuser_fallback()
791 # raised if win32api not available
792 # raised if win32api not available
792 raise Abort(_('user name not available - set USERNAME '
793 raise Abort(_('user name not available - set USERNAME '
793 'environment variable'))
794 'environment variable'))
794
795
795 def username(uid=None):
796 def username(uid=None):
796 """Return the name of the user with the given uid.
797 """Return the name of the user with the given uid.
797
798
798 If uid is None, return the name of the current user."""
799 If uid is None, return the name of the current user."""
799 try:
800 try:
800 import pwd
801 import pwd
801 if uid is None:
802 if uid is None:
802 uid = os.getuid()
803 uid = os.getuid()
803 try:
804 try:
804 return pwd.getpwuid(uid)[0]
805 return pwd.getpwuid(uid)[0]
805 except KeyError:
806 except KeyError:
806 return str(uid)
807 return str(uid)
807 except ImportError:
808 except ImportError:
808 return None
809 return None
809
810
810 def groupname(gid=None):
811 def groupname(gid=None):
811 """Return the name of the group with the given gid.
812 """Return the name of the group with the given gid.
812
813
813 If gid is None, return the name of the current group."""
814 If gid is None, return the name of the current group."""
814 try:
815 try:
815 import grp
816 import grp
816 if gid is None:
817 if gid is None:
817 gid = os.getgid()
818 gid = os.getgid()
818 try:
819 try:
819 return grp.getgrgid(gid)[0]
820 return grp.getgrgid(gid)[0]
820 except KeyError:
821 except KeyError:
821 return str(gid)
822 return str(gid)
822 except ImportError:
823 except ImportError:
823 return None
824 return None
824
825
825 # File system features
826 # File system features
826
827
827 def checkfolding(path):
828 def checkfolding(path):
828 """
829 """
829 Check whether the given path is on a case-sensitive filesystem
830 Check whether the given path is on a case-sensitive filesystem
830
831
831 Requires a path (like /foo/.hg) ending with a foldable final
832 Requires a path (like /foo/.hg) ending with a foldable final
832 directory component.
833 directory component.
833 """
834 """
834 s1 = os.stat(path)
835 s1 = os.stat(path)
835 d, b = os.path.split(path)
836 d, b = os.path.split(path)
836 p2 = os.path.join(d, b.upper())
837 p2 = os.path.join(d, b.upper())
837 if path == p2:
838 if path == p2:
838 p2 = os.path.join(d, b.lower())
839 p2 = os.path.join(d, b.lower())
839 try:
840 try:
840 s2 = os.stat(p2)
841 s2 = os.stat(p2)
841 if s2 == s1:
842 if s2 == s1:
842 return False
843 return False
843 return True
844 return True
844 except:
845 except:
845 return True
846 return True
846
847
847 def checkexec(path):
848 def checkexec(path):
848 """
849 """
849 Check whether the given path is on a filesystem with UNIX-like exec flags
850 Check whether the given path is on a filesystem with UNIX-like exec flags
850
851
851 Requires a directory (like /foo/.hg)
852 Requires a directory (like /foo/.hg)
852 """
853 """
853 try:
854 try:
854 EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
855 EXECFLAGS = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
855 fh, fn = tempfile.mkstemp("", "", path)
856 fh, fn = tempfile.mkstemp("", "", path)
856 os.close(fh)
857 os.close(fh)
857 m = os.stat(fn).st_mode
858 m = os.stat(fn).st_mode
858 # VFAT on Linux can flip mode but it doesn't persist a FS remount.
859 # VFAT on Linux can flip mode but it doesn't persist a FS remount.
859 # frequently we can detect it if files are created with exec bit on.
860 # frequently we can detect it if files are created with exec bit on.
860 new_file_has_exec = m & EXECFLAGS
861 new_file_has_exec = m & EXECFLAGS
861 os.chmod(fn, m ^ EXECFLAGS)
862 os.chmod(fn, m ^ EXECFLAGS)
862 exec_flags_cannot_flip = (os.stat(fn).st_mode == m)
863 exec_flags_cannot_flip = (os.stat(fn).st_mode == m)
863 os.unlink(fn)
864 os.unlink(fn)
864 except (IOError,OSError):
865 except (IOError,OSError):
865 # we don't care, the user probably won't be able to commit anyway
866 # we don't care, the user probably won't be able to commit anyway
866 return False
867 return False
867 return not (new_file_has_exec or exec_flags_cannot_flip)
868 return not (new_file_has_exec or exec_flags_cannot_flip)
868
869
869 def execfunc(path, fallback):
870 def execfunc(path, fallback):
870 '''return an is_exec() function with default to fallback'''
871 '''return an is_exec() function with default to fallback'''
871 if checkexec(path):
872 if checkexec(path):
872 return lambda x: is_exec(os.path.join(path, x))
873 return lambda x: is_exec(os.path.join(path, x))
873 return fallback
874 return fallback
874
875
875 def checklink(path):
876 def checklink(path):
876 """check whether the given path is on a symlink-capable filesystem"""
877 """check whether the given path is on a symlink-capable filesystem"""
877 # mktemp is not racy because symlink creation will fail if the
878 # mktemp is not racy because symlink creation will fail if the
878 # file already exists
879 # file already exists
879 name = tempfile.mktemp(dir=path)
880 name = tempfile.mktemp(dir=path)
880 try:
881 try:
881 os.symlink(".", name)
882 os.symlink(".", name)
882 os.unlink(name)
883 os.unlink(name)
883 return True
884 return True
884 except (OSError, AttributeError):
885 except (OSError, AttributeError):
885 return False
886 return False
886
887
887 def linkfunc(path, fallback):
888 def linkfunc(path, fallback):
888 '''return an is_link() function with default to fallback'''
889 '''return an is_link() function with default to fallback'''
889 if checklink(path):
890 if checklink(path):
890 return lambda x: os.path.islink(os.path.join(path, x))
891 return lambda x: os.path.islink(os.path.join(path, x))
891 return fallback
892 return fallback
892
893
893 _umask = os.umask(0)
894 _umask = os.umask(0)
894 os.umask(_umask)
895 os.umask(_umask)
895
896
896 def needbinarypatch():
897 def needbinarypatch():
897 """return True if patches should be applied in binary mode by default."""
898 """return True if patches should be applied in binary mode by default."""
898 return os.name == 'nt'
899 return os.name == 'nt'
899
900
900 # Platform specific variants
901 # Platform specific variants
901 if os.name == 'nt':
902 if os.name == 'nt':
902 import msvcrt
903 import msvcrt
903 nulldev = 'NUL:'
904 nulldev = 'NUL:'
904
905
905 class winstdout:
906 class winstdout:
906 '''stdout on windows misbehaves if sent through a pipe'''
907 '''stdout on windows misbehaves if sent through a pipe'''
907
908
908 def __init__(self, fp):
909 def __init__(self, fp):
909 self.fp = fp
910 self.fp = fp
910
911
911 def __getattr__(self, key):
912 def __getattr__(self, key):
912 return getattr(self.fp, key)
913 return getattr(self.fp, key)
913
914
914 def close(self):
915 def close(self):
915 try:
916 try:
916 self.fp.close()
917 self.fp.close()
917 except: pass
918 except: pass
918
919
919 def write(self, s):
920 def write(self, s):
920 try:
921 try:
921 return self.fp.write(s)
922 return self.fp.write(s)
922 except IOError, inst:
923 except IOError, inst:
923 if inst.errno != 0: raise
924 if inst.errno != 0: raise
924 self.close()
925 self.close()
925 raise IOError(errno.EPIPE, 'Broken pipe')
926 raise IOError(errno.EPIPE, 'Broken pipe')
926
927
927 def flush(self):
928 def flush(self):
928 try:
929 try:
929 return self.fp.flush()
930 return self.fp.flush()
930 except IOError, inst:
931 except IOError, inst:
931 if inst.errno != errno.EINVAL: raise
932 if inst.errno != errno.EINVAL: raise
932 self.close()
933 self.close()
933 raise IOError(errno.EPIPE, 'Broken pipe')
934 raise IOError(errno.EPIPE, 'Broken pipe')
934
935
935 sys.stdout = winstdout(sys.stdout)
936 sys.stdout = winstdout(sys.stdout)
936
937
937 def system_rcpath():
938 def system_rcpath():
938 try:
939 try:
939 return system_rcpath_win32()
940 return system_rcpath_win32()
940 except:
941 except:
941 return [r'c:\mercurial\mercurial.ini']
942 return [r'c:\mercurial\mercurial.ini']
942
943
943 def user_rcpath():
944 def user_rcpath():
944 '''return os-specific hgrc search path to the user dir'''
945 '''return os-specific hgrc search path to the user dir'''
945 try:
946 try:
946 userrc = user_rcpath_win32()
947 userrc = user_rcpath_win32()
947 except:
948 except:
948 userrc = os.path.join(os.path.expanduser('~'), 'mercurial.ini')
949 userrc = os.path.join(os.path.expanduser('~'), 'mercurial.ini')
949 path = [userrc]
950 path = [userrc]
950 userprofile = os.environ.get('USERPROFILE')
951 userprofile = os.environ.get('USERPROFILE')
951 if userprofile:
952 if userprofile:
952 path.append(os.path.join(userprofile, 'mercurial.ini'))
953 path.append(os.path.join(userprofile, 'mercurial.ini'))
953 return path
954 return path
954
955
955 def parse_patch_output(output_line):
956 def parse_patch_output(output_line):
956 """parses the output produced by patch and returns the file name"""
957 """parses the output produced by patch and returns the file name"""
957 pf = output_line[14:]
958 pf = output_line[14:]
958 if pf[0] == '`':
959 if pf[0] == '`':
959 pf = pf[1:-1] # Remove the quotes
960 pf = pf[1:-1] # Remove the quotes
960 return pf
961 return pf
961
962
962 def testpid(pid):
963 def testpid(pid):
963 '''return False if pid dead, True if running or not known'''
964 '''return False if pid dead, True if running or not known'''
964 return True
965 return True
965
966
966 def set_exec(f, mode):
967 def set_exec(f, mode):
967 pass
968 pass
968
969
969 def set_link(f, mode):
970 def set_link(f, mode):
970 pass
971 pass
971
972
972 def set_binary(fd):
973 def set_binary(fd):
973 msvcrt.setmode(fd.fileno(), os.O_BINARY)
974 msvcrt.setmode(fd.fileno(), os.O_BINARY)
974
975
975 def pconvert(path):
976 def pconvert(path):
976 return path.replace("\\", "/")
977 return path.replace("\\", "/")
977
978
978 def localpath(path):
979 def localpath(path):
979 return path.replace('/', '\\')
980 return path.replace('/', '\\')
980
981
981 def normpath(path):
982 def normpath(path):
982 return pconvert(os.path.normpath(path))
983 return pconvert(os.path.normpath(path))
983
984
984 makelock = _makelock_file
985 makelock = _makelock_file
985 readlock = _readlock_file
986 readlock = _readlock_file
986
987
987 def samestat(s1, s2):
988 def samestat(s1, s2):
988 return False
989 return False
989
990
990 # A sequence of backslashes is special iff it precedes a double quote:
991 # A sequence of backslashes is special iff it precedes a double quote:
991 # - if there's an even number of backslashes, the double quote is not
992 # - if there's an even number of backslashes, the double quote is not
992 # quoted (i.e. it ends the quoted region)
993 # quoted (i.e. it ends the quoted region)
993 # - if there's an odd number of backslashes, the double quote is quoted
994 # - if there's an odd number of backslashes, the double quote is quoted
994 # - in both cases, every pair of backslashes is unquoted into a single
995 # - in both cases, every pair of backslashes is unquoted into a single
995 # backslash
996 # backslash
996 # (See http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx )
997 # (See http://msdn2.microsoft.com/en-us/library/a1y7w461.aspx )
997 # So, to quote a string, we must surround it in double quotes, double
998 # So, to quote a string, we must surround it in double quotes, double
998 # the number of backslashes that preceed double quotes and add another
999 # the number of backslashes that preceed double quotes and add another
999 # backslash before every double quote (being careful with the double
1000 # backslash before every double quote (being careful with the double
1000 # quote we've appended to the end)
1001 # quote we've appended to the end)
1001 _quotere = None
1002 _quotere = None
1002 def shellquote(s):
1003 def shellquote(s):
1003 global _quotere
1004 global _quotere
1004 if _quotere is None:
1005 if _quotere is None:
1005 _quotere = re.compile(r'(\\*)("|\\$)')
1006 _quotere = re.compile(r'(\\*)("|\\$)')
1006 return '"%s"' % _quotere.sub(r'\1\1\\\2', s)
1007 return '"%s"' % _quotere.sub(r'\1\1\\\2', s)
1007
1008
1008 def quotecommand(cmd):
1009 def quotecommand(cmd):
1009 """Build a command string suitable for os.popen* calls."""
1010 """Build a command string suitable for os.popen* calls."""
1010 # The extra quotes are needed because popen* runs the command
1011 # The extra quotes are needed because popen* runs the command
1011 # through the current COMSPEC. cmd.exe suppress enclosing quotes.
1012 # through the current COMSPEC. cmd.exe suppress enclosing quotes.
1012 return '"' + cmd + '"'
1013 return '"' + cmd + '"'
1013
1014
1014 def popen(command):
1015 def popen(command):
1015 # Work around "popen spawned process may not write to stdout
1016 # Work around "popen spawned process may not write to stdout
1016 # under windows"
1017 # under windows"
1017 # http://bugs.python.org/issue1366
1018 # http://bugs.python.org/issue1366
1018 command += " 2> %s" % nulldev
1019 command += " 2> %s" % nulldev
1019 return os.popen(quotecommand(command))
1020 return os.popen(quotecommand(command))
1020
1021
1021 def explain_exit(code):
1022 def explain_exit(code):
1022 return _("exited with status %d") % code, code
1023 return _("exited with status %d") % code, code
1023
1024
1024 # if you change this stub into a real check, please try to implement the
1025 # if you change this stub into a real check, please try to implement the
1025 # username and groupname functions above, too.
1026 # username and groupname functions above, too.
1026 def isowner(fp, st=None):
1027 def isowner(fp, st=None):
1027 return True
1028 return True
1028
1029
1029 def find_in_path(name, path, default=None):
1030 def find_in_path(name, path, default=None):
1030 '''find name in search path. path can be string (will be split
1031 '''find name in search path. path can be string (will be split
1031 with os.pathsep), or iterable thing that returns strings. if name
1032 with os.pathsep), or iterable thing that returns strings. if name
1032 found, return path to name. else return default. name is looked up
1033 found, return path to name. else return default. name is looked up
1033 using cmd.exe rules, using PATHEXT.'''
1034 using cmd.exe rules, using PATHEXT.'''
1034 if isinstance(path, str):
1035 if isinstance(path, str):
1035 path = path.split(os.pathsep)
1036 path = path.split(os.pathsep)
1036
1037
1037 pathext = os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD')
1038 pathext = os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD')
1038 pathext = pathext.lower().split(os.pathsep)
1039 pathext = pathext.lower().split(os.pathsep)
1039 isexec = os.path.splitext(name)[1].lower() in pathext
1040 isexec = os.path.splitext(name)[1].lower() in pathext
1040
1041
1041 for p in path:
1042 for p in path:
1042 p_name = os.path.join(p, name)
1043 p_name = os.path.join(p, name)
1043
1044
1044 if isexec and os.path.exists(p_name):
1045 if isexec and os.path.exists(p_name):
1045 return p_name
1046 return p_name
1046
1047
1047 for ext in pathext:
1048 for ext in pathext:
1048 p_name_ext = p_name + ext
1049 p_name_ext = p_name + ext
1049 if os.path.exists(p_name_ext):
1050 if os.path.exists(p_name_ext):
1050 return p_name_ext
1051 return p_name_ext
1051 return default
1052 return default
1052
1053
1053 def set_signal_handler():
1054 def set_signal_handler():
1054 try:
1055 try:
1055 set_signal_handler_win32()
1056 set_signal_handler_win32()
1056 except NameError:
1057 except NameError:
1057 pass
1058 pass
1058
1059
1059 try:
1060 try:
1060 # override functions with win32 versions if possible
1061 # override functions with win32 versions if possible
1061 from util_win32 import *
1062 from util_win32 import *
1062 if not is_win_9x():
1063 if not is_win_9x():
1063 posixfile = posixfile_nt
1064 posixfile = posixfile_nt
1064 except ImportError:
1065 except ImportError:
1065 pass
1066 pass
1066
1067
1067 else:
1068 else:
1068 nulldev = '/dev/null'
1069 nulldev = '/dev/null'
1069
1070
1070 def rcfiles(path):
1071 def rcfiles(path):
1071 rcs = [os.path.join(path, 'hgrc')]
1072 rcs = [os.path.join(path, 'hgrc')]
1072 rcdir = os.path.join(path, 'hgrc.d')
1073 rcdir = os.path.join(path, 'hgrc.d')
1073 try:
1074 try:
1074 rcs.extend([os.path.join(rcdir, f)
1075 rcs.extend([os.path.join(rcdir, f)
1075 for f, kind in osutil.listdir(rcdir)
1076 for f, kind in osutil.listdir(rcdir)
1076 if f.endswith(".rc")])
1077 if f.endswith(".rc")])
1077 except OSError:
1078 except OSError:
1078 pass
1079 pass
1079 return rcs
1080 return rcs
1080
1081
1081 def system_rcpath():
1082 def system_rcpath():
1082 path = []
1083 path = []
1083 # old mod_python does not set sys.argv
1084 # old mod_python does not set sys.argv
1084 if len(getattr(sys, 'argv', [])) > 0:
1085 if len(getattr(sys, 'argv', [])) > 0:
1085 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
1086 path.extend(rcfiles(os.path.dirname(sys.argv[0]) +
1086 '/../etc/mercurial'))
1087 '/../etc/mercurial'))
1087 path.extend(rcfiles('/etc/mercurial'))
1088 path.extend(rcfiles('/etc/mercurial'))
1088 return path
1089 return path
1089
1090
1090 def user_rcpath():
1091 def user_rcpath():
1091 return [os.path.expanduser('~/.hgrc')]
1092 return [os.path.expanduser('~/.hgrc')]
1092
1093
1093 def parse_patch_output(output_line):
1094 def parse_patch_output(output_line):
1094 """parses the output produced by patch and returns the file name"""
1095 """parses the output produced by patch and returns the file name"""
1095 pf = output_line[14:]
1096 pf = output_line[14:]
1096 if os.sys.platform == 'OpenVMS':
1097 if os.sys.platform == 'OpenVMS':
1097 if pf[0] == '`':
1098 if pf[0] == '`':
1098 pf = pf[1:-1] # Remove the quotes
1099 pf = pf[1:-1] # Remove the quotes
1099 else:
1100 else:
1100 if pf.startswith("'") and pf.endswith("'") and " " in pf:
1101 if pf.startswith("'") and pf.endswith("'") and " " in pf:
1101 pf = pf[1:-1] # Remove the quotes
1102 pf = pf[1:-1] # Remove the quotes
1102 return pf
1103 return pf
1103
1104
1104 def is_exec(f):
1105 def is_exec(f):
1105 """check whether a file is executable"""
1106 """check whether a file is executable"""
1106 return (os.lstat(f).st_mode & 0100 != 0)
1107 return (os.lstat(f).st_mode & 0100 != 0)
1107
1108
1108 def set_exec(f, mode):
1109 def set_exec(f, mode):
1109 s = os.lstat(f).st_mode
1110 s = os.lstat(f).st_mode
1110 if stat.S_ISLNK(s) or (s & 0100 != 0) == mode:
1111 if stat.S_ISLNK(s) or (s & 0100 != 0) == mode:
1111 return
1112 return
1112 if mode:
1113 if mode:
1113 # Turn on +x for every +r bit when making a file executable
1114 # Turn on +x for every +r bit when making a file executable
1114 # and obey umask.
1115 # and obey umask.
1115 os.chmod(f, s | (s & 0444) >> 2 & ~_umask)
1116 os.chmod(f, s | (s & 0444) >> 2 & ~_umask)
1116 else:
1117 else:
1117 os.chmod(f, s & 0666)
1118 os.chmod(f, s & 0666)
1118
1119
1119 def set_link(f, mode):
1120 def set_link(f, mode):
1120 """make a file a symbolic link/regular file
1121 """make a file a symbolic link/regular file
1121
1122
1122 if a file is changed to a link, its contents become the link data
1123 if a file is changed to a link, its contents become the link data
1123 if a link is changed to a file, its link data become its contents
1124 if a link is changed to a file, its link data become its contents
1124 """
1125 """
1125
1126
1126 m = os.path.islink(f)
1127 m = os.path.islink(f)
1127 if m == bool(mode):
1128 if m == bool(mode):
1128 return
1129 return
1129
1130
1130 if mode: # switch file to link
1131 if mode: # switch file to link
1131 data = file(f).read()
1132 data = file(f).read()
1132 os.unlink(f)
1133 os.unlink(f)
1133 os.symlink(data, f)
1134 os.symlink(data, f)
1134 else:
1135 else:
1135 data = os.readlink(f)
1136 data = os.readlink(f)
1136 os.unlink(f)
1137 os.unlink(f)
1137 file(f, "w").write(data)
1138 file(f, "w").write(data)
1138
1139
1139 def set_binary(fd):
1140 def set_binary(fd):
1140 pass
1141 pass
1141
1142
1142 def pconvert(path):
1143 def pconvert(path):
1143 return path
1144 return path
1144
1145
1145 def localpath(path):
1146 def localpath(path):
1146 return path
1147 return path
1147
1148
1148 normpath = os.path.normpath
1149 normpath = os.path.normpath
1149 samestat = os.path.samestat
1150 samestat = os.path.samestat
1150
1151
1151 def makelock(info, pathname):
1152 def makelock(info, pathname):
1152 try:
1153 try:
1153 os.symlink(info, pathname)
1154 os.symlink(info, pathname)
1154 except OSError, why:
1155 except OSError, why:
1155 if why.errno == errno.EEXIST:
1156 if why.errno == errno.EEXIST:
1156 raise
1157 raise
1157 else:
1158 else:
1158 _makelock_file(info, pathname)
1159 _makelock_file(info, pathname)
1159
1160
1160 def readlock(pathname):
1161 def readlock(pathname):
1161 try:
1162 try:
1162 return os.readlink(pathname)
1163 return os.readlink(pathname)
1163 except OSError, why:
1164 except OSError, why:
1164 if why.errno in (errno.EINVAL, errno.ENOSYS):
1165 if why.errno in (errno.EINVAL, errno.ENOSYS):
1165 return _readlock_file(pathname)
1166 return _readlock_file(pathname)
1166 else:
1167 else:
1167 raise
1168 raise
1168
1169
1169 def shellquote(s):
1170 def shellquote(s):
1170 if os.sys.platform == 'OpenVMS':
1171 if os.sys.platform == 'OpenVMS':
1171 return '"%s"' % s
1172 return '"%s"' % s
1172 else:
1173 else:
1173 return "'%s'" % s.replace("'", "'\\''")
1174 return "'%s'" % s.replace("'", "'\\''")
1174
1175
1175 def quotecommand(cmd):
1176 def quotecommand(cmd):
1176 return cmd
1177 return cmd
1177
1178
1178 def popen(command):
1179 def popen(command):
1179 return os.popen(command)
1180 return os.popen(command)
1180
1181
1181 def testpid(pid):
1182 def testpid(pid):
1182 '''return False if pid dead, True if running or not sure'''
1183 '''return False if pid dead, True if running or not sure'''
1183 if os.sys.platform == 'OpenVMS':
1184 if os.sys.platform == 'OpenVMS':
1184 return True
1185 return True
1185 try:
1186 try:
1186 os.kill(pid, 0)
1187 os.kill(pid, 0)
1187 return True
1188 return True
1188 except OSError, inst:
1189 except OSError, inst:
1189 return inst.errno != errno.ESRCH
1190 return inst.errno != errno.ESRCH
1190
1191
1191 def explain_exit(code):
1192 def explain_exit(code):
1192 """return a 2-tuple (desc, code) describing a process's status"""
1193 """return a 2-tuple (desc, code) describing a process's status"""
1193 if os.WIFEXITED(code):
1194 if os.WIFEXITED(code):
1194 val = os.WEXITSTATUS(code)
1195 val = os.WEXITSTATUS(code)
1195 return _("exited with status %d") % val, val
1196 return _("exited with status %d") % val, val
1196 elif os.WIFSIGNALED(code):
1197 elif os.WIFSIGNALED(code):
1197 val = os.WTERMSIG(code)
1198 val = os.WTERMSIG(code)
1198 return _("killed by signal %d") % val, val
1199 return _("killed by signal %d") % val, val
1199 elif os.WIFSTOPPED(code):
1200 elif os.WIFSTOPPED(code):
1200 val = os.WSTOPSIG(code)
1201 val = os.WSTOPSIG(code)
1201 return _("stopped by signal %d") % val, val
1202 return _("stopped by signal %d") % val, val
1202 raise ValueError(_("invalid exit code"))
1203 raise ValueError(_("invalid exit code"))
1203
1204
1204 def isowner(fp, st=None):
1205 def isowner(fp, st=None):
1205 """Return True if the file object f belongs to the current user.
1206 """Return True if the file object f belongs to the current user.
1206
1207
1207 The return value of a util.fstat(f) may be passed as the st argument.
1208 The return value of a util.fstat(f) may be passed as the st argument.
1208 """
1209 """
1209 if st is None:
1210 if st is None:
1210 st = fstat(fp)
1211 st = fstat(fp)
1211 return st.st_uid == os.getuid()
1212 return st.st_uid == os.getuid()
1212
1213
1213 def find_in_path(name, path, default=None):
1214 def find_in_path(name, path, default=None):
1214 '''find name in search path. path can be string (will be split
1215 '''find name in search path. path can be string (will be split
1215 with os.pathsep), or iterable thing that returns strings. if name
1216 with os.pathsep), or iterable thing that returns strings. if name
1216 found, return path to name. else return default.'''
1217 found, return path to name. else return default.'''
1217 if isinstance(path, str):
1218 if isinstance(path, str):
1218 path = path.split(os.pathsep)
1219 path = path.split(os.pathsep)
1219 for p in path:
1220 for p in path:
1220 p_name = os.path.join(p, name)
1221 p_name = os.path.join(p, name)
1221 if os.path.exists(p_name):
1222 if os.path.exists(p_name):
1222 return p_name
1223 return p_name
1223 return default
1224 return default
1224
1225
1225 def set_signal_handler():
1226 def set_signal_handler():
1226 pass
1227 pass
1227
1228
1228 def find_exe(name, default=None):
1229 def find_exe(name, default=None):
1229 '''find path of an executable.
1230 '''find path of an executable.
1230 if name contains a path component, return it as is. otherwise,
1231 if name contains a path component, return it as is. otherwise,
1231 use normal executable search path.'''
1232 use normal executable search path.'''
1232
1233
1233 if os.sep in name or sys.platform == 'OpenVMS':
1234 if os.sep in name or sys.platform == 'OpenVMS':
1234 # don't check the executable bit. if the file isn't
1235 # don't check the executable bit. if the file isn't
1235 # executable, whoever tries to actually run it will give a
1236 # executable, whoever tries to actually run it will give a
1236 # much more useful error message.
1237 # much more useful error message.
1237 return name
1238 return name
1238 return find_in_path(name, os.environ.get('PATH', ''), default=default)
1239 return find_in_path(name, os.environ.get('PATH', ''), default=default)
1239
1240
1240 def _buildencodefun():
1241 def _buildencodefun():
1241 e = '_'
1242 e = '_'
1242 win_reserved = [ord(x) for x in '\\:*?"<>|']
1243 win_reserved = [ord(x) for x in '\\:*?"<>|']
1243 cmap = dict([ (chr(x), chr(x)) for x in xrange(127) ])
1244 cmap = dict([ (chr(x), chr(x)) for x in xrange(127) ])
1244 for x in (range(32) + range(126, 256) + win_reserved):
1245 for x in (range(32) + range(126, 256) + win_reserved):
1245 cmap[chr(x)] = "~%02x" % x
1246 cmap[chr(x)] = "~%02x" % x
1246 for x in range(ord("A"), ord("Z")+1) + [ord(e)]:
1247 for x in range(ord("A"), ord("Z")+1) + [ord(e)]:
1247 cmap[chr(x)] = e + chr(x).lower()
1248 cmap[chr(x)] = e + chr(x).lower()
1248 dmap = {}
1249 dmap = {}
1249 for k, v in cmap.iteritems():
1250 for k, v in cmap.iteritems():
1250 dmap[v] = k
1251 dmap[v] = k
1251 def decode(s):
1252 def decode(s):
1252 i = 0
1253 i = 0
1253 while i < len(s):
1254 while i < len(s):
1254 for l in xrange(1, 4):
1255 for l in xrange(1, 4):
1255 try:
1256 try:
1256 yield dmap[s[i:i+l]]
1257 yield dmap[s[i:i+l]]
1257 i += l
1258 i += l
1258 break
1259 break
1259 except KeyError:
1260 except KeyError:
1260 pass
1261 pass
1261 else:
1262 else:
1262 raise KeyError
1263 raise KeyError
1263 return (lambda s: "".join([cmap[c] for c in s]),
1264 return (lambda s: "".join([cmap[c] for c in s]),
1264 lambda s: "".join(list(decode(s))))
1265 lambda s: "".join(list(decode(s))))
1265
1266
1266 encodefilename, decodefilename = _buildencodefun()
1267 encodefilename, decodefilename = _buildencodefun()
1267
1268
1268 def encodedopener(openerfn, fn):
1269 def encodedopener(openerfn, fn):
1269 def o(path, *args, **kw):
1270 def o(path, *args, **kw):
1270 return openerfn(fn(path), *args, **kw)
1271 return openerfn(fn(path), *args, **kw)
1271 return o
1272 return o
1272
1273
1273 def mktempcopy(name, emptyok=False):
1274 def mktempcopy(name, emptyok=False):
1274 """Create a temporary file with the same contents from name
1275 """Create a temporary file with the same contents from name
1275
1276
1276 The permission bits are copied from the original file.
1277 The permission bits are copied from the original file.
1277
1278
1278 If the temporary file is going to be truncated immediately, you
1279 If the temporary file is going to be truncated immediately, you
1279 can use emptyok=True as an optimization.
1280 can use emptyok=True as an optimization.
1280
1281
1281 Returns the name of the temporary file.
1282 Returns the name of the temporary file.
1282 """
1283 """
1283 d, fn = os.path.split(name)
1284 d, fn = os.path.split(name)
1284 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
1285 fd, temp = tempfile.mkstemp(prefix='.%s-' % fn, dir=d)
1285 os.close(fd)
1286 os.close(fd)
1286 # Temporary files are created with mode 0600, which is usually not
1287 # Temporary files are created with mode 0600, which is usually not
1287 # what we want. If the original file already exists, just copy
1288 # what we want. If the original file already exists, just copy
1288 # its mode. Otherwise, manually obey umask.
1289 # its mode. Otherwise, manually obey umask.
1289 try:
1290 try:
1290 st_mode = os.lstat(name).st_mode
1291 st_mode = os.lstat(name).st_mode
1291 except OSError, inst:
1292 except OSError, inst:
1292 if inst.errno != errno.ENOENT:
1293 if inst.errno != errno.ENOENT:
1293 raise
1294 raise
1294 st_mode = 0666 & ~_umask
1295 st_mode = 0666 & ~_umask
1295 os.chmod(temp, st_mode)
1296 os.chmod(temp, st_mode)
1296 if emptyok:
1297 if emptyok:
1297 return temp
1298 return temp
1298 try:
1299 try:
1299 try:
1300 try:
1300 ifp = posixfile(name, "rb")
1301 ifp = posixfile(name, "rb")
1301 except IOError, inst:
1302 except IOError, inst:
1302 if inst.errno == errno.ENOENT:
1303 if inst.errno == errno.ENOENT:
1303 return temp
1304 return temp
1304 if not getattr(inst, 'filename', None):
1305 if not getattr(inst, 'filename', None):
1305 inst.filename = name
1306 inst.filename = name
1306 raise
1307 raise
1307 ofp = posixfile(temp, "wb")
1308 ofp = posixfile(temp, "wb")
1308 for chunk in filechunkiter(ifp):
1309 for chunk in filechunkiter(ifp):
1309 ofp.write(chunk)
1310 ofp.write(chunk)
1310 ifp.close()
1311 ifp.close()
1311 ofp.close()
1312 ofp.close()
1312 except:
1313 except:
1313 try: os.unlink(temp)
1314 try: os.unlink(temp)
1314 except: pass
1315 except: pass
1315 raise
1316 raise
1316 return temp
1317 return temp
1317
1318
1318 class atomictempfile(posixfile):
1319 class atomictempfile(posixfile):
1319 """file-like object that atomically updates a file
1320 """file-like object that atomically updates a file
1320
1321
1321 All writes will be redirected to a temporary copy of the original
1322 All writes will be redirected to a temporary copy of the original
1322 file. When rename is called, the copy is renamed to the original
1323 file. When rename is called, the copy is renamed to the original
1323 name, making the changes visible.
1324 name, making the changes visible.
1324 """
1325 """
1325 def __init__(self, name, mode):
1326 def __init__(self, name, mode):
1326 self.__name = name
1327 self.__name = name
1327 self.temp = mktempcopy(name, emptyok=('w' in mode))
1328 self.temp = mktempcopy(name, emptyok=('w' in mode))
1328 posixfile.__init__(self, self.temp, mode)
1329 posixfile.__init__(self, self.temp, mode)
1329
1330
1330 def rename(self):
1331 def rename(self):
1331 if not self.closed:
1332 if not self.closed:
1332 posixfile.close(self)
1333 posixfile.close(self)
1333 rename(self.temp, localpath(self.__name))
1334 rename(self.temp, localpath(self.__name))
1334
1335
1335 def __del__(self):
1336 def __del__(self):
1336 if not self.closed:
1337 if not self.closed:
1337 try:
1338 try:
1338 os.unlink(self.temp)
1339 os.unlink(self.temp)
1339 except: pass
1340 except: pass
1340 posixfile.close(self)
1341 posixfile.close(self)
1341
1342
1342 class opener(object):
1343 class opener(object):
1343 """Open files relative to a base directory
1344 """Open files relative to a base directory
1344
1345
1345 This class is used to hide the details of COW semantics and
1346 This class is used to hide the details of COW semantics and
1346 remote file access from higher level code.
1347 remote file access from higher level code.
1347 """
1348 """
1348 def __init__(self, base, audit=True):
1349 def __init__(self, base, audit=True):
1349 self.base = base
1350 self.base = base
1350 if audit:
1351 if audit:
1351 self.audit_path = path_auditor(base)
1352 self.audit_path = path_auditor(base)
1352 else:
1353 else:
1353 self.audit_path = always
1354 self.audit_path = always
1354
1355
1355 def __getattr__(self, name):
1356 def __getattr__(self, name):
1356 if name == '_can_symlink':
1357 if name == '_can_symlink':
1357 self._can_symlink = checklink(self.base)
1358 self._can_symlink = checklink(self.base)
1358 return self._can_symlink
1359 return self._can_symlink
1359 raise AttributeError(name)
1360 raise AttributeError(name)
1360
1361
1361 def __call__(self, path, mode="r", text=False, atomictemp=False):
1362 def __call__(self, path, mode="r", text=False, atomictemp=False):
1362 self.audit_path(path)
1363 self.audit_path(path)
1363 f = os.path.join(self.base, path)
1364 f = os.path.join(self.base, path)
1364
1365
1365 if not text and "b" not in mode:
1366 if not text and "b" not in mode:
1366 mode += "b" # for that other OS
1367 mode += "b" # for that other OS
1367
1368
1368 if mode[0] != "r":
1369 if mode[0] != "r":
1369 try:
1370 try:
1370 nlink = nlinks(f)
1371 nlink = nlinks(f)
1371 except OSError:
1372 except OSError:
1372 nlink = 0
1373 nlink = 0
1373 d = os.path.dirname(f)
1374 d = os.path.dirname(f)
1374 if not os.path.isdir(d):
1375 if not os.path.isdir(d):
1375 os.makedirs(d)
1376 os.makedirs(d)
1376 if atomictemp:
1377 if atomictemp:
1377 return atomictempfile(f, mode)
1378 return atomictempfile(f, mode)
1378 if nlink > 1:
1379 if nlink > 1:
1379 rename(mktempcopy(f), f)
1380 rename(mktempcopy(f), f)
1380 return posixfile(f, mode)
1381 return posixfile(f, mode)
1381
1382
1382 def symlink(self, src, dst):
1383 def symlink(self, src, dst):
1383 self.audit_path(dst)
1384 self.audit_path(dst)
1384 linkname = os.path.join(self.base, dst)
1385 linkname = os.path.join(self.base, dst)
1385 try:
1386 try:
1386 os.unlink(linkname)
1387 os.unlink(linkname)
1387 except OSError:
1388 except OSError:
1388 pass
1389 pass
1389
1390
1390 dirname = os.path.dirname(linkname)
1391 dirname = os.path.dirname(linkname)
1391 if not os.path.exists(dirname):
1392 if not os.path.exists(dirname):
1392 os.makedirs(dirname)
1393 os.makedirs(dirname)
1393
1394
1394 if self._can_symlink:
1395 if self._can_symlink:
1395 try:
1396 try:
1396 os.symlink(src, linkname)
1397 os.symlink(src, linkname)
1397 except OSError, err:
1398 except OSError, err:
1398 raise OSError(err.errno, _('could not symlink to %r: %s') %
1399 raise OSError(err.errno, _('could not symlink to %r: %s') %
1399 (src, err.strerror), linkname)
1400 (src, err.strerror), linkname)
1400 else:
1401 else:
1401 f = self(dst, "w")
1402 f = self(dst, "w")
1402 f.write(src)
1403 f.write(src)
1403 f.close()
1404 f.close()
1404
1405
1405 class chunkbuffer(object):
1406 class chunkbuffer(object):
1406 """Allow arbitrary sized chunks of data to be efficiently read from an
1407 """Allow arbitrary sized chunks of data to be efficiently read from an
1407 iterator over chunks of arbitrary size."""
1408 iterator over chunks of arbitrary size."""
1408
1409
1409 def __init__(self, in_iter):
1410 def __init__(self, in_iter):
1410 """in_iter is the iterator that's iterating over the input chunks.
1411 """in_iter is the iterator that's iterating over the input chunks.
1411 targetsize is how big a buffer to try to maintain."""
1412 targetsize is how big a buffer to try to maintain."""
1412 self.iter = iter(in_iter)
1413 self.iter = iter(in_iter)
1413 self.buf = ''
1414 self.buf = ''
1414 self.targetsize = 2**16
1415 self.targetsize = 2**16
1415
1416
1416 def read(self, l):
1417 def read(self, l):
1417 """Read L bytes of data from the iterator of chunks of data.
1418 """Read L bytes of data from the iterator of chunks of data.
1418 Returns less than L bytes if the iterator runs dry."""
1419 Returns less than L bytes if the iterator runs dry."""
1419 if l > len(self.buf) and self.iter:
1420 if l > len(self.buf) and self.iter:
1420 # Clamp to a multiple of self.targetsize
1421 # Clamp to a multiple of self.targetsize
1421 targetsize = max(l, self.targetsize)
1422 targetsize = max(l, self.targetsize)
1422 collector = cStringIO.StringIO()
1423 collector = cStringIO.StringIO()
1423 collector.write(self.buf)
1424 collector.write(self.buf)
1424 collected = len(self.buf)
1425 collected = len(self.buf)
1425 for chunk in self.iter:
1426 for chunk in self.iter:
1426 collector.write(chunk)
1427 collector.write(chunk)
1427 collected += len(chunk)
1428 collected += len(chunk)
1428 if collected >= targetsize:
1429 if collected >= targetsize:
1429 break
1430 break
1430 if collected < targetsize:
1431 if collected < targetsize:
1431 self.iter = False
1432 self.iter = False
1432 self.buf = collector.getvalue()
1433 self.buf = collector.getvalue()
1433 if len(self.buf) == l:
1434 if len(self.buf) == l:
1434 s, self.buf = str(self.buf), ''
1435 s, self.buf = str(self.buf), ''
1435 else:
1436 else:
1436 s, self.buf = self.buf[:l], buffer(self.buf, l)
1437 s, self.buf = self.buf[:l], buffer(self.buf, l)
1437 return s
1438 return s
1438
1439
1439 def filechunkiter(f, size=65536, limit=None):
1440 def filechunkiter(f, size=65536, limit=None):
1440 """Create a generator that produces the data in the file size
1441 """Create a generator that produces the data in the file size
1441 (default 65536) bytes at a time, up to optional limit (default is
1442 (default 65536) bytes at a time, up to optional limit (default is
1442 to read all data). Chunks may be less than size bytes if the
1443 to read all data). Chunks may be less than size bytes if the
1443 chunk is the last chunk in the file, or the file is a socket or
1444 chunk is the last chunk in the file, or the file is a socket or
1444 some other type of file that sometimes reads less data than is
1445 some other type of file that sometimes reads less data than is
1445 requested."""
1446 requested."""
1446 assert size >= 0
1447 assert size >= 0
1447 assert limit is None or limit >= 0
1448 assert limit is None or limit >= 0
1448 while True:
1449 while True:
1449 if limit is None: nbytes = size
1450 if limit is None: nbytes = size
1450 else: nbytes = min(limit, size)
1451 else: nbytes = min(limit, size)
1451 s = nbytes and f.read(nbytes)
1452 s = nbytes and f.read(nbytes)
1452 if not s: break
1453 if not s: break
1453 if limit: limit -= len(s)
1454 if limit: limit -= len(s)
1454 yield s
1455 yield s
1455
1456
1456 def makedate():
1457 def makedate():
1457 lt = time.localtime()
1458 lt = time.localtime()
1458 if lt[8] == 1 and time.daylight:
1459 if lt[8] == 1 and time.daylight:
1459 tz = time.altzone
1460 tz = time.altzone
1460 else:
1461 else:
1461 tz = time.timezone
1462 tz = time.timezone
1462 return time.mktime(lt), tz
1463 return time.mktime(lt), tz
1463
1464
1464 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True, timezone_format=" %+03d%02d"):
1465 def datestr(date=None, format='%a %b %d %H:%M:%S %Y', timezone=True, timezone_format=" %+03d%02d"):
1465 """represent a (unixtime, offset) tuple as a localized time.
1466 """represent a (unixtime, offset) tuple as a localized time.
1466 unixtime is seconds since the epoch, and offset is the time zone's
1467 unixtime is seconds since the epoch, and offset is the time zone's
1467 number of seconds away from UTC. if timezone is false, do not
1468 number of seconds away from UTC. if timezone is false, do not
1468 append time zone to string."""
1469 append time zone to string."""
1469 t, tz = date or makedate()
1470 t, tz = date or makedate()
1470 s = time.strftime(format, time.gmtime(float(t) - tz))
1471 s = time.strftime(format, time.gmtime(float(t) - tz))
1471 if timezone:
1472 if timezone:
1472 s += timezone_format % (-tz / 3600, ((-tz % 3600) / 60))
1473 s += timezone_format % (-tz / 3600, ((-tz % 3600) / 60))
1473 return s
1474 return s
1474
1475
1475 def strdate(string, format, defaults=[]):
1476 def strdate(string, format, defaults=[]):
1476 """parse a localized time string and return a (unixtime, offset) tuple.
1477 """parse a localized time string and return a (unixtime, offset) tuple.
1477 if the string cannot be parsed, ValueError is raised."""
1478 if the string cannot be parsed, ValueError is raised."""
1478 def timezone(string):
1479 def timezone(string):
1479 tz = string.split()[-1]
1480 tz = string.split()[-1]
1480 if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
1481 if tz[0] in "+-" and len(tz) == 5 and tz[1:].isdigit():
1481 tz = int(tz)
1482 tz = int(tz)
1482 offset = - 3600 * (tz / 100) - 60 * (tz % 100)
1483 offset = - 3600 * (tz / 100) - 60 * (tz % 100)
1483 return offset
1484 return offset
1484 if tz == "GMT" or tz == "UTC":
1485 if tz == "GMT" or tz == "UTC":
1485 return 0
1486 return 0
1486 return None
1487 return None
1487
1488
1488 # NOTE: unixtime = localunixtime + offset
1489 # NOTE: unixtime = localunixtime + offset
1489 offset, date = timezone(string), string
1490 offset, date = timezone(string), string
1490 if offset != None:
1491 if offset != None:
1491 date = " ".join(string.split()[:-1])
1492 date = " ".join(string.split()[:-1])
1492
1493
1493 # add missing elements from defaults
1494 # add missing elements from defaults
1494 for part in defaults:
1495 for part in defaults:
1495 found = [True for p in part if ("%"+p) in format]
1496 found = [True for p in part if ("%"+p) in format]
1496 if not found:
1497 if not found:
1497 date += "@" + defaults[part]
1498 date += "@" + defaults[part]
1498 format += "@%" + part[0]
1499 format += "@%" + part[0]
1499
1500
1500 timetuple = time.strptime(date, format)
1501 timetuple = time.strptime(date, format)
1501 localunixtime = int(calendar.timegm(timetuple))
1502 localunixtime = int(calendar.timegm(timetuple))
1502 if offset is None:
1503 if offset is None:
1503 # local timezone
1504 # local timezone
1504 unixtime = int(time.mktime(timetuple))
1505 unixtime = int(time.mktime(timetuple))
1505 offset = unixtime - localunixtime
1506 offset = unixtime - localunixtime
1506 else:
1507 else:
1507 unixtime = localunixtime + offset
1508 unixtime = localunixtime + offset
1508 return unixtime, offset
1509 return unixtime, offset
1509
1510
1510 def parsedate(string, formats=None, defaults=None):
1511 def parsedate(string, formats=None, defaults=None):
1511 """parse a localized time string and return a (unixtime, offset) tuple.
1512 """parse a localized time string and return a (unixtime, offset) tuple.
1512 The date may be a "unixtime offset" string or in one of the specified
1513 The date may be a "unixtime offset" string or in one of the specified
1513 formats."""
1514 formats."""
1514 if not string:
1515 if not string:
1515 return 0, 0
1516 return 0, 0
1516 if not formats:
1517 if not formats:
1517 formats = defaultdateformats
1518 formats = defaultdateformats
1518 string = string.strip()
1519 string = string.strip()
1519 try:
1520 try:
1520 when, offset = map(int, string.split(' '))
1521 when, offset = map(int, string.split(' '))
1521 except ValueError:
1522 except ValueError:
1522 # fill out defaults
1523 # fill out defaults
1523 if not defaults:
1524 if not defaults:
1524 defaults = {}
1525 defaults = {}
1525 now = makedate()
1526 now = makedate()
1526 for part in "d mb yY HI M S".split():
1527 for part in "d mb yY HI M S".split():
1527 if part not in defaults:
1528 if part not in defaults:
1528 if part[0] in "HMS":
1529 if part[0] in "HMS":
1529 defaults[part] = "00"
1530 defaults[part] = "00"
1530 elif part[0] in "dm":
1531 elif part[0] in "dm":
1531 defaults[part] = "1"
1532 defaults[part] = "1"
1532 else:
1533 else:
1533 defaults[part] = datestr(now, "%" + part[0], False)
1534 defaults[part] = datestr(now, "%" + part[0], False)
1534
1535
1535 for format in formats:
1536 for format in formats:
1536 try:
1537 try:
1537 when, offset = strdate(string, format, defaults)
1538 when, offset = strdate(string, format, defaults)
1538 except ValueError:
1539 except ValueError:
1539 pass
1540 pass
1540 else:
1541 else:
1541 break
1542 break
1542 else:
1543 else:
1543 raise Abort(_('invalid date: %r ') % string)
1544 raise Abort(_('invalid date: %r ') % string)
1544 # validate explicit (probably user-specified) date and
1545 # validate explicit (probably user-specified) date and
1545 # time zone offset. values must fit in signed 32 bits for
1546 # time zone offset. values must fit in signed 32 bits for
1546 # current 32-bit linux runtimes. timezones go from UTC-12
1547 # current 32-bit linux runtimes. timezones go from UTC-12
1547 # to UTC+14
1548 # to UTC+14
1548 if abs(when) > 0x7fffffff:
1549 if abs(when) > 0x7fffffff:
1549 raise Abort(_('date exceeds 32 bits: %d') % when)
1550 raise Abort(_('date exceeds 32 bits: %d') % when)
1550 if offset < -50400 or offset > 43200:
1551 if offset < -50400 or offset > 43200:
1551 raise Abort(_('impossible time zone offset: %d') % offset)
1552 raise Abort(_('impossible time zone offset: %d') % offset)
1552 return when, offset
1553 return when, offset
1553
1554
1554 def matchdate(date):
1555 def matchdate(date):
1555 """Return a function that matches a given date match specifier
1556 """Return a function that matches a given date match specifier
1556
1557
1557 Formats include:
1558 Formats include:
1558
1559
1559 '{date}' match a given date to the accuracy provided
1560 '{date}' match a given date to the accuracy provided
1560
1561
1561 '<{date}' on or before a given date
1562 '<{date}' on or before a given date
1562
1563
1563 '>{date}' on or after a given date
1564 '>{date}' on or after a given date
1564
1565
1565 """
1566 """
1566
1567
1567 def lower(date):
1568 def lower(date):
1568 return parsedate(date, extendeddateformats)[0]
1569 return parsedate(date, extendeddateformats)[0]
1569
1570
1570 def upper(date):
1571 def upper(date):
1571 d = dict(mb="12", HI="23", M="59", S="59")
1572 d = dict(mb="12", HI="23", M="59", S="59")
1572 for days in "31 30 29".split():
1573 for days in "31 30 29".split():
1573 try:
1574 try:
1574 d["d"] = days
1575 d["d"] = days
1575 return parsedate(date, extendeddateformats, d)[0]
1576 return parsedate(date, extendeddateformats, d)[0]
1576 except:
1577 except:
1577 pass
1578 pass
1578 d["d"] = "28"
1579 d["d"] = "28"
1579 return parsedate(date, extendeddateformats, d)[0]
1580 return parsedate(date, extendeddateformats, d)[0]
1580
1581
1581 if date[0] == "<":
1582 if date[0] == "<":
1582 when = upper(date[1:])
1583 when = upper(date[1:])
1583 return lambda x: x <= when
1584 return lambda x: x <= when
1584 elif date[0] == ">":
1585 elif date[0] == ">":
1585 when = lower(date[1:])
1586 when = lower(date[1:])
1586 return lambda x: x >= when
1587 return lambda x: x >= when
1587 elif date[0] == "-":
1588 elif date[0] == "-":
1588 try:
1589 try:
1589 days = int(date[1:])
1590 days = int(date[1:])
1590 except ValueError:
1591 except ValueError:
1591 raise Abort(_("invalid day spec: %s") % date[1:])
1592 raise Abort(_("invalid day spec: %s") % date[1:])
1592 when = makedate()[0] - days * 3600 * 24
1593 when = makedate()[0] - days * 3600 * 24
1593 return lambda x: x >= when
1594 return lambda x: x >= when
1594 elif " to " in date:
1595 elif " to " in date:
1595 a, b = date.split(" to ")
1596 a, b = date.split(" to ")
1596 start, stop = lower(a), upper(b)
1597 start, stop = lower(a), upper(b)
1597 return lambda x: x >= start and x <= stop
1598 return lambda x: x >= start and x <= stop
1598 else:
1599 else:
1599 start, stop = lower(date), upper(date)
1600 start, stop = lower(date), upper(date)
1600 return lambda x: x >= start and x <= stop
1601 return lambda x: x >= start and x <= stop
1601
1602
1602 def shortuser(user):
1603 def shortuser(user):
1603 """Return a short representation of a user name or email address."""
1604 """Return a short representation of a user name or email address."""
1604 f = user.find('@')
1605 f = user.find('@')
1605 if f >= 0:
1606 if f >= 0:
1606 user = user[:f]
1607 user = user[:f]
1607 f = user.find('<')
1608 f = user.find('<')
1608 if f >= 0:
1609 if f >= 0:
1609 user = user[f+1:]
1610 user = user[f+1:]
1610 f = user.find(' ')
1611 f = user.find(' ')
1611 if f >= 0:
1612 if f >= 0:
1612 user = user[:f]
1613 user = user[:f]
1613 f = user.find('.')
1614 f = user.find('.')
1614 if f >= 0:
1615 if f >= 0:
1615 user = user[:f]
1616 user = user[:f]
1616 return user
1617 return user
1617
1618
1618 def ellipsis(text, maxlength=400):
1619 def ellipsis(text, maxlength=400):
1619 """Trim string to at most maxlength (default: 400) characters."""
1620 """Trim string to at most maxlength (default: 400) characters."""
1620 if len(text) <= maxlength:
1621 if len(text) <= maxlength:
1621 return text
1622 return text
1622 else:
1623 else:
1623 return "%s..." % (text[:maxlength-3])
1624 return "%s..." % (text[:maxlength-3])
1624
1625
1625 def walkrepos(path):
1626 def walkrepos(path):
1626 '''yield every hg repository under path, recursively.'''
1627 '''yield every hg repository under path, recursively.'''
1627 def errhandler(err):
1628 def errhandler(err):
1628 if err.filename == path:
1629 if err.filename == path:
1629 raise err
1630 raise err
1630
1631
1631 for root, dirs, files in os.walk(path, onerror=errhandler):
1632 for root, dirs, files in os.walk(path, onerror=errhandler):
1632 for d in dirs:
1633 for d in dirs:
1633 if d == '.hg':
1634 if d == '.hg':
1634 yield root
1635 yield root
1635 dirs[:] = []
1636 dirs[:] = []
1636 break
1637 break
1637
1638
1638 _rcpath = None
1639 _rcpath = None
1639
1640
1640 def os_rcpath():
1641 def os_rcpath():
1641 '''return default os-specific hgrc search path'''
1642 '''return default os-specific hgrc search path'''
1642 path = system_rcpath()
1643 path = system_rcpath()
1643 path.extend(user_rcpath())
1644 path.extend(user_rcpath())
1644 path = [os.path.normpath(f) for f in path]
1645 path = [os.path.normpath(f) for f in path]
1645 return path
1646 return path
1646
1647
1647 def rcpath():
1648 def rcpath():
1648 '''return hgrc search path. if env var HGRCPATH is set, use it.
1649 '''return hgrc search path. if env var HGRCPATH is set, use it.
1649 for each item in path, if directory, use files ending in .rc,
1650 for each item in path, if directory, use files ending in .rc,
1650 else use item.
1651 else use item.
1651 make HGRCPATH empty to only look in .hg/hgrc of current repo.
1652 make HGRCPATH empty to only look in .hg/hgrc of current repo.
1652 if no HGRCPATH, use default os-specific path.'''
1653 if no HGRCPATH, use default os-specific path.'''
1653 global _rcpath
1654 global _rcpath
1654 if _rcpath is None:
1655 if _rcpath is None:
1655 if 'HGRCPATH' in os.environ:
1656 if 'HGRCPATH' in os.environ:
1656 _rcpath = []
1657 _rcpath = []
1657 for p in os.environ['HGRCPATH'].split(os.pathsep):
1658 for p in os.environ['HGRCPATH'].split(os.pathsep):
1658 if not p: continue
1659 if not p: continue
1659 if os.path.isdir(p):
1660 if os.path.isdir(p):
1660 for f, kind in osutil.listdir(p):
1661 for f, kind in osutil.listdir(p):
1661 if f.endswith('.rc'):
1662 if f.endswith('.rc'):
1662 _rcpath.append(os.path.join(p, f))
1663 _rcpath.append(os.path.join(p, f))
1663 else:
1664 else:
1664 _rcpath.append(p)
1665 _rcpath.append(p)
1665 else:
1666 else:
1666 _rcpath = os_rcpath()
1667 _rcpath = os_rcpath()
1667 return _rcpath
1668 return _rcpath
1668
1669
1669 def bytecount(nbytes):
1670 def bytecount(nbytes):
1670 '''return byte count formatted as readable string, with units'''
1671 '''return byte count formatted as readable string, with units'''
1671
1672
1672 units = (
1673 units = (
1673 (100, 1<<30, _('%.0f GB')),
1674 (100, 1<<30, _('%.0f GB')),
1674 (10, 1<<30, _('%.1f GB')),
1675 (10, 1<<30, _('%.1f GB')),
1675 (1, 1<<30, _('%.2f GB')),
1676 (1, 1<<30, _('%.2f GB')),
1676 (100, 1<<20, _('%.0f MB')),
1677 (100, 1<<20, _('%.0f MB')),
1677 (10, 1<<20, _('%.1f MB')),
1678 (10, 1<<20, _('%.1f MB')),
1678 (1, 1<<20, _('%.2f MB')),
1679 (1, 1<<20, _('%.2f MB')),
1679 (100, 1<<10, _('%.0f KB')),
1680 (100, 1<<10, _('%.0f KB')),
1680 (10, 1<<10, _('%.1f KB')),
1681 (10, 1<<10, _('%.1f KB')),
1681 (1, 1<<10, _('%.2f KB')),
1682 (1, 1<<10, _('%.2f KB')),
1682 (1, 1, _('%.0f bytes')),
1683 (1, 1, _('%.0f bytes')),
1683 )
1684 )
1684
1685
1685 for multiplier, divisor, format in units:
1686 for multiplier, divisor, format in units:
1686 if nbytes >= divisor * multiplier:
1687 if nbytes >= divisor * multiplier:
1687 return format % (nbytes / float(divisor))
1688 return format % (nbytes / float(divisor))
1688 return units[-1][2] % nbytes
1689 return units[-1][2] % nbytes
1689
1690
1690 def drop_scheme(scheme, path):
1691 def drop_scheme(scheme, path):
1691 sc = scheme + ':'
1692 sc = scheme + ':'
1692 if path.startswith(sc):
1693 if path.startswith(sc):
1693 path = path[len(sc):]
1694 path = path[len(sc):]
1694 if path.startswith('//'):
1695 if path.startswith('//'):
1695 path = path[2:]
1696 path = path[2:]
1696 return path
1697 return path
1697
1698
1698 def uirepr(s):
1699 def uirepr(s):
1699 # Avoid double backslash in Windows path repr()
1700 # Avoid double backslash in Windows path repr()
1700 return repr(s).replace('\\\\', '\\')
1701 return repr(s).replace('\\\\', '\\')
1702
1703 def hidepassword(url):
1704 '''replaces the password in the url string by three asterisks (***)
1705
1706 >>> hidepassword('http://www.example.com/some/path#fragment')
1707 'http://www.example.com/some/path#fragment'
1708 >>> hidepassword('http://me@www.example.com/some/path#fragment')
1709 'http://me@www.example.com/some/path#fragment'
1710 >>> hidepassword('http://me:simplepw@www.example.com/path#frag')
1711 'http://me:***@www.example.com/path#frag'
1712 >>> hidepassword('http://me:complex:pw@www.example.com/path#frag')
1713 'http://me:***@www.example.com/path#frag'
1714 >>> hidepassword('/path/to/repo')
1715 '/path/to/repo'
1716 >>> hidepassword('relative/path/to/repo')
1717 'relative/path/to/repo'
1718 >>> hidepassword('c:\\\\path\\\\to\\\\repo')
1719 'c:\\\\path\\\\to\\\\repo'
1720 >>> hidepassword('c:/path/to/repo')
1721 'c:/path/to/repo'
1722 >>> hidepassword('bundle://path/to/bundle')
1723 'bundle://path/to/bundle'
1724 '''
1725 url_parts = list(urlparse.urlparse(url))
1726 host_with_pw_pattern = re.compile('^([^:]*):([^@]*)@(.*)$')
1727 if host_with_pw_pattern.match(url_parts[1]):
1728 url_parts[1] = re.sub(host_with_pw_pattern, r'\1:***@\3',
1729 url_parts[1])
1730 return urlparse.urlunparse(url_parts)
1731
@@ -1,9 +1,12 b''
1 import doctest
1 import doctest
2
2
3 import mercurial.changelog
3 import mercurial.changelog
4 # test doctest from changelog
4 # test doctest from changelog
5
5
6 doctest.testmod(mercurial.changelog)
6 doctest.testmod(mercurial.changelog)
7
7
8 import mercurial.httprepo
8 import mercurial.httprepo
9 doctest.testmod(mercurial.httprepo)
9 doctest.testmod(mercurial.httprepo)
10
11 import mercurial.util
12 doctest.testmod(mercurial.util)
General Comments 0
You need to be logged in to leave comments. Login now