##// END OF EJS Templates
notify, commands: word-wrap help strings
Martin Geisler -
r8029:e0c434ab default
parent child Browse files
Show More
@@ -1,290 +1,290
1 1 # notify.py - email notifications for mercurial
2 2 #
3 3 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 '''hook extension to email notifications on commits/pushes
9 9
10 10 Subscriptions can be managed through hgrc. Default mode is to print
11 11 messages to stdout, for testing and configuring.
12 12
13 13 To use, configure notify extension and enable in hgrc like this:
14 14
15 15 [extensions]
16 16 hgext.notify =
17 17
18 18 [hooks]
19 19 # one email for each incoming changeset
20 20 incoming.notify = python:hgext.notify.hook
21 21 # batch emails when many changesets incoming at one time
22 22 changegroup.notify = python:hgext.notify.hook
23 23
24 24 [notify]
25 25 # config items go in here
26 26
27 27 config items:
28 28
29 29 REQUIRED:
30 30 config = /path/to/file # file containing subscriptions
31 31
32 32 OPTIONAL:
33 33 test = True # print messages to stdout for testing
34 34 strip = 3 # number of slashes to strip for url paths
35 35 domain = example.com # domain to use if committer missing domain
36 36 style = ... # style file to use when formatting email
37 37 template = ... # template to use when formatting email
38 38 incoming = ... # template to use when run as incoming hook
39 39 changegroup = ... # template when run as changegroup hook
40 40 maxdiff = 300 # max lines of diffs to include (0=none, -1=all)
41 41 maxsubject = 67 # truncate subject line longer than this
42 42 diffstat = True # add a diffstat before the diff content
43 43 sources = serve # notify if source of incoming changes in this list
44 44 # (serve == ssh or http, push, pull, bundle)
45 45 [email]
46 46 from = user@host.com # email address to send as if none given
47 47 [web]
48 48 baseurl = http://hgserver/... # root of hg web site for browsing commits
49 49
50 50 notify config file has same format as regular hgrc. it has two
51 51 sections so you can express subscriptions in whatever way is handier
52 52 for you.
53 53
54 54 [usersubs]
55 55 # key is subscriber email, value is ","-separated list of glob patterns
56 56 user@host = pattern
57 57
58 58 [reposubs]
59 59 # key is glob pattern, value is ","-separated list of subscriber emails
60 60 pattern = user@host
61 61
62 62 glob patterns are matched against path to repository root.
63 63
64 if you like, you can put notify config file in repository that users can
65 push changes to, they can manage their own subscriptions.'''
64 if you like, you can put notify config file in repository that users
65 can push changes to, they can manage their own subscriptions.'''
66 66
67 67 from mercurial.i18n import _
68 68 from mercurial import patch, cmdutil, templater, util, mail
69 69 import email.Parser, fnmatch, socket, time
70 70
71 71 # template for single changeset can include email headers.
72 72 single_template = '''
73 73 Subject: changeset in {webroot}: {desc|firstline|strip}
74 74 From: {author}
75 75
76 76 changeset {node|short} in {root}
77 77 details: {baseurl}{webroot}?cmd=changeset;node={node|short}
78 78 description:
79 79 \t{desc|tabindent|strip}
80 80 '''.lstrip()
81 81
82 82 # template for multiple changesets should not contain email headers,
83 83 # because only first set of headers will be used and result will look
84 84 # strange.
85 85 multiple_template = '''
86 86 changeset {node|short} in {root}
87 87 details: {baseurl}{webroot}?cmd=changeset;node={node|short}
88 88 summary: {desc|firstline}
89 89 '''
90 90
91 91 deftemplates = {
92 92 'changegroup': multiple_template,
93 93 }
94 94
95 95 class notifier(object):
96 96 '''email notification class.'''
97 97
98 98 def __init__(self, ui, repo, hooktype):
99 99 self.ui = ui
100 100 cfg = self.ui.config('notify', 'config')
101 101 if cfg:
102 102 self.ui.readsections(cfg, 'usersubs', 'reposubs')
103 103 self.repo = repo
104 104 self.stripcount = int(self.ui.config('notify', 'strip', 0))
105 105 self.root = self.strip(self.repo.root)
106 106 self.domain = self.ui.config('notify', 'domain')
107 107 self.test = self.ui.configbool('notify', 'test', True)
108 108 self.charsets = mail._charsets(self.ui)
109 109 self.subs = self.subscribers()
110 110
111 111 mapfile = self.ui.config('notify', 'style')
112 112 template = (self.ui.config('notify', hooktype) or
113 113 self.ui.config('notify', 'template'))
114 114 self.t = cmdutil.changeset_templater(self.ui, self.repo,
115 115 False, None, mapfile, False)
116 116 if not mapfile and not template:
117 117 template = deftemplates.get(hooktype) or single_template
118 118 if template:
119 119 template = templater.parsestring(template, quoted=False)
120 120 self.t.use_template(template)
121 121
122 122 def strip(self, path):
123 123 '''strip leading slashes from local path, turn into web-safe path.'''
124 124
125 125 path = util.pconvert(path)
126 126 count = self.stripcount
127 127 while count > 0:
128 128 c = path.find('/')
129 129 if c == -1:
130 130 break
131 131 path = path[c+1:]
132 132 count -= 1
133 133 return path
134 134
135 135 def fixmail(self, addr):
136 136 '''try to clean up email addresses.'''
137 137
138 138 addr = util.email(addr.strip())
139 139 if self.domain:
140 140 a = addr.find('@localhost')
141 141 if a != -1:
142 142 addr = addr[:a]
143 143 if '@' not in addr:
144 144 return addr + '@' + self.domain
145 145 return addr
146 146
147 147 def subscribers(self):
148 148 '''return list of email addresses of subscribers to this repo.'''
149 149 subs = {}
150 150 for user, pats in self.ui.configitems('usersubs'):
151 151 for pat in pats.split(','):
152 152 if fnmatch.fnmatch(self.repo.root, pat.strip()):
153 153 subs[self.fixmail(user)] = 1
154 154 for pat, users in self.ui.configitems('reposubs'):
155 155 if fnmatch.fnmatch(self.repo.root, pat):
156 156 for user in users.split(','):
157 157 subs[self.fixmail(user)] = 1
158 158 subs = util.sort(subs)
159 159 return [mail.addressencode(self.ui, s, self.charsets, self.test)
160 160 for s in subs]
161 161
162 162 def url(self, path=None):
163 163 return self.ui.config('web', 'baseurl') + (path or self.root)
164 164
165 165 def node(self, ctx):
166 166 '''format one changeset.'''
167 167 self.t.show(ctx, changes=ctx.changeset(),
168 168 baseurl=self.ui.config('web', 'baseurl'),
169 169 root=self.repo.root, webroot=self.root)
170 170
171 171 def skipsource(self, source):
172 172 '''true if incoming changes from this source should be skipped.'''
173 173 ok_sources = self.ui.config('notify', 'sources', 'serve').split()
174 174 return source not in ok_sources
175 175
176 176 def send(self, ctx, count, data):
177 177 '''send message.'''
178 178
179 179 p = email.Parser.Parser()
180 180 msg = p.parsestr(data)
181 181
182 182 # store sender and subject
183 183 sender, subject = msg['From'], msg['Subject']
184 184 del msg['From'], msg['Subject']
185 185 # store remaining headers
186 186 headers = msg.items()
187 187 # create fresh mime message from msg body
188 188 text = msg.get_payload()
189 189 # for notification prefer readability over data precision
190 190 msg = mail.mimeencode(self.ui, text, self.charsets, self.test)
191 191 # reinstate custom headers
192 192 for k, v in headers:
193 193 msg[k] = v
194 194
195 195 msg['Date'] = util.datestr(format="%a, %d %b %Y %H:%M:%S %1%2")
196 196
197 197 # try to make subject line exist and be useful
198 198 if not subject:
199 199 if count > 1:
200 200 subject = _('%s: %d new changesets') % (self.root, count)
201 201 else:
202 202 s = ctx.description().lstrip().split('\n', 1)[0].rstrip()
203 203 subject = '%s: %s' % (self.root, s)
204 204 maxsubject = int(self.ui.config('notify', 'maxsubject', 67))
205 205 if maxsubject and len(subject) > maxsubject:
206 206 subject = subject[:maxsubject-3] + '...'
207 207 msg['Subject'] = mail.headencode(self.ui, subject,
208 208 self.charsets, self.test)
209 209
210 210 # try to make message have proper sender
211 211 if not sender:
212 212 sender = self.ui.config('email', 'from') or self.ui.username()
213 213 if '@' not in sender or '@localhost' in sender:
214 214 sender = self.fixmail(sender)
215 215 msg['From'] = mail.addressencode(self.ui, sender,
216 216 self.charsets, self.test)
217 217
218 218 msg['X-Hg-Notification'] = 'changeset %s' % ctx
219 219 if not msg['Message-Id']:
220 220 msg['Message-Id'] = ('<hg.%s.%s.%s@%s>' %
221 221 (ctx, int(time.time()),
222 222 hash(self.repo.root), socket.getfqdn()))
223 223 msg['To'] = ', '.join(self.subs)
224 224
225 225 msgtext = msg.as_string(0)
226 226 if self.test:
227 227 self.ui.write(msgtext)
228 228 if not msgtext.endswith('\n'):
229 229 self.ui.write('\n')
230 230 else:
231 231 self.ui.status(_('notify: sending %d subscribers %d changes\n') %
232 232 (len(self.subs), count))
233 233 mail.sendmail(self.ui, util.email(msg['From']),
234 234 self.subs, msgtext)
235 235
236 236 def diff(self, ctx, ref=None):
237 237
238 238 maxdiff = int(self.ui.config('notify', 'maxdiff', 300))
239 239 prev = ctx.parents()[0].node()
240 240 ref = ref and ref.node() or ctx.node()
241 241 chunks = patch.diff(self.repo, prev, ref, opts=patch.diffopts(self.ui))
242 242 difflines = ''.join(chunks).splitlines()
243 243
244 244 if self.ui.configbool('notify', 'diffstat', True):
245 245 s = patch.diffstat(difflines)
246 246 # s may be nil, don't include the header if it is
247 247 if s:
248 248 self.ui.write('\ndiffstat:\n\n%s' % s)
249 249
250 250 if maxdiff == 0:
251 251 return
252 252 elif maxdiff > 0 and len(difflines) > maxdiff:
253 253 msg = _('\ndiffs (truncated from %d to %d lines):\n\n')
254 254 self.ui.write(msg % (len(difflines), maxdiff))
255 255 difflines = difflines[:maxdiff]
256 256 elif difflines:
257 257 self.ui.write(_('\ndiffs (%d lines):\n\n') % len(difflines))
258 258
259 259 self.ui.write("\n".join(difflines))
260 260
261 261 def hook(ui, repo, hooktype, node=None, source=None, **kwargs):
262 262 '''send email notifications to interested subscribers.
263 263
264 264 if used as changegroup hook, send one email for all changesets in
265 265 changegroup. else send one email per changeset.'''
266 266
267 267 n = notifier(ui, repo, hooktype)
268 268 ctx = repo[node]
269 269
270 270 if not n.subs:
271 271 ui.debug(_('notify: no subscribers to repository %s\n') % n.root)
272 272 return
273 273 if n.skipsource(source):
274 274 ui.debug(_('notify: changes have source "%s" - skipping\n') % source)
275 275 return
276 276
277 277 ui.pushbuffer()
278 278 if hooktype == 'changegroup':
279 279 start, end = ctx.rev(), len(repo)
280 280 count = end - start
281 281 for rev in xrange(start, end):
282 282 n.node(repo[rev])
283 283 n.diff(ctx, repo['tip'])
284 284 else:
285 285 count = 1
286 286 n.node(ctx)
287 287 n.diff(ctx)
288 288
289 289 data = ui.popbuffer()
290 290 n.send(ctx, count, data)
@@ -1,3453 +1,3454
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 from node import hex, nullid, nullrev, short
9 9 from i18n import _, gettext
10 10 import os, re, sys
11 11 import hg, util, revlog, bundlerepo, extensions, copies, context, error
12 12 import difflib, patch, time, help, mdiff, tempfile, url, encoding
13 13 import archival, changegroup, cmdutil, hgweb.server, sshserver, hbisect
14 14 import merge as merge_
15 15
16 16 # Commands start here, listed alphabetically
17 17
18 18 def add(ui, repo, *pats, **opts):
19 19 """add the specified files on the next commit
20 20
21 21 Schedule files to be version controlled and added to the
22 22 repository.
23 23
24 24 The files will be added to the repository at the next commit. To
25 25 undo an add before that, see hg revert.
26 26
27 27 If no names are given, add all files to the repository.
28 28 """
29 29
30 30 rejected = None
31 31 exacts = {}
32 32 names = []
33 33 m = cmdutil.match(repo, pats, opts)
34 34 m.bad = lambda x,y: True
35 35 for abs in repo.walk(m):
36 36 if m.exact(abs):
37 37 if ui.verbose:
38 38 ui.status(_('adding %s\n') % m.rel(abs))
39 39 names.append(abs)
40 40 exacts[abs] = 1
41 41 elif abs not in repo.dirstate:
42 42 ui.status(_('adding %s\n') % m.rel(abs))
43 43 names.append(abs)
44 44 if not opts.get('dry_run'):
45 45 rejected = repo.add(names)
46 46 rejected = [p for p in rejected if p in exacts]
47 47 return rejected and 1 or 0
48 48
49 49 def addremove(ui, repo, *pats, **opts):
50 50 """add all new files, delete all missing files
51 51
52 52 Add all new files and remove all missing files from the
53 53 repository.
54 54
55 55 New files are ignored if they match any of the patterns in
56 56 .hgignore. As with add, these changes take effect at the next
57 57 commit.
58 58
59 59 Use the -s option to detect renamed files. With a parameter > 0,
60 60 this compares every removed file with every added file and records
61 61 those similar enough as renames. This option takes a percentage
62 62 between 0 (disabled) and 100 (files must be identical) as its
63 63 parameter. Detecting renamed files this way can be expensive.
64 64 """
65 65 try:
66 66 sim = float(opts.get('similarity') or 0)
67 67 except ValueError:
68 68 raise util.Abort(_('similarity must be a number'))
69 69 if sim < 0 or sim > 100:
70 70 raise util.Abort(_('similarity must be between 0 and 100'))
71 71 return cmdutil.addremove(repo, pats, opts, similarity=sim/100.)
72 72
73 73 def annotate(ui, repo, *pats, **opts):
74 74 """show changeset information per file line
75 75
76 76 List changes in files, showing the revision id responsible for
77 77 each line
78 78
79 79 This command is useful to discover who did a change or when a
80 80 change took place.
81 81
82 82 Without the -a option, annotate will avoid processing files it
83 83 detects as binary. With -a, annotate will generate an annotation
84 84 anyway, probably with undesirable results.
85 85 """
86 86 datefunc = ui.quiet and util.shortdate or util.datestr
87 87 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
88 88
89 89 if not pats:
90 90 raise util.Abort(_('at least one file name or pattern required'))
91 91
92 92 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
93 93 ('number', lambda x: str(x[0].rev())),
94 94 ('changeset', lambda x: short(x[0].node())),
95 95 ('date', getdate),
96 96 ('follow', lambda x: x[0].path()),
97 97 ]
98 98
99 99 if (not opts.get('user') and not opts.get('changeset') and not opts.get('date')
100 100 and not opts.get('follow')):
101 101 opts['number'] = 1
102 102
103 103 linenumber = opts.get('line_number') is not None
104 104 if (linenumber and (not opts.get('changeset')) and (not opts.get('number'))):
105 105 raise util.Abort(_('at least one of -n/-c is required for -l'))
106 106
107 107 funcmap = [func for op, func in opmap if opts.get(op)]
108 108 if linenumber:
109 109 lastfunc = funcmap[-1]
110 110 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
111 111
112 112 ctx = repo[opts.get('rev')]
113 113
114 114 m = cmdutil.match(repo, pats, opts)
115 115 for abs in ctx.walk(m):
116 116 fctx = ctx[abs]
117 117 if not opts.get('text') and util.binary(fctx.data()):
118 118 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
119 119 continue
120 120
121 121 lines = fctx.annotate(follow=opts.get('follow'),
122 122 linenumber=linenumber)
123 123 pieces = []
124 124
125 125 for f in funcmap:
126 126 l = [f(n) for n, dummy in lines]
127 127 if l:
128 128 ml = max(map(len, l))
129 129 pieces.append(["%*s" % (ml, x) for x in l])
130 130
131 131 if pieces:
132 132 for p, l in zip(zip(*pieces), lines):
133 133 ui.write("%s: %s" % (" ".join(p), l[1]))
134 134
135 135 def archive(ui, repo, dest, **opts):
136 136 '''create unversioned archive of a repository revision
137 137
138 138 By default, the revision used is the parent of the working
139 139 directory; use "-r" to specify a different revision.
140 140
141 141 To specify the type of archive to create, use "-t". Valid types
142 142 are:
143 143
144 144 "files" (default): a directory full of files
145 145 "tar": tar archive, uncompressed
146 146 "tbz2": tar archive, compressed using bzip2
147 147 "tgz": tar archive, compressed using gzip
148 148 "uzip": zip archive, uncompressed
149 149 "zip": zip archive, compressed using deflate
150 150
151 151 The exact name of the destination archive or directory is given
152 152 using a format string; see 'hg help export' for details.
153 153
154 154 Each member added to an archive file has a directory prefix
155 155 prepended. Use "-p" to specify a format string for the prefix. The
156 156 default is the basename of the archive, with suffixes removed.
157 157 '''
158 158
159 159 ctx = repo[opts.get('rev')]
160 160 if not ctx:
161 161 raise util.Abort(_('no working directory: please specify a revision'))
162 162 node = ctx.node()
163 163 dest = cmdutil.make_filename(repo, dest, node)
164 164 if os.path.realpath(dest) == repo.root:
165 165 raise util.Abort(_('repository root cannot be destination'))
166 166 matchfn = cmdutil.match(repo, [], opts)
167 167 kind = opts.get('type') or 'files'
168 168 prefix = opts.get('prefix')
169 169 if dest == '-':
170 170 if kind == 'files':
171 171 raise util.Abort(_('cannot archive plain files to stdout'))
172 172 dest = sys.stdout
173 173 if not prefix: prefix = os.path.basename(repo.root) + '-%h'
174 174 prefix = cmdutil.make_filename(repo, prefix, node)
175 175 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
176 176 matchfn, prefix)
177 177
178 178 def backout(ui, repo, node=None, rev=None, **opts):
179 179 '''reverse effect of earlier changeset
180 180
181 181 Commit the backed out changes as a new changeset. The new
182 182 changeset is a child of the backed out changeset.
183 183
184 184 If you back out a changeset other than the tip, a new head is
185 185 created. This head will be the new tip and you should merge this
186 186 backout changeset with another head (current one by default).
187 187
188 188 The --merge option remembers the parent of the working directory
189 189 before starting the backout, then merges the new head with that
190 190 changeset afterwards. This saves you from doing the merge by hand.
191 191 The result of this merge is not committed, as with a normal merge.
192 192
193 193 See \'hg help dates\' for a list of formats valid for -d/--date.
194 194 '''
195 195 if rev and node:
196 196 raise util.Abort(_("please specify just one revision"))
197 197
198 198 if not rev:
199 199 rev = node
200 200
201 201 if not rev:
202 202 raise util.Abort(_("please specify a revision to backout"))
203 203
204 204 date = opts.get('date')
205 205 if date:
206 206 opts['date'] = util.parsedate(date)
207 207
208 208 cmdutil.bail_if_changed(repo)
209 209 node = repo.lookup(rev)
210 210
211 211 op1, op2 = repo.dirstate.parents()
212 212 a = repo.changelog.ancestor(op1, node)
213 213 if a != node:
214 214 raise util.Abort(_('cannot back out change on a different branch'))
215 215
216 216 p1, p2 = repo.changelog.parents(node)
217 217 if p1 == nullid:
218 218 raise util.Abort(_('cannot back out a change with no parents'))
219 219 if p2 != nullid:
220 220 if not opts.get('parent'):
221 221 raise util.Abort(_('cannot back out a merge changeset without '
222 222 '--parent'))
223 223 p = repo.lookup(opts['parent'])
224 224 if p not in (p1, p2):
225 225 raise util.Abort(_('%s is not a parent of %s') %
226 226 (short(p), short(node)))
227 227 parent = p
228 228 else:
229 229 if opts.get('parent'):
230 230 raise util.Abort(_('cannot use --parent on non-merge changeset'))
231 231 parent = p1
232 232
233 233 # the backout should appear on the same branch
234 234 branch = repo.dirstate.branch()
235 235 hg.clean(repo, node, show_stats=False)
236 236 repo.dirstate.setbranch(branch)
237 237 revert_opts = opts.copy()
238 238 revert_opts['date'] = None
239 239 revert_opts['all'] = True
240 240 revert_opts['rev'] = hex(parent)
241 241 revert_opts['no_backup'] = None
242 242 revert(ui, repo, **revert_opts)
243 243 commit_opts = opts.copy()
244 244 commit_opts['addremove'] = False
245 245 if not commit_opts['message'] and not commit_opts['logfile']:
246 246 commit_opts['message'] = _("Backed out changeset %s") % (short(node))
247 247 commit_opts['force_editor'] = True
248 248 commit(ui, repo, **commit_opts)
249 249 def nice(node):
250 250 return '%d:%s' % (repo.changelog.rev(node), short(node))
251 251 ui.status(_('changeset %s backs out changeset %s\n') %
252 252 (nice(repo.changelog.tip()), nice(node)))
253 253 if op1 != node:
254 254 hg.clean(repo, op1, show_stats=False)
255 255 if opts.get('merge'):
256 256 ui.status(_('merging with changeset %s\n') % nice(repo.changelog.tip()))
257 257 hg.merge(repo, hex(repo.changelog.tip()))
258 258 else:
259 259 ui.status(_('the backout changeset is a new head - '
260 260 'do not forget to merge\n'))
261 261 ui.status(_('(use "backout --merge" '
262 262 'if you want to auto-merge)\n'))
263 263
264 264 def bisect(ui, repo, rev=None, extra=None, command=None,
265 265 reset=None, good=None, bad=None, skip=None, noupdate=None):
266 266 """subdivision search of changesets
267 267
268 268 This command helps to find changesets which introduce problems. To
269 269 use, mark the earliest changeset you know exhibits the problem as
270 270 bad, then mark the latest changeset which is free from the problem
271 271 as good. Bisect will update your working directory to a revision
272 272 for testing (unless the --noupdate option is specified). Once you
273 273 have performed tests, mark the working directory as bad or good
274 274 and bisect will either update to another candidate changeset or
275 275 announce that it has found the bad revision.
276 276
277 277 As a shortcut, you can also use the revision argument to mark a
278 278 revision as good or bad without checking it out first.
279 279
280 280 If you supply a command it will be used for automatic bisection.
281 281 Its exit status will be used as flag to mark revision as bad or
282 282 good. In case exit status is 0 the revision is marked as good, 125
283 283 - skipped, 127 (command not found) - bisection will be aborted;
284 284 any other status bigger than 0 will mark revision as bad.
285 285 """
286 286 def print_result(nodes, good):
287 287 displayer = cmdutil.show_changeset(ui, repo, {})
288 288 transition = (good and "good" or "bad")
289 289 if len(nodes) == 1:
290 290 # narrowed it down to a single revision
291 291 ui.write(_("The first %s revision is:\n") % transition)
292 292 displayer.show(repo[nodes[0]])
293 293 else:
294 294 # multiple possible revisions
295 295 ui.write(_("Due to skipped revisions, the first "
296 296 "%s revision could be any of:\n") % transition)
297 297 for n in nodes:
298 298 displayer.show(repo[n])
299 299
300 300 def check_state(state, interactive=True):
301 301 if not state['good'] or not state['bad']:
302 302 if (good or bad or skip or reset) and interactive:
303 303 return
304 304 if not state['good']:
305 305 raise util.Abort(_('cannot bisect (no known good revisions)'))
306 306 else:
307 307 raise util.Abort(_('cannot bisect (no known bad revisions)'))
308 308 return True
309 309
310 310 # backward compatibility
311 311 if rev in "good bad reset init".split():
312 312 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
313 313 cmd, rev, extra = rev, extra, None
314 314 if cmd == "good":
315 315 good = True
316 316 elif cmd == "bad":
317 317 bad = True
318 318 else:
319 319 reset = True
320 320 elif extra or good + bad + skip + reset + bool(command) > 1:
321 321 raise util.Abort(_('incompatible arguments'))
322 322
323 323 if reset:
324 324 p = repo.join("bisect.state")
325 325 if os.path.exists(p):
326 326 os.unlink(p)
327 327 return
328 328
329 329 state = hbisect.load_state(repo)
330 330
331 331 if command:
332 332 commandpath = util.find_exe(command)
333 333 changesets = 1
334 334 try:
335 335 while changesets:
336 336 # update state
337 337 status = os.spawnl(os.P_WAIT, commandpath, commandpath)
338 338 if status == 125:
339 339 transition = "skip"
340 340 elif status == 0:
341 341 transition = "good"
342 342 # status < 0 means process was killed
343 343 elif status == 127:
344 344 raise util.Abort(_("failed to execute %s") % command)
345 345 elif status < 0:
346 346 raise util.Abort(_("%s killed") % command)
347 347 else:
348 348 transition = "bad"
349 349 node = repo.lookup(rev or '.')
350 350 state[transition].append(node)
351 351 ui.note(_('Changeset %s: %s\n') % (short(node), transition))
352 352 check_state(state, interactive=False)
353 353 # bisect
354 354 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
355 355 # update to next check
356 356 cmdutil.bail_if_changed(repo)
357 357 hg.clean(repo, nodes[0], show_stats=False)
358 358 finally:
359 359 hbisect.save_state(repo, state)
360 360 return print_result(nodes, not status)
361 361
362 362 # update state
363 363 node = repo.lookup(rev or '.')
364 364 if good:
365 365 state['good'].append(node)
366 366 elif bad:
367 367 state['bad'].append(node)
368 368 elif skip:
369 369 state['skip'].append(node)
370 370
371 371 hbisect.save_state(repo, state)
372 372
373 373 if not check_state(state):
374 374 return
375 375
376 376 # actually bisect
377 377 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
378 378 if changesets == 0:
379 379 print_result(nodes, good)
380 380 else:
381 381 assert len(nodes) == 1 # only a single node can be tested next
382 382 node = nodes[0]
383 383 # compute the approximate number of remaining tests
384 384 tests, size = 0, 2
385 385 while size <= changesets:
386 386 tests, size = tests + 1, size * 2
387 387 rev = repo.changelog.rev(node)
388 388 ui.write(_("Testing changeset %s:%s "
389 389 "(%s changesets remaining, ~%s tests)\n")
390 390 % (rev, short(node), changesets, tests))
391 391 if not noupdate:
392 392 cmdutil.bail_if_changed(repo)
393 393 return hg.clean(repo, node)
394 394
395 395 def branch(ui, repo, label=None, **opts):
396 396 """set or show the current branch name
397 397
398 398 With no argument, show the current branch name. With one argument,
399 399 set the working directory branch name (the branch does not exist
400 400 in the repository until the next commit). It is recommended to use
401 401 the 'default' branch as your primary development branch.
402 402
403 403 Unless --force is specified, branch will not let you set a branch
404 404 name that shadows an existing branch.
405 405
406 406 Use --clean to reset the working directory branch to that of the
407 407 parent of the working directory, negating a previous branch
408 408 change.
409 409
410 410 Use the command 'hg update' to switch to an existing branch.
411 411 """
412 412
413 413 if opts.get('clean'):
414 414 label = repo[None].parents()[0].branch()
415 415 repo.dirstate.setbranch(label)
416 416 ui.status(_('reset working directory to branch %s\n') % label)
417 417 elif label:
418 418 if not opts.get('force') and label in repo.branchtags():
419 419 if label not in [p.branch() for p in repo.parents()]:
420 420 raise util.Abort(_('a branch of the same name already exists'
421 421 ' (use --force to override)'))
422 422 repo.dirstate.setbranch(encoding.fromlocal(label))
423 423 ui.status(_('marked working directory as branch %s\n') % label)
424 424 else:
425 425 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
426 426
427 427 def branches(ui, repo, active=False):
428 428 """list repository named branches
429 429
430 430 List the repository's named branches, indicating which ones are
431 431 inactive. If active is specified, only show active branches.
432 432
433 433 A branch is considered active if it contains repository heads.
434 434
435 435 Use the command 'hg update' to switch to an existing branch.
436 436 """
437 437 hexfunc = ui.debugflag and hex or short
438 438 activebranches = [encoding.tolocal(repo[n].branch())
439 439 for n in repo.heads(closed=False)]
440 440 branches = util.sort([(tag in activebranches, repo.changelog.rev(node), tag)
441 441 for tag, node in repo.branchtags().items()])
442 442 branches.reverse()
443 443
444 444 for isactive, node, tag in branches:
445 445 if (not active) or isactive:
446 446 if ui.quiet:
447 447 ui.write("%s\n" % tag)
448 448 else:
449 449 hn = repo.lookup(node)
450 450 if isactive:
451 451 notice = ''
452 452 elif hn not in repo.branchheads(tag, closed=False):
453 453 notice = ' (closed)'
454 454 else:
455 455 notice = ' (inactive)'
456 456 rev = str(node).rjust(31 - encoding.colwidth(tag))
457 457 data = tag, rev, hexfunc(hn), notice
458 458 ui.write("%s %s:%s%s\n" % data)
459 459
460 460 def bundle(ui, repo, fname, dest=None, **opts):
461 461 """create a changegroup file
462 462
463 463 Generate a compressed changegroup file collecting changesets not
464 464 known to be in another repository.
465 465
466 466 If no destination repository is specified the destination is
467 467 assumed to have all the nodes specified by one or more --base
468 468 parameters. To create a bundle containing all changesets, use
469 469 --all (or --base null). To change the compression method applied,
470 470 use the -t option (by default, bundles are compressed using bz2).
471 471
472 472 The bundle file can then be transferred using conventional means
473 473 and applied to another repository with the unbundle or pull
474 474 command. This is useful when direct push and pull are not
475 475 available or when exporting an entire repository is undesirable.
476 476
477 477 Applying bundles preserves all changeset contents including
478 478 permissions, copy/rename information, and revision history.
479 479 """
480 480 revs = opts.get('rev') or None
481 481 if revs:
482 482 revs = [repo.lookup(rev) for rev in revs]
483 483 if opts.get('all'):
484 484 base = ['null']
485 485 else:
486 486 base = opts.get('base')
487 487 if base:
488 488 if dest:
489 489 raise util.Abort(_("--base is incompatible with specifiying "
490 490 "a destination"))
491 491 base = [repo.lookup(rev) for rev in base]
492 492 # create the right base
493 493 # XXX: nodesbetween / changegroup* should be "fixed" instead
494 494 o = []
495 495 has = {nullid: None}
496 496 for n in base:
497 497 has.update(repo.changelog.reachable(n))
498 498 if revs:
499 499 visit = list(revs)
500 500 else:
501 501 visit = repo.changelog.heads()
502 502 seen = {}
503 503 while visit:
504 504 n = visit.pop(0)
505 505 parents = [p for p in repo.changelog.parents(n) if p not in has]
506 506 if len(parents) == 0:
507 507 o.insert(0, n)
508 508 else:
509 509 for p in parents:
510 510 if p not in seen:
511 511 seen[p] = 1
512 512 visit.append(p)
513 513 else:
514 514 cmdutil.setremoteconfig(ui, opts)
515 515 dest, revs, checkout = hg.parseurl(
516 516 ui.expandpath(dest or 'default-push', dest or 'default'), revs)
517 517 other = hg.repository(ui, dest)
518 518 o = repo.findoutgoing(other, force=opts.get('force'))
519 519
520 520 if revs:
521 521 cg = repo.changegroupsubset(o, revs, 'bundle')
522 522 else:
523 523 cg = repo.changegroup(o, 'bundle')
524 524
525 525 bundletype = opts.get('type', 'bzip2').lower()
526 526 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
527 527 bundletype = btypes.get(bundletype)
528 528 if bundletype not in changegroup.bundletypes:
529 529 raise util.Abort(_('unknown bundle type specified with --type'))
530 530
531 531 changegroup.writebundle(cg, fname, bundletype)
532 532
533 533 def cat(ui, repo, file1, *pats, **opts):
534 534 """output the current or given revision of files
535 535
536 536 Print the specified files as they were at the given revision. If
537 537 no revision is given, the parent of the working directory is used,
538 538 or tip if no revision is checked out.
539 539
540 540 Output may be to a file, in which case the name of the file is
541 541 given using a format string. The formatting rules are the same as
542 542 for the export command, with the following additions:
543 543
544 544 %s basename of file being printed
545 545 %d dirname of file being printed, or '.' if in repository root
546 546 %p root-relative path name of file being printed
547 547 """
548 548 ctx = repo[opts.get('rev')]
549 549 err = 1
550 550 m = cmdutil.match(repo, (file1,) + pats, opts)
551 551 for abs in ctx.walk(m):
552 552 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
553 553 data = ctx[abs].data()
554 554 if opts.get('decode'):
555 555 data = repo.wwritedata(abs, data)
556 556 fp.write(data)
557 557 err = 0
558 558 return err
559 559
560 560 def clone(ui, source, dest=None, **opts):
561 561 """make a copy of an existing repository
562 562
563 563 Create a copy of an existing repository in a new directory.
564 564
565 565 If no destination directory name is specified, it defaults to the
566 566 basename of the source.
567 567
568 568 The location of the source is added to the new repository's
569 569 .hg/hgrc file, as the default to be used for future pulls.
570 570
571 571 If you use the -r option to clone up to a specific revision, no
572 572 subsequent revisions (including subsequent tags) will be present
573 573 in the cloned repository. This option implies --pull, even on
574 574 local repositories.
575 575
576 576 By default, clone will check out the head of the 'default' branch.
577 577 If the -U option is used, the new clone will contain only a
578 578 repository (.hg) and no working copy (the working copy parent is
579 579 the null revision).
580 580
581 581 See 'hg help urls' for valid source format details.
582 582
583 583 It is possible to specify an ssh:// URL as the destination, but no
584 584 .hg/hgrc and working directory will be created on the remote side.
585 585 Look at the help text for URLs for important details about ssh://
586 586 URLs.
587 587
588 588 For efficiency, hardlinks are used for cloning whenever the source
589 589 and destination are on the same filesystem (note this applies only
590 590 to the repository data, not to the checked out files). Some
591 591 filesystems, such as AFS, implement hardlinking incorrectly, but
592 592 do not report errors. In these cases, use the --pull option to
593 593 avoid hardlinking.
594 594
595 595 In some cases, you can clone repositories and checked out files
596 596 using full hardlinks with
597 597
598 598 $ cp -al REPO REPOCLONE
599 599
600 600 This is the fastest way to clone, but it is not always safe. The
601 601 operation is not atomic (making sure REPO is not modified during
602 602 the operation is up to you) and you have to make sure your editor
603 603 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
604 604 this is not compatible with certain extensions that place their
605 605 metadata under the .hg directory, such as mq.
606 606
607 607 """
608 608 cmdutil.setremoteconfig(ui, opts)
609 609 hg.clone(ui, source, dest,
610 610 pull=opts.get('pull'),
611 611 stream=opts.get('uncompressed'),
612 612 rev=opts.get('rev'),
613 613 update=not opts.get('noupdate'))
614 614
615 615 def commit(ui, repo, *pats, **opts):
616 616 """commit the specified files or all outstanding changes
617 617
618 618 Commit changes to the given files into the repository. Unlike a
619 619 centralized RCS, this operation is a local operation. See hg push
620 620 for means to actively distribute your changes.
621 621
622 622 If a list of files is omitted, all changes reported by "hg status"
623 623 will be committed.
624 624
625 625 If you are committing the result of a merge, do not provide any
626 626 file names or -I/-X filters.
627 627
628 628 If no commit message is specified, the configured editor is
629 629 started to prompt you for a message.
630 630
631 631 See 'hg help dates' for a list of formats valid for -d/--date.
632 632 """
633 633 extra = {}
634 634 if opts.get('close_branch'):
635 635 extra['close'] = 1
636 636 def commitfunc(ui, repo, message, match, opts):
637 637 return repo.commit(match.files(), message, opts.get('user'),
638 638 opts.get('date'), match, force_editor=opts.get('force_editor'),
639 639 extra=extra)
640 640
641 641 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
642 642 if not node:
643 643 return
644 644 cl = repo.changelog
645 645 rev = cl.rev(node)
646 646 parents = cl.parentrevs(rev)
647 647 if rev - 1 in parents:
648 648 # one of the parents was the old tip
649 649 pass
650 650 elif (parents == (nullrev, nullrev) or
651 651 len(cl.heads(cl.node(parents[0]))) > 1 and
652 652 (parents[1] == nullrev or len(cl.heads(cl.node(parents[1]))) > 1)):
653 653 ui.status(_('created new head\n'))
654 654
655 655 if ui.debugflag:
656 656 ui.write(_('committed changeset %d:%s\n') % (rev,hex(node)))
657 657 elif ui.verbose:
658 658 ui.write(_('committed changeset %d:%s\n') % (rev,short(node)))
659 659
660 660 def copy(ui, repo, *pats, **opts):
661 661 """mark files as copied for the next commit
662 662
663 663 Mark dest as having copies of source files. If dest is a
664 664 directory, copies are put in that directory. If dest is a file,
665 665 the source must be a single file.
666 666
667 667 By default, this command copies the contents of files as they
668 668 stand in the working directory. If invoked with --after, the
669 669 operation is recorded, but no copying is performed.
670 670
671 671 This command takes effect with the next commit. To undo a copy
672 672 before that, see hg revert.
673 673 """
674 674 wlock = repo.wlock(False)
675 675 try:
676 676 return cmdutil.copy(ui, repo, pats, opts)
677 677 finally:
678 678 del wlock
679 679
680 680 def debugancestor(ui, repo, *args):
681 681 """find the ancestor revision of two revisions in a given index"""
682 682 if len(args) == 3:
683 683 index, rev1, rev2 = args
684 684 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
685 685 lookup = r.lookup
686 686 elif len(args) == 2:
687 687 if not repo:
688 688 raise util.Abort(_("There is no Mercurial repository here "
689 689 "(.hg not found)"))
690 690 rev1, rev2 = args
691 691 r = repo.changelog
692 692 lookup = repo.lookup
693 693 else:
694 694 raise util.Abort(_('either two or three arguments required'))
695 695 a = r.ancestor(lookup(rev1), lookup(rev2))
696 696 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
697 697
698 698 def debugcommands(ui, cmd='', *args):
699 699 for cmd, vals in util.sort(table.iteritems()):
700 700 cmd = cmd.split('|')[0].strip('^')
701 701 opts = ', '.join([i[1] for i in vals[1]])
702 702 ui.write('%s: %s\n' % (cmd, opts))
703 703
704 704 def debugcomplete(ui, cmd='', **opts):
705 705 """returns the completion list associated with the given command"""
706 706
707 707 if opts.get('options'):
708 708 options = []
709 709 otables = [globalopts]
710 710 if cmd:
711 711 aliases, entry = cmdutil.findcmd(cmd, table, False)
712 712 otables.append(entry[1])
713 713 for t in otables:
714 714 for o in t:
715 715 if o[0]:
716 716 options.append('-%s' % o[0])
717 717 options.append('--%s' % o[1])
718 718 ui.write("%s\n" % "\n".join(options))
719 719 return
720 720
721 721 cmdlist = cmdutil.findpossible(cmd, table)
722 722 if ui.verbose:
723 723 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
724 724 ui.write("%s\n" % "\n".join(util.sort(cmdlist)))
725 725
726 726 def debugfsinfo(ui, path = "."):
727 727 file('.debugfsinfo', 'w').write('')
728 728 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
729 729 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
730 730 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
731 731 and 'yes' or 'no'))
732 732 os.unlink('.debugfsinfo')
733 733
734 734 def debugrebuildstate(ui, repo, rev="tip"):
735 735 """rebuild the dirstate as it would look like for the given revision"""
736 736 ctx = repo[rev]
737 737 wlock = repo.wlock()
738 738 try:
739 739 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
740 740 finally:
741 741 del wlock
742 742
743 743 def debugcheckstate(ui, repo):
744 744 """validate the correctness of the current dirstate"""
745 745 parent1, parent2 = repo.dirstate.parents()
746 746 m1 = repo[parent1].manifest()
747 747 m2 = repo[parent2].manifest()
748 748 errors = 0
749 749 for f in repo.dirstate:
750 750 state = repo.dirstate[f]
751 751 if state in "nr" and f not in m1:
752 752 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
753 753 errors += 1
754 754 if state in "a" and f in m1:
755 755 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
756 756 errors += 1
757 757 if state in "m" and f not in m1 and f not in m2:
758 758 ui.warn(_("%s in state %s, but not in either manifest\n") %
759 759 (f, state))
760 760 errors += 1
761 761 for f in m1:
762 762 state = repo.dirstate[f]
763 763 if state not in "nrm":
764 764 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
765 765 errors += 1
766 766 if errors:
767 767 error = _(".hg/dirstate inconsistent with current parent's manifest")
768 768 raise util.Abort(error)
769 769
770 770 def showconfig(ui, repo, *values, **opts):
771 771 """show combined config settings from all hgrc files
772 772
773 773 With no args, print names and values of all config items.
774 774
775 775 With one arg of the form section.name, print just the value of
776 776 that config item.
777 777
778 778 With multiple args, print names and values of all config items
779 779 with matching section names."""
780 780
781 781 untrusted = bool(opts.get('untrusted'))
782 782 if values:
783 783 if len([v for v in values if '.' in v]) > 1:
784 784 raise util.Abort(_('only one config item permitted'))
785 785 for section, name, value in ui.walkconfig(untrusted=untrusted):
786 786 sectname = section + '.' + name
787 787 if values:
788 788 for v in values:
789 789 if v == section:
790 790 ui.write('%s=%s\n' % (sectname, value))
791 791 elif v == sectname:
792 792 ui.write(value, '\n')
793 793 else:
794 794 ui.write('%s=%s\n' % (sectname, value))
795 795
796 796 def debugsetparents(ui, repo, rev1, rev2=None):
797 797 """manually set the parents of the current working directory
798 798
799 799 This is useful for writing repository conversion tools, but should
800 800 be used with care.
801 801 """
802 802
803 803 if not rev2:
804 804 rev2 = hex(nullid)
805 805
806 806 wlock = repo.wlock()
807 807 try:
808 808 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
809 809 finally:
810 810 del wlock
811 811
812 812 def debugstate(ui, repo, nodates=None):
813 813 """show the contents of the current dirstate"""
814 814 timestr = ""
815 815 showdate = not nodates
816 816 for file_, ent in util.sort(repo.dirstate._map.iteritems()):
817 817 if showdate:
818 818 if ent[3] == -1:
819 819 # Pad or slice to locale representation
820 820 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(0)))
821 821 timestr = 'unset'
822 822 timestr = timestr[:locale_len] + ' '*(locale_len - len(timestr))
823 823 else:
824 824 timestr = time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(ent[3]))
825 825 if ent[1] & 020000:
826 826 mode = 'lnk'
827 827 else:
828 828 mode = '%3o' % (ent[1] & 0777)
829 829 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
830 830 for f in repo.dirstate.copies():
831 831 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
832 832
833 833 def debugdata(ui, file_, rev):
834 834 """dump the contents of a data file revision"""
835 835 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
836 836 try:
837 837 ui.write(r.revision(r.lookup(rev)))
838 838 except KeyError:
839 839 raise util.Abort(_('invalid revision identifier %s') % rev)
840 840
841 841 def debugdate(ui, date, range=None, **opts):
842 842 """parse and display a date"""
843 843 if opts["extended"]:
844 844 d = util.parsedate(date, util.extendeddateformats)
845 845 else:
846 846 d = util.parsedate(date)
847 847 ui.write("internal: %s %s\n" % d)
848 848 ui.write("standard: %s\n" % util.datestr(d))
849 849 if range:
850 850 m = util.matchdate(range)
851 851 ui.write("match: %s\n" % m(d[0]))
852 852
853 853 def debugindex(ui, file_):
854 854 """dump the contents of an index file"""
855 855 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
856 856 ui.write(" rev offset length base linkrev"
857 857 " nodeid p1 p2\n")
858 858 for i in r:
859 859 node = r.node(i)
860 860 try:
861 861 pp = r.parents(node)
862 862 except:
863 863 pp = [nullid, nullid]
864 864 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
865 865 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
866 866 short(node), short(pp[0]), short(pp[1])))
867 867
868 868 def debugindexdot(ui, file_):
869 869 """dump an index DAG as a .dot file"""
870 870 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
871 871 ui.write("digraph G {\n")
872 872 for i in r:
873 873 node = r.node(i)
874 874 pp = r.parents(node)
875 875 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
876 876 if pp[1] != nullid:
877 877 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
878 878 ui.write("}\n")
879 879
880 880 def debuginstall(ui):
881 881 '''test Mercurial installation'''
882 882
883 883 def writetemp(contents):
884 884 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
885 885 f = os.fdopen(fd, "wb")
886 886 f.write(contents)
887 887 f.close()
888 888 return name
889 889
890 890 problems = 0
891 891
892 892 # encoding
893 893 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
894 894 try:
895 895 encoding.fromlocal("test")
896 896 except util.Abort, inst:
897 897 ui.write(" %s\n" % inst)
898 898 ui.write(_(" (check that your locale is properly set)\n"))
899 899 problems += 1
900 900
901 901 # compiled modules
902 902 ui.status(_("Checking extensions...\n"))
903 903 try:
904 904 import bdiff, mpatch, base85
905 905 except Exception, inst:
906 906 ui.write(" %s\n" % inst)
907 907 ui.write(_(" One or more extensions could not be found"))
908 908 ui.write(_(" (check that you compiled the extensions)\n"))
909 909 problems += 1
910 910
911 911 # templates
912 912 ui.status(_("Checking templates...\n"))
913 913 try:
914 914 import templater
915 915 templater.templater(templater.templatepath("map-cmdline.default"))
916 916 except Exception, inst:
917 917 ui.write(" %s\n" % inst)
918 918 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
919 919 problems += 1
920 920
921 921 # patch
922 922 ui.status(_("Checking patch...\n"))
923 923 patchproblems = 0
924 924 a = "1\n2\n3\n4\n"
925 925 b = "1\n2\n3\ninsert\n4\n"
926 926 fa = writetemp(a)
927 927 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
928 928 os.path.basename(fa))
929 929 fd = writetemp(d)
930 930
931 931 files = {}
932 932 try:
933 933 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
934 934 except util.Abort, e:
935 935 ui.write(_(" patch call failed:\n"))
936 936 ui.write(" " + str(e) + "\n")
937 937 patchproblems += 1
938 938 else:
939 939 if list(files) != [os.path.basename(fa)]:
940 940 ui.write(_(" unexpected patch output!\n"))
941 941 patchproblems += 1
942 942 a = file(fa).read()
943 943 if a != b:
944 944 ui.write(_(" patch test failed!\n"))
945 945 patchproblems += 1
946 946
947 947 if patchproblems:
948 948 if ui.config('ui', 'patch'):
949 949 ui.write(_(" (Current patch tool may be incompatible with patch,"
950 950 " or misconfigured. Please check your .hgrc file)\n"))
951 951 else:
952 952 ui.write(_(" Internal patcher failure, please report this error"
953 953 " to http://www.selenic.com/mercurial/bts\n"))
954 954 problems += patchproblems
955 955
956 956 os.unlink(fa)
957 957 os.unlink(fd)
958 958
959 959 # editor
960 960 ui.status(_("Checking commit editor...\n"))
961 961 editor = ui.geteditor()
962 962 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
963 963 if not cmdpath:
964 964 if editor == 'vi':
965 965 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
966 966 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
967 967 else:
968 968 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
969 969 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
970 970 problems += 1
971 971
972 972 # check username
973 973 ui.status(_("Checking username...\n"))
974 974 user = os.environ.get("HGUSER")
975 975 if user is None:
976 976 user = ui.config("ui", "username")
977 977 if user is None:
978 978 user = os.environ.get("EMAIL")
979 979 if not user:
980 980 ui.warn(" ")
981 981 ui.username()
982 982 ui.write(_(" (specify a username in your .hgrc file)\n"))
983 983
984 984 if not problems:
985 985 ui.status(_("No problems detected\n"))
986 986 else:
987 987 ui.write(_("%s problems detected,"
988 988 " please check your install!\n") % problems)
989 989
990 990 return problems
991 991
992 992 def debugrename(ui, repo, file1, *pats, **opts):
993 993 """dump rename information"""
994 994
995 995 ctx = repo[opts.get('rev')]
996 996 m = cmdutil.match(repo, (file1,) + pats, opts)
997 997 for abs in ctx.walk(m):
998 998 fctx = ctx[abs]
999 999 o = fctx.filelog().renamed(fctx.filenode())
1000 1000 rel = m.rel(abs)
1001 1001 if o:
1002 1002 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1003 1003 else:
1004 1004 ui.write(_("%s not renamed\n") % rel)
1005 1005
1006 1006 def debugwalk(ui, repo, *pats, **opts):
1007 1007 """show how files match on given patterns"""
1008 1008 m = cmdutil.match(repo, pats, opts)
1009 1009 items = list(repo.walk(m))
1010 1010 if not items:
1011 1011 return
1012 1012 fmt = 'f %%-%ds %%-%ds %%s' % (
1013 1013 max([len(abs) for abs in items]),
1014 1014 max([len(m.rel(abs)) for abs in items]))
1015 1015 for abs in items:
1016 1016 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1017 1017 ui.write("%s\n" % line.rstrip())
1018 1018
1019 1019 def diff(ui, repo, *pats, **opts):
1020 1020 """diff repository (or selected files)
1021 1021
1022 1022 Show differences between revisions for the specified files.
1023 1023
1024 1024 Differences between files are shown using the unified diff format.
1025 1025
1026 1026 NOTE: diff may generate unexpected results for merges, as it will
1027 1027 default to comparing against the working directory's first parent
1028 1028 changeset if no revisions are specified.
1029 1029
1030 1030 When two revision arguments are given, then changes are shown
1031 1031 between those revisions. If only one revision is specified then
1032 1032 that revision is compared to the working directory, and, when no
1033 1033 revisions are specified, the working directory files are compared
1034 1034 to its parent.
1035 1035
1036 1036 Without the -a option, diff will avoid generating diffs of files
1037 1037 it detects as binary. With -a, diff will generate a diff anyway,
1038 1038 probably with undesirable results.
1039 1039
1040 1040 Use the --git option to generate diffs in the git extended diff
1041 1041 format. For more information, read 'hg help diffs'.
1042 1042 """
1043 1043
1044 1044 revs = opts.get('rev')
1045 1045 change = opts.get('change')
1046 1046
1047 1047 if revs and change:
1048 1048 msg = _('cannot specify --rev and --change at the same time')
1049 1049 raise util.Abort(msg)
1050 1050 elif change:
1051 1051 node2 = repo.lookup(change)
1052 1052 node1 = repo[node2].parents()[0].node()
1053 1053 else:
1054 1054 node1, node2 = cmdutil.revpair(repo, revs)
1055 1055
1056 1056 m = cmdutil.match(repo, pats, opts)
1057 1057 it = patch.diff(repo, node1, node2, match=m, opts=patch.diffopts(ui, opts))
1058 1058 for chunk in it:
1059 1059 repo.ui.write(chunk)
1060 1060
1061 1061 def export(ui, repo, *changesets, **opts):
1062 1062 """dump the header and diffs for one or more changesets
1063 1063
1064 1064 Print the changeset header and diffs for one or more revisions.
1065 1065
1066 1066 The information shown in the changeset header is: author,
1067 1067 changeset hash, parent(s) and commit comment.
1068 1068
1069 1069 NOTE: export may generate unexpected diff output for merge
1070 1070 changesets, as it will compare the merge changeset against its
1071 1071 first parent only.
1072 1072
1073 1073 Output may be to a file, in which case the name of the file is
1074 1074 given using a format string. The formatting rules are as follows:
1075 1075
1076 1076 %% literal "%" character
1077 1077 %H changeset hash (40 bytes of hexadecimal)
1078 1078 %N number of patches being generated
1079 1079 %R changeset revision number
1080 1080 %b basename of the exporting repository
1081 1081 %h short-form changeset hash (12 bytes of hexadecimal)
1082 1082 %n zero-padded sequence number, starting at 1
1083 1083 %r zero-padded changeset revision number
1084 1084
1085 1085 Without the -a option, export will avoid generating diffs of files
1086 1086 it detects as binary. With -a, export will generate a diff anyway,
1087 1087 probably with undesirable results.
1088 1088
1089 1089 Use the --git option to generate diffs in the git extended diff
1090 1090 format. Read the diffs help topic for more information.
1091 1091
1092 1092 With the --switch-parent option, the diff will be against the
1093 1093 second parent. It can be useful to review a merge.
1094 1094 """
1095 1095 if not changesets:
1096 1096 raise util.Abort(_("export requires at least one changeset"))
1097 1097 revs = cmdutil.revrange(repo, changesets)
1098 1098 if len(revs) > 1:
1099 1099 ui.note(_('exporting patches:\n'))
1100 1100 else:
1101 1101 ui.note(_('exporting patch:\n'))
1102 1102 patch.export(repo, revs, template=opts.get('output'),
1103 1103 switch_parent=opts.get('switch_parent'),
1104 1104 opts=patch.diffopts(ui, opts))
1105 1105
1106 1106 def grep(ui, repo, pattern, *pats, **opts):
1107 1107 """search for a pattern in specified files and revisions
1108 1108
1109 1109 Search revisions of files for a regular expression.
1110 1110
1111 1111 This command behaves differently than Unix grep. It only accepts
1112 1112 Python/Perl regexps. It searches repository history, not the
1113 1113 working directory. It always prints the revision number in which a
1114 1114 match appears.
1115 1115
1116 1116 By default, grep only prints output for the first revision of a
1117 1117 file in which it finds a match. To get it to print every revision
1118 1118 that contains a change in match status ("-" for a match that
1119 1119 becomes a non-match, or "+" for a non-match that becomes a match),
1120 1120 use the --all flag.
1121 1121 """
1122 1122 reflags = 0
1123 1123 if opts.get('ignore_case'):
1124 1124 reflags |= re.I
1125 1125 try:
1126 1126 regexp = re.compile(pattern, reflags)
1127 1127 except Exception, inst:
1128 1128 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1129 1129 return None
1130 1130 sep, eol = ':', '\n'
1131 1131 if opts.get('print0'):
1132 1132 sep = eol = '\0'
1133 1133
1134 1134 fcache = {}
1135 1135 def getfile(fn):
1136 1136 if fn not in fcache:
1137 1137 fcache[fn] = repo.file(fn)
1138 1138 return fcache[fn]
1139 1139
1140 1140 def matchlines(body):
1141 1141 begin = 0
1142 1142 linenum = 0
1143 1143 while True:
1144 1144 match = regexp.search(body, begin)
1145 1145 if not match:
1146 1146 break
1147 1147 mstart, mend = match.span()
1148 1148 linenum += body.count('\n', begin, mstart) + 1
1149 1149 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1150 1150 begin = body.find('\n', mend) + 1 or len(body)
1151 1151 lend = begin - 1
1152 1152 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1153 1153
1154 1154 class linestate(object):
1155 1155 def __init__(self, line, linenum, colstart, colend):
1156 1156 self.line = line
1157 1157 self.linenum = linenum
1158 1158 self.colstart = colstart
1159 1159 self.colend = colend
1160 1160
1161 1161 def __hash__(self):
1162 1162 return hash((self.linenum, self.line))
1163 1163
1164 1164 def __eq__(self, other):
1165 1165 return self.line == other.line
1166 1166
1167 1167 matches = {}
1168 1168 copies = {}
1169 1169 def grepbody(fn, rev, body):
1170 1170 matches[rev].setdefault(fn, [])
1171 1171 m = matches[rev][fn]
1172 1172 for lnum, cstart, cend, line in matchlines(body):
1173 1173 s = linestate(line, lnum, cstart, cend)
1174 1174 m.append(s)
1175 1175
1176 1176 def difflinestates(a, b):
1177 1177 sm = difflib.SequenceMatcher(None, a, b)
1178 1178 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1179 1179 if tag == 'insert':
1180 1180 for i in xrange(blo, bhi):
1181 1181 yield ('+', b[i])
1182 1182 elif tag == 'delete':
1183 1183 for i in xrange(alo, ahi):
1184 1184 yield ('-', a[i])
1185 1185 elif tag == 'replace':
1186 1186 for i in xrange(alo, ahi):
1187 1187 yield ('-', a[i])
1188 1188 for i in xrange(blo, bhi):
1189 1189 yield ('+', b[i])
1190 1190
1191 1191 prev = {}
1192 1192 def display(fn, rev, states, prevstates):
1193 1193 datefunc = ui.quiet and util.shortdate or util.datestr
1194 1194 found = False
1195 1195 filerevmatches = {}
1196 1196 r = prev.get(fn, -1)
1197 1197 if opts.get('all'):
1198 1198 iter = difflinestates(states, prevstates)
1199 1199 else:
1200 1200 iter = [('', l) for l in prevstates]
1201 1201 for change, l in iter:
1202 1202 cols = [fn, str(r)]
1203 1203 if opts.get('line_number'):
1204 1204 cols.append(str(l.linenum))
1205 1205 if opts.get('all'):
1206 1206 cols.append(change)
1207 1207 if opts.get('user'):
1208 1208 cols.append(ui.shortuser(get(r)[1]))
1209 1209 if opts.get('date'):
1210 1210 cols.append(datefunc(get(r)[2]))
1211 1211 if opts.get('files_with_matches'):
1212 1212 c = (fn, r)
1213 1213 if c in filerevmatches:
1214 1214 continue
1215 1215 filerevmatches[c] = 1
1216 1216 else:
1217 1217 cols.append(l.line)
1218 1218 ui.write(sep.join(cols), eol)
1219 1219 found = True
1220 1220 return found
1221 1221
1222 1222 fstate = {}
1223 1223 skip = {}
1224 1224 get = util.cachefunc(lambda r: repo[r].changeset())
1225 1225 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1226 1226 found = False
1227 1227 follow = opts.get('follow')
1228 1228 for st, rev, fns in changeiter:
1229 1229 if st == 'window':
1230 1230 matches.clear()
1231 1231 elif st == 'add':
1232 1232 ctx = repo[rev]
1233 1233 matches[rev] = {}
1234 1234 for fn in fns:
1235 1235 if fn in skip:
1236 1236 continue
1237 1237 try:
1238 1238 grepbody(fn, rev, getfile(fn).read(ctx.filenode(fn)))
1239 1239 fstate.setdefault(fn, [])
1240 1240 if follow:
1241 1241 copied = getfile(fn).renamed(ctx.filenode(fn))
1242 1242 if copied:
1243 1243 copies.setdefault(rev, {})[fn] = copied[0]
1244 1244 except error.LookupError:
1245 1245 pass
1246 1246 elif st == 'iter':
1247 1247 for fn, m in util.sort(matches[rev].items()):
1248 1248 copy = copies.get(rev, {}).get(fn)
1249 1249 if fn in skip:
1250 1250 if copy:
1251 1251 skip[copy] = True
1252 1252 continue
1253 1253 if fn in prev or fstate[fn]:
1254 1254 r = display(fn, rev, m, fstate[fn])
1255 1255 found = found or r
1256 1256 if r and not opts.get('all'):
1257 1257 skip[fn] = True
1258 1258 if copy:
1259 1259 skip[copy] = True
1260 1260 fstate[fn] = m
1261 1261 if copy:
1262 1262 fstate[copy] = m
1263 1263 prev[fn] = rev
1264 1264
1265 1265 for fn, state in util.sort(fstate.items()):
1266 1266 if fn in skip:
1267 1267 continue
1268 1268 if fn not in copies.get(prev[fn], {}):
1269 1269 found = display(fn, rev, {}, state) or found
1270 1270 return (not found and 1) or 0
1271 1271
1272 1272 def heads(ui, repo, *branchrevs, **opts):
1273 1273 """show current repository heads or show branch heads
1274 1274
1275 1275 With no arguments, show all repository head changesets.
1276 1276
1277 1277 If branch or revisions names are given this will show the heads of
1278 1278 the specified branches or the branches those revisions are tagged
1279 1279 with.
1280 1280
1281 1281 Repository "heads" are changesets that don't have child
1282 1282 changesets. They are where development generally takes place and
1283 1283 are the usual targets for update and merge operations.
1284 1284
1285 1285 Branch heads are changesets that have a given branch tag, but have
1286 1286 no child changesets with that tag. They are usually where
1287 1287 development on the given branch takes place.
1288 1288 """
1289 1289 if opts.get('rev'):
1290 1290 start = repo.lookup(opts['rev'])
1291 1291 else:
1292 1292 start = None
1293 1293 closed = not opts.get('active')
1294 1294 if not branchrevs:
1295 1295 # Assume we're looking repo-wide heads if no revs were specified.
1296 1296 heads = repo.heads(start, closed=closed)
1297 1297 else:
1298 1298 heads = []
1299 1299 visitedset = util.set()
1300 1300 for branchrev in branchrevs:
1301 1301 branch = repo[branchrev].branch()
1302 1302 if branch in visitedset:
1303 1303 continue
1304 1304 visitedset.add(branch)
1305 1305 bheads = repo.branchheads(branch, start, closed=closed)
1306 1306 if not bheads:
1307 1307 if branch != branchrev:
1308 1308 ui.warn(_("no changes on branch %s containing %s are "
1309 1309 "reachable from %s\n")
1310 1310 % (branch, branchrev, opts.get('rev')))
1311 1311 else:
1312 1312 ui.warn(_("no changes on branch %s are reachable from %s\n")
1313 1313 % (branch, opts.get('rev')))
1314 1314 heads.extend(bheads)
1315 1315 if not heads:
1316 1316 return 1
1317 1317 displayer = cmdutil.show_changeset(ui, repo, opts)
1318 1318 for n in heads:
1319 1319 displayer.show(repo[n])
1320 1320
1321 1321 def help_(ui, name=None, with_version=False):
1322 1322 """show help for a given topic or a help overview
1323 1323
1324 1324 With no arguments, print a list of commands and short help.
1325 1325
1326 1326 Given a topic, extension, or command name, print help for that
1327 1327 topic."""
1328 1328 option_lists = []
1329 1329
1330 1330 def addglobalopts(aliases):
1331 1331 if ui.verbose:
1332 1332 option_lists.append((_("global options:"), globalopts))
1333 1333 if name == 'shortlist':
1334 1334 option_lists.append((_('use "hg help" for the full list '
1335 1335 'of commands'), ()))
1336 1336 else:
1337 1337 if name == 'shortlist':
1338 1338 msg = _('use "hg help" for the full list of commands '
1339 1339 'or "hg -v" for details')
1340 1340 elif aliases:
1341 1341 msg = _('use "hg -v help%s" to show aliases and '
1342 1342 'global options') % (name and " " + name or "")
1343 1343 else:
1344 1344 msg = _('use "hg -v help %s" to show global options') % name
1345 1345 option_lists.append((msg, ()))
1346 1346
1347 1347 def helpcmd(name):
1348 1348 if with_version:
1349 1349 version_(ui)
1350 1350 ui.write('\n')
1351 1351
1352 1352 try:
1353 1353 aliases, i = cmdutil.findcmd(name, table, False)
1354 1354 except error.AmbiguousCommand, inst:
1355 1355 select = lambda c: c.lstrip('^').startswith(inst.args[0])
1356 1356 helplist(_('list of commands:\n\n'), select)
1357 1357 return
1358 1358
1359 1359 # synopsis
1360 1360 if len(i) > 2:
1361 1361 if i[2].startswith('hg'):
1362 1362 ui.write("%s\n" % i[2])
1363 1363 else:
1364 1364 ui.write('hg %s %s\n' % (aliases[0], i[2]))
1365 1365 else:
1366 1366 ui.write('hg %s\n' % aliases[0])
1367 1367
1368 1368 # aliases
1369 1369 if not ui.quiet and len(aliases) > 1:
1370 1370 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1371 1371
1372 1372 # description
1373 1373 doc = gettext(i[0].__doc__)
1374 1374 if not doc:
1375 1375 doc = _("(no help text available)")
1376 1376 if ui.quiet:
1377 1377 doc = doc.splitlines(0)[0]
1378 1378 ui.write("\n%s\n" % doc.rstrip())
1379 1379
1380 1380 if not ui.quiet:
1381 1381 # options
1382 1382 if i[1]:
1383 1383 option_lists.append((_("options:\n"), i[1]))
1384 1384
1385 1385 addglobalopts(False)
1386 1386
1387 1387 def helplist(header, select=None):
1388 1388 h = {}
1389 1389 cmds = {}
1390 1390 for c, e in table.iteritems():
1391 1391 f = c.split("|", 1)[0]
1392 1392 if select and not select(f):
1393 1393 continue
1394 1394 if (not select and name != 'shortlist' and
1395 1395 e[0].__module__ != __name__):
1396 1396 continue
1397 1397 if name == "shortlist" and not f.startswith("^"):
1398 1398 continue
1399 1399 f = f.lstrip("^")
1400 1400 if not ui.debugflag and f.startswith("debug"):
1401 1401 continue
1402 1402 doc = gettext(e[0].__doc__)
1403 1403 if not doc:
1404 1404 doc = _("(no help text available)")
1405 1405 h[f] = doc.splitlines(0)[0].rstrip()
1406 1406 cmds[f] = c.lstrip("^")
1407 1407
1408 1408 if not h:
1409 1409 ui.status(_('no commands defined\n'))
1410 1410 return
1411 1411
1412 1412 ui.status(header)
1413 1413 fns = util.sort(h)
1414 1414 m = max(map(len, fns))
1415 1415 for f in fns:
1416 1416 if ui.verbose:
1417 1417 commands = cmds[f].replace("|",", ")
1418 1418 ui.write(" %s:\n %s\n"%(commands, h[f]))
1419 1419 else:
1420 1420 ui.write(' %-*s %s\n' % (m, f, h[f]))
1421 1421
1422 1422 exts = list(extensions.extensions())
1423 1423 if exts and name != 'shortlist':
1424 1424 ui.write(_('\nenabled extensions:\n\n'))
1425 1425 maxlength = 0
1426 1426 exthelps = []
1427 1427 for ename, ext in exts:
1428 1428 doc = (gettext(ext.__doc__) or _('(no help text available)'))
1429 1429 ename = ename.split('.')[-1]
1430 1430 maxlength = max(len(ename), maxlength)
1431 1431 exthelps.append((ename, doc.splitlines(0)[0].strip()))
1432 1432 for ename, text in exthelps:
1433 1433 ui.write(_(' %s %s\n') % (ename.ljust(maxlength), text))
1434 1434
1435 1435 if not ui.quiet:
1436 1436 addglobalopts(True)
1437 1437
1438 1438 def helptopic(name):
1439 1439 for names, header, doc in help.helptable:
1440 1440 if name in names:
1441 1441 break
1442 1442 else:
1443 1443 raise error.UnknownCommand(name)
1444 1444
1445 1445 # description
1446 1446 if not doc:
1447 1447 doc = _("(no help text available)")
1448 1448 if callable(doc):
1449 1449 doc = doc()
1450 1450
1451 1451 ui.write("%s\n" % header)
1452 1452 ui.write("%s\n" % doc.rstrip())
1453 1453
1454 1454 def helpext(name):
1455 1455 try:
1456 1456 mod = extensions.find(name)
1457 1457 except KeyError:
1458 1458 raise error.UnknownCommand(name)
1459 1459
1460 1460 doc = gettext(mod.__doc__) or _('no help text available')
1461 1461 doc = doc.splitlines(0)
1462 1462 ui.write(_('%s extension - %s\n') % (name.split('.')[-1], doc[0]))
1463 1463 for d in doc[1:]:
1464 1464 ui.write(d, '\n')
1465 1465
1466 1466 ui.status('\n')
1467 1467
1468 1468 try:
1469 1469 ct = mod.cmdtable
1470 1470 except AttributeError:
1471 1471 ct = {}
1472 1472
1473 1473 modcmds = dict.fromkeys([c.split('|', 1)[0] for c in ct])
1474 1474 helplist(_('list of commands:\n\n'), modcmds.has_key)
1475 1475
1476 1476 if name and name != 'shortlist':
1477 1477 i = None
1478 1478 for f in (helptopic, helpcmd, helpext):
1479 1479 try:
1480 1480 f(name)
1481 1481 i = None
1482 1482 break
1483 1483 except error.UnknownCommand, inst:
1484 1484 i = inst
1485 1485 if i:
1486 1486 raise i
1487 1487
1488 1488 else:
1489 1489 # program name
1490 1490 if ui.verbose or with_version:
1491 1491 version_(ui)
1492 1492 else:
1493 1493 ui.status(_("Mercurial Distributed SCM\n"))
1494 1494 ui.status('\n')
1495 1495
1496 1496 # list of commands
1497 1497 if name == "shortlist":
1498 1498 header = _('basic commands:\n\n')
1499 1499 else:
1500 1500 header = _('list of commands:\n\n')
1501 1501
1502 1502 helplist(header)
1503 1503
1504 1504 # list all option lists
1505 1505 opt_output = []
1506 1506 for title, options in option_lists:
1507 1507 opt_output.append(("\n%s" % title, None))
1508 1508 for shortopt, longopt, default, desc in options:
1509 1509 if "DEPRECATED" in desc and not ui.verbose: continue
1510 1510 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1511 1511 longopt and " --%s" % longopt),
1512 1512 "%s%s" % (desc,
1513 1513 default
1514 1514 and _(" (default: %s)") % default
1515 1515 or "")))
1516 1516
1517 1517 if not name:
1518 1518 ui.write(_("\nadditional help topics:\n\n"))
1519 1519 topics = []
1520 1520 for names, header, doc in help.helptable:
1521 1521 names = [(-len(name), name) for name in names]
1522 1522 names.sort()
1523 1523 topics.append((names[0][1], header))
1524 1524 topics_len = max([len(s[0]) for s in topics])
1525 1525 for t, desc in topics:
1526 1526 ui.write(" %-*s %s\n" % (topics_len, t, desc))
1527 1527
1528 1528 if opt_output:
1529 1529 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1530 1530 for first, second in opt_output:
1531 1531 if second:
1532 1532 ui.write(" %-*s %s\n" % (opts_len, first, second))
1533 1533 else:
1534 1534 ui.write("%s\n" % first)
1535 1535
1536 1536 def identify(ui, repo, source=None,
1537 1537 rev=None, num=None, id=None, branch=None, tags=None):
1538 1538 """identify the working copy or specified revision
1539 1539
1540 1540 With no revision, print a summary of the current state of the
1541 1541 repository.
1542 1542
1543 1543 With a path, do a lookup in another repository.
1544 1544
1545 1545 This summary identifies the repository state using one or two
1546 1546 parent hash identifiers, followed by a "+" if there are
1547 1547 uncommitted changes in the working directory, a list of tags for
1548 1548 this revision and a branch name for non-default branches.
1549 1549 """
1550 1550
1551 1551 if not repo and not source:
1552 1552 raise util.Abort(_("There is no Mercurial repository here "
1553 1553 "(.hg not found)"))
1554 1554
1555 1555 hexfunc = ui.debugflag and hex or short
1556 1556 default = not (num or id or branch or tags)
1557 1557 output = []
1558 1558
1559 1559 revs = []
1560 1560 if source:
1561 1561 source, revs, checkout = hg.parseurl(ui.expandpath(source), [])
1562 1562 repo = hg.repository(ui, source)
1563 1563
1564 1564 if not repo.local():
1565 1565 if not rev and revs:
1566 1566 rev = revs[0]
1567 1567 if not rev:
1568 1568 rev = "tip"
1569 1569 if num or branch or tags:
1570 1570 raise util.Abort(
1571 1571 "can't query remote revision number, branch, or tags")
1572 1572 output = [hexfunc(repo.lookup(rev))]
1573 1573 elif not rev:
1574 1574 ctx = repo[None]
1575 1575 parents = ctx.parents()
1576 1576 changed = False
1577 1577 if default or id or num:
1578 1578 changed = ctx.files() + ctx.deleted()
1579 1579 if default or id:
1580 1580 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1581 1581 (changed) and "+" or "")]
1582 1582 if num:
1583 1583 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1584 1584 (changed) and "+" or ""))
1585 1585 else:
1586 1586 ctx = repo[rev]
1587 1587 if default or id:
1588 1588 output = [hexfunc(ctx.node())]
1589 1589 if num:
1590 1590 output.append(str(ctx.rev()))
1591 1591
1592 1592 if repo.local() and default and not ui.quiet:
1593 1593 b = encoding.tolocal(ctx.branch())
1594 1594 if b != 'default':
1595 1595 output.append("(%s)" % b)
1596 1596
1597 1597 # multiple tags for a single parent separated by '/'
1598 1598 t = "/".join(ctx.tags())
1599 1599 if t:
1600 1600 output.append(t)
1601 1601
1602 1602 if branch:
1603 1603 output.append(encoding.tolocal(ctx.branch()))
1604 1604
1605 1605 if tags:
1606 1606 output.extend(ctx.tags())
1607 1607
1608 1608 ui.write("%s\n" % ' '.join(output))
1609 1609
1610 1610 def import_(ui, repo, patch1, *patches, **opts):
1611 1611 """import an ordered set of patches
1612 1612
1613 1613 Import a list of patches and commit them individually.
1614 1614
1615 1615 If there are outstanding changes in the working directory, import
1616 1616 will abort unless given the -f flag.
1617 1617
1618 1618 You can import a patch straight from a mail message. Even patches
1619 1619 as attachments work (body part must be type text/plain or
1620 1620 text/x-patch to be used). From and Subject headers of email
1621 1621 message are used as default committer and commit message. All
1622 1622 text/plain body parts before first diff are added to commit
1623 1623 message.
1624 1624
1625 1625 If the imported patch was generated by hg export, user and
1626 1626 description from patch override values from message headers and
1627 1627 body. Values given on command line with -m and -u override these.
1628 1628
1629 1629 If --exact is specified, import will set the working directory to
1630 1630 the parent of each patch before applying it, and will abort if the
1631 1631 resulting changeset has a different ID than the one recorded in
1632 1632 the patch. This may happen due to character set problems or other
1633 1633 deficiencies in the text patch format.
1634 1634
1635 1635 With --similarity, hg will attempt to discover renames and copies
1636 1636 in the patch in the same way as 'addremove'.
1637 1637
1638 1638 To read a patch from standard input, use patch name "-". See 'hg
1639 1639 help dates' for a list of formats valid for -d/--date.
1640 1640 """
1641 1641 patches = (patch1,) + patches
1642 1642
1643 1643 date = opts.get('date')
1644 1644 if date:
1645 1645 opts['date'] = util.parsedate(date)
1646 1646
1647 1647 try:
1648 1648 sim = float(opts.get('similarity') or 0)
1649 1649 except ValueError:
1650 1650 raise util.Abort(_('similarity must be a number'))
1651 1651 if sim < 0 or sim > 100:
1652 1652 raise util.Abort(_('similarity must be between 0 and 100'))
1653 1653
1654 1654 if opts.get('exact') or not opts.get('force'):
1655 1655 cmdutil.bail_if_changed(repo)
1656 1656
1657 1657 d = opts["base"]
1658 1658 strip = opts["strip"]
1659 1659 wlock = lock = None
1660 1660 try:
1661 1661 wlock = repo.wlock()
1662 1662 lock = repo.lock()
1663 1663 for p in patches:
1664 1664 pf = os.path.join(d, p)
1665 1665
1666 1666 if pf == '-':
1667 1667 ui.status(_("applying patch from stdin\n"))
1668 1668 pf = sys.stdin
1669 1669 else:
1670 1670 ui.status(_("applying %s\n") % p)
1671 1671 pf = url.open(ui, pf)
1672 1672 data = patch.extract(ui, pf)
1673 1673 tmpname, message, user, date, branch, nodeid, p1, p2 = data
1674 1674
1675 1675 if tmpname is None:
1676 1676 raise util.Abort(_('no diffs found'))
1677 1677
1678 1678 try:
1679 1679 cmdline_message = cmdutil.logmessage(opts)
1680 1680 if cmdline_message:
1681 1681 # pickup the cmdline msg
1682 1682 message = cmdline_message
1683 1683 elif message:
1684 1684 # pickup the patch msg
1685 1685 message = message.strip()
1686 1686 else:
1687 1687 # launch the editor
1688 1688 message = None
1689 1689 ui.debug(_('message:\n%s\n') % message)
1690 1690
1691 1691 wp = repo.parents()
1692 1692 if opts.get('exact'):
1693 1693 if not nodeid or not p1:
1694 1694 raise util.Abort(_('not a mercurial patch'))
1695 1695 p1 = repo.lookup(p1)
1696 1696 p2 = repo.lookup(p2 or hex(nullid))
1697 1697
1698 1698 if p1 != wp[0].node():
1699 1699 hg.clean(repo, p1)
1700 1700 repo.dirstate.setparents(p1, p2)
1701 1701 elif p2:
1702 1702 try:
1703 1703 p1 = repo.lookup(p1)
1704 1704 p2 = repo.lookup(p2)
1705 1705 if p1 == wp[0].node():
1706 1706 repo.dirstate.setparents(p1, p2)
1707 1707 except error.RepoError:
1708 1708 pass
1709 1709 if opts.get('exact') or opts.get('import_branch'):
1710 1710 repo.dirstate.setbranch(branch or 'default')
1711 1711
1712 1712 files = {}
1713 1713 try:
1714 1714 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1715 1715 files=files)
1716 1716 finally:
1717 1717 files = patch.updatedir(ui, repo, files, similarity=sim/100.)
1718 1718 if not opts.get('no_commit'):
1719 1719 n = repo.commit(files, message, opts.get('user') or user,
1720 1720 opts.get('date') or date)
1721 1721 if opts.get('exact'):
1722 1722 if hex(n) != nodeid:
1723 1723 repo.rollback()
1724 1724 raise util.Abort(_('patch is damaged'
1725 1725 ' or loses information'))
1726 1726 # Force a dirstate write so that the next transaction
1727 1727 # backups an up-do-date file.
1728 1728 repo.dirstate.write()
1729 1729 finally:
1730 1730 os.unlink(tmpname)
1731 1731 finally:
1732 1732 del lock, wlock
1733 1733
1734 1734 def incoming(ui, repo, source="default", **opts):
1735 1735 """show new changesets found in source
1736 1736
1737 1737 Show new changesets found in the specified path/URL or the default
1738 1738 pull location. These are the changesets that would be pulled if a
1739 1739 pull was requested.
1740 1740
1741 1741 For remote repository, using --bundle avoids downloading the
1742 1742 changesets twice if the incoming is followed by a pull.
1743 1743
1744 1744 See pull for valid source format details.
1745 1745 """
1746 1746 limit = cmdutil.loglimit(opts)
1747 1747 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts.get('rev'))
1748 1748 cmdutil.setremoteconfig(ui, opts)
1749 1749
1750 1750 other = hg.repository(ui, source)
1751 1751 ui.status(_('comparing with %s\n') % url.hidepassword(source))
1752 1752 if revs:
1753 1753 revs = [other.lookup(rev) for rev in revs]
1754 1754 common, incoming, rheads = repo.findcommonincoming(other, heads=revs,
1755 1755 force=opts["force"])
1756 1756 if not incoming:
1757 1757 try:
1758 1758 os.unlink(opts["bundle"])
1759 1759 except:
1760 1760 pass
1761 1761 ui.status(_("no changes found\n"))
1762 1762 return 1
1763 1763
1764 1764 cleanup = None
1765 1765 try:
1766 1766 fname = opts["bundle"]
1767 1767 if fname or not other.local():
1768 1768 # create a bundle (uncompressed if other repo is not local)
1769 1769
1770 1770 if revs is None and other.capable('changegroupsubset'):
1771 1771 revs = rheads
1772 1772
1773 1773 if revs is None:
1774 1774 cg = other.changegroup(incoming, "incoming")
1775 1775 else:
1776 1776 cg = other.changegroupsubset(incoming, revs, 'incoming')
1777 1777 bundletype = other.local() and "HG10BZ" or "HG10UN"
1778 1778 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
1779 1779 # keep written bundle?
1780 1780 if opts["bundle"]:
1781 1781 cleanup = None
1782 1782 if not other.local():
1783 1783 # use the created uncompressed bundlerepo
1784 1784 other = bundlerepo.bundlerepository(ui, repo.root, fname)
1785 1785
1786 1786 o = other.changelog.nodesbetween(incoming, revs)[0]
1787 1787 if opts.get('newest_first'):
1788 1788 o.reverse()
1789 1789 displayer = cmdutil.show_changeset(ui, other, opts)
1790 1790 count = 0
1791 1791 for n in o:
1792 1792 if count >= limit:
1793 1793 break
1794 1794 parents = [p for p in other.changelog.parents(n) if p != nullid]
1795 1795 if opts.get('no_merges') and len(parents) == 2:
1796 1796 continue
1797 1797 count += 1
1798 1798 displayer.show(other[n])
1799 1799 finally:
1800 1800 if hasattr(other, 'close'):
1801 1801 other.close()
1802 1802 if cleanup:
1803 1803 os.unlink(cleanup)
1804 1804
1805 1805 def init(ui, dest=".", **opts):
1806 1806 """create a new repository in the given directory
1807 1807
1808 1808 Initialize a new repository in the given directory. If the given
1809 1809 directory does not exist, it is created.
1810 1810
1811 1811 If no directory is given, the current directory is used.
1812 1812
1813 1813 It is possible to specify an ssh:// URL as the destination.
1814 1814 See 'hg help urls' for more information.
1815 1815 """
1816 1816 cmdutil.setremoteconfig(ui, opts)
1817 1817 hg.repository(ui, dest, create=1)
1818 1818
1819 1819 def locate(ui, repo, *pats, **opts):
1820 1820 """locate files matching specific patterns
1821 1821
1822 1822 Print all files under Mercurial control whose names match the
1823 1823 given patterns.
1824 1824
1825 1825 This command searches the entire repository by default. To search
1826 1826 just the current directory and its subdirectories, use
1827 1827 "--include .".
1828 1828
1829 1829 If no patterns are given to match, this command prints all file
1830 1830 names.
1831 1831
1832 1832 If you want to feed the output of this command into the "xargs"
1833 1833 command, use the "-0" option to both this command and "xargs".
1834 1834 This will avoid the problem of "xargs" treating single filenames
1835 1835 that contain white space as multiple filenames.
1836 1836 """
1837 1837 end = opts.get('print0') and '\0' or '\n'
1838 1838 rev = opts.get('rev') or None
1839 1839
1840 1840 ret = 1
1841 1841 m = cmdutil.match(repo, pats, opts, default='relglob')
1842 1842 m.bad = lambda x,y: False
1843 1843 for abs in repo[rev].walk(m):
1844 1844 if not rev and abs not in repo.dirstate:
1845 1845 continue
1846 1846 if opts.get('fullpath'):
1847 1847 ui.write(repo.wjoin(abs), end)
1848 1848 else:
1849 1849 ui.write(((pats and m.rel(abs)) or abs), end)
1850 1850 ret = 0
1851 1851
1852 1852 return ret
1853 1853
1854 1854 def log(ui, repo, *pats, **opts):
1855 1855 """show revision history of entire repository or files
1856 1856
1857 1857 Print the revision history of the specified files or the entire
1858 1858 project.
1859 1859
1860 1860 File history is shown without following rename or copy history of
1861 1861 files. Use -f/--follow with a file name to follow history across
1862 1862 renames and copies. --follow without a file name will only show
1863 1863 ancestors or descendants of the starting revision. --follow-first
1864 1864 only follows the first parent of merge revisions.
1865 1865
1866 1866 If no revision range is specified, the default is tip:0 unless
1867 1867 --follow is set, in which case the working directory parent is
1868 1868 used as the starting revision.
1869 1869
1870 1870 See 'hg help dates' for a list of formats valid for -d/--date.
1871 1871
1872 1872 By default this command outputs: changeset id and hash, tags,
1873 1873 non-trivial parents, user, date and time, and a summary for each
1874 1874 commit. When the -v/--verbose switch is used, the list of changed
1875 1875 files and full commit message is shown.
1876 1876
1877 1877 NOTE: log -p may generate unexpected diff output for merge
1878 1878 changesets, as it will only compare the merge changeset against
1879 1879 its first parent. Also, the files: list will only reflect files
1880 1880 that are different from BOTH parents.
1881 1881
1882 1882 """
1883 1883
1884 1884 get = util.cachefunc(lambda r: repo[r].changeset())
1885 1885 changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, pats, get, opts)
1886 1886
1887 1887 limit = cmdutil.loglimit(opts)
1888 1888 count = 0
1889 1889
1890 1890 if opts.get('copies') and opts.get('rev'):
1891 1891 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
1892 1892 else:
1893 1893 endrev = len(repo)
1894 1894 rcache = {}
1895 1895 ncache = {}
1896 1896 def getrenamed(fn, rev):
1897 1897 '''looks up all renames for a file (up to endrev) the first
1898 1898 time the file is given. It indexes on the changerev and only
1899 1899 parses the manifest if linkrev != changerev.
1900 1900 Returns rename info for fn at changerev rev.'''
1901 1901 if fn not in rcache:
1902 1902 rcache[fn] = {}
1903 1903 ncache[fn] = {}
1904 1904 fl = repo.file(fn)
1905 1905 for i in fl:
1906 1906 node = fl.node(i)
1907 1907 lr = fl.linkrev(i)
1908 1908 renamed = fl.renamed(node)
1909 1909 rcache[fn][lr] = renamed
1910 1910 if renamed:
1911 1911 ncache[fn][node] = renamed
1912 1912 if lr >= endrev:
1913 1913 break
1914 1914 if rev in rcache[fn]:
1915 1915 return rcache[fn][rev]
1916 1916
1917 1917 # If linkrev != rev (i.e. rev not found in rcache) fallback to
1918 1918 # filectx logic.
1919 1919
1920 1920 try:
1921 1921 return repo[rev][fn].renamed()
1922 1922 except error.LookupError:
1923 1923 pass
1924 1924 return None
1925 1925
1926 1926 df = False
1927 1927 if opts["date"]:
1928 1928 df = util.matchdate(opts["date"])
1929 1929
1930 1930 only_branches = opts.get('only_branch')
1931 1931
1932 1932 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
1933 1933 for st, rev, fns in changeiter:
1934 1934 if st == 'add':
1935 1935 parents = [p for p in repo.changelog.parentrevs(rev)
1936 1936 if p != nullrev]
1937 1937 if opts.get('no_merges') and len(parents) == 2:
1938 1938 continue
1939 1939 if opts.get('only_merges') and len(parents) != 2:
1940 1940 continue
1941 1941
1942 1942 if only_branches:
1943 1943 revbranch = get(rev)[5]['branch']
1944 1944 if revbranch not in only_branches:
1945 1945 continue
1946 1946
1947 1947 if df:
1948 1948 changes = get(rev)
1949 1949 if not df(changes[2][0]):
1950 1950 continue
1951 1951
1952 1952 if opts.get('keyword'):
1953 1953 changes = get(rev)
1954 1954 miss = 0
1955 1955 for k in [kw.lower() for kw in opts['keyword']]:
1956 1956 if not (k in changes[1].lower() or
1957 1957 k in changes[4].lower() or
1958 1958 k in " ".join(changes[3]).lower()):
1959 1959 miss = 1
1960 1960 break
1961 1961 if miss:
1962 1962 continue
1963 1963
1964 1964 if opts['user']:
1965 1965 changes = get(rev)
1966 1966 if not [k for k in opts['user'] if k in changes[1]]:
1967 1967 continue
1968 1968
1969 1969 copies = []
1970 1970 if opts.get('copies') and rev:
1971 1971 for fn in get(rev)[3]:
1972 1972 rename = getrenamed(fn, rev)
1973 1973 if rename:
1974 1974 copies.append((fn, rename[0]))
1975 1975 displayer.show(context.changectx(repo, rev), copies=copies)
1976 1976 elif st == 'iter':
1977 1977 if count == limit: break
1978 1978 if displayer.flush(rev):
1979 1979 count += 1
1980 1980
1981 1981 def manifest(ui, repo, node=None, rev=None):
1982 1982 """output the current or given revision of the project manifest
1983 1983
1984 1984 Print a list of version controlled files for the given revision.
1985 1985 If no revision is given, the first parent of the working directory
1986 1986 is used, or tip if no revision is checked out.
1987 1987
1988 1988 With -v flag, print file permissions, symlink and executable bits.
1989 1989 With --debug flag, print file revision hashes.
1990 1990 """
1991 1991
1992 1992 if rev and node:
1993 1993 raise util.Abort(_("please specify just one revision"))
1994 1994
1995 1995 if not node:
1996 1996 node = rev
1997 1997
1998 1998 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
1999 1999 ctx = repo[node]
2000 2000 for f in ctx:
2001 2001 if ui.debugflag:
2002 2002 ui.write("%40s " % hex(ctx.manifest()[f]))
2003 2003 if ui.verbose:
2004 2004 ui.write(decor[ctx.flags(f)])
2005 2005 ui.write("%s\n" % f)
2006 2006
2007 2007 def merge(ui, repo, node=None, force=None, rev=None):
2008 2008 """merge working directory with another revision
2009 2009
2010 2010 The contents of the current working directory is updated with all
2011 2011 changes made in the requested revision since the last common
2012 2012 predecessor revision.
2013 2013
2014 2014 Files that changed between either parent are marked as changed for
2015 2015 the next commit and a commit must be performed before any further
2016 2016 updates are allowed. The next commit has two parents.
2017 2017
2018 2018 If no revision is specified, the working directory's parent is a
2019 2019 head revision, and the current branch contains exactly one other
2020 2020 head, the other head is merged with by default. Otherwise, an
2021 2021 explicit revision to merge with must be provided.
2022 2022 """
2023 2023
2024 2024 if rev and node:
2025 2025 raise util.Abort(_("please specify just one revision"))
2026 2026 if not node:
2027 2027 node = rev
2028 2028
2029 2029 if not node:
2030 2030 branch = repo.changectx(None).branch()
2031 2031 bheads = repo.branchheads(branch)
2032 2032 if len(bheads) > 2:
2033 2033 raise util.Abort(_("branch '%s' has %d heads - "
2034 2034 "please merge with an explicit rev") %
2035 2035 (branch, len(bheads)))
2036 2036
2037 2037 parent = repo.dirstate.parents()[0]
2038 2038 if len(bheads) == 1:
2039 2039 if len(repo.heads()) > 1:
2040 2040 raise util.Abort(_("branch '%s' has one head - "
2041 2041 "please merge with an explicit rev") %
2042 2042 branch)
2043 2043 msg = _('there is nothing to merge')
2044 2044 if parent != repo.lookup(repo[None].branch()):
2045 2045 msg = _('%s - use "hg update" instead') % msg
2046 2046 raise util.Abort(msg)
2047 2047
2048 2048 if parent not in bheads:
2049 2049 raise util.Abort(_('working dir not at a head rev - '
2050 2050 'use "hg update" or merge with an explicit rev'))
2051 2051 node = parent == bheads[0] and bheads[-1] or bheads[0]
2052 2052 return hg.merge(repo, node, force=force)
2053 2053
2054 2054 def outgoing(ui, repo, dest=None, **opts):
2055 2055 """show changesets not found in destination
2056 2056
2057 2057 Show changesets not found in the specified destination repository
2058 2058 or the default push location. These are the changesets that would
2059 2059 be pushed if a push was requested.
2060 2060
2061 2061 See pull for valid destination format details.
2062 2062 """
2063 2063 limit = cmdutil.loglimit(opts)
2064 2064 dest, revs, checkout = hg.parseurl(
2065 2065 ui.expandpath(dest or 'default-push', dest or 'default'), opts.get('rev'))
2066 2066 cmdutil.setremoteconfig(ui, opts)
2067 2067 if revs:
2068 2068 revs = [repo.lookup(rev) for rev in revs]
2069 2069
2070 2070 other = hg.repository(ui, dest)
2071 2071 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2072 2072 o = repo.findoutgoing(other, force=opts.get('force'))
2073 2073 if not o:
2074 2074 ui.status(_("no changes found\n"))
2075 2075 return 1
2076 2076 o = repo.changelog.nodesbetween(o, revs)[0]
2077 2077 if opts.get('newest_first'):
2078 2078 o.reverse()
2079 2079 displayer = cmdutil.show_changeset(ui, repo, opts)
2080 2080 count = 0
2081 2081 for n in o:
2082 2082 if count >= limit:
2083 2083 break
2084 2084 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2085 2085 if opts.get('no_merges') and len(parents) == 2:
2086 2086 continue
2087 2087 count += 1
2088 2088 displayer.show(repo[n])
2089 2089
2090 2090 def parents(ui, repo, file_=None, **opts):
2091 2091 """show the parents of the working directory or revision
2092 2092
2093 2093 Print the working directory's parent revisions. If a revision is
2094 2094 given via --rev, the parent of that revision will be printed. If a
2095 2095 file argument is given, revision in which the file was last
2096 2096 changed (before the working directory revision or the argument to
2097 2097 --rev if given) is printed.
2098 2098 """
2099 2099 rev = opts.get('rev')
2100 2100 if rev:
2101 2101 ctx = repo[rev]
2102 2102 else:
2103 2103 ctx = repo[None]
2104 2104
2105 2105 if file_:
2106 2106 m = cmdutil.match(repo, (file_,), opts)
2107 2107 if m.anypats() or len(m.files()) != 1:
2108 2108 raise util.Abort(_('can only specify an explicit file name'))
2109 2109 file_ = m.files()[0]
2110 2110 filenodes = []
2111 2111 for cp in ctx.parents():
2112 2112 if not cp:
2113 2113 continue
2114 2114 try:
2115 2115 filenodes.append(cp.filenode(file_))
2116 2116 except error.LookupError:
2117 2117 pass
2118 2118 if not filenodes:
2119 2119 raise util.Abort(_("'%s' not found in manifest!") % file_)
2120 2120 fl = repo.file(file_)
2121 2121 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2122 2122 else:
2123 2123 p = [cp.node() for cp in ctx.parents()]
2124 2124
2125 2125 displayer = cmdutil.show_changeset(ui, repo, opts)
2126 2126 for n in p:
2127 2127 if n != nullid:
2128 2128 displayer.show(repo[n])
2129 2129
2130 2130 def paths(ui, repo, search=None):
2131 2131 """show aliases for remote repositories
2132 2132
2133 2133 Show definition of symbolic path name NAME. If no name is given,
2134 2134 show definition of available names.
2135 2135
2136 2136 Path names are defined in the [paths] section of /etc/mercurial/hgrc
2137 2137 and $HOME/.hgrc. If run inside a repository, .hg/hgrc is used, too.
2138 2138
2139 2139 See 'hg help urls' for more information.
2140 2140 """
2141 2141 if search:
2142 2142 for name, path in ui.configitems("paths"):
2143 2143 if name == search:
2144 2144 ui.write("%s\n" % url.hidepassword(path))
2145 2145 return
2146 2146 ui.warn(_("not found!\n"))
2147 2147 return 1
2148 2148 else:
2149 2149 for name, path in ui.configitems("paths"):
2150 2150 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2151 2151
2152 2152 def postincoming(ui, repo, modheads, optupdate, checkout):
2153 2153 if modheads == 0:
2154 2154 return
2155 2155 if optupdate:
2156 2156 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2157 2157 return hg.update(repo, checkout)
2158 2158 else:
2159 2159 ui.status(_("not updating, since new heads added\n"))
2160 2160 if modheads > 1:
2161 2161 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2162 2162 else:
2163 2163 ui.status(_("(run 'hg update' to get a working copy)\n"))
2164 2164
2165 2165 def pull(ui, repo, source="default", **opts):
2166 2166 """pull changes from the specified source
2167 2167
2168 2168 Pull changes from a remote repository to the local one.
2169 2169
2170 2170 This finds all changes from the repository at the specified path
2171 2171 or URL and adds them to the local repository. By default, this
2172 2172 does not update the copy of the project in the working directory.
2173 2173
2174 2174 Use hg incoming if you want to see what will be added by the next
2175 2175 pull without actually adding the changes to the repository.
2176 2176
2177 2177 If SOURCE is omitted, the 'default' path will be used.
2178 2178 See 'hg help urls' for more information.
2179 2179 """
2180 2180 source, revs, checkout = hg.parseurl(ui.expandpath(source), opts.get('rev'))
2181 2181 cmdutil.setremoteconfig(ui, opts)
2182 2182
2183 2183 other = hg.repository(ui, source)
2184 2184 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2185 2185 if revs:
2186 2186 try:
2187 2187 revs = [other.lookup(rev) for rev in revs]
2188 2188 except error.CapabilityError:
2189 2189 err = _("Other repository doesn't support revision lookup, "
2190 2190 "so a rev cannot be specified.")
2191 2191 raise util.Abort(err)
2192 2192
2193 2193 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2194 2194 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2195 2195
2196 2196 def push(ui, repo, dest=None, **opts):
2197 2197 """push changes to the specified destination
2198 2198
2199 2199 Push changes from the local repository to the given destination.
2200 2200
2201 2201 This is the symmetrical operation for pull. It moves changes from
2202 2202 the current repository to a different one. If the destination is
2203 2203 local this is identical to a pull in that directory from the
2204 2204 current one.
2205 2205
2206 2206 By default, push will refuse to run if it detects the result would
2207 2207 increase the number of remote heads. This generally indicates the
2208 2208 the client has forgotten to pull and merge before pushing.
2209 2209
2210 2210 If -r is used, the named revision and all its ancestors will be
2211 2211 pushed to the remote repository.
2212 2212
2213 2213 Look at the help text for URLs for important details about ssh://
2214 2214 URLs. If DESTINATION is omitted, a default path will be used.
2215 2215 See 'hg help urls' for more information.
2216 2216 """
2217 2217 dest, revs, checkout = hg.parseurl(
2218 2218 ui.expandpath(dest or 'default-push', dest or 'default'), opts.get('rev'))
2219 2219 cmdutil.setremoteconfig(ui, opts)
2220 2220
2221 2221 other = hg.repository(ui, dest)
2222 2222 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2223 2223 if revs:
2224 2224 revs = [repo.lookup(rev) for rev in revs]
2225 2225 r = repo.push(other, opts.get('force'), revs=revs)
2226 2226 return r == 0
2227 2227
2228 2228 def rawcommit(ui, repo, *pats, **opts):
2229 2229 """raw commit interface (DEPRECATED)
2230 2230
2231 2231 (DEPRECATED)
2232 2232 Lowlevel commit, for use in helper scripts.
2233 2233
2234 2234 This command is not intended to be used by normal users, as it is
2235 2235 primarily useful for importing from other SCMs.
2236 2236
2237 2237 This command is now deprecated and will be removed in a future
2238 2238 release, please use debugsetparents and commit instead.
2239 2239 """
2240 2240
2241 2241 ui.warn(_("(the rawcommit command is deprecated)\n"))
2242 2242
2243 2243 message = cmdutil.logmessage(opts)
2244 2244
2245 2245 files = cmdutil.match(repo, pats, opts).files()
2246 2246 if opts.get('files'):
2247 2247 files += open(opts['files']).read().splitlines()
2248 2248
2249 2249 parents = [repo.lookup(p) for p in opts['parent']]
2250 2250
2251 2251 try:
2252 2252 repo.rawcommit(files, message, opts['user'], opts['date'], *parents)
2253 2253 except ValueError, inst:
2254 2254 raise util.Abort(str(inst))
2255 2255
2256 2256 def recover(ui, repo):
2257 2257 """roll back an interrupted transaction
2258 2258
2259 2259 Recover from an interrupted commit or pull.
2260 2260
2261 2261 This command tries to fix the repository status after an
2262 2262 interrupted operation. It should only be necessary when Mercurial
2263 2263 suggests it.
2264 2264 """
2265 2265 if repo.recover():
2266 2266 return hg.verify(repo)
2267 2267 return 1
2268 2268
2269 2269 def remove(ui, repo, *pats, **opts):
2270 2270 """remove the specified files on the next commit
2271 2271
2272 2272 Schedule the indicated files for removal from the repository.
2273 2273
2274 2274 This only removes files from the current branch, not from the
2275 2275 entire project history. -A can be used to remove only files that
2276 2276 have already been deleted, -f can be used to force deletion, and
2277 2277 -Af can be used to remove files from the next revision without
2278 2278 deleting them.
2279 2279
2280 2280 The following table details the behavior of remove for different
2281 2281 file states (columns) and option combinations (rows). The file
2282 2282 states are Added, Clean, Modified and Missing (as reported by hg
2283 2283 status). The actions are Warn, Remove (from branch) and Delete
2284 2284 (from disk).
2285 2285
2286 2286 A C M !
2287 2287 none W RD W R
2288 2288 -f R RD RD R
2289 2289 -A W W W R
2290 2290 -Af R R R R
2291 2291
2292 2292 This command schedules the files to be removed at the next commit.
2293 2293 To undo a remove before that, see hg revert.
2294 2294 """
2295 2295
2296 2296 after, force = opts.get('after'), opts.get('force')
2297 2297 if not pats and not after:
2298 2298 raise util.Abort(_('no files specified'))
2299 2299
2300 2300 m = cmdutil.match(repo, pats, opts)
2301 2301 s = repo.status(match=m, clean=True)
2302 2302 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2303 2303
2304 2304 def warn(files, reason):
2305 2305 for f in files:
2306 2306 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2307 2307 % (m.rel(f), reason))
2308 2308
2309 2309 if force:
2310 2310 remove, forget = modified + deleted + clean, added
2311 2311 elif after:
2312 2312 remove, forget = deleted, []
2313 2313 warn(modified + added + clean, _('still exists'))
2314 2314 else:
2315 2315 remove, forget = deleted + clean, []
2316 2316 warn(modified, _('is modified'))
2317 2317 warn(added, _('has been marked for add'))
2318 2318
2319 2319 for f in util.sort(remove + forget):
2320 2320 if ui.verbose or not m.exact(f):
2321 2321 ui.status(_('removing %s\n') % m.rel(f))
2322 2322
2323 2323 repo.forget(forget)
2324 2324 repo.remove(remove, unlink=not after)
2325 2325
2326 2326 def rename(ui, repo, *pats, **opts):
2327 2327 """rename files; equivalent of copy + remove
2328 2328
2329 2329 Mark dest as copies of sources; mark sources for deletion. If dest
2330 2330 is a directory, copies are put in that directory. If dest is a
2331 2331 file, there can only be one source.
2332 2332
2333 2333 By default, this command copies the contents of files as they
2334 2334 exist in the working directory. If invoked with --after, the
2335 2335 operation is recorded, but no copying is performed.
2336 2336
2337 2337 This command takes effect at the next commit. To undo a rename
2338 2338 before that, see hg revert.
2339 2339 """
2340 2340 wlock = repo.wlock(False)
2341 2341 try:
2342 2342 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2343 2343 finally:
2344 2344 del wlock
2345 2345
2346 2346 def resolve(ui, repo, *pats, **opts):
2347 2347 """retry file merges from a merge or update
2348 2348
2349 2349 This command will cleanly retry unresolved file merges using file
2350 2350 revisions preserved from the last update or merge. To attempt to
2351 2351 resolve all unresolved files, use the -a switch.
2352 2352
2353 2353 If a conflict is resolved manually, please note that the changes
2354 2354 will be overwritten if the merge is retried with resolve. The -m
2355 2355 switch should be used to mark the file as resolved.
2356 2356
2357 2357 This command will also allow listing resolved files and manually
2358 2358 marking and unmarking files as resolved. All files must be marked
2359 2359 as resolved before the new commits are permitted.
2360 2360
2361 2361 The codes used to show the status of files are:
2362 2362 U = unresolved
2363 2363 R = resolved
2364 2364 """
2365 2365
2366 2366 all, mark, unmark, show = [opts.get(o) for o in 'all mark unmark list'.split()]
2367 2367
2368 2368 if (show and (mark or unmark)) or (mark and unmark):
2369 2369 raise util.Abort(_("too many options specified"))
2370 2370 if pats and all:
2371 2371 raise util.Abort(_("can't specify --all and patterns"))
2372 2372 if not (all or pats or show or mark or unmark):
2373 2373 raise util.Abort(_('no files or directories specified; '
2374 2374 'use --all to remerge all files'))
2375 2375
2376 2376 ms = merge_.mergestate(repo)
2377 2377 m = cmdutil.match(repo, pats, opts)
2378 2378
2379 2379 for f in ms:
2380 2380 if m(f):
2381 2381 if show:
2382 2382 ui.write("%s %s\n" % (ms[f].upper(), f))
2383 2383 elif mark:
2384 2384 ms.mark(f, "r")
2385 2385 elif unmark:
2386 2386 ms.mark(f, "u")
2387 2387 else:
2388 2388 wctx = repo[None]
2389 2389 mctx = wctx.parents()[-1]
2390 2390
2391 2391 # backup pre-resolve (merge uses .orig for its own purposes)
2392 2392 a = repo.wjoin(f)
2393 2393 util.copyfile(a, a + ".resolve")
2394 2394
2395 2395 # resolve file
2396 2396 ms.resolve(f, wctx, mctx)
2397 2397
2398 2398 # replace filemerge's .orig file with our resolve file
2399 2399 util.rename(a + ".resolve", a + ".orig")
2400 2400
2401 2401 def revert(ui, repo, *pats, **opts):
2402 2402 """restore individual files or directories to an earlier state
2403 2403
2404 2404 (use update -r to check out earlier revisions, revert does not
2405 2405 change the working directory parents)
2406 2406
2407 2407 With no revision specified, revert the named files or directories
2408 2408 to the contents they had in the parent of the working directory.
2409 2409 This restores the contents of the affected files to an unmodified
2410 2410 state and unschedules adds, removes, copies, and renames. If the
2411 2411 working directory has two parents, you must explicitly specify the
2412 2412 revision to revert to.
2413 2413
2414 2414 Using the -r option, revert the given files or directories to
2415 2415 their contents as of a specific revision. This can be helpful to
2416 2416 "roll back" some or all of an earlier change. See 'hg help dates'
2417 2417 for a list of formats valid for -d/--date.
2418 2418
2419 2419 Revert modifies the working directory. It does not commit any
2420 2420 changes, or change the parent of the working directory. If you
2421 2421 revert to a revision other than the parent of the working
2422 2422 directory, the reverted files will thus appear modified
2423 2423 afterwards.
2424 2424
2425 2425 If a file has been deleted, it is restored. If the executable mode
2426 2426 of a file was changed, it is reset.
2427 2427
2428 2428 If names are given, all files matching the names are reverted.
2429 2429 If no arguments are given, no files are reverted.
2430 2430
2431 2431 Modified files are saved with a .orig suffix before reverting.
2432 2432 To disable these backups, use --no-backup.
2433 2433 """
2434 2434
2435 2435 if opts["date"]:
2436 2436 if opts["rev"]:
2437 2437 raise util.Abort(_("you can't specify a revision and a date"))
2438 2438 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2439 2439
2440 2440 if not pats and not opts.get('all'):
2441 2441 raise util.Abort(_('no files or directories specified; '
2442 2442 'use --all to revert the whole repo'))
2443 2443
2444 2444 parent, p2 = repo.dirstate.parents()
2445 2445 if not opts.get('rev') and p2 != nullid:
2446 2446 raise util.Abort(_('uncommitted merge - please provide a '
2447 2447 'specific revision'))
2448 2448 ctx = repo[opts.get('rev')]
2449 2449 node = ctx.node()
2450 2450 mf = ctx.manifest()
2451 2451 if node == parent:
2452 2452 pmf = mf
2453 2453 else:
2454 2454 pmf = None
2455 2455
2456 2456 # need all matching names in dirstate and manifest of target rev,
2457 2457 # so have to walk both. do not print errors if files exist in one
2458 2458 # but not other.
2459 2459
2460 2460 names = {}
2461 2461
2462 2462 wlock = repo.wlock()
2463 2463 try:
2464 2464 # walk dirstate.
2465 2465
2466 2466 m = cmdutil.match(repo, pats, opts)
2467 2467 m.bad = lambda x,y: False
2468 2468 for abs in repo.walk(m):
2469 2469 names[abs] = m.rel(abs), m.exact(abs)
2470 2470
2471 2471 # walk target manifest.
2472 2472
2473 2473 def badfn(path, msg):
2474 2474 if path in names:
2475 2475 return False
2476 2476 path_ = path + '/'
2477 2477 for f in names:
2478 2478 if f.startswith(path_):
2479 2479 return False
2480 2480 repo.ui.warn("%s: %s\n" % (m.rel(path), msg))
2481 2481 return False
2482 2482
2483 2483 m = cmdutil.match(repo, pats, opts)
2484 2484 m.bad = badfn
2485 2485 for abs in repo[node].walk(m):
2486 2486 if abs not in names:
2487 2487 names[abs] = m.rel(abs), m.exact(abs)
2488 2488
2489 2489 m = cmdutil.matchfiles(repo, names)
2490 2490 changes = repo.status(match=m)[:4]
2491 2491 modified, added, removed, deleted = map(dict.fromkeys, changes)
2492 2492
2493 2493 # if f is a rename, also revert the source
2494 2494 cwd = repo.getcwd()
2495 2495 for f in added:
2496 2496 src = repo.dirstate.copied(f)
2497 2497 if src and src not in names and repo.dirstate[src] == 'r':
2498 2498 removed[src] = None
2499 2499 names[src] = (repo.pathto(src, cwd), True)
2500 2500
2501 2501 def removeforget(abs):
2502 2502 if repo.dirstate[abs] == 'a':
2503 2503 return _('forgetting %s\n')
2504 2504 return _('removing %s\n')
2505 2505
2506 2506 revert = ([], _('reverting %s\n'))
2507 2507 add = ([], _('adding %s\n'))
2508 2508 remove = ([], removeforget)
2509 2509 undelete = ([], _('undeleting %s\n'))
2510 2510
2511 2511 disptable = (
2512 2512 # dispatch table:
2513 2513 # file state
2514 2514 # action if in target manifest
2515 2515 # action if not in target manifest
2516 2516 # make backup if in target manifest
2517 2517 # make backup if not in target manifest
2518 2518 (modified, revert, remove, True, True),
2519 2519 (added, revert, remove, True, False),
2520 2520 (removed, undelete, None, False, False),
2521 2521 (deleted, revert, remove, False, False),
2522 2522 )
2523 2523
2524 2524 for abs, (rel, exact) in util.sort(names.items()):
2525 2525 mfentry = mf.get(abs)
2526 2526 target = repo.wjoin(abs)
2527 2527 def handle(xlist, dobackup):
2528 2528 xlist[0].append(abs)
2529 2529 if dobackup and not opts.get('no_backup') and util.lexists(target):
2530 2530 bakname = "%s.orig" % rel
2531 2531 ui.note(_('saving current version of %s as %s\n') %
2532 2532 (rel, bakname))
2533 2533 if not opts.get('dry_run'):
2534 2534 util.copyfile(target, bakname)
2535 2535 if ui.verbose or not exact:
2536 2536 msg = xlist[1]
2537 2537 if not isinstance(msg, basestring):
2538 2538 msg = msg(abs)
2539 2539 ui.status(msg % rel)
2540 2540 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2541 2541 if abs not in table: continue
2542 2542 # file has changed in dirstate
2543 2543 if mfentry:
2544 2544 handle(hitlist, backuphit)
2545 2545 elif misslist is not None:
2546 2546 handle(misslist, backupmiss)
2547 2547 break
2548 2548 else:
2549 2549 if abs not in repo.dirstate:
2550 2550 if mfentry:
2551 2551 handle(add, True)
2552 2552 elif exact:
2553 2553 ui.warn(_('file not managed: %s\n') % rel)
2554 2554 continue
2555 2555 # file has not changed in dirstate
2556 2556 if node == parent:
2557 2557 if exact: ui.warn(_('no changes needed to %s\n') % rel)
2558 2558 continue
2559 2559 if pmf is None:
2560 2560 # only need parent manifest in this unlikely case,
2561 2561 # so do not read by default
2562 2562 pmf = repo[parent].manifest()
2563 2563 if abs in pmf:
2564 2564 if mfentry:
2565 2565 # if version of file is same in parent and target
2566 2566 # manifests, do nothing
2567 2567 if (pmf[abs] != mfentry or
2568 2568 pmf.flags(abs) != mf.flags(abs)):
2569 2569 handle(revert, False)
2570 2570 else:
2571 2571 handle(remove, False)
2572 2572
2573 2573 if not opts.get('dry_run'):
2574 2574 def checkout(f):
2575 2575 fc = ctx[f]
2576 2576 repo.wwrite(f, fc.data(), fc.flags())
2577 2577
2578 2578 audit_path = util.path_auditor(repo.root)
2579 2579 for f in remove[0]:
2580 2580 if repo.dirstate[f] == 'a':
2581 2581 repo.dirstate.forget(f)
2582 2582 continue
2583 2583 audit_path(f)
2584 2584 try:
2585 2585 util.unlink(repo.wjoin(f))
2586 2586 except OSError:
2587 2587 pass
2588 2588 repo.dirstate.remove(f)
2589 2589
2590 2590 normal = None
2591 2591 if node == parent:
2592 2592 # We're reverting to our parent. If possible, we'd like status
2593 2593 # to report the file as clean. We have to use normallookup for
2594 2594 # merges to avoid losing information about merged/dirty files.
2595 2595 if p2 != nullid:
2596 2596 normal = repo.dirstate.normallookup
2597 2597 else:
2598 2598 normal = repo.dirstate.normal
2599 2599 for f in revert[0]:
2600 2600 checkout(f)
2601 2601 if normal:
2602 2602 normal(f)
2603 2603
2604 2604 for f in add[0]:
2605 2605 checkout(f)
2606 2606 repo.dirstate.add(f)
2607 2607
2608 2608 normal = repo.dirstate.normallookup
2609 2609 if node == parent and p2 == nullid:
2610 2610 normal = repo.dirstate.normal
2611 2611 for f in undelete[0]:
2612 2612 checkout(f)
2613 2613 normal(f)
2614 2614
2615 2615 finally:
2616 2616 del wlock
2617 2617
2618 2618 def rollback(ui, repo):
2619 2619 """roll back the last transaction
2620 2620
2621 2621 This command should be used with care. There is only one level of
2622 2622 rollback, and there is no way to undo a rollback. It will also
2623 2623 restore the dirstate at the time of the last transaction, losing
2624 2624 any dirstate changes since that time.
2625 2625
2626 2626 Transactions are used to encapsulate the effects of all commands
2627 2627 that create new changesets or propagate existing changesets into a
2628 2628 repository. For example, the following commands are transactional,
2629 2629 and their effects can be rolled back:
2630 2630
2631 2631 commit
2632 2632 import
2633 2633 pull
2634 2634 push (with this repository as destination)
2635 2635 unbundle
2636 2636
2637 2637 This command is not intended for use on public repositories. Once
2638 2638 changes are visible for pull by other users, rolling a transaction
2639 2639 back locally is ineffective (someone else may already have pulled
2640 2640 the changes). Furthermore, a race is possible with readers of the
2641 2641 repository; for example an in-progress pull from the repository
2642 2642 may fail if a rollback is performed.
2643 2643 """
2644 2644 repo.rollback()
2645 2645
2646 2646 def root(ui, repo):
2647 2647 """print the root (top) of the current working directory
2648 2648
2649 2649 Print the root directory of the current repository.
2650 2650 """
2651 2651 ui.write(repo.root + "\n")
2652 2652
2653 2653 def serve(ui, repo, **opts):
2654 2654 """export the repository via HTTP
2655 2655
2656 2656 Start a local HTTP repository browser and pull server.
2657 2657
2658 2658 By default, the server logs accesses to stdout and errors to
2659 2659 stderr. Use the "-A" and "-E" options to log to files.
2660 2660 """
2661 2661
2662 2662 if opts["stdio"]:
2663 2663 if repo is None:
2664 2664 raise error.RepoError(_("There is no Mercurial repository here"
2665 2665 " (.hg not found)"))
2666 2666 s = sshserver.sshserver(ui, repo)
2667 2667 s.serve_forever()
2668 2668
2669 2669 parentui = ui.parentui or ui
2670 2670 optlist = ("name templates style address port prefix ipv6"
2671 2671 " accesslog errorlog webdir_conf certificate")
2672 2672 for o in optlist.split():
2673 2673 if opts[o]:
2674 2674 parentui.setconfig("web", o, str(opts[o]))
2675 2675 if (repo is not None) and (repo.ui != parentui):
2676 2676 repo.ui.setconfig("web", o, str(opts[o]))
2677 2677
2678 2678 if repo is None and not ui.config("web", "webdir_conf"):
2679 2679 raise error.RepoError(_("There is no Mercurial repository here"
2680 2680 " (.hg not found)"))
2681 2681
2682 2682 class service:
2683 2683 def init(self):
2684 2684 util.set_signal_handler()
2685 2685 self.httpd = hgweb.server.create_server(parentui, repo)
2686 2686
2687 2687 if not ui.verbose: return
2688 2688
2689 2689 if self.httpd.prefix:
2690 2690 prefix = self.httpd.prefix.strip('/') + '/'
2691 2691 else:
2692 2692 prefix = ''
2693 2693
2694 2694 port = ':%d' % self.httpd.port
2695 2695 if port == ':80':
2696 2696 port = ''
2697 2697
2698 2698 bindaddr = self.httpd.addr
2699 2699 if bindaddr == '0.0.0.0':
2700 2700 bindaddr = '*'
2701 2701 elif ':' in bindaddr: # IPv6
2702 2702 bindaddr = '[%s]' % bindaddr
2703 2703
2704 2704 fqaddr = self.httpd.fqaddr
2705 2705 if ':' in fqaddr:
2706 2706 fqaddr = '[%s]' % fqaddr
2707 2707 ui.status(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
2708 2708 (fqaddr, port, prefix, bindaddr, self.httpd.port))
2709 2709
2710 2710 def run(self):
2711 2711 self.httpd.serve_forever()
2712 2712
2713 2713 service = service()
2714 2714
2715 2715 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2716 2716
2717 2717 def status(ui, repo, *pats, **opts):
2718 2718 """show changed files in the working directory
2719 2719
2720 2720 Show status of files in the repository. If names are given, only
2721 2721 files that match are shown. Files that are clean or ignored or
2722 2722 source of a copy/move operation, are not listed unless -c (clean),
2723 2723 -i (ignored), -C (copies) or -A is given. Unless options described
2724 2724 with "show only ..." are given, the options -mardu are used.
2725 2725
2726 2726 Option -q/--quiet hides untracked (unknown and ignored) files
2727 2727 unless explicitly requested with -u/--unknown or -i/--ignored.
2728 2728
2729 2729 NOTE: status may appear to disagree with diff if permissions have
2730 2730 changed or a merge has occurred. The standard diff format does not
2731 2731 report permission changes and diff only reports changes relative
2732 2732 to one merge parent.
2733 2733
2734 2734 If one revision is given, it is used as the base revision.
2735 2735 If two revisions are given, the difference between them is shown.
2736 2736
2737 2737 The codes used to show the status of files are:
2738 2738 M = modified
2739 2739 A = added
2740 2740 R = removed
2741 2741 C = clean
2742 2742 ! = missing, but still tracked
2743 2743 ? = not tracked
2744 2744 I = ignored
2745 2745 = the previous added file was copied from here
2746 2746 """
2747 2747
2748 2748 node1, node2 = cmdutil.revpair(repo, opts.get('rev'))
2749 2749 cwd = (pats and repo.getcwd()) or ''
2750 2750 end = opts.get('print0') and '\0' or '\n'
2751 2751 copy = {}
2752 2752 states = 'modified added removed deleted unknown ignored clean'.split()
2753 2753 show = [k for k in states if opts.get(k)]
2754 2754 if opts.get('all'):
2755 2755 show += ui.quiet and (states[:4] + ['clean']) or states
2756 2756 if not show:
2757 2757 show = ui.quiet and states[:4] or states[:5]
2758 2758
2759 2759 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
2760 2760 'ignored' in show, 'clean' in show, 'unknown' in show)
2761 2761 changestates = zip(states, 'MAR!?IC', stat)
2762 2762
2763 2763 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
2764 2764 ctxn = repo[nullid]
2765 2765 ctx1 = repo[node1]
2766 2766 ctx2 = repo[node2]
2767 2767 added = stat[1]
2768 2768 if node2 is None:
2769 2769 added = stat[0] + stat[1] # merged?
2770 2770
2771 2771 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
2772 2772 if k in added:
2773 2773 copy[k] = v
2774 2774 elif v in added:
2775 2775 copy[v] = k
2776 2776
2777 2777 for state, char, files in changestates:
2778 2778 if state in show:
2779 2779 format = "%s %%s%s" % (char, end)
2780 2780 if opts.get('no_status'):
2781 2781 format = "%%s%s" % end
2782 2782
2783 2783 for f in files:
2784 2784 ui.write(format % repo.pathto(f, cwd))
2785 2785 if f in copy:
2786 2786 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end))
2787 2787
2788 2788 def tag(ui, repo, name1, *names, **opts):
2789 2789 """add one or more tags for the current or given revision
2790 2790
2791 2791 Name a particular revision using <name>.
2792 2792
2793 2793 Tags are used to name particular revisions of the repository and are
2794 2794 very useful to compare different revisions, to go back to significant
2795 2795 earlier versions or to mark branch points as releases, etc.
2796 2796
2797 2797 If no revision is given, the parent of the working directory is
2798 2798 used, or tip if no revision is checked out.
2799 2799
2800 2800 To facilitate version control, distribution, and merging of tags,
2801 2801 they are stored as a file named ".hgtags" which is managed
2802 2802 similarly to other project files and can be hand-edited if
2803 2803 necessary. The file '.hg/localtags' is used for local tags (not
2804 2804 shared among repositories).
2805 2805
2806 2806 See 'hg help dates' for a list of formats valid for -d/--date.
2807 2807 """
2808 2808
2809 2809 rev_ = "."
2810 2810 names = (name1,) + names
2811 2811 if len(names) != len(dict.fromkeys(names)):
2812 2812 raise util.Abort(_('tag names must be unique'))
2813 2813 for n in names:
2814 2814 if n in ['tip', '.', 'null']:
2815 2815 raise util.Abort(_('the name \'%s\' is reserved') % n)
2816 2816 if opts.get('rev') and opts.get('remove'):
2817 2817 raise util.Abort(_("--rev and --remove are incompatible"))
2818 2818 if opts.get('rev'):
2819 2819 rev_ = opts['rev']
2820 2820 message = opts.get('message')
2821 2821 if opts.get('remove'):
2822 2822 expectedtype = opts.get('local') and 'local' or 'global'
2823 2823 for n in names:
2824 2824 if not repo.tagtype(n):
2825 2825 raise util.Abort(_('tag \'%s\' does not exist') % n)
2826 2826 if repo.tagtype(n) != expectedtype:
2827 2827 if expectedtype == 'global':
2828 2828 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
2829 2829 else:
2830 2830 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
2831 2831 rev_ = nullid
2832 2832 if not message:
2833 2833 message = _('Removed tag %s') % ', '.join(names)
2834 2834 elif not opts.get('force'):
2835 2835 for n in names:
2836 2836 if n in repo.tags():
2837 2837 raise util.Abort(_('tag \'%s\' already exists '
2838 2838 '(use -f to force)') % n)
2839 2839 if not rev_ and repo.dirstate.parents()[1] != nullid:
2840 2840 raise util.Abort(_('uncommitted merge - please provide a '
2841 2841 'specific revision'))
2842 2842 r = repo[rev_].node()
2843 2843
2844 2844 if not message:
2845 2845 message = (_('Added tag %s for changeset %s') %
2846 2846 (', '.join(names), short(r)))
2847 2847
2848 2848 date = opts.get('date')
2849 2849 if date:
2850 2850 date = util.parsedate(date)
2851 2851
2852 2852 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
2853 2853
2854 2854 def tags(ui, repo):
2855 2855 """list repository tags
2856 2856
2857 2857 This lists both regular and local tags. When the -v/--verbose
2858 2858 switch is used, a third column "local" is printed for local tags.
2859 2859 """
2860 2860
2861 2861 l = repo.tagslist()
2862 2862 l.reverse()
2863 2863 hexfunc = ui.debugflag and hex or short
2864 2864 tagtype = ""
2865 2865
2866 2866 for t, n in l:
2867 2867 if ui.quiet:
2868 2868 ui.write("%s\n" % t)
2869 2869 continue
2870 2870
2871 2871 try:
2872 2872 hn = hexfunc(n)
2873 2873 r = "%5d:%s" % (repo.changelog.rev(n), hn)
2874 2874 except error.LookupError:
2875 2875 r = " ?:%s" % hn
2876 2876 else:
2877 2877 spaces = " " * (30 - encoding.colwidth(t))
2878 2878 if ui.verbose:
2879 2879 if repo.tagtype(t) == 'local':
2880 2880 tagtype = " local"
2881 2881 else:
2882 2882 tagtype = ""
2883 2883 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
2884 2884
2885 2885 def tip(ui, repo, **opts):
2886 2886 """show the tip revision
2887 2887
2888 2888 The tip revision (usually just called the tip) is the most
2889 2889 recently added changeset in the repository, the most recently
2890 2890 changed head.
2891 2891
2892 2892 If you have just made a commit, that commit will be the tip. If
2893 2893 you have just pulled changes from another repository, the tip of
2894 2894 that repository becomes the current tip. The "tip" tag is special
2895 2895 and cannot be renamed or assigned to a different changeset.
2896 2896 """
2897 2897 cmdutil.show_changeset(ui, repo, opts).show(repo[len(repo) - 1])
2898 2898
2899 2899 def unbundle(ui, repo, fname1, *fnames, **opts):
2900 2900 """apply one or more changegroup files
2901 2901
2902 2902 Apply one or more compressed changegroup files generated by the
2903 2903 bundle command.
2904 2904 """
2905 2905 fnames = (fname1,) + fnames
2906 2906
2907 2907 lock = None
2908 2908 try:
2909 2909 lock = repo.lock()
2910 2910 for fname in fnames:
2911 2911 f = url.open(ui, fname)
2912 2912 gen = changegroup.readbundle(f, fname)
2913 2913 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
2914 2914 finally:
2915 2915 del lock
2916 2916
2917 2917 return postincoming(ui, repo, modheads, opts.get('update'), None)
2918 2918
2919 2919 def update(ui, repo, node=None, rev=None, clean=False, date=None):
2920 2920 """update working directory
2921 2921
2922 2922 Update the repository's working directory to the specified
2923 2923 revision, or the tip of the current branch if none is specified.
2924 2924 Use null as the revision to remove the working copy (like 'hg
2925 2925 clone -U').
2926 2926
2927 When the working directory contains no uncommitted changes, it will be
2928 replaced by the state of the requested revision from the repository.
2929 When the requested revision is on a different branch, the working
2930 directory will additionally be switched to that branch.
2927 When the working directory contains no uncommitted changes, it
2928 will be replaced by the state of the requested revision from the
2929 repository. When the requested revision is on a different branch,
2930 the working directory will additionally be switched to that
2931 branch.
2931 2932
2932 2933 When there are uncommitted changes, use option -C to discard them,
2933 forcibly replacing the state of the working directory with the requested
2934 revision.
2934 forcibly replacing the state of the working directory with the
2935 requested revision.
2935 2936
2936 2937 When there are uncommitted changes and option -C is not used, and
2937 2938 the parent revision and requested revision are on the same branch,
2938 2939 and one of them is an ancestor of the other, then the new working
2939 2940 directory will contain the requested revision merged with the
2940 2941 uncommitted changes. Otherwise, the update will fail with a
2941 2942 suggestion to use 'merge' or 'update -C' instead.
2942 2943
2943 2944 If you want to update just one file to an older revision, use
2944 2945 revert.
2945 2946
2946 2947 See 'hg help dates' for a list of formats valid for --date.
2947 2948 """
2948 2949 if rev and node:
2949 2950 raise util.Abort(_("please specify just one revision"))
2950 2951
2951 2952 if not rev:
2952 2953 rev = node
2953 2954
2954 2955 if date:
2955 2956 if rev:
2956 2957 raise util.Abort(_("you can't specify a revision and a date"))
2957 2958 rev = cmdutil.finddate(ui, repo, date)
2958 2959
2959 2960 if clean:
2960 2961 return hg.clean(repo, rev)
2961 2962 else:
2962 2963 return hg.update(repo, rev)
2963 2964
2964 2965 def verify(ui, repo):
2965 2966 """verify the integrity of the repository
2966 2967
2967 2968 Verify the integrity of the current repository.
2968 2969
2969 2970 This will perform an extensive check of the repository's
2970 2971 integrity, validating the hashes and checksums of each entry in
2971 2972 the changelog, manifest, and tracked files, as well as the
2972 2973 integrity of their crosslinks and indices.
2973 2974 """
2974 2975 return hg.verify(repo)
2975 2976
2976 2977 def version_(ui):
2977 2978 """output version and copyright information"""
2978 2979 ui.write(_("Mercurial Distributed SCM (version %s)\n")
2979 2980 % util.version())
2980 2981 ui.status(_(
2981 2982 "\nCopyright (C) 2005-2009 Matt Mackall <mpm@selenic.com> and others\n"
2982 2983 "This is free software; see the source for copying conditions. "
2983 2984 "There is NO\nwarranty; "
2984 2985 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
2985 2986 ))
2986 2987
2987 2988 # Command options and aliases are listed here, alphabetically
2988 2989
2989 2990 globalopts = [
2990 2991 ('R', 'repository', '',
2991 2992 _('repository root directory or symbolic path name')),
2992 2993 ('', 'cwd', '', _('change working directory')),
2993 2994 ('y', 'noninteractive', None,
2994 2995 _('do not prompt, assume \'yes\' for any required answers')),
2995 2996 ('q', 'quiet', None, _('suppress output')),
2996 2997 ('v', 'verbose', None, _('enable additional output')),
2997 2998 ('', 'config', [], _('set/override config option')),
2998 2999 ('', 'debug', None, _('enable debugging output')),
2999 3000 ('', 'debugger', None, _('start debugger')),
3000 3001 ('', 'encoding', encoding.encoding, _('set the charset encoding')),
3001 3002 ('', 'encodingmode', encoding.encodingmode,
3002 3003 _('set the charset encoding mode')),
3003 3004 ('', 'traceback', None, _('print traceback on exception')),
3004 3005 ('', 'time', None, _('time how long the command takes')),
3005 3006 ('', 'profile', None, _('print command execution profile')),
3006 3007 ('', 'version', None, _('output version information and exit')),
3007 3008 ('h', 'help', None, _('display help and exit')),
3008 3009 ]
3009 3010
3010 3011 dryrunopts = [('n', 'dry-run', None,
3011 3012 _('do not perform actions, just print output'))]
3012 3013
3013 3014 remoteopts = [
3014 3015 ('e', 'ssh', '', _('specify ssh command to use')),
3015 3016 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
3016 3017 ]
3017 3018
3018 3019 walkopts = [
3019 3020 ('I', 'include', [], _('include names matching the given patterns')),
3020 3021 ('X', 'exclude', [], _('exclude names matching the given patterns')),
3021 3022 ]
3022 3023
3023 3024 commitopts = [
3024 3025 ('m', 'message', '', _('use <text> as commit message')),
3025 3026 ('l', 'logfile', '', _('read commit message from <file>')),
3026 3027 ]
3027 3028
3028 3029 commitopts2 = [
3029 3030 ('d', 'date', '', _('record datecode as commit date')),
3030 3031 ('u', 'user', '', _('record user as committer')),
3031 3032 ]
3032 3033
3033 3034 templateopts = [
3034 3035 ('', 'style', '', _('display using template map file')),
3035 3036 ('', 'template', '', _('display with template')),
3036 3037 ]
3037 3038
3038 3039 logopts = [
3039 3040 ('p', 'patch', None, _('show patch')),
3040 3041 ('g', 'git', None, _('use git extended diff format')),
3041 3042 ('l', 'limit', '', _('limit number of changes displayed')),
3042 3043 ('M', 'no-merges', None, _('do not show merges')),
3043 3044 ] + templateopts
3044 3045
3045 3046 diffopts = [
3046 3047 ('a', 'text', None, _('treat all files as text')),
3047 3048 ('g', 'git', None, _('use git extended diff format')),
3048 3049 ('', 'nodates', None, _("don't include dates in diff headers"))
3049 3050 ]
3050 3051
3051 3052 diffopts2 = [
3052 3053 ('p', 'show-function', None, _('show which function each change is in')),
3053 3054 ('w', 'ignore-all-space', None,
3054 3055 _('ignore white space when comparing lines')),
3055 3056 ('b', 'ignore-space-change', None,
3056 3057 _('ignore changes in the amount of white space')),
3057 3058 ('B', 'ignore-blank-lines', None,
3058 3059 _('ignore changes whose lines are all blank')),
3059 3060 ('U', 'unified', '', _('number of lines of context to show'))
3060 3061 ]
3061 3062
3062 3063 similarityopts = [
3063 3064 ('s', 'similarity', '',
3064 3065 _('guess renamed files by similarity (0<=s<=100)'))
3065 3066 ]
3066 3067
3067 3068 table = {
3068 3069 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3069 3070 "addremove":
3070 3071 (addremove, similarityopts + walkopts + dryrunopts,
3071 3072 _('[OPTION]... [FILE]...')),
3072 3073 "^annotate|blame":
3073 3074 (annotate,
3074 3075 [('r', 'rev', '', _('annotate the specified revision')),
3075 3076 ('f', 'follow', None, _('follow file copies and renames')),
3076 3077 ('a', 'text', None, _('treat all files as text')),
3077 3078 ('u', 'user', None, _('list the author (long with -v)')),
3078 3079 ('d', 'date', None, _('list the date (short with -q)')),
3079 3080 ('n', 'number', None, _('list the revision number (default)')),
3080 3081 ('c', 'changeset', None, _('list the changeset')),
3081 3082 ('l', 'line-number', None,
3082 3083 _('show line number at the first appearance'))
3083 3084 ] + walkopts,
3084 3085 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3085 3086 "archive":
3086 3087 (archive,
3087 3088 [('', 'no-decode', None, _('do not pass files through decoders')),
3088 3089 ('p', 'prefix', '', _('directory prefix for files in archive')),
3089 3090 ('r', 'rev', '', _('revision to distribute')),
3090 3091 ('t', 'type', '', _('type of distribution to create')),
3091 3092 ] + walkopts,
3092 3093 _('[OPTION]... DEST')),
3093 3094 "backout":
3094 3095 (backout,
3095 3096 [('', 'merge', None,
3096 3097 _('merge with old dirstate parent after backout')),
3097 3098 ('', 'parent', '', _('parent to choose when backing out merge')),
3098 3099 ('r', 'rev', '', _('revision to backout')),
3099 3100 ] + walkopts + commitopts + commitopts2,
3100 3101 _('[OPTION]... [-r] REV')),
3101 3102 "bisect":
3102 3103 (bisect,
3103 3104 [('r', 'reset', False, _('reset bisect state')),
3104 3105 ('g', 'good', False, _('mark changeset good')),
3105 3106 ('b', 'bad', False, _('mark changeset bad')),
3106 3107 ('s', 'skip', False, _('skip testing changeset')),
3107 3108 ('c', 'command', '', _('use command to check changeset state')),
3108 3109 ('U', 'noupdate', False, _('do not update to target'))],
3109 3110 _("[-gbsr] [-c CMD] [REV]")),
3110 3111 "branch":
3111 3112 (branch,
3112 3113 [('f', 'force', None,
3113 3114 _('set branch name even if it shadows an existing branch')),
3114 3115 ('C', 'clean', None, _('reset branch name to parent branch name'))],
3115 3116 _('[-fC] [NAME]')),
3116 3117 "branches":
3117 3118 (branches,
3118 3119 [('a', 'active', False,
3119 3120 _('show only branches that have unmerged heads'))],
3120 3121 _('[-a]')),
3121 3122 "bundle":
3122 3123 (bundle,
3123 3124 [('f', 'force', None,
3124 3125 _('run even when remote repository is unrelated')),
3125 3126 ('r', 'rev', [],
3126 3127 _('a changeset up to which you would like to bundle')),
3127 3128 ('', 'base', [],
3128 3129 _('a base changeset to specify instead of a destination')),
3129 3130 ('a', 'all', None, _('bundle all changesets in the repository')),
3130 3131 ('t', 'type', 'bzip2', _('bundle compression type to use')),
3131 3132 ] + remoteopts,
3132 3133 _('[-f] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
3133 3134 "cat":
3134 3135 (cat,
3135 3136 [('o', 'output', '', _('print output to file with formatted name')),
3136 3137 ('r', 'rev', '', _('print the given revision')),
3137 3138 ('', 'decode', None, _('apply any matching decode filter')),
3138 3139 ] + walkopts,
3139 3140 _('[OPTION]... FILE...')),
3140 3141 "^clone":
3141 3142 (clone,
3142 3143 [('U', 'noupdate', None,
3143 3144 _('the clone will only contain a repository (no working copy)')),
3144 3145 ('r', 'rev', [],
3145 3146 _('a changeset you would like to have after cloning')),
3146 3147 ('', 'pull', None, _('use pull protocol to copy metadata')),
3147 3148 ('', 'uncompressed', None,
3148 3149 _('use uncompressed transfer (fast over LAN)')),
3149 3150 ] + remoteopts,
3150 3151 _('[OPTION]... SOURCE [DEST]')),
3151 3152 "^commit|ci":
3152 3153 (commit,
3153 3154 [('A', 'addremove', None,
3154 3155 _('mark new/missing files as added/removed before committing')),
3155 3156 ('', 'close-branch', None,
3156 3157 _('mark a branch as closed, hiding it from the branch list')),
3157 3158 ] + walkopts + commitopts + commitopts2,
3158 3159 _('[OPTION]... [FILE]...')),
3159 3160 "copy|cp":
3160 3161 (copy,
3161 3162 [('A', 'after', None, _('record a copy that has already occurred')),
3162 3163 ('f', 'force', None,
3163 3164 _('forcibly copy over an existing managed file')),
3164 3165 ] + walkopts + dryrunopts,
3165 3166 _('[OPTION]... [SOURCE]... DEST')),
3166 3167 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
3167 3168 "debugcheckstate": (debugcheckstate, []),
3168 3169 "debugcommands": (debugcommands, [], _('[COMMAND]')),
3169 3170 "debugcomplete":
3170 3171 (debugcomplete,
3171 3172 [('o', 'options', None, _('show the command options'))],
3172 3173 _('[-o] CMD')),
3173 3174 "debugdate":
3174 3175 (debugdate,
3175 3176 [('e', 'extended', None, _('try extended date formats'))],
3176 3177 _('[-e] DATE [RANGE]')),
3177 3178 "debugdata": (debugdata, [], _('FILE REV')),
3178 3179 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
3179 3180 "debugindex": (debugindex, [], _('FILE')),
3180 3181 "debugindexdot": (debugindexdot, [], _('FILE')),
3181 3182 "debuginstall": (debuginstall, []),
3182 3183 "debugrawcommit|rawcommit":
3183 3184 (rawcommit,
3184 3185 [('p', 'parent', [], _('parent')),
3185 3186 ('F', 'files', '', _('file list'))
3186 3187 ] + commitopts + commitopts2,
3187 3188 _('[OPTION]... [FILE]...')),
3188 3189 "debugrebuildstate":
3189 3190 (debugrebuildstate,
3190 3191 [('r', 'rev', '', _('revision to rebuild to'))],
3191 3192 _('[-r REV] [REV]')),
3192 3193 "debugrename":
3193 3194 (debugrename,
3194 3195 [('r', 'rev', '', _('revision to debug'))],
3195 3196 _('[-r REV] FILE')),
3196 3197 "debugsetparents":
3197 3198 (debugsetparents, [], _('REV1 [REV2]')),
3198 3199 "debugstate":
3199 3200 (debugstate,
3200 3201 [('', 'nodates', None, _('do not display the saved mtime'))],
3201 3202 _('[OPTION]...')),
3202 3203 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
3203 3204 "^diff":
3204 3205 (diff,
3205 3206 [('r', 'rev', [], _('revision')),
3206 3207 ('c', 'change', '', _('change made by revision'))
3207 3208 ] + diffopts + diffopts2 + walkopts,
3208 3209 _('[OPTION]... [-r REV1 [-r REV2]] [FILE]...')),
3209 3210 "^export":
3210 3211 (export,
3211 3212 [('o', 'output', '', _('print output to file with formatted name')),
3212 3213 ('', 'switch-parent', None, _('diff against the second parent'))
3213 3214 ] + diffopts,
3214 3215 _('[OPTION]... [-o OUTFILESPEC] REV...')),
3215 3216 "grep":
3216 3217 (grep,
3217 3218 [('0', 'print0', None, _('end fields with NUL')),
3218 3219 ('', 'all', None, _('print all revisions that match')),
3219 3220 ('f', 'follow', None,
3220 3221 _('follow changeset history, or file history across copies and renames')),
3221 3222 ('i', 'ignore-case', None, _('ignore case when matching')),
3222 3223 ('l', 'files-with-matches', None,
3223 3224 _('print only filenames and revisions that match')),
3224 3225 ('n', 'line-number', None, _('print matching line numbers')),
3225 3226 ('r', 'rev', [], _('search in given revision range')),
3226 3227 ('u', 'user', None, _('list the author (long with -v)')),
3227 3228 ('d', 'date', None, _('list the date (short with -q)')),
3228 3229 ] + walkopts,
3229 3230 _('[OPTION]... PATTERN [FILE]...')),
3230 3231 "heads":
3231 3232 (heads,
3232 3233 [('r', 'rev', '', _('show only heads which are descendants of rev')),
3233 3234 ('a', 'active', False,
3234 3235 _('show only the active heads from open branches')),
3235 3236 ] + templateopts,
3236 3237 _('[-r REV] [REV]...')),
3237 3238 "help": (help_, [], _('[TOPIC]')),
3238 3239 "identify|id":
3239 3240 (identify,
3240 3241 [('r', 'rev', '', _('identify the specified revision')),
3241 3242 ('n', 'num', None, _('show local revision number')),
3242 3243 ('i', 'id', None, _('show global revision id')),
3243 3244 ('b', 'branch', None, _('show branch')),
3244 3245 ('t', 'tags', None, _('show tags'))],
3245 3246 _('[-nibt] [-r REV] [SOURCE]')),
3246 3247 "import|patch":
3247 3248 (import_,
3248 3249 [('p', 'strip', 1,
3249 3250 _('directory strip option for patch. This has the same\n'
3250 3251 'meaning as the corresponding patch option')),
3251 3252 ('b', 'base', '', _('base path')),
3252 3253 ('f', 'force', None,
3253 3254 _('skip check for outstanding uncommitted changes')),
3254 3255 ('', 'no-commit', None, _("don't commit, just update the working directory")),
3255 3256 ('', 'exact', None,
3256 3257 _('apply patch to the nodes from which it was generated')),
3257 3258 ('', 'import-branch', None,
3258 3259 _('Use any branch information in patch (implied by --exact)'))] +
3259 3260 commitopts + commitopts2 + similarityopts,
3260 3261 _('[OPTION]... PATCH...')),
3261 3262 "incoming|in":
3262 3263 (incoming,
3263 3264 [('f', 'force', None,
3264 3265 _('run even when remote repository is unrelated')),
3265 3266 ('n', 'newest-first', None, _('show newest record first')),
3266 3267 ('', 'bundle', '', _('file to store the bundles into')),
3267 3268 ('r', 'rev', [],
3268 3269 _('a specific revision up to which you would like to pull')),
3269 3270 ] + logopts + remoteopts,
3270 3271 _('[-p] [-n] [-M] [-f] [-r REV]...'
3271 3272 ' [--bundle FILENAME] [SOURCE]')),
3272 3273 "^init":
3273 3274 (init,
3274 3275 remoteopts,
3275 3276 _('[-e CMD] [--remotecmd CMD] [DEST]')),
3276 3277 "locate":
3277 3278 (locate,
3278 3279 [('r', 'rev', '', _('search the repository as it stood at rev')),
3279 3280 ('0', 'print0', None,
3280 3281 _('end filenames with NUL, for use with xargs')),
3281 3282 ('f', 'fullpath', None,
3282 3283 _('print complete paths from the filesystem root')),
3283 3284 ] + walkopts,
3284 3285 _('[OPTION]... [PATTERN]...')),
3285 3286 "^log|history":
3286 3287 (log,
3287 3288 [('f', 'follow', None,
3288 3289 _('follow changeset history, or file history across copies and renames')),
3289 3290 ('', 'follow-first', None,
3290 3291 _('only follow the first parent of merge changesets')),
3291 3292 ('d', 'date', '', _('show revisions matching date spec')),
3292 3293 ('C', 'copies', None, _('show copied files')),
3293 3294 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3294 3295 ('r', 'rev', [], _('show the specified revision or range')),
3295 3296 ('', 'removed', None, _('include revisions where files were removed')),
3296 3297 ('m', 'only-merges', None, _('show only merges')),
3297 3298 ('u', 'user', [], _('revisions committed by user')),
3298 3299 ('b', 'only-branch', [],
3299 3300 _('show only changesets within the given named branch')),
3300 3301 ('P', 'prune', [], _('do not display revision or any of its ancestors')),
3301 3302 ] + logopts + walkopts,
3302 3303 _('[OPTION]... [FILE]')),
3303 3304 "manifest":
3304 3305 (manifest,
3305 3306 [('r', 'rev', '', _('revision to display'))],
3306 3307 _('[-r REV]')),
3307 3308 "^merge":
3308 3309 (merge,
3309 3310 [('f', 'force', None, _('force a merge with outstanding changes')),
3310 3311 ('r', 'rev', '', _('revision to merge')),
3311 3312 ],
3312 3313 _('[-f] [[-r] REV]')),
3313 3314 "outgoing|out":
3314 3315 (outgoing,
3315 3316 [('f', 'force', None,
3316 3317 _('run even when remote repository is unrelated')),
3317 3318 ('r', 'rev', [],
3318 3319 _('a specific revision up to which you would like to push')),
3319 3320 ('n', 'newest-first', None, _('show newest record first')),
3320 3321 ] + logopts + remoteopts,
3321 3322 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3322 3323 "^parents":
3323 3324 (parents,
3324 3325 [('r', 'rev', '', _('show parents from the specified revision')),
3325 3326 ] + templateopts,
3326 3327 _('hg parents [-r REV] [FILE]')),
3327 3328 "paths": (paths, [], _('[NAME]')),
3328 3329 "^pull":
3329 3330 (pull,
3330 3331 [('u', 'update', None,
3331 3332 _('update to new tip if changesets were pulled')),
3332 3333 ('f', 'force', None,
3333 3334 _('run even when remote repository is unrelated')),
3334 3335 ('r', 'rev', [],
3335 3336 _('a specific revision up to which you would like to pull')),
3336 3337 ] + remoteopts,
3337 3338 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3338 3339 "^push":
3339 3340 (push,
3340 3341 [('f', 'force', None, _('force push')),
3341 3342 ('r', 'rev', [],
3342 3343 _('a specific revision up to which you would like to push')),
3343 3344 ] + remoteopts,
3344 3345 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3345 3346 "recover": (recover, []),
3346 3347 "^remove|rm":
3347 3348 (remove,
3348 3349 [('A', 'after', None, _('record delete for missing files')),
3349 3350 ('f', 'force', None,
3350 3351 _('remove (and delete) file even if added or modified')),
3351 3352 ] + walkopts,
3352 3353 _('[OPTION]... FILE...')),
3353 3354 "rename|mv":
3354 3355 (rename,
3355 3356 [('A', 'after', None, _('record a rename that has already occurred')),
3356 3357 ('f', 'force', None,
3357 3358 _('forcibly copy over an existing managed file')),
3358 3359 ] + walkopts + dryrunopts,
3359 3360 _('[OPTION]... SOURCE... DEST')),
3360 3361 "resolve":
3361 3362 (resolve,
3362 3363 [('a', 'all', None, _('remerge all unresolved files')),
3363 3364 ('l', 'list', None, _('list state of files needing merge')),
3364 3365 ('m', 'mark', None, _('mark files as resolved')),
3365 3366 ('u', 'unmark', None, _('unmark files as resolved'))]
3366 3367 + walkopts,
3367 3368 _('[OPTION]... [FILE]...')),
3368 3369 "revert":
3369 3370 (revert,
3370 3371 [('a', 'all', None, _('revert all changes when no arguments given')),
3371 3372 ('d', 'date', '', _('tipmost revision matching date')),
3372 3373 ('r', 'rev', '', _('revision to revert to')),
3373 3374 ('', 'no-backup', None, _('do not save backup copies of files')),
3374 3375 ] + walkopts + dryrunopts,
3375 3376 _('[OPTION]... [-r REV] [NAME]...')),
3376 3377 "rollback": (rollback, []),
3377 3378 "root": (root, []),
3378 3379 "^serve":
3379 3380 (serve,
3380 3381 [('A', 'accesslog', '', _('name of access log file to write to')),
3381 3382 ('d', 'daemon', None, _('run server in background')),
3382 3383 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3383 3384 ('E', 'errorlog', '', _('name of error log file to write to')),
3384 3385 ('p', 'port', 0, _('port to listen on (default: 8000)')),
3385 3386 ('a', 'address', '', _('address to listen on (default: all interfaces)')),
3386 3387 ('', 'prefix', '', _('prefix path to serve from (default: server root)')),
3387 3388 ('n', 'name', '',
3388 3389 _('name to show in web pages (default: working directory)')),
3389 3390 ('', 'webdir-conf', '', _('name of the webdir config file'
3390 3391 ' (serve more than one repository)')),
3391 3392 ('', 'pid-file', '', _('name of file to write process ID to')),
3392 3393 ('', 'stdio', None, _('for remote clients')),
3393 3394 ('t', 'templates', '', _('web templates to use')),
3394 3395 ('', 'style', '', _('template style to use')),
3395 3396 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3396 3397 ('', 'certificate', '', _('SSL certificate file'))],
3397 3398 _('[OPTION]...')),
3398 3399 "showconfig|debugconfig":
3399 3400 (showconfig,
3400 3401 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3401 3402 _('[-u] [NAME]...')),
3402 3403 "^status|st":
3403 3404 (status,
3404 3405 [('A', 'all', None, _('show status of all files')),
3405 3406 ('m', 'modified', None, _('show only modified files')),
3406 3407 ('a', 'added', None, _('show only added files')),
3407 3408 ('r', 'removed', None, _('show only removed files')),
3408 3409 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3409 3410 ('c', 'clean', None, _('show only files without changes')),
3410 3411 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3411 3412 ('i', 'ignored', None, _('show only ignored files')),
3412 3413 ('n', 'no-status', None, _('hide status prefix')),
3413 3414 ('C', 'copies', None, _('show source of copied files')),
3414 3415 ('0', 'print0', None,
3415 3416 _('end filenames with NUL, for use with xargs')),
3416 3417 ('', 'rev', [], _('show difference from revision')),
3417 3418 ] + walkopts,
3418 3419 _('[OPTION]... [FILE]...')),
3419 3420 "tag":
3420 3421 (tag,
3421 3422 [('f', 'force', None, _('replace existing tag')),
3422 3423 ('l', 'local', None, _('make the tag local')),
3423 3424 ('r', 'rev', '', _('revision to tag')),
3424 3425 ('', 'remove', None, _('remove a tag')),
3425 3426 # -l/--local is already there, commitopts cannot be used
3426 3427 ('m', 'message', '', _('use <text> as commit message')),
3427 3428 ] + commitopts2,
3428 3429 _('[-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
3429 3430 "tags": (tags, []),
3430 3431 "tip":
3431 3432 (tip,
3432 3433 [('p', 'patch', None, _('show patch')),
3433 3434 ('g', 'git', None, _('use git extended diff format')),
3434 3435 ] + templateopts,
3435 3436 _('[-p]')),
3436 3437 "unbundle":
3437 3438 (unbundle,
3438 3439 [('u', 'update', None,
3439 3440 _('update to new tip if changesets were unbundled'))],
3440 3441 _('[-u] FILE...')),
3441 3442 "^update|up|checkout|co":
3442 3443 (update,
3443 3444 [('C', 'clean', None, _('overwrite locally modified files (no backup)')),
3444 3445 ('d', 'date', '', _('tipmost revision matching date')),
3445 3446 ('r', 'rev', '', _('revision'))],
3446 3447 _('[-C] [-d DATE] [[-r] REV]')),
3447 3448 "verify": (verify, []),
3448 3449 "version": (version_, []),
3449 3450 }
3450 3451
3451 3452 norepo = ("clone init version help debugcommands debugcomplete debugdata"
3452 3453 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3453 3454 optionalrepo = ("identify paths serve showconfig debugancestor")
@@ -1,219 +1,219
1 1 notify extension - hook extension to email notifications on commits/pushes
2 2
3 3 Subscriptions can be managed through hgrc. Default mode is to print
4 4 messages to stdout, for testing and configuring.
5 5
6 6 To use, configure notify extension and enable in hgrc like this:
7 7
8 8 [extensions]
9 9 hgext.notify =
10 10
11 11 [hooks]
12 12 # one email for each incoming changeset
13 13 incoming.notify = python:hgext.notify.hook
14 14 # batch emails when many changesets incoming at one time
15 15 changegroup.notify = python:hgext.notify.hook
16 16
17 17 [notify]
18 18 # config items go in here
19 19
20 20 config items:
21 21
22 22 REQUIRED:
23 23 config = /path/to/file # file containing subscriptions
24 24
25 25 OPTIONAL:
26 26 test = True # print messages to stdout for testing
27 27 strip = 3 # number of slashes to strip for url paths
28 28 domain = example.com # domain to use if committer missing domain
29 29 style = ... # style file to use when formatting email
30 30 template = ... # template to use when formatting email
31 31 incoming = ... # template to use when run as incoming hook
32 32 changegroup = ... # template when run as changegroup hook
33 33 maxdiff = 300 # max lines of diffs to include (0=none, -1=all)
34 34 maxsubject = 67 # truncate subject line longer than this
35 35 diffstat = True # add a diffstat before the diff content
36 36 sources = serve # notify if source of incoming changes in this list
37 37 # (serve == ssh or http, push, pull, bundle)
38 38 [email]
39 39 from = user@host.com # email address to send as if none given
40 40 [web]
41 41 baseurl = http://hgserver/... # root of hg web site for browsing commits
42 42
43 43 notify config file has same format as regular hgrc. it has two
44 44 sections so you can express subscriptions in whatever way is handier
45 45 for you.
46 46
47 47 [usersubs]
48 48 # key is subscriber email, value is ","-separated list of glob patterns
49 49 user@host = pattern
50 50
51 51 [reposubs]
52 52 # key is glob pattern, value is ","-separated list of subscriber emails
53 53 pattern = user@host
54 54
55 55 glob patterns are matched against path to repository root.
56 56
57 if you like, you can put notify config file in repository that users can
58 push changes to, they can manage their own subscriptions.
57 if you like, you can put notify config file in repository that users
58 can push changes to, they can manage their own subscriptions.
59 59
60 60 no commands defined
61 61 % commit
62 62 adding a
63 63 % clone
64 64 updating working directory
65 65 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
66 66 % commit
67 67 % pull (minimal config)
68 68 pulling from ../a
69 69 searching for changes
70 70 adding changesets
71 71 adding manifests
72 72 adding file changes
73 73 added 1 changesets with 1 changes to 1 files
74 74 Content-Type: text/plain; charset="us-ascii"
75 75 MIME-Version: 1.0
76 76 Content-Transfer-Encoding: 7bit
77 77 Date:
78 78 Subject: changeset in test-notify/b: b
79 79 From: test
80 80 X-Hg-Notification: changeset 0647d048b600
81 81 Message-Id:
82 82 To: baz, foo@bar
83 83
84 84 changeset 0647d048b600 in test-notify/b
85 85 details: test-notify/b?cmd=changeset;node=0647d048b600
86 86 description: b
87 87
88 88 diffs (6 lines):
89 89
90 90 diff -r cb9a9f314b8b -r 0647d048b600 a
91 91 --- a/a Thu Jan 01 00:00:00 1970 +0000
92 92 +++ b/a Thu Jan 01 00:00:01 1970 +0000
93 93 @@ -1,1 +1,2 @@
94 94 a
95 95 +a
96 96 (run 'hg update' to get a working copy)
97 97 % fail for config file is missing
98 98 rolling back last transaction
99 99 pull failed
100 100 % pull
101 101 rolling back last transaction
102 102 pulling from ../a
103 103 searching for changes
104 104 adding changesets
105 105 adding manifests
106 106 adding file changes
107 107 added 1 changesets with 1 changes to 1 files
108 108 Content-Type: text/plain; charset="us-ascii"
109 109 MIME-Version: 1.0
110 110 Content-Transfer-Encoding: 7bit
111 111 X-Test: foo
112 112 Date:
113 113 Subject: b
114 114 From: test@test.com
115 115 X-Hg-Notification: changeset 0647d048b600
116 116 Message-Id:
117 117 To: baz@test.com, foo@bar
118 118
119 119 changeset 0647d048b600
120 120 description:
121 121 b
122 122 diffs (6 lines):
123 123
124 124 diff -r cb9a9f314b8b -r 0647d048b600 a
125 125 --- a/a Thu Jan 01 00:00:00 1970 +0000
126 126 +++ b/a Thu Jan 01 00:00:01 1970 +0000
127 127 @@ -1,1 +1,2 @@
128 128 a
129 129 +a
130 130 (run 'hg update' to get a working copy)
131 131 % pull
132 132 rolling back last transaction
133 133 pulling from ../a
134 134 searching for changes
135 135 adding changesets
136 136 adding manifests
137 137 adding file changes
138 138 added 1 changesets with 1 changes to 1 files
139 139 Content-Type: text/plain; charset="us-ascii"
140 140 MIME-Version: 1.0
141 141 Content-Transfer-Encoding: 7bit
142 142 X-Test: foo
143 143 Date:
144 144 Subject: b
145 145 From: test@test.com
146 146 X-Hg-Notification: changeset 0647d048b600
147 147 Message-Id:
148 148 To: baz@test.com, foo@bar
149 149
150 150 changeset 0647d048b600
151 151 description:
152 152 b
153 153 diffstat:
154 154
155 155 a | 1 +
156 156 1 files changed, 1 insertions(+), 0 deletions(-)
157 157
158 158 diffs (6 lines):
159 159
160 160 diff -r cb9a9f314b8b -r 0647d048b600 a
161 161 --- a/a Thu Jan 01 00:00:00 1970 +0000
162 162 +++ b/a Thu Jan 01 00:00:01 1970 +0000
163 163 @@ -1,1 +1,2 @@
164 164 a
165 165 +a
166 166 (run 'hg update' to get a working copy)
167 167 % test merge
168 168 1 files updated, 0 files merged, 0 files removed, 0 files unresolved
169 169 created new head
170 170 0 files updated, 0 files merged, 0 files removed, 0 files unresolved
171 171 (branch merge, don't forget to commit)
172 172 pulling from ../a
173 173 searching for changes
174 174 adding changesets
175 175 adding manifests
176 176 adding file changes
177 177 added 2 changesets with 0 changes to 1 files
178 178 Content-Type: text/plain; charset="us-ascii"
179 179 MIME-Version: 1.0
180 180 Content-Transfer-Encoding: 7bit
181 181 X-Test: foo
182 182 Date:
183 183 Subject: adda2
184 184 From: test@test.com
185 185 X-Hg-Notification: changeset 0a184ce6067f
186 186 Message-Id:
187 187 To: baz@test.com, foo@bar
188 188
189 189 changeset 0a184ce6067f
190 190 description:
191 191 adda2
192 192 diffstat:
193 193
194 194 a | 1 +
195 195 1 files changed, 1 insertions(+), 0 deletions(-)
196 196
197 197 diffs (6 lines):
198 198
199 199 diff -r cb9a9f314b8b -r 0a184ce6067f a
200 200 --- a/a Thu Jan 01 00:00:00 1970 +0000
201 201 +++ b/a Thu Jan 01 00:00:02 1970 +0000
202 202 @@ -1,1 +1,2 @@
203 203 a
204 204 +a
205 205 Content-Type: text/plain; charset="us-ascii"
206 206 MIME-Version: 1.0
207 207 Content-Transfer-Encoding: 7bit
208 208 X-Test: foo
209 209 Date:
210 210 Subject: merge
211 211 From: test@test.com
212 212 X-Hg-Notification: changeset 22c88b85aa27
213 213 Message-Id:
214 214 To: baz@test.com, foo@bar
215 215
216 216 changeset 22c88b85aa27
217 217 description:
218 218 merge
219 219 (run 'hg update' to get a working copy)
General Comments 0
You need to be logged in to leave comments. Login now