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