##// END OF EJS Templates
commands: refactor diff --stat and qdiff --stat...
Yuya Nishihara -
r11050:5d35f7d9 default
parent child Browse files
Show More
@@ -1,2821 +1,2805 b''
1 # mq.py - patch queues for mercurial
1 # mq.py - patch queues for mercurial
2 #
2 #
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 '''manage a stack of patches
8 '''manage a stack of patches
9
9
10 This extension lets you work with a stack of patches in a Mercurial
10 This extension lets you work with a stack of patches in a Mercurial
11 repository. It manages two stacks of patches - all known patches, and
11 repository. It manages two stacks of patches - all known patches, and
12 applied patches (subset of known patches).
12 applied patches (subset of known patches).
13
13
14 Known patches are represented as patch files in the .hg/patches
14 Known patches are represented as patch files in the .hg/patches
15 directory. Applied patches are both patch files and changesets.
15 directory. Applied patches are both patch files and changesets.
16
16
17 Common tasks (use :hg:`help command` for more details)::
17 Common tasks (use :hg:`help command` for more details)::
18
18
19 create new patch qnew
19 create new patch qnew
20 import existing patch qimport
20 import existing patch qimport
21
21
22 print patch series qseries
22 print patch series qseries
23 print applied patches qapplied
23 print applied patches qapplied
24
24
25 add known patch to applied stack qpush
25 add known patch to applied stack qpush
26 remove patch from applied stack qpop
26 remove patch from applied stack qpop
27 refresh contents of top applied patch qrefresh
27 refresh contents of top applied patch qrefresh
28
28
29 By default, mq will automatically use git patches when required to
29 By default, mq will automatically use git patches when required to
30 avoid losing file mode changes, copy records, binary files or empty
30 avoid losing file mode changes, copy records, binary files or empty
31 files creations or deletions. This behaviour can be configured with::
31 files creations or deletions. This behaviour can be configured with::
32
32
33 [mq]
33 [mq]
34 git = auto/keep/yes/no
34 git = auto/keep/yes/no
35
35
36 If set to 'keep', mq will obey the [diff] section configuration while
36 If set to 'keep', mq will obey the [diff] section configuration while
37 preserving existing git patches upon qrefresh. If set to 'yes' or
37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 'no', mq will override the [diff] section and always generate git or
38 'no', mq will override the [diff] section and always generate git or
39 regular patches, possibly losing data in the second case.
39 regular patches, possibly losing data in the second case.
40 '''
40 '''
41
41
42 from mercurial.i18n import _
42 from mercurial.i18n import _
43 from mercurial.node import bin, hex, short, nullid, nullrev
43 from mercurial.node import bin, hex, short, nullid, nullrev
44 from mercurial.lock import release
44 from mercurial.lock import release
45 from mercurial import commands, cmdutil, hg, patch, util
45 from mercurial import commands, cmdutil, hg, patch, util
46 from mercurial import repair, extensions, url, error
46 from mercurial import repair, extensions, url, error
47 import os, sys, re, errno
47 import os, sys, re, errno
48
48
49 commands.norepo += " qclone"
49 commands.norepo += " qclone"
50
50
51 # Patch names looks like unix-file names.
51 # Patch names looks like unix-file names.
52 # They must be joinable with queue directory and result in the patch path.
52 # They must be joinable with queue directory and result in the patch path.
53 normname = util.normpath
53 normname = util.normpath
54
54
55 class statusentry(object):
55 class statusentry(object):
56 def __init__(self, node, name):
56 def __init__(self, node, name):
57 self.node, self.name = node, name
57 self.node, self.name = node, name
58
58
59 def __str__(self):
59 def __str__(self):
60 return hex(self.node) + ':' + self.name
60 return hex(self.node) + ':' + self.name
61
61
62 class patchheader(object):
62 class patchheader(object):
63 def __init__(self, pf, plainmode=False):
63 def __init__(self, pf, plainmode=False):
64 def eatdiff(lines):
64 def eatdiff(lines):
65 while lines:
65 while lines:
66 l = lines[-1]
66 l = lines[-1]
67 if (l.startswith("diff -") or
67 if (l.startswith("diff -") or
68 l.startswith("Index:") or
68 l.startswith("Index:") or
69 l.startswith("===========")):
69 l.startswith("===========")):
70 del lines[-1]
70 del lines[-1]
71 else:
71 else:
72 break
72 break
73 def eatempty(lines):
73 def eatempty(lines):
74 while lines:
74 while lines:
75 if not lines[-1].strip():
75 if not lines[-1].strip():
76 del lines[-1]
76 del lines[-1]
77 else:
77 else:
78 break
78 break
79
79
80 message = []
80 message = []
81 comments = []
81 comments = []
82 user = None
82 user = None
83 date = None
83 date = None
84 parent = None
84 parent = None
85 format = None
85 format = None
86 subject = None
86 subject = None
87 diffstart = 0
87 diffstart = 0
88
88
89 for line in file(pf):
89 for line in file(pf):
90 line = line.rstrip()
90 line = line.rstrip()
91 if (line.startswith('diff --git')
91 if (line.startswith('diff --git')
92 or (diffstart and line.startswith('+++ '))):
92 or (diffstart and line.startswith('+++ '))):
93 diffstart = 2
93 diffstart = 2
94 break
94 break
95 diffstart = 0 # reset
95 diffstart = 0 # reset
96 if line.startswith("--- "):
96 if line.startswith("--- "):
97 diffstart = 1
97 diffstart = 1
98 continue
98 continue
99 elif format == "hgpatch":
99 elif format == "hgpatch":
100 # parse values when importing the result of an hg export
100 # parse values when importing the result of an hg export
101 if line.startswith("# User "):
101 if line.startswith("# User "):
102 user = line[7:]
102 user = line[7:]
103 elif line.startswith("# Date "):
103 elif line.startswith("# Date "):
104 date = line[7:]
104 date = line[7:]
105 elif line.startswith("# Parent "):
105 elif line.startswith("# Parent "):
106 parent = line[9:]
106 parent = line[9:]
107 elif not line.startswith("# ") and line:
107 elif not line.startswith("# ") and line:
108 message.append(line)
108 message.append(line)
109 format = None
109 format = None
110 elif line == '# HG changeset patch':
110 elif line == '# HG changeset patch':
111 message = []
111 message = []
112 format = "hgpatch"
112 format = "hgpatch"
113 elif (format != "tagdone" and (line.startswith("Subject: ") or
113 elif (format != "tagdone" and (line.startswith("Subject: ") or
114 line.startswith("subject: "))):
114 line.startswith("subject: "))):
115 subject = line[9:]
115 subject = line[9:]
116 format = "tag"
116 format = "tag"
117 elif (format != "tagdone" and (line.startswith("From: ") or
117 elif (format != "tagdone" and (line.startswith("From: ") or
118 line.startswith("from: "))):
118 line.startswith("from: "))):
119 user = line[6:]
119 user = line[6:]
120 format = "tag"
120 format = "tag"
121 elif (format != "tagdone" and (line.startswith("Date: ") or
121 elif (format != "tagdone" and (line.startswith("Date: ") or
122 line.startswith("date: "))):
122 line.startswith("date: "))):
123 date = line[6:]
123 date = line[6:]
124 format = "tag"
124 format = "tag"
125 elif format == "tag" and line == "":
125 elif format == "tag" and line == "":
126 # when looking for tags (subject: from: etc) they
126 # when looking for tags (subject: from: etc) they
127 # end once you find a blank line in the source
127 # end once you find a blank line in the source
128 format = "tagdone"
128 format = "tagdone"
129 elif message or line:
129 elif message or line:
130 message.append(line)
130 message.append(line)
131 comments.append(line)
131 comments.append(line)
132
132
133 eatdiff(message)
133 eatdiff(message)
134 eatdiff(comments)
134 eatdiff(comments)
135 eatempty(message)
135 eatempty(message)
136 eatempty(comments)
136 eatempty(comments)
137
137
138 # make sure message isn't empty
138 # make sure message isn't empty
139 if format and format.startswith("tag") and subject:
139 if format and format.startswith("tag") and subject:
140 message.insert(0, "")
140 message.insert(0, "")
141 message.insert(0, subject)
141 message.insert(0, subject)
142
142
143 self.message = message
143 self.message = message
144 self.comments = comments
144 self.comments = comments
145 self.user = user
145 self.user = user
146 self.date = date
146 self.date = date
147 self.parent = parent
147 self.parent = parent
148 self.haspatch = diffstart > 1
148 self.haspatch = diffstart > 1
149 self.plainmode = plainmode
149 self.plainmode = plainmode
150
150
151 def setuser(self, user):
151 def setuser(self, user):
152 if not self.updateheader(['From: ', '# User '], user):
152 if not self.updateheader(['From: ', '# User '], user):
153 try:
153 try:
154 patchheaderat = self.comments.index('# HG changeset patch')
154 patchheaderat = self.comments.index('# HG changeset patch')
155 self.comments.insert(patchheaderat + 1, '# User ' + user)
155 self.comments.insert(patchheaderat + 1, '# User ' + user)
156 except ValueError:
156 except ValueError:
157 if self.plainmode or self._hasheader(['Date: ']):
157 if self.plainmode or self._hasheader(['Date: ']):
158 self.comments = ['From: ' + user] + self.comments
158 self.comments = ['From: ' + user] + self.comments
159 else:
159 else:
160 tmp = ['# HG changeset patch', '# User ' + user, '']
160 tmp = ['# HG changeset patch', '# User ' + user, '']
161 self.comments = tmp + self.comments
161 self.comments = tmp + self.comments
162 self.user = user
162 self.user = user
163
163
164 def setdate(self, date):
164 def setdate(self, date):
165 if not self.updateheader(['Date: ', '# Date '], date):
165 if not self.updateheader(['Date: ', '# Date '], date):
166 try:
166 try:
167 patchheaderat = self.comments.index('# HG changeset patch')
167 patchheaderat = self.comments.index('# HG changeset patch')
168 self.comments.insert(patchheaderat + 1, '# Date ' + date)
168 self.comments.insert(patchheaderat + 1, '# Date ' + date)
169 except ValueError:
169 except ValueError:
170 if self.plainmode or self._hasheader(['From: ']):
170 if self.plainmode or self._hasheader(['From: ']):
171 self.comments = ['Date: ' + date] + self.comments
171 self.comments = ['Date: ' + date] + self.comments
172 else:
172 else:
173 tmp = ['# HG changeset patch', '# Date ' + date, '']
173 tmp = ['# HG changeset patch', '# Date ' + date, '']
174 self.comments = tmp + self.comments
174 self.comments = tmp + self.comments
175 self.date = date
175 self.date = date
176
176
177 def setparent(self, parent):
177 def setparent(self, parent):
178 if not self.updateheader(['# Parent '], parent):
178 if not self.updateheader(['# Parent '], parent):
179 try:
179 try:
180 patchheaderat = self.comments.index('# HG changeset patch')
180 patchheaderat = self.comments.index('# HG changeset patch')
181 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
181 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
182 except ValueError:
182 except ValueError:
183 pass
183 pass
184 self.parent = parent
184 self.parent = parent
185
185
186 def setmessage(self, message):
186 def setmessage(self, message):
187 if self.comments:
187 if self.comments:
188 self._delmsg()
188 self._delmsg()
189 self.message = [message]
189 self.message = [message]
190 self.comments += self.message
190 self.comments += self.message
191
191
192 def updateheader(self, prefixes, new):
192 def updateheader(self, prefixes, new):
193 '''Update all references to a field in the patch header.
193 '''Update all references to a field in the patch header.
194 Return whether the field is present.'''
194 Return whether the field is present.'''
195 res = False
195 res = False
196 for prefix in prefixes:
196 for prefix in prefixes:
197 for i in xrange(len(self.comments)):
197 for i in xrange(len(self.comments)):
198 if self.comments[i].startswith(prefix):
198 if self.comments[i].startswith(prefix):
199 self.comments[i] = prefix + new
199 self.comments[i] = prefix + new
200 res = True
200 res = True
201 break
201 break
202 return res
202 return res
203
203
204 def _hasheader(self, prefixes):
204 def _hasheader(self, prefixes):
205 '''Check if a header starts with any of the given prefixes.'''
205 '''Check if a header starts with any of the given prefixes.'''
206 for prefix in prefixes:
206 for prefix in prefixes:
207 for comment in self.comments:
207 for comment in self.comments:
208 if comment.startswith(prefix):
208 if comment.startswith(prefix):
209 return True
209 return True
210 return False
210 return False
211
211
212 def __str__(self):
212 def __str__(self):
213 if not self.comments:
213 if not self.comments:
214 return ''
214 return ''
215 return '\n'.join(self.comments) + '\n\n'
215 return '\n'.join(self.comments) + '\n\n'
216
216
217 def _delmsg(self):
217 def _delmsg(self):
218 '''Remove existing message, keeping the rest of the comments fields.
218 '''Remove existing message, keeping the rest of the comments fields.
219 If comments contains 'subject: ', message will prepend
219 If comments contains 'subject: ', message will prepend
220 the field and a blank line.'''
220 the field and a blank line.'''
221 if self.message:
221 if self.message:
222 subj = 'subject: ' + self.message[0].lower()
222 subj = 'subject: ' + self.message[0].lower()
223 for i in xrange(len(self.comments)):
223 for i in xrange(len(self.comments)):
224 if subj == self.comments[i].lower():
224 if subj == self.comments[i].lower():
225 del self.comments[i]
225 del self.comments[i]
226 self.message = self.message[2:]
226 self.message = self.message[2:]
227 break
227 break
228 ci = 0
228 ci = 0
229 for mi in self.message:
229 for mi in self.message:
230 while mi != self.comments[ci]:
230 while mi != self.comments[ci]:
231 ci += 1
231 ci += 1
232 del self.comments[ci]
232 del self.comments[ci]
233
233
234 class queue(object):
234 class queue(object):
235 def __init__(self, ui, path, patchdir=None):
235 def __init__(self, ui, path, patchdir=None):
236 self.basepath = path
236 self.basepath = path
237 self.path = patchdir or os.path.join(path, "patches")
237 self.path = patchdir or os.path.join(path, "patches")
238 self.opener = util.opener(self.path)
238 self.opener = util.opener(self.path)
239 self.ui = ui
239 self.ui = ui
240 self.applied_dirty = 0
240 self.applied_dirty = 0
241 self.series_dirty = 0
241 self.series_dirty = 0
242 self.series_path = "series"
242 self.series_path = "series"
243 self.status_path = "status"
243 self.status_path = "status"
244 self.guards_path = "guards"
244 self.guards_path = "guards"
245 self.active_guards = None
245 self.active_guards = None
246 self.guards_dirty = False
246 self.guards_dirty = False
247 # Handle mq.git as a bool with extended values
247 # Handle mq.git as a bool with extended values
248 try:
248 try:
249 gitmode = ui.configbool('mq', 'git', None)
249 gitmode = ui.configbool('mq', 'git', None)
250 if gitmode is None:
250 if gitmode is None:
251 raise error.ConfigError()
251 raise error.ConfigError()
252 self.gitmode = gitmode and 'yes' or 'no'
252 self.gitmode = gitmode and 'yes' or 'no'
253 except error.ConfigError:
253 except error.ConfigError:
254 self.gitmode = ui.config('mq', 'git', 'auto').lower()
254 self.gitmode = ui.config('mq', 'git', 'auto').lower()
255 self.plainmode = ui.configbool('mq', 'plain', False)
255 self.plainmode = ui.configbool('mq', 'plain', False)
256
256
257 @util.propertycache
257 @util.propertycache
258 def applied(self):
258 def applied(self):
259 if os.path.exists(self.join(self.status_path)):
259 if os.path.exists(self.join(self.status_path)):
260 def parse(l):
260 def parse(l):
261 n, name = l.split(':', 1)
261 n, name = l.split(':', 1)
262 return statusentry(bin(n), name)
262 return statusentry(bin(n), name)
263 lines = self.opener(self.status_path).read().splitlines()
263 lines = self.opener(self.status_path).read().splitlines()
264 return [parse(l) for l in lines]
264 return [parse(l) for l in lines]
265 return []
265 return []
266
266
267 @util.propertycache
267 @util.propertycache
268 def full_series(self):
268 def full_series(self):
269 if os.path.exists(self.join(self.series_path)):
269 if os.path.exists(self.join(self.series_path)):
270 return self.opener(self.series_path).read().splitlines()
270 return self.opener(self.series_path).read().splitlines()
271 return []
271 return []
272
272
273 @util.propertycache
273 @util.propertycache
274 def series(self):
274 def series(self):
275 self.parse_series()
275 self.parse_series()
276 return self.series
276 return self.series
277
277
278 @util.propertycache
278 @util.propertycache
279 def series_guards(self):
279 def series_guards(self):
280 self.parse_series()
280 self.parse_series()
281 return self.series_guards
281 return self.series_guards
282
282
283 def invalidate(self):
283 def invalidate(self):
284 for a in 'applied full_series series series_guards'.split():
284 for a in 'applied full_series series series_guards'.split():
285 if a in self.__dict__:
285 if a in self.__dict__:
286 delattr(self, a)
286 delattr(self, a)
287 self.applied_dirty = 0
287 self.applied_dirty = 0
288 self.series_dirty = 0
288 self.series_dirty = 0
289 self.guards_dirty = False
289 self.guards_dirty = False
290 self.active_guards = None
290 self.active_guards = None
291
291
292 def diffopts(self, opts={}, patchfn=None):
292 def diffopts(self, opts={}, patchfn=None):
293 diffopts = patch.diffopts(self.ui, opts)
293 diffopts = patch.diffopts(self.ui, opts)
294 if self.gitmode == 'auto':
294 if self.gitmode == 'auto':
295 diffopts.upgrade = True
295 diffopts.upgrade = True
296 elif self.gitmode == 'keep':
296 elif self.gitmode == 'keep':
297 pass
297 pass
298 elif self.gitmode in ('yes', 'no'):
298 elif self.gitmode in ('yes', 'no'):
299 diffopts.git = self.gitmode == 'yes'
299 diffopts.git = self.gitmode == 'yes'
300 else:
300 else:
301 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
301 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
302 ' got %s') % self.gitmode)
302 ' got %s') % self.gitmode)
303 if patchfn:
303 if patchfn:
304 diffopts = self.patchopts(diffopts, patchfn)
304 diffopts = self.patchopts(diffopts, patchfn)
305 return diffopts
305 return diffopts
306
306
307 def patchopts(self, diffopts, *patches):
307 def patchopts(self, diffopts, *patches):
308 """Return a copy of input diff options with git set to true if
308 """Return a copy of input diff options with git set to true if
309 referenced patch is a git patch and should be preserved as such.
309 referenced patch is a git patch and should be preserved as such.
310 """
310 """
311 diffopts = diffopts.copy()
311 diffopts = diffopts.copy()
312 if not diffopts.git and self.gitmode == 'keep':
312 if not diffopts.git and self.gitmode == 'keep':
313 for patchfn in patches:
313 for patchfn in patches:
314 patchf = self.opener(patchfn, 'r')
314 patchf = self.opener(patchfn, 'r')
315 # if the patch was a git patch, refresh it as a git patch
315 # if the patch was a git patch, refresh it as a git patch
316 for line in patchf:
316 for line in patchf:
317 if line.startswith('diff --git'):
317 if line.startswith('diff --git'):
318 diffopts.git = True
318 diffopts.git = True
319 break
319 break
320 patchf.close()
320 patchf.close()
321 return diffopts
321 return diffopts
322
322
323 def join(self, *p):
323 def join(self, *p):
324 return os.path.join(self.path, *p)
324 return os.path.join(self.path, *p)
325
325
326 def find_series(self, patch):
326 def find_series(self, patch):
327 def matchpatch(l):
327 def matchpatch(l):
328 l = l.split('#', 1)[0]
328 l = l.split('#', 1)[0]
329 return l.strip() == patch
329 return l.strip() == patch
330 for index, l in enumerate(self.full_series):
330 for index, l in enumerate(self.full_series):
331 if matchpatch(l):
331 if matchpatch(l):
332 return index
332 return index
333 return None
333 return None
334
334
335 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
335 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
336
336
337 def parse_series(self):
337 def parse_series(self):
338 self.series = []
338 self.series = []
339 self.series_guards = []
339 self.series_guards = []
340 for l in self.full_series:
340 for l in self.full_series:
341 h = l.find('#')
341 h = l.find('#')
342 if h == -1:
342 if h == -1:
343 patch = l
343 patch = l
344 comment = ''
344 comment = ''
345 elif h == 0:
345 elif h == 0:
346 continue
346 continue
347 else:
347 else:
348 patch = l[:h]
348 patch = l[:h]
349 comment = l[h:]
349 comment = l[h:]
350 patch = patch.strip()
350 patch = patch.strip()
351 if patch:
351 if patch:
352 if patch in self.series:
352 if patch in self.series:
353 raise util.Abort(_('%s appears more than once in %s') %
353 raise util.Abort(_('%s appears more than once in %s') %
354 (patch, self.join(self.series_path)))
354 (patch, self.join(self.series_path)))
355 self.series.append(patch)
355 self.series.append(patch)
356 self.series_guards.append(self.guard_re.findall(comment))
356 self.series_guards.append(self.guard_re.findall(comment))
357
357
358 def check_guard(self, guard):
358 def check_guard(self, guard):
359 if not guard:
359 if not guard:
360 return _('guard cannot be an empty string')
360 return _('guard cannot be an empty string')
361 bad_chars = '# \t\r\n\f'
361 bad_chars = '# \t\r\n\f'
362 first = guard[0]
362 first = guard[0]
363 if first in '-+':
363 if first in '-+':
364 return (_('guard %r starts with invalid character: %r') %
364 return (_('guard %r starts with invalid character: %r') %
365 (guard, first))
365 (guard, first))
366 for c in bad_chars:
366 for c in bad_chars:
367 if c in guard:
367 if c in guard:
368 return _('invalid character in guard %r: %r') % (guard, c)
368 return _('invalid character in guard %r: %r') % (guard, c)
369
369
370 def set_active(self, guards):
370 def set_active(self, guards):
371 for guard in guards:
371 for guard in guards:
372 bad = self.check_guard(guard)
372 bad = self.check_guard(guard)
373 if bad:
373 if bad:
374 raise util.Abort(bad)
374 raise util.Abort(bad)
375 guards = sorted(set(guards))
375 guards = sorted(set(guards))
376 self.ui.debug('active guards: %s\n' % ' '.join(guards))
376 self.ui.debug('active guards: %s\n' % ' '.join(guards))
377 self.active_guards = guards
377 self.active_guards = guards
378 self.guards_dirty = True
378 self.guards_dirty = True
379
379
380 def active(self):
380 def active(self):
381 if self.active_guards is None:
381 if self.active_guards is None:
382 self.active_guards = []
382 self.active_guards = []
383 try:
383 try:
384 guards = self.opener(self.guards_path).read().split()
384 guards = self.opener(self.guards_path).read().split()
385 except IOError, err:
385 except IOError, err:
386 if err.errno != errno.ENOENT:
386 if err.errno != errno.ENOENT:
387 raise
387 raise
388 guards = []
388 guards = []
389 for i, guard in enumerate(guards):
389 for i, guard in enumerate(guards):
390 bad = self.check_guard(guard)
390 bad = self.check_guard(guard)
391 if bad:
391 if bad:
392 self.ui.warn('%s:%d: %s\n' %
392 self.ui.warn('%s:%d: %s\n' %
393 (self.join(self.guards_path), i + 1, bad))
393 (self.join(self.guards_path), i + 1, bad))
394 else:
394 else:
395 self.active_guards.append(guard)
395 self.active_guards.append(guard)
396 return self.active_guards
396 return self.active_guards
397
397
398 def set_guards(self, idx, guards):
398 def set_guards(self, idx, guards):
399 for g in guards:
399 for g in guards:
400 if len(g) < 2:
400 if len(g) < 2:
401 raise util.Abort(_('guard %r too short') % g)
401 raise util.Abort(_('guard %r too short') % g)
402 if g[0] not in '-+':
402 if g[0] not in '-+':
403 raise util.Abort(_('guard %r starts with invalid char') % g)
403 raise util.Abort(_('guard %r starts with invalid char') % g)
404 bad = self.check_guard(g[1:])
404 bad = self.check_guard(g[1:])
405 if bad:
405 if bad:
406 raise util.Abort(bad)
406 raise util.Abort(bad)
407 drop = self.guard_re.sub('', self.full_series[idx])
407 drop = self.guard_re.sub('', self.full_series[idx])
408 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
408 self.full_series[idx] = drop + ''.join([' #' + g for g in guards])
409 self.parse_series()
409 self.parse_series()
410 self.series_dirty = True
410 self.series_dirty = True
411
411
412 def pushable(self, idx):
412 def pushable(self, idx):
413 if isinstance(idx, str):
413 if isinstance(idx, str):
414 idx = self.series.index(idx)
414 idx = self.series.index(idx)
415 patchguards = self.series_guards[idx]
415 patchguards = self.series_guards[idx]
416 if not patchguards:
416 if not patchguards:
417 return True, None
417 return True, None
418 guards = self.active()
418 guards = self.active()
419 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
419 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
420 if exactneg:
420 if exactneg:
421 return False, exactneg[0]
421 return False, exactneg[0]
422 pos = [g for g in patchguards if g[0] == '+']
422 pos = [g for g in patchguards if g[0] == '+']
423 exactpos = [g for g in pos if g[1:] in guards]
423 exactpos = [g for g in pos if g[1:] in guards]
424 if pos:
424 if pos:
425 if exactpos:
425 if exactpos:
426 return True, exactpos[0]
426 return True, exactpos[0]
427 return False, pos
427 return False, pos
428 return True, ''
428 return True, ''
429
429
430 def explain_pushable(self, idx, all_patches=False):
430 def explain_pushable(self, idx, all_patches=False):
431 write = all_patches and self.ui.write or self.ui.warn
431 write = all_patches and self.ui.write or self.ui.warn
432 if all_patches or self.ui.verbose:
432 if all_patches or self.ui.verbose:
433 if isinstance(idx, str):
433 if isinstance(idx, str):
434 idx = self.series.index(idx)
434 idx = self.series.index(idx)
435 pushable, why = self.pushable(idx)
435 pushable, why = self.pushable(idx)
436 if all_patches and pushable:
436 if all_patches and pushable:
437 if why is None:
437 if why is None:
438 write(_('allowing %s - no guards in effect\n') %
438 write(_('allowing %s - no guards in effect\n') %
439 self.series[idx])
439 self.series[idx])
440 else:
440 else:
441 if not why:
441 if not why:
442 write(_('allowing %s - no matching negative guards\n') %
442 write(_('allowing %s - no matching negative guards\n') %
443 self.series[idx])
443 self.series[idx])
444 else:
444 else:
445 write(_('allowing %s - guarded by %r\n') %
445 write(_('allowing %s - guarded by %r\n') %
446 (self.series[idx], why))
446 (self.series[idx], why))
447 if not pushable:
447 if not pushable:
448 if why:
448 if why:
449 write(_('skipping %s - guarded by %r\n') %
449 write(_('skipping %s - guarded by %r\n') %
450 (self.series[idx], why))
450 (self.series[idx], why))
451 else:
451 else:
452 write(_('skipping %s - no matching guards\n') %
452 write(_('skipping %s - no matching guards\n') %
453 self.series[idx])
453 self.series[idx])
454
454
455 def save_dirty(self):
455 def save_dirty(self):
456 def write_list(items, path):
456 def write_list(items, path):
457 fp = self.opener(path, 'w')
457 fp = self.opener(path, 'w')
458 for i in items:
458 for i in items:
459 fp.write("%s\n" % i)
459 fp.write("%s\n" % i)
460 fp.close()
460 fp.close()
461 if self.applied_dirty:
461 if self.applied_dirty:
462 write_list(map(str, self.applied), self.status_path)
462 write_list(map(str, self.applied), self.status_path)
463 if self.series_dirty:
463 if self.series_dirty:
464 write_list(self.full_series, self.series_path)
464 write_list(self.full_series, self.series_path)
465 if self.guards_dirty:
465 if self.guards_dirty:
466 write_list(self.active_guards, self.guards_path)
466 write_list(self.active_guards, self.guards_path)
467
467
468 def removeundo(self, repo):
468 def removeundo(self, repo):
469 undo = repo.sjoin('undo')
469 undo = repo.sjoin('undo')
470 if not os.path.exists(undo):
470 if not os.path.exists(undo):
471 return
471 return
472 try:
472 try:
473 os.unlink(undo)
473 os.unlink(undo)
474 except OSError, inst:
474 except OSError, inst:
475 self.ui.warn(_('error removing undo: %s\n') % str(inst))
475 self.ui.warn(_('error removing undo: %s\n') % str(inst))
476
476
477 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
477 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
478 fp=None, changes=None, opts={}):
478 fp=None, changes=None, opts={}):
479 stat = opts.get('stat')
479 stat = opts.get('stat')
480
481 m = cmdutil.match(repo, files, opts)
480 m = cmdutil.match(repo, files, opts)
482 if fp is None:
481 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
483 write = repo.ui.write
482 changes, stat, fp)
484 else:
485 def write(s, **kw):
486 fp.write(s)
487 if stat:
488 diffopts.context = 0
489 width = self.ui.interactive() and util.termwidth() or 80
490 chunks = patch.diff(repo, node1, node2, m, changes, diffopts)
491 for chunk, label in patch.diffstatui(util.iterlines(chunks),
492 width=width,
493 git=diffopts.git):
494 write(chunk, label=label)
495 else:
496 for chunk, label in patch.diffui(repo, node1, node2, m, changes,
497 diffopts):
498 write(chunk, label=label)
499
483
500 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
484 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
501 # first try just applying the patch
485 # first try just applying the patch
502 (err, n) = self.apply(repo, [patch], update_status=False,
486 (err, n) = self.apply(repo, [patch], update_status=False,
503 strict=True, merge=rev)
487 strict=True, merge=rev)
504
488
505 if err == 0:
489 if err == 0:
506 return (err, n)
490 return (err, n)
507
491
508 if n is None:
492 if n is None:
509 raise util.Abort(_("apply failed for patch %s") % patch)
493 raise util.Abort(_("apply failed for patch %s") % patch)
510
494
511 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
495 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
512
496
513 # apply failed, strip away that rev and merge.
497 # apply failed, strip away that rev and merge.
514 hg.clean(repo, head)
498 hg.clean(repo, head)
515 self.strip(repo, n, update=False, backup='strip')
499 self.strip(repo, n, update=False, backup='strip')
516
500
517 ctx = repo[rev]
501 ctx = repo[rev]
518 ret = hg.merge(repo, rev)
502 ret = hg.merge(repo, rev)
519 if ret:
503 if ret:
520 raise util.Abort(_("update returned %d") % ret)
504 raise util.Abort(_("update returned %d") % ret)
521 n = repo.commit(ctx.description(), ctx.user(), force=True)
505 n = repo.commit(ctx.description(), ctx.user(), force=True)
522 if n is None:
506 if n is None:
523 raise util.Abort(_("repo commit failed"))
507 raise util.Abort(_("repo commit failed"))
524 try:
508 try:
525 ph = patchheader(mergeq.join(patch), self.plainmode)
509 ph = patchheader(mergeq.join(patch), self.plainmode)
526 except:
510 except:
527 raise util.Abort(_("unable to read %s") % patch)
511 raise util.Abort(_("unable to read %s") % patch)
528
512
529 diffopts = self.patchopts(diffopts, patch)
513 diffopts = self.patchopts(diffopts, patch)
530 patchf = self.opener(patch, "w")
514 patchf = self.opener(patch, "w")
531 comments = str(ph)
515 comments = str(ph)
532 if comments:
516 if comments:
533 patchf.write(comments)
517 patchf.write(comments)
534 self.printdiff(repo, diffopts, head, n, fp=patchf)
518 self.printdiff(repo, diffopts, head, n, fp=patchf)
535 patchf.close()
519 patchf.close()
536 self.removeundo(repo)
520 self.removeundo(repo)
537 return (0, n)
521 return (0, n)
538
522
539 def qparents(self, repo, rev=None):
523 def qparents(self, repo, rev=None):
540 if rev is None:
524 if rev is None:
541 (p1, p2) = repo.dirstate.parents()
525 (p1, p2) = repo.dirstate.parents()
542 if p2 == nullid:
526 if p2 == nullid:
543 return p1
527 return p1
544 if not self.applied:
528 if not self.applied:
545 return None
529 return None
546 return self.applied[-1].node
530 return self.applied[-1].node
547 p1, p2 = repo.changelog.parents(rev)
531 p1, p2 = repo.changelog.parents(rev)
548 if p2 != nullid and p2 in [x.node for x in self.applied]:
532 if p2 != nullid and p2 in [x.node for x in self.applied]:
549 return p2
533 return p2
550 return p1
534 return p1
551
535
552 def mergepatch(self, repo, mergeq, series, diffopts):
536 def mergepatch(self, repo, mergeq, series, diffopts):
553 if not self.applied:
537 if not self.applied:
554 # each of the patches merged in will have two parents. This
538 # each of the patches merged in will have two parents. This
555 # can confuse the qrefresh, qdiff, and strip code because it
539 # can confuse the qrefresh, qdiff, and strip code because it
556 # needs to know which parent is actually in the patch queue.
540 # needs to know which parent is actually in the patch queue.
557 # so, we insert a merge marker with only one parent. This way
541 # so, we insert a merge marker with only one parent. This way
558 # the first patch in the queue is never a merge patch
542 # the first patch in the queue is never a merge patch
559 #
543 #
560 pname = ".hg.patches.merge.marker"
544 pname = ".hg.patches.merge.marker"
561 n = repo.commit('[mq]: merge marker', force=True)
545 n = repo.commit('[mq]: merge marker', force=True)
562 self.removeundo(repo)
546 self.removeundo(repo)
563 self.applied.append(statusentry(n, pname))
547 self.applied.append(statusentry(n, pname))
564 self.applied_dirty = 1
548 self.applied_dirty = 1
565
549
566 head = self.qparents(repo)
550 head = self.qparents(repo)
567
551
568 for patch in series:
552 for patch in series:
569 patch = mergeq.lookup(patch, strict=True)
553 patch = mergeq.lookup(patch, strict=True)
570 if not patch:
554 if not patch:
571 self.ui.warn(_("patch %s does not exist\n") % patch)
555 self.ui.warn(_("patch %s does not exist\n") % patch)
572 return (1, None)
556 return (1, None)
573 pushable, reason = self.pushable(patch)
557 pushable, reason = self.pushable(patch)
574 if not pushable:
558 if not pushable:
575 self.explain_pushable(patch, all_patches=True)
559 self.explain_pushable(patch, all_patches=True)
576 continue
560 continue
577 info = mergeq.isapplied(patch)
561 info = mergeq.isapplied(patch)
578 if not info:
562 if not info:
579 self.ui.warn(_("patch %s is not applied\n") % patch)
563 self.ui.warn(_("patch %s is not applied\n") % patch)
580 return (1, None)
564 return (1, None)
581 rev = info[1]
565 rev = info[1]
582 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
566 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
583 if head:
567 if head:
584 self.applied.append(statusentry(head, patch))
568 self.applied.append(statusentry(head, patch))
585 self.applied_dirty = 1
569 self.applied_dirty = 1
586 if err:
570 if err:
587 return (err, head)
571 return (err, head)
588 self.save_dirty()
572 self.save_dirty()
589 return (0, head)
573 return (0, head)
590
574
591 def patch(self, repo, patchfile):
575 def patch(self, repo, patchfile):
592 '''Apply patchfile to the working directory.
576 '''Apply patchfile to the working directory.
593 patchfile: name of patch file'''
577 patchfile: name of patch file'''
594 files = {}
578 files = {}
595 try:
579 try:
596 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
580 fuzz = patch.patch(patchfile, self.ui, strip=1, cwd=repo.root,
597 files=files, eolmode=None)
581 files=files, eolmode=None)
598 except Exception, inst:
582 except Exception, inst:
599 self.ui.note(str(inst) + '\n')
583 self.ui.note(str(inst) + '\n')
600 if not self.ui.verbose:
584 if not self.ui.verbose:
601 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
585 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
602 return (False, files, False)
586 return (False, files, False)
603
587
604 return (True, files, fuzz)
588 return (True, files, fuzz)
605
589
606 def apply(self, repo, series, list=False, update_status=True,
590 def apply(self, repo, series, list=False, update_status=True,
607 strict=False, patchdir=None, merge=None, all_files=None):
591 strict=False, patchdir=None, merge=None, all_files=None):
608 wlock = lock = tr = None
592 wlock = lock = tr = None
609 try:
593 try:
610 wlock = repo.wlock()
594 wlock = repo.wlock()
611 lock = repo.lock()
595 lock = repo.lock()
612 tr = repo.transaction("qpush")
596 tr = repo.transaction("qpush")
613 try:
597 try:
614 ret = self._apply(repo, series, list, update_status,
598 ret = self._apply(repo, series, list, update_status,
615 strict, patchdir, merge, all_files=all_files)
599 strict, patchdir, merge, all_files=all_files)
616 tr.close()
600 tr.close()
617 self.save_dirty()
601 self.save_dirty()
618 return ret
602 return ret
619 except:
603 except:
620 try:
604 try:
621 tr.abort()
605 tr.abort()
622 finally:
606 finally:
623 repo.invalidate()
607 repo.invalidate()
624 repo.dirstate.invalidate()
608 repo.dirstate.invalidate()
625 raise
609 raise
626 finally:
610 finally:
627 del tr
611 del tr
628 release(lock, wlock)
612 release(lock, wlock)
629 self.removeundo(repo)
613 self.removeundo(repo)
630
614
631 def _apply(self, repo, series, list=False, update_status=True,
615 def _apply(self, repo, series, list=False, update_status=True,
632 strict=False, patchdir=None, merge=None, all_files=None):
616 strict=False, patchdir=None, merge=None, all_files=None):
633 '''returns (error, hash)
617 '''returns (error, hash)
634 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
618 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
635 # TODO unify with commands.py
619 # TODO unify with commands.py
636 if not patchdir:
620 if not patchdir:
637 patchdir = self.path
621 patchdir = self.path
638 err = 0
622 err = 0
639 n = None
623 n = None
640 for patchname in series:
624 for patchname in series:
641 pushable, reason = self.pushable(patchname)
625 pushable, reason = self.pushable(patchname)
642 if not pushable:
626 if not pushable:
643 self.explain_pushable(patchname, all_patches=True)
627 self.explain_pushable(patchname, all_patches=True)
644 continue
628 continue
645 self.ui.status(_("applying %s\n") % patchname)
629 self.ui.status(_("applying %s\n") % patchname)
646 pf = os.path.join(patchdir, patchname)
630 pf = os.path.join(patchdir, patchname)
647
631
648 try:
632 try:
649 ph = patchheader(self.join(patchname), self.plainmode)
633 ph = patchheader(self.join(patchname), self.plainmode)
650 except:
634 except:
651 self.ui.warn(_("unable to read %s\n") % patchname)
635 self.ui.warn(_("unable to read %s\n") % patchname)
652 err = 1
636 err = 1
653 break
637 break
654
638
655 message = ph.message
639 message = ph.message
656 if not message:
640 if not message:
657 message = "imported patch %s\n" % patchname
641 message = "imported patch %s\n" % patchname
658 else:
642 else:
659 if list:
643 if list:
660 message.append("\nimported patch %s" % patchname)
644 message.append("\nimported patch %s" % patchname)
661 message = '\n'.join(message)
645 message = '\n'.join(message)
662
646
663 if ph.haspatch:
647 if ph.haspatch:
664 (patcherr, files, fuzz) = self.patch(repo, pf)
648 (patcherr, files, fuzz) = self.patch(repo, pf)
665 if all_files is not None:
649 if all_files is not None:
666 all_files.update(files)
650 all_files.update(files)
667 patcherr = not patcherr
651 patcherr = not patcherr
668 else:
652 else:
669 self.ui.warn(_("patch %s is empty\n") % patchname)
653 self.ui.warn(_("patch %s is empty\n") % patchname)
670 patcherr, files, fuzz = 0, [], 0
654 patcherr, files, fuzz = 0, [], 0
671
655
672 if merge and files:
656 if merge and files:
673 # Mark as removed/merged and update dirstate parent info
657 # Mark as removed/merged and update dirstate parent info
674 removed = []
658 removed = []
675 merged = []
659 merged = []
676 for f in files:
660 for f in files:
677 if os.path.exists(repo.wjoin(f)):
661 if os.path.exists(repo.wjoin(f)):
678 merged.append(f)
662 merged.append(f)
679 else:
663 else:
680 removed.append(f)
664 removed.append(f)
681 for f in removed:
665 for f in removed:
682 repo.dirstate.remove(f)
666 repo.dirstate.remove(f)
683 for f in merged:
667 for f in merged:
684 repo.dirstate.merge(f)
668 repo.dirstate.merge(f)
685 p1, p2 = repo.dirstate.parents()
669 p1, p2 = repo.dirstate.parents()
686 repo.dirstate.setparents(p1, merge)
670 repo.dirstate.setparents(p1, merge)
687
671
688 files = patch.updatedir(self.ui, repo, files)
672 files = patch.updatedir(self.ui, repo, files)
689 match = cmdutil.matchfiles(repo, files or [])
673 match = cmdutil.matchfiles(repo, files or [])
690 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
674 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
691
675
692 if n is None:
676 if n is None:
693 raise util.Abort(_("repo commit failed"))
677 raise util.Abort(_("repo commit failed"))
694
678
695 if update_status:
679 if update_status:
696 self.applied.append(statusentry(n, patchname))
680 self.applied.append(statusentry(n, patchname))
697
681
698 if patcherr:
682 if patcherr:
699 self.ui.warn(_("patch failed, rejects left in working dir\n"))
683 self.ui.warn(_("patch failed, rejects left in working dir\n"))
700 err = 2
684 err = 2
701 break
685 break
702
686
703 if fuzz and strict:
687 if fuzz and strict:
704 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
688 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
705 err = 3
689 err = 3
706 break
690 break
707 return (err, n)
691 return (err, n)
708
692
709 def _cleanup(self, patches, numrevs, keep=False):
693 def _cleanup(self, patches, numrevs, keep=False):
710 if not keep:
694 if not keep:
711 r = self.qrepo()
695 r = self.qrepo()
712 if r:
696 if r:
713 r.remove(patches, True)
697 r.remove(patches, True)
714 else:
698 else:
715 for p in patches:
699 for p in patches:
716 os.unlink(self.join(p))
700 os.unlink(self.join(p))
717
701
718 if numrevs:
702 if numrevs:
719 del self.applied[:numrevs]
703 del self.applied[:numrevs]
720 self.applied_dirty = 1
704 self.applied_dirty = 1
721
705
722 for i in sorted([self.find_series(p) for p in patches], reverse=True):
706 for i in sorted([self.find_series(p) for p in patches], reverse=True):
723 del self.full_series[i]
707 del self.full_series[i]
724 self.parse_series()
708 self.parse_series()
725 self.series_dirty = 1
709 self.series_dirty = 1
726
710
727 def _revpatches(self, repo, revs):
711 def _revpatches(self, repo, revs):
728 firstrev = repo[self.applied[0].node].rev()
712 firstrev = repo[self.applied[0].node].rev()
729 patches = []
713 patches = []
730 for i, rev in enumerate(revs):
714 for i, rev in enumerate(revs):
731
715
732 if rev < firstrev:
716 if rev < firstrev:
733 raise util.Abort(_('revision %d is not managed') % rev)
717 raise util.Abort(_('revision %d is not managed') % rev)
734
718
735 ctx = repo[rev]
719 ctx = repo[rev]
736 base = self.applied[i].node
720 base = self.applied[i].node
737 if ctx.node() != base:
721 if ctx.node() != base:
738 msg = _('cannot delete revision %d above applied patches')
722 msg = _('cannot delete revision %d above applied patches')
739 raise util.Abort(msg % rev)
723 raise util.Abort(msg % rev)
740
724
741 patch = self.applied[i].name
725 patch = self.applied[i].name
742 for fmt in ('[mq]: %s', 'imported patch %s'):
726 for fmt in ('[mq]: %s', 'imported patch %s'):
743 if ctx.description() == fmt % patch:
727 if ctx.description() == fmt % patch:
744 msg = _('patch %s finalized without changeset message\n')
728 msg = _('patch %s finalized without changeset message\n')
745 repo.ui.status(msg % patch)
729 repo.ui.status(msg % patch)
746 break
730 break
747
731
748 patches.append(patch)
732 patches.append(patch)
749 return patches
733 return patches
750
734
751 def finish(self, repo, revs):
735 def finish(self, repo, revs):
752 patches = self._revpatches(repo, sorted(revs))
736 patches = self._revpatches(repo, sorted(revs))
753 self._cleanup(patches, len(patches))
737 self._cleanup(patches, len(patches))
754
738
755 def delete(self, repo, patches, opts):
739 def delete(self, repo, patches, opts):
756 if not patches and not opts.get('rev'):
740 if not patches and not opts.get('rev'):
757 raise util.Abort(_('qdelete requires at least one revision or '
741 raise util.Abort(_('qdelete requires at least one revision or '
758 'patch name'))
742 'patch name'))
759
743
760 realpatches = []
744 realpatches = []
761 for patch in patches:
745 for patch in patches:
762 patch = self.lookup(patch, strict=True)
746 patch = self.lookup(patch, strict=True)
763 info = self.isapplied(patch)
747 info = self.isapplied(patch)
764 if info:
748 if info:
765 raise util.Abort(_("cannot delete applied patch %s") % patch)
749 raise util.Abort(_("cannot delete applied patch %s") % patch)
766 if patch not in self.series:
750 if patch not in self.series:
767 raise util.Abort(_("patch %s not in series file") % patch)
751 raise util.Abort(_("patch %s not in series file") % patch)
768 realpatches.append(patch)
752 realpatches.append(patch)
769
753
770 numrevs = 0
754 numrevs = 0
771 if opts.get('rev'):
755 if opts.get('rev'):
772 if not self.applied:
756 if not self.applied:
773 raise util.Abort(_('no patches applied'))
757 raise util.Abort(_('no patches applied'))
774 revs = cmdutil.revrange(repo, opts['rev'])
758 revs = cmdutil.revrange(repo, opts['rev'])
775 if len(revs) > 1 and revs[0] > revs[1]:
759 if len(revs) > 1 and revs[0] > revs[1]:
776 revs.reverse()
760 revs.reverse()
777 revpatches = self._revpatches(repo, revs)
761 revpatches = self._revpatches(repo, revs)
778 realpatches += revpatches
762 realpatches += revpatches
779 numrevs = len(revpatches)
763 numrevs = len(revpatches)
780
764
781 self._cleanup(realpatches, numrevs, opts.get('keep'))
765 self._cleanup(realpatches, numrevs, opts.get('keep'))
782
766
783 def check_toppatch(self, repo):
767 def check_toppatch(self, repo):
784 if self.applied:
768 if self.applied:
785 top = self.applied[-1].node
769 top = self.applied[-1].node
786 patch = self.applied[-1].name
770 patch = self.applied[-1].name
787 pp = repo.dirstate.parents()
771 pp = repo.dirstate.parents()
788 if top not in pp:
772 if top not in pp:
789 raise util.Abort(_("working directory revision is not qtip"))
773 raise util.Abort(_("working directory revision is not qtip"))
790 return top, patch
774 return top, patch
791 return None, None
775 return None, None
792
776
793 def check_localchanges(self, repo, force=False, refresh=True):
777 def check_localchanges(self, repo, force=False, refresh=True):
794 m, a, r, d = repo.status()[:4]
778 m, a, r, d = repo.status()[:4]
795 if (m or a or r or d) and not force:
779 if (m or a or r or d) and not force:
796 if refresh:
780 if refresh:
797 raise util.Abort(_("local changes found, refresh first"))
781 raise util.Abort(_("local changes found, refresh first"))
798 else:
782 else:
799 raise util.Abort(_("local changes found"))
783 raise util.Abort(_("local changes found"))
800 return m, a, r, d
784 return m, a, r, d
801
785
802 _reserved = ('series', 'status', 'guards')
786 _reserved = ('series', 'status', 'guards')
803 def check_reserved_name(self, name):
787 def check_reserved_name(self, name):
804 if (name in self._reserved or name.startswith('.hg')
788 if (name in self._reserved or name.startswith('.hg')
805 or name.startswith('.mq') or '#' in name or ':' in name):
789 or name.startswith('.mq') or '#' in name or ':' in name):
806 raise util.Abort(_('"%s" cannot be used as the name of a patch')
790 raise util.Abort(_('"%s" cannot be used as the name of a patch')
807 % name)
791 % name)
808
792
809 def new(self, repo, patchfn, *pats, **opts):
793 def new(self, repo, patchfn, *pats, **opts):
810 """options:
794 """options:
811 msg: a string or a no-argument function returning a string
795 msg: a string or a no-argument function returning a string
812 """
796 """
813 msg = opts.get('msg')
797 msg = opts.get('msg')
814 user = opts.get('user')
798 user = opts.get('user')
815 date = opts.get('date')
799 date = opts.get('date')
816 if date:
800 if date:
817 date = util.parsedate(date)
801 date = util.parsedate(date)
818 diffopts = self.diffopts({'git': opts.get('git')})
802 diffopts = self.diffopts({'git': opts.get('git')})
819 self.check_reserved_name(patchfn)
803 self.check_reserved_name(patchfn)
820 if os.path.exists(self.join(patchfn)):
804 if os.path.exists(self.join(patchfn)):
821 raise util.Abort(_('patch "%s" already exists') % patchfn)
805 raise util.Abort(_('patch "%s" already exists') % patchfn)
822 if opts.get('include') or opts.get('exclude') or pats:
806 if opts.get('include') or opts.get('exclude') or pats:
823 match = cmdutil.match(repo, pats, opts)
807 match = cmdutil.match(repo, pats, opts)
824 # detect missing files in pats
808 # detect missing files in pats
825 def badfn(f, msg):
809 def badfn(f, msg):
826 raise util.Abort('%s: %s' % (f, msg))
810 raise util.Abort('%s: %s' % (f, msg))
827 match.bad = badfn
811 match.bad = badfn
828 m, a, r, d = repo.status(match=match)[:4]
812 m, a, r, d = repo.status(match=match)[:4]
829 else:
813 else:
830 m, a, r, d = self.check_localchanges(repo, force=True)
814 m, a, r, d = self.check_localchanges(repo, force=True)
831 match = cmdutil.matchfiles(repo, m + a + r)
815 match = cmdutil.matchfiles(repo, m + a + r)
832 if len(repo[None].parents()) > 1:
816 if len(repo[None].parents()) > 1:
833 raise util.Abort(_('cannot manage merge changesets'))
817 raise util.Abort(_('cannot manage merge changesets'))
834 commitfiles = m + a + r
818 commitfiles = m + a + r
835 self.check_toppatch(repo)
819 self.check_toppatch(repo)
836 insert = self.full_series_end()
820 insert = self.full_series_end()
837 wlock = repo.wlock()
821 wlock = repo.wlock()
838 try:
822 try:
839 # if patch file write fails, abort early
823 # if patch file write fails, abort early
840 p = self.opener(patchfn, "w")
824 p = self.opener(patchfn, "w")
841 try:
825 try:
842 if self.plainmode:
826 if self.plainmode:
843 if user:
827 if user:
844 p.write("From: " + user + "\n")
828 p.write("From: " + user + "\n")
845 if not date:
829 if not date:
846 p.write("\n")
830 p.write("\n")
847 if date:
831 if date:
848 p.write("Date: %d %d\n\n" % date)
832 p.write("Date: %d %d\n\n" % date)
849 else:
833 else:
850 p.write("# HG changeset patch\n")
834 p.write("# HG changeset patch\n")
851 p.write("# Parent "
835 p.write("# Parent "
852 + hex(repo[None].parents()[0].node()) + "\n")
836 + hex(repo[None].parents()[0].node()) + "\n")
853 if user:
837 if user:
854 p.write("# User " + user + "\n")
838 p.write("# User " + user + "\n")
855 if date:
839 if date:
856 p.write("# Date %s %s\n\n" % date)
840 p.write("# Date %s %s\n\n" % date)
857 if hasattr(msg, '__call__'):
841 if hasattr(msg, '__call__'):
858 msg = msg()
842 msg = msg()
859 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
843 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
860 n = repo.commit(commitmsg, user, date, match=match, force=True)
844 n = repo.commit(commitmsg, user, date, match=match, force=True)
861 if n is None:
845 if n is None:
862 raise util.Abort(_("repo commit failed"))
846 raise util.Abort(_("repo commit failed"))
863 try:
847 try:
864 self.full_series[insert:insert] = [patchfn]
848 self.full_series[insert:insert] = [patchfn]
865 self.applied.append(statusentry(n, patchfn))
849 self.applied.append(statusentry(n, patchfn))
866 self.parse_series()
850 self.parse_series()
867 self.series_dirty = 1
851 self.series_dirty = 1
868 self.applied_dirty = 1
852 self.applied_dirty = 1
869 if msg:
853 if msg:
870 msg = msg + "\n\n"
854 msg = msg + "\n\n"
871 p.write(msg)
855 p.write(msg)
872 if commitfiles:
856 if commitfiles:
873 parent = self.qparents(repo, n)
857 parent = self.qparents(repo, n)
874 chunks = patch.diff(repo, node1=parent, node2=n,
858 chunks = patch.diff(repo, node1=parent, node2=n,
875 match=match, opts=diffopts)
859 match=match, opts=diffopts)
876 for chunk in chunks:
860 for chunk in chunks:
877 p.write(chunk)
861 p.write(chunk)
878 p.close()
862 p.close()
879 wlock.release()
863 wlock.release()
880 wlock = None
864 wlock = None
881 r = self.qrepo()
865 r = self.qrepo()
882 if r:
866 if r:
883 r.add([patchfn])
867 r.add([patchfn])
884 except:
868 except:
885 repo.rollback()
869 repo.rollback()
886 raise
870 raise
887 except Exception:
871 except Exception:
888 patchpath = self.join(patchfn)
872 patchpath = self.join(patchfn)
889 try:
873 try:
890 os.unlink(patchpath)
874 os.unlink(patchpath)
891 except:
875 except:
892 self.ui.warn(_('error unlinking %s\n') % patchpath)
876 self.ui.warn(_('error unlinking %s\n') % patchpath)
893 raise
877 raise
894 self.removeundo(repo)
878 self.removeundo(repo)
895 finally:
879 finally:
896 release(wlock)
880 release(wlock)
897
881
898 def strip(self, repo, rev, update=True, backup="all", force=None):
882 def strip(self, repo, rev, update=True, backup="all", force=None):
899 wlock = lock = None
883 wlock = lock = None
900 try:
884 try:
901 wlock = repo.wlock()
885 wlock = repo.wlock()
902 lock = repo.lock()
886 lock = repo.lock()
903
887
904 if update:
888 if update:
905 self.check_localchanges(repo, force=force, refresh=False)
889 self.check_localchanges(repo, force=force, refresh=False)
906 urev = self.qparents(repo, rev)
890 urev = self.qparents(repo, rev)
907 hg.clean(repo, urev)
891 hg.clean(repo, urev)
908 repo.dirstate.write()
892 repo.dirstate.write()
909
893
910 self.removeundo(repo)
894 self.removeundo(repo)
911 repair.strip(self.ui, repo, rev, backup)
895 repair.strip(self.ui, repo, rev, backup)
912 # strip may have unbundled a set of backed up revisions after
896 # strip may have unbundled a set of backed up revisions after
913 # the actual strip
897 # the actual strip
914 self.removeundo(repo)
898 self.removeundo(repo)
915 finally:
899 finally:
916 release(lock, wlock)
900 release(lock, wlock)
917
901
918 def isapplied(self, patch):
902 def isapplied(self, patch):
919 """returns (index, rev, patch)"""
903 """returns (index, rev, patch)"""
920 for i, a in enumerate(self.applied):
904 for i, a in enumerate(self.applied):
921 if a.name == patch:
905 if a.name == patch:
922 return (i, a.node, a.name)
906 return (i, a.node, a.name)
923 return None
907 return None
924
908
925 # if the exact patch name does not exist, we try a few
909 # if the exact patch name does not exist, we try a few
926 # variations. If strict is passed, we try only #1
910 # variations. If strict is passed, we try only #1
927 #
911 #
928 # 1) a number to indicate an offset in the series file
912 # 1) a number to indicate an offset in the series file
929 # 2) a unique substring of the patch name was given
913 # 2) a unique substring of the patch name was given
930 # 3) patchname[-+]num to indicate an offset in the series file
914 # 3) patchname[-+]num to indicate an offset in the series file
931 def lookup(self, patch, strict=False):
915 def lookup(self, patch, strict=False):
932 patch = patch and str(patch)
916 patch = patch and str(patch)
933
917
934 def partial_name(s):
918 def partial_name(s):
935 if s in self.series:
919 if s in self.series:
936 return s
920 return s
937 matches = [x for x in self.series if s in x]
921 matches = [x for x in self.series if s in x]
938 if len(matches) > 1:
922 if len(matches) > 1:
939 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
923 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
940 for m in matches:
924 for m in matches:
941 self.ui.warn(' %s\n' % m)
925 self.ui.warn(' %s\n' % m)
942 return None
926 return None
943 if matches:
927 if matches:
944 return matches[0]
928 return matches[0]
945 if self.series and self.applied:
929 if self.series and self.applied:
946 if s == 'qtip':
930 if s == 'qtip':
947 return self.series[self.series_end(True)-1]
931 return self.series[self.series_end(True)-1]
948 if s == 'qbase':
932 if s == 'qbase':
949 return self.series[0]
933 return self.series[0]
950 return None
934 return None
951
935
952 if patch is None:
936 if patch is None:
953 return None
937 return None
954 if patch in self.series:
938 if patch in self.series:
955 return patch
939 return patch
956
940
957 if not os.path.isfile(self.join(patch)):
941 if not os.path.isfile(self.join(patch)):
958 try:
942 try:
959 sno = int(patch)
943 sno = int(patch)
960 except (ValueError, OverflowError):
944 except (ValueError, OverflowError):
961 pass
945 pass
962 else:
946 else:
963 if -len(self.series) <= sno < len(self.series):
947 if -len(self.series) <= sno < len(self.series):
964 return self.series[sno]
948 return self.series[sno]
965
949
966 if not strict:
950 if not strict:
967 res = partial_name(patch)
951 res = partial_name(patch)
968 if res:
952 if res:
969 return res
953 return res
970 minus = patch.rfind('-')
954 minus = patch.rfind('-')
971 if minus >= 0:
955 if minus >= 0:
972 res = partial_name(patch[:minus])
956 res = partial_name(patch[:minus])
973 if res:
957 if res:
974 i = self.series.index(res)
958 i = self.series.index(res)
975 try:
959 try:
976 off = int(patch[minus + 1:] or 1)
960 off = int(patch[minus + 1:] or 1)
977 except (ValueError, OverflowError):
961 except (ValueError, OverflowError):
978 pass
962 pass
979 else:
963 else:
980 if i - off >= 0:
964 if i - off >= 0:
981 return self.series[i - off]
965 return self.series[i - off]
982 plus = patch.rfind('+')
966 plus = patch.rfind('+')
983 if plus >= 0:
967 if plus >= 0:
984 res = partial_name(patch[:plus])
968 res = partial_name(patch[:plus])
985 if res:
969 if res:
986 i = self.series.index(res)
970 i = self.series.index(res)
987 try:
971 try:
988 off = int(patch[plus + 1:] or 1)
972 off = int(patch[plus + 1:] or 1)
989 except (ValueError, OverflowError):
973 except (ValueError, OverflowError):
990 pass
974 pass
991 else:
975 else:
992 if i + off < len(self.series):
976 if i + off < len(self.series):
993 return self.series[i + off]
977 return self.series[i + off]
994 raise util.Abort(_("patch %s not in series") % patch)
978 raise util.Abort(_("patch %s not in series") % patch)
995
979
996 def push(self, repo, patch=None, force=False, list=False,
980 def push(self, repo, patch=None, force=False, list=False,
997 mergeq=None, all=False):
981 mergeq=None, all=False):
998 diffopts = self.diffopts()
982 diffopts = self.diffopts()
999 wlock = repo.wlock()
983 wlock = repo.wlock()
1000 try:
984 try:
1001 heads = []
985 heads = []
1002 for b, ls in repo.branchmap().iteritems():
986 for b, ls in repo.branchmap().iteritems():
1003 heads += ls
987 heads += ls
1004 if not heads:
988 if not heads:
1005 heads = [nullid]
989 heads = [nullid]
1006 if repo.dirstate.parents()[0] not in heads:
990 if repo.dirstate.parents()[0] not in heads:
1007 self.ui.status(_("(working directory not at a head)\n"))
991 self.ui.status(_("(working directory not at a head)\n"))
1008
992
1009 if not self.series:
993 if not self.series:
1010 self.ui.warn(_('no patches in series\n'))
994 self.ui.warn(_('no patches in series\n'))
1011 return 0
995 return 0
1012
996
1013 patch = self.lookup(patch)
997 patch = self.lookup(patch)
1014 # Suppose our series file is: A B C and the current 'top'
998 # Suppose our series file is: A B C and the current 'top'
1015 # patch is B. qpush C should be performed (moving forward)
999 # patch is B. qpush C should be performed (moving forward)
1016 # qpush B is a NOP (no change) qpush A is an error (can't
1000 # qpush B is a NOP (no change) qpush A is an error (can't
1017 # go backwards with qpush)
1001 # go backwards with qpush)
1018 if patch:
1002 if patch:
1019 info = self.isapplied(patch)
1003 info = self.isapplied(patch)
1020 if info:
1004 if info:
1021 if info[0] < len(self.applied) - 1:
1005 if info[0] < len(self.applied) - 1:
1022 raise util.Abort(
1006 raise util.Abort(
1023 _("cannot push to a previous patch: %s") % patch)
1007 _("cannot push to a previous patch: %s") % patch)
1024 self.ui.warn(
1008 self.ui.warn(
1025 _('qpush: %s is already at the top\n') % patch)
1009 _('qpush: %s is already at the top\n') % patch)
1026 return
1010 return
1027 pushable, reason = self.pushable(patch)
1011 pushable, reason = self.pushable(patch)
1028 if not pushable:
1012 if not pushable:
1029 if reason:
1013 if reason:
1030 reason = _('guarded by %r') % reason
1014 reason = _('guarded by %r') % reason
1031 else:
1015 else:
1032 reason = _('no matching guards')
1016 reason = _('no matching guards')
1033 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1017 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1034 return 1
1018 return 1
1035 elif all:
1019 elif all:
1036 patch = self.series[-1]
1020 patch = self.series[-1]
1037 if self.isapplied(patch):
1021 if self.isapplied(patch):
1038 self.ui.warn(_('all patches are currently applied\n'))
1022 self.ui.warn(_('all patches are currently applied\n'))
1039 return 0
1023 return 0
1040
1024
1041 # Following the above example, starting at 'top' of B:
1025 # Following the above example, starting at 'top' of B:
1042 # qpush should be performed (pushes C), but a subsequent
1026 # qpush should be performed (pushes C), but a subsequent
1043 # qpush without an argument is an error (nothing to
1027 # qpush without an argument is an error (nothing to
1044 # apply). This allows a loop of "...while hg qpush..." to
1028 # apply). This allows a loop of "...while hg qpush..." to
1045 # work as it detects an error when done
1029 # work as it detects an error when done
1046 start = self.series_end()
1030 start = self.series_end()
1047 if start == len(self.series):
1031 if start == len(self.series):
1048 self.ui.warn(_('patch series already fully applied\n'))
1032 self.ui.warn(_('patch series already fully applied\n'))
1049 return 1
1033 return 1
1050 if not force:
1034 if not force:
1051 self.check_localchanges(repo)
1035 self.check_localchanges(repo)
1052
1036
1053 self.applied_dirty = 1
1037 self.applied_dirty = 1
1054 if start > 0:
1038 if start > 0:
1055 self.check_toppatch(repo)
1039 self.check_toppatch(repo)
1056 if not patch:
1040 if not patch:
1057 patch = self.series[start]
1041 patch = self.series[start]
1058 end = start + 1
1042 end = start + 1
1059 else:
1043 else:
1060 end = self.series.index(patch, start) + 1
1044 end = self.series.index(patch, start) + 1
1061
1045
1062 s = self.series[start:end]
1046 s = self.series[start:end]
1063 all_files = set()
1047 all_files = set()
1064 try:
1048 try:
1065 if mergeq:
1049 if mergeq:
1066 ret = self.mergepatch(repo, mergeq, s, diffopts)
1050 ret = self.mergepatch(repo, mergeq, s, diffopts)
1067 else:
1051 else:
1068 ret = self.apply(repo, s, list, all_files=all_files)
1052 ret = self.apply(repo, s, list, all_files=all_files)
1069 except:
1053 except:
1070 self.ui.warn(_('cleaning up working directory...'))
1054 self.ui.warn(_('cleaning up working directory...'))
1071 node = repo.dirstate.parents()[0]
1055 node = repo.dirstate.parents()[0]
1072 hg.revert(repo, node, None)
1056 hg.revert(repo, node, None)
1073 # only remove unknown files that we know we touched or
1057 # only remove unknown files that we know we touched or
1074 # created while patching
1058 # created while patching
1075 for f in all_files:
1059 for f in all_files:
1076 if f not in repo.dirstate:
1060 if f not in repo.dirstate:
1077 try:
1061 try:
1078 util.unlink(repo.wjoin(f))
1062 util.unlink(repo.wjoin(f))
1079 except OSError, inst:
1063 except OSError, inst:
1080 if inst.errno != errno.ENOENT:
1064 if inst.errno != errno.ENOENT:
1081 raise
1065 raise
1082 self.ui.warn(_('done\n'))
1066 self.ui.warn(_('done\n'))
1083 raise
1067 raise
1084
1068
1085 if not self.applied:
1069 if not self.applied:
1086 return ret[0]
1070 return ret[0]
1087 top = self.applied[-1].name
1071 top = self.applied[-1].name
1088 if ret[0] and ret[0] > 1:
1072 if ret[0] and ret[0] > 1:
1089 msg = _("errors during apply, please fix and refresh %s\n")
1073 msg = _("errors during apply, please fix and refresh %s\n")
1090 self.ui.write(msg % top)
1074 self.ui.write(msg % top)
1091 else:
1075 else:
1092 self.ui.write(_("now at: %s\n") % top)
1076 self.ui.write(_("now at: %s\n") % top)
1093 return ret[0]
1077 return ret[0]
1094
1078
1095 finally:
1079 finally:
1096 wlock.release()
1080 wlock.release()
1097
1081
1098 def pop(self, repo, patch=None, force=False, update=True, all=False):
1082 def pop(self, repo, patch=None, force=False, update=True, all=False):
1099 wlock = repo.wlock()
1083 wlock = repo.wlock()
1100 try:
1084 try:
1101 if patch:
1085 if patch:
1102 # index, rev, patch
1086 # index, rev, patch
1103 info = self.isapplied(patch)
1087 info = self.isapplied(patch)
1104 if not info:
1088 if not info:
1105 patch = self.lookup(patch)
1089 patch = self.lookup(patch)
1106 info = self.isapplied(patch)
1090 info = self.isapplied(patch)
1107 if not info:
1091 if not info:
1108 raise util.Abort(_("patch %s is not applied") % patch)
1092 raise util.Abort(_("patch %s is not applied") % patch)
1109
1093
1110 if not self.applied:
1094 if not self.applied:
1111 # Allow qpop -a to work repeatedly,
1095 # Allow qpop -a to work repeatedly,
1112 # but not qpop without an argument
1096 # but not qpop without an argument
1113 self.ui.warn(_("no patches applied\n"))
1097 self.ui.warn(_("no patches applied\n"))
1114 return not all
1098 return not all
1115
1099
1116 if all:
1100 if all:
1117 start = 0
1101 start = 0
1118 elif patch:
1102 elif patch:
1119 start = info[0] + 1
1103 start = info[0] + 1
1120 else:
1104 else:
1121 start = len(self.applied) - 1
1105 start = len(self.applied) - 1
1122
1106
1123 if start >= len(self.applied):
1107 if start >= len(self.applied):
1124 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1108 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1125 return
1109 return
1126
1110
1127 if not update:
1111 if not update:
1128 parents = repo.dirstate.parents()
1112 parents = repo.dirstate.parents()
1129 rr = [x.node for x in self.applied]
1113 rr = [x.node for x in self.applied]
1130 for p in parents:
1114 for p in parents:
1131 if p in rr:
1115 if p in rr:
1132 self.ui.warn(_("qpop: forcing dirstate update\n"))
1116 self.ui.warn(_("qpop: forcing dirstate update\n"))
1133 update = True
1117 update = True
1134 else:
1118 else:
1135 parents = [p.node() for p in repo[None].parents()]
1119 parents = [p.node() for p in repo[None].parents()]
1136 needupdate = False
1120 needupdate = False
1137 for entry in self.applied[start:]:
1121 for entry in self.applied[start:]:
1138 if entry.node in parents:
1122 if entry.node in parents:
1139 needupdate = True
1123 needupdate = True
1140 break
1124 break
1141 update = needupdate
1125 update = needupdate
1142
1126
1143 if not force and update:
1127 if not force and update:
1144 self.check_localchanges(repo)
1128 self.check_localchanges(repo)
1145
1129
1146 self.applied_dirty = 1
1130 self.applied_dirty = 1
1147 end = len(self.applied)
1131 end = len(self.applied)
1148 rev = self.applied[start].node
1132 rev = self.applied[start].node
1149 if update:
1133 if update:
1150 top = self.check_toppatch(repo)[0]
1134 top = self.check_toppatch(repo)[0]
1151
1135
1152 try:
1136 try:
1153 heads = repo.changelog.heads(rev)
1137 heads = repo.changelog.heads(rev)
1154 except error.LookupError:
1138 except error.LookupError:
1155 node = short(rev)
1139 node = short(rev)
1156 raise util.Abort(_('trying to pop unknown node %s') % node)
1140 raise util.Abort(_('trying to pop unknown node %s') % node)
1157
1141
1158 if heads != [self.applied[-1].node]:
1142 if heads != [self.applied[-1].node]:
1159 raise util.Abort(_("popping would remove a revision not "
1143 raise util.Abort(_("popping would remove a revision not "
1160 "managed by this patch queue"))
1144 "managed by this patch queue"))
1161
1145
1162 # we know there are no local changes, so we can make a simplified
1146 # we know there are no local changes, so we can make a simplified
1163 # form of hg.update.
1147 # form of hg.update.
1164 if update:
1148 if update:
1165 qp = self.qparents(repo, rev)
1149 qp = self.qparents(repo, rev)
1166 ctx = repo[qp]
1150 ctx = repo[qp]
1167 m, a, r, d = repo.status(qp, top)[:4]
1151 m, a, r, d = repo.status(qp, top)[:4]
1168 if d:
1152 if d:
1169 raise util.Abort(_("deletions found between repo revs"))
1153 raise util.Abort(_("deletions found between repo revs"))
1170 for f in a:
1154 for f in a:
1171 try:
1155 try:
1172 util.unlink(repo.wjoin(f))
1156 util.unlink(repo.wjoin(f))
1173 except OSError, e:
1157 except OSError, e:
1174 if e.errno != errno.ENOENT:
1158 if e.errno != errno.ENOENT:
1175 raise
1159 raise
1176 repo.dirstate.forget(f)
1160 repo.dirstate.forget(f)
1177 for f in m + r:
1161 for f in m + r:
1178 fctx = ctx[f]
1162 fctx = ctx[f]
1179 repo.wwrite(f, fctx.data(), fctx.flags())
1163 repo.wwrite(f, fctx.data(), fctx.flags())
1180 repo.dirstate.normal(f)
1164 repo.dirstate.normal(f)
1181 repo.dirstate.setparents(qp, nullid)
1165 repo.dirstate.setparents(qp, nullid)
1182 for patch in reversed(self.applied[start:end]):
1166 for patch in reversed(self.applied[start:end]):
1183 self.ui.status(_("popping %s\n") % patch.name)
1167 self.ui.status(_("popping %s\n") % patch.name)
1184 del self.applied[start:end]
1168 del self.applied[start:end]
1185 self.strip(repo, rev, update=False, backup='strip')
1169 self.strip(repo, rev, update=False, backup='strip')
1186 if self.applied:
1170 if self.applied:
1187 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1171 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1188 else:
1172 else:
1189 self.ui.write(_("patch queue now empty\n"))
1173 self.ui.write(_("patch queue now empty\n"))
1190 finally:
1174 finally:
1191 wlock.release()
1175 wlock.release()
1192
1176
1193 def diff(self, repo, pats, opts):
1177 def diff(self, repo, pats, opts):
1194 top, patch = self.check_toppatch(repo)
1178 top, patch = self.check_toppatch(repo)
1195 if not top:
1179 if not top:
1196 self.ui.write(_("no patches applied\n"))
1180 self.ui.write(_("no patches applied\n"))
1197 return
1181 return
1198 qp = self.qparents(repo, top)
1182 qp = self.qparents(repo, top)
1199 if opts.get('reverse'):
1183 if opts.get('reverse'):
1200 node1, node2 = None, qp
1184 node1, node2 = None, qp
1201 else:
1185 else:
1202 node1, node2 = qp, None
1186 node1, node2 = qp, None
1203 diffopts = self.diffopts(opts, patch)
1187 diffopts = self.diffopts(opts, patch)
1204 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1188 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1205
1189
1206 def refresh(self, repo, pats=None, **opts):
1190 def refresh(self, repo, pats=None, **opts):
1207 if not self.applied:
1191 if not self.applied:
1208 self.ui.write(_("no patches applied\n"))
1192 self.ui.write(_("no patches applied\n"))
1209 return 1
1193 return 1
1210 msg = opts.get('msg', '').rstrip()
1194 msg = opts.get('msg', '').rstrip()
1211 newuser = opts.get('user')
1195 newuser = opts.get('user')
1212 newdate = opts.get('date')
1196 newdate = opts.get('date')
1213 if newdate:
1197 if newdate:
1214 newdate = '%d %d' % util.parsedate(newdate)
1198 newdate = '%d %d' % util.parsedate(newdate)
1215 wlock = repo.wlock()
1199 wlock = repo.wlock()
1216
1200
1217 try:
1201 try:
1218 self.check_toppatch(repo)
1202 self.check_toppatch(repo)
1219 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1203 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1220 if repo.changelog.heads(top) != [top]:
1204 if repo.changelog.heads(top) != [top]:
1221 raise util.Abort(_("cannot refresh a revision with children"))
1205 raise util.Abort(_("cannot refresh a revision with children"))
1222
1206
1223 cparents = repo.changelog.parents(top)
1207 cparents = repo.changelog.parents(top)
1224 patchparent = self.qparents(repo, top)
1208 patchparent = self.qparents(repo, top)
1225 ph = patchheader(self.join(patchfn), self.plainmode)
1209 ph = patchheader(self.join(patchfn), self.plainmode)
1226 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1210 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1227 if msg:
1211 if msg:
1228 ph.setmessage(msg)
1212 ph.setmessage(msg)
1229 if newuser:
1213 if newuser:
1230 ph.setuser(newuser)
1214 ph.setuser(newuser)
1231 if newdate:
1215 if newdate:
1232 ph.setdate(newdate)
1216 ph.setdate(newdate)
1233 ph.setparent(hex(patchparent))
1217 ph.setparent(hex(patchparent))
1234
1218
1235 # only commit new patch when write is complete
1219 # only commit new patch when write is complete
1236 patchf = self.opener(patchfn, 'w', atomictemp=True)
1220 patchf = self.opener(patchfn, 'w', atomictemp=True)
1237
1221
1238 comments = str(ph)
1222 comments = str(ph)
1239 if comments:
1223 if comments:
1240 patchf.write(comments)
1224 patchf.write(comments)
1241
1225
1242 # update the dirstate in place, strip off the qtip commit
1226 # update the dirstate in place, strip off the qtip commit
1243 # and then commit.
1227 # and then commit.
1244 #
1228 #
1245 # this should really read:
1229 # this should really read:
1246 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1230 # mm, dd, aa, aa2 = repo.status(tip, patchparent)[:4]
1247 # but we do it backwards to take advantage of manifest/chlog
1231 # but we do it backwards to take advantage of manifest/chlog
1248 # caching against the next repo.status call
1232 # caching against the next repo.status call
1249 mm, aa, dd, aa2 = repo.status(patchparent, top)[:4]
1233 mm, aa, dd, aa2 = repo.status(patchparent, top)[:4]
1250 changes = repo.changelog.read(top)
1234 changes = repo.changelog.read(top)
1251 man = repo.manifest.read(changes[0])
1235 man = repo.manifest.read(changes[0])
1252 aaa = aa[:]
1236 aaa = aa[:]
1253 matchfn = cmdutil.match(repo, pats, opts)
1237 matchfn = cmdutil.match(repo, pats, opts)
1254 # in short mode, we only diff the files included in the
1238 # in short mode, we only diff the files included in the
1255 # patch already plus specified files
1239 # patch already plus specified files
1256 if opts.get('short'):
1240 if opts.get('short'):
1257 # if amending a patch, we start with existing
1241 # if amending a patch, we start with existing
1258 # files plus specified files - unfiltered
1242 # files plus specified files - unfiltered
1259 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1243 match = cmdutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1260 # filter with inc/exl options
1244 # filter with inc/exl options
1261 matchfn = cmdutil.match(repo, opts=opts)
1245 matchfn = cmdutil.match(repo, opts=opts)
1262 else:
1246 else:
1263 match = cmdutil.matchall(repo)
1247 match = cmdutil.matchall(repo)
1264 m, a, r, d = repo.status(match=match)[:4]
1248 m, a, r, d = repo.status(match=match)[:4]
1265
1249
1266 # we might end up with files that were added between
1250 # we might end up with files that were added between
1267 # qtip and the dirstate parent, but then changed in the
1251 # qtip and the dirstate parent, but then changed in the
1268 # local dirstate. in this case, we want them to only
1252 # local dirstate. in this case, we want them to only
1269 # show up in the added section
1253 # show up in the added section
1270 for x in m:
1254 for x in m:
1271 if x not in aa:
1255 if x not in aa:
1272 mm.append(x)
1256 mm.append(x)
1273 # we might end up with files added by the local dirstate that
1257 # we might end up with files added by the local dirstate that
1274 # were deleted by the patch. In this case, they should only
1258 # were deleted by the patch. In this case, they should only
1275 # show up in the changed section.
1259 # show up in the changed section.
1276 for x in a:
1260 for x in a:
1277 if x in dd:
1261 if x in dd:
1278 del dd[dd.index(x)]
1262 del dd[dd.index(x)]
1279 mm.append(x)
1263 mm.append(x)
1280 else:
1264 else:
1281 aa.append(x)
1265 aa.append(x)
1282 # make sure any files deleted in the local dirstate
1266 # make sure any files deleted in the local dirstate
1283 # are not in the add or change column of the patch
1267 # are not in the add or change column of the patch
1284 forget = []
1268 forget = []
1285 for x in d + r:
1269 for x in d + r:
1286 if x in aa:
1270 if x in aa:
1287 del aa[aa.index(x)]
1271 del aa[aa.index(x)]
1288 forget.append(x)
1272 forget.append(x)
1289 continue
1273 continue
1290 elif x in mm:
1274 elif x in mm:
1291 del mm[mm.index(x)]
1275 del mm[mm.index(x)]
1292 dd.append(x)
1276 dd.append(x)
1293
1277
1294 m = list(set(mm))
1278 m = list(set(mm))
1295 r = list(set(dd))
1279 r = list(set(dd))
1296 a = list(set(aa))
1280 a = list(set(aa))
1297 c = [filter(matchfn, l) for l in (m, a, r)]
1281 c = [filter(matchfn, l) for l in (m, a, r)]
1298 match = cmdutil.matchfiles(repo, set(c[0] + c[1] + c[2]))
1282 match = cmdutil.matchfiles(repo, set(c[0] + c[1] + c[2]))
1299 chunks = patch.diff(repo, patchparent, match=match,
1283 chunks = patch.diff(repo, patchparent, match=match,
1300 changes=c, opts=diffopts)
1284 changes=c, opts=diffopts)
1301 for chunk in chunks:
1285 for chunk in chunks:
1302 patchf.write(chunk)
1286 patchf.write(chunk)
1303
1287
1304 try:
1288 try:
1305 if diffopts.git or diffopts.upgrade:
1289 if diffopts.git or diffopts.upgrade:
1306 copies = {}
1290 copies = {}
1307 for dst in a:
1291 for dst in a:
1308 src = repo.dirstate.copied(dst)
1292 src = repo.dirstate.copied(dst)
1309 # during qfold, the source file for copies may
1293 # during qfold, the source file for copies may
1310 # be removed. Treat this as a simple add.
1294 # be removed. Treat this as a simple add.
1311 if src is not None and src in repo.dirstate:
1295 if src is not None and src in repo.dirstate:
1312 copies.setdefault(src, []).append(dst)
1296 copies.setdefault(src, []).append(dst)
1313 repo.dirstate.add(dst)
1297 repo.dirstate.add(dst)
1314 # remember the copies between patchparent and qtip
1298 # remember the copies between patchparent and qtip
1315 for dst in aaa:
1299 for dst in aaa:
1316 f = repo.file(dst)
1300 f = repo.file(dst)
1317 src = f.renamed(man[dst])
1301 src = f.renamed(man[dst])
1318 if src:
1302 if src:
1319 copies.setdefault(src[0], []).extend(
1303 copies.setdefault(src[0], []).extend(
1320 copies.get(dst, []))
1304 copies.get(dst, []))
1321 if dst in a:
1305 if dst in a:
1322 copies[src[0]].append(dst)
1306 copies[src[0]].append(dst)
1323 # we can't copy a file created by the patch itself
1307 # we can't copy a file created by the patch itself
1324 if dst in copies:
1308 if dst in copies:
1325 del copies[dst]
1309 del copies[dst]
1326 for src, dsts in copies.iteritems():
1310 for src, dsts in copies.iteritems():
1327 for dst in dsts:
1311 for dst in dsts:
1328 repo.dirstate.copy(src, dst)
1312 repo.dirstate.copy(src, dst)
1329 else:
1313 else:
1330 for dst in a:
1314 for dst in a:
1331 repo.dirstate.add(dst)
1315 repo.dirstate.add(dst)
1332 # Drop useless copy information
1316 # Drop useless copy information
1333 for f in list(repo.dirstate.copies()):
1317 for f in list(repo.dirstate.copies()):
1334 repo.dirstate.copy(None, f)
1318 repo.dirstate.copy(None, f)
1335 for f in r:
1319 for f in r:
1336 repo.dirstate.remove(f)
1320 repo.dirstate.remove(f)
1337 # if the patch excludes a modified file, mark that
1321 # if the patch excludes a modified file, mark that
1338 # file with mtime=0 so status can see it.
1322 # file with mtime=0 so status can see it.
1339 mm = []
1323 mm = []
1340 for i in xrange(len(m)-1, -1, -1):
1324 for i in xrange(len(m)-1, -1, -1):
1341 if not matchfn(m[i]):
1325 if not matchfn(m[i]):
1342 mm.append(m[i])
1326 mm.append(m[i])
1343 del m[i]
1327 del m[i]
1344 for f in m:
1328 for f in m:
1345 repo.dirstate.normal(f)
1329 repo.dirstate.normal(f)
1346 for f in mm:
1330 for f in mm:
1347 repo.dirstate.normallookup(f)
1331 repo.dirstate.normallookup(f)
1348 for f in forget:
1332 for f in forget:
1349 repo.dirstate.forget(f)
1333 repo.dirstate.forget(f)
1350
1334
1351 if not msg:
1335 if not msg:
1352 if not ph.message:
1336 if not ph.message:
1353 message = "[mq]: %s\n" % patchfn
1337 message = "[mq]: %s\n" % patchfn
1354 else:
1338 else:
1355 message = "\n".join(ph.message)
1339 message = "\n".join(ph.message)
1356 else:
1340 else:
1357 message = msg
1341 message = msg
1358
1342
1359 user = ph.user or changes[1]
1343 user = ph.user or changes[1]
1360
1344
1361 # assumes strip can roll itself back if interrupted
1345 # assumes strip can roll itself back if interrupted
1362 repo.dirstate.setparents(*cparents)
1346 repo.dirstate.setparents(*cparents)
1363 self.applied.pop()
1347 self.applied.pop()
1364 self.applied_dirty = 1
1348 self.applied_dirty = 1
1365 self.strip(repo, top, update=False,
1349 self.strip(repo, top, update=False,
1366 backup='strip')
1350 backup='strip')
1367 except:
1351 except:
1368 repo.dirstate.invalidate()
1352 repo.dirstate.invalidate()
1369 raise
1353 raise
1370
1354
1371 try:
1355 try:
1372 # might be nice to attempt to roll back strip after this
1356 # might be nice to attempt to roll back strip after this
1373 patchf.rename()
1357 patchf.rename()
1374 n = repo.commit(message, user, ph.date, match=match,
1358 n = repo.commit(message, user, ph.date, match=match,
1375 force=True)
1359 force=True)
1376 self.applied.append(statusentry(n, patchfn))
1360 self.applied.append(statusentry(n, patchfn))
1377 except:
1361 except:
1378 ctx = repo[cparents[0]]
1362 ctx = repo[cparents[0]]
1379 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1363 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1380 self.save_dirty()
1364 self.save_dirty()
1381 self.ui.warn(_('refresh interrupted while patch was popped! '
1365 self.ui.warn(_('refresh interrupted while patch was popped! '
1382 '(revert --all, qpush to recover)\n'))
1366 '(revert --all, qpush to recover)\n'))
1383 raise
1367 raise
1384 finally:
1368 finally:
1385 wlock.release()
1369 wlock.release()
1386 self.removeundo(repo)
1370 self.removeundo(repo)
1387
1371
1388 def init(self, repo, create=False):
1372 def init(self, repo, create=False):
1389 if not create and os.path.isdir(self.path):
1373 if not create and os.path.isdir(self.path):
1390 raise util.Abort(_("patch queue directory already exists"))
1374 raise util.Abort(_("patch queue directory already exists"))
1391 try:
1375 try:
1392 os.mkdir(self.path)
1376 os.mkdir(self.path)
1393 except OSError, inst:
1377 except OSError, inst:
1394 if inst.errno != errno.EEXIST or not create:
1378 if inst.errno != errno.EEXIST or not create:
1395 raise
1379 raise
1396 if create:
1380 if create:
1397 return self.qrepo(create=True)
1381 return self.qrepo(create=True)
1398
1382
1399 def unapplied(self, repo, patch=None):
1383 def unapplied(self, repo, patch=None):
1400 if patch and patch not in self.series:
1384 if patch and patch not in self.series:
1401 raise util.Abort(_("patch %s is not in series file") % patch)
1385 raise util.Abort(_("patch %s is not in series file") % patch)
1402 if not patch:
1386 if not patch:
1403 start = self.series_end()
1387 start = self.series_end()
1404 else:
1388 else:
1405 start = self.series.index(patch) + 1
1389 start = self.series.index(patch) + 1
1406 unapplied = []
1390 unapplied = []
1407 for i in xrange(start, len(self.series)):
1391 for i in xrange(start, len(self.series)):
1408 pushable, reason = self.pushable(i)
1392 pushable, reason = self.pushable(i)
1409 if pushable:
1393 if pushable:
1410 unapplied.append((i, self.series[i]))
1394 unapplied.append((i, self.series[i]))
1411 self.explain_pushable(i)
1395 self.explain_pushable(i)
1412 return unapplied
1396 return unapplied
1413
1397
1414 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1398 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1415 summary=False):
1399 summary=False):
1416 def displayname(pfx, patchname, state):
1400 def displayname(pfx, patchname, state):
1417 if pfx:
1401 if pfx:
1418 self.ui.write(pfx)
1402 self.ui.write(pfx)
1419 if summary:
1403 if summary:
1420 ph = patchheader(self.join(patchname), self.plainmode)
1404 ph = patchheader(self.join(patchname), self.plainmode)
1421 msg = ph.message and ph.message[0] or ''
1405 msg = ph.message and ph.message[0] or ''
1422 if not self.ui.plain():
1406 if not self.ui.plain():
1423 width = util.termwidth() - len(pfx) - len(patchname) - 2
1407 width = util.termwidth() - len(pfx) - len(patchname) - 2
1424 if width > 0:
1408 if width > 0:
1425 msg = util.ellipsis(msg, width)
1409 msg = util.ellipsis(msg, width)
1426 else:
1410 else:
1427 msg = ''
1411 msg = ''
1428 self.ui.write(patchname, label='qseries.' + state)
1412 self.ui.write(patchname, label='qseries.' + state)
1429 self.ui.write(': ')
1413 self.ui.write(': ')
1430 self.ui.write(msg, label='qseries.message.' + state)
1414 self.ui.write(msg, label='qseries.message.' + state)
1431 else:
1415 else:
1432 self.ui.write(patchname, label='qseries.' + state)
1416 self.ui.write(patchname, label='qseries.' + state)
1433 self.ui.write('\n')
1417 self.ui.write('\n')
1434
1418
1435 applied = set([p.name for p in self.applied])
1419 applied = set([p.name for p in self.applied])
1436 if length is None:
1420 if length is None:
1437 length = len(self.series) - start
1421 length = len(self.series) - start
1438 if not missing:
1422 if not missing:
1439 if self.ui.verbose:
1423 if self.ui.verbose:
1440 idxwidth = len(str(start + length - 1))
1424 idxwidth = len(str(start + length - 1))
1441 for i in xrange(start, start + length):
1425 for i in xrange(start, start + length):
1442 patch = self.series[i]
1426 patch = self.series[i]
1443 if patch in applied:
1427 if patch in applied:
1444 char, state = 'A', 'applied'
1428 char, state = 'A', 'applied'
1445 elif self.pushable(i)[0]:
1429 elif self.pushable(i)[0]:
1446 char, state = 'U', 'unapplied'
1430 char, state = 'U', 'unapplied'
1447 else:
1431 else:
1448 char, state = 'G', 'guarded'
1432 char, state = 'G', 'guarded'
1449 pfx = ''
1433 pfx = ''
1450 if self.ui.verbose:
1434 if self.ui.verbose:
1451 pfx = '%*d %s ' % (idxwidth, i, char)
1435 pfx = '%*d %s ' % (idxwidth, i, char)
1452 elif status and status != char:
1436 elif status and status != char:
1453 continue
1437 continue
1454 displayname(pfx, patch, state)
1438 displayname(pfx, patch, state)
1455 else:
1439 else:
1456 msng_list = []
1440 msng_list = []
1457 for root, dirs, files in os.walk(self.path):
1441 for root, dirs, files in os.walk(self.path):
1458 d = root[len(self.path) + 1:]
1442 d = root[len(self.path) + 1:]
1459 for f in files:
1443 for f in files:
1460 fl = os.path.join(d, f)
1444 fl = os.path.join(d, f)
1461 if (fl not in self.series and
1445 if (fl not in self.series and
1462 fl not in (self.status_path, self.series_path,
1446 fl not in (self.status_path, self.series_path,
1463 self.guards_path)
1447 self.guards_path)
1464 and not fl.startswith('.')):
1448 and not fl.startswith('.')):
1465 msng_list.append(fl)
1449 msng_list.append(fl)
1466 for x in sorted(msng_list):
1450 for x in sorted(msng_list):
1467 pfx = self.ui.verbose and ('D ') or ''
1451 pfx = self.ui.verbose and ('D ') or ''
1468 displayname(pfx, x, 'missing')
1452 displayname(pfx, x, 'missing')
1469
1453
1470 def issaveline(self, l):
1454 def issaveline(self, l):
1471 if l.name == '.hg.patches.save.line':
1455 if l.name == '.hg.patches.save.line':
1472 return True
1456 return True
1473
1457
1474 def qrepo(self, create=False):
1458 def qrepo(self, create=False):
1475 if create or os.path.isdir(self.join(".hg")):
1459 if create or os.path.isdir(self.join(".hg")):
1476 return hg.repository(self.ui, path=self.path, create=create)
1460 return hg.repository(self.ui, path=self.path, create=create)
1477
1461
1478 def restore(self, repo, rev, delete=None, qupdate=None):
1462 def restore(self, repo, rev, delete=None, qupdate=None):
1479 desc = repo[rev].description().strip()
1463 desc = repo[rev].description().strip()
1480 lines = desc.splitlines()
1464 lines = desc.splitlines()
1481 i = 0
1465 i = 0
1482 datastart = None
1466 datastart = None
1483 series = []
1467 series = []
1484 applied = []
1468 applied = []
1485 qpp = None
1469 qpp = None
1486 for i, line in enumerate(lines):
1470 for i, line in enumerate(lines):
1487 if line == 'Patch Data:':
1471 if line == 'Patch Data:':
1488 datastart = i + 1
1472 datastart = i + 1
1489 elif line.startswith('Dirstate:'):
1473 elif line.startswith('Dirstate:'):
1490 l = line.rstrip()
1474 l = line.rstrip()
1491 l = l[10:].split(' ')
1475 l = l[10:].split(' ')
1492 qpp = [bin(x) for x in l]
1476 qpp = [bin(x) for x in l]
1493 elif datastart != None:
1477 elif datastart != None:
1494 l = line.rstrip()
1478 l = line.rstrip()
1495 n, name = l.split(':', 1)
1479 n, name = l.split(':', 1)
1496 if n:
1480 if n:
1497 applied.append(statusentry(bin(n), name))
1481 applied.append(statusentry(bin(n), name))
1498 else:
1482 else:
1499 series.append(l)
1483 series.append(l)
1500 if datastart is None:
1484 if datastart is None:
1501 self.ui.warn(_("No saved patch data found\n"))
1485 self.ui.warn(_("No saved patch data found\n"))
1502 return 1
1486 return 1
1503 self.ui.warn(_("restoring status: %s\n") % lines[0])
1487 self.ui.warn(_("restoring status: %s\n") % lines[0])
1504 self.full_series = series
1488 self.full_series = series
1505 self.applied = applied
1489 self.applied = applied
1506 self.parse_series()
1490 self.parse_series()
1507 self.series_dirty = 1
1491 self.series_dirty = 1
1508 self.applied_dirty = 1
1492 self.applied_dirty = 1
1509 heads = repo.changelog.heads()
1493 heads = repo.changelog.heads()
1510 if delete:
1494 if delete:
1511 if rev not in heads:
1495 if rev not in heads:
1512 self.ui.warn(_("save entry has children, leaving it alone\n"))
1496 self.ui.warn(_("save entry has children, leaving it alone\n"))
1513 else:
1497 else:
1514 self.ui.warn(_("removing save entry %s\n") % short(rev))
1498 self.ui.warn(_("removing save entry %s\n") % short(rev))
1515 pp = repo.dirstate.parents()
1499 pp = repo.dirstate.parents()
1516 if rev in pp:
1500 if rev in pp:
1517 update = True
1501 update = True
1518 else:
1502 else:
1519 update = False
1503 update = False
1520 self.strip(repo, rev, update=update, backup='strip')
1504 self.strip(repo, rev, update=update, backup='strip')
1521 if qpp:
1505 if qpp:
1522 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1506 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1523 (short(qpp[0]), short(qpp[1])))
1507 (short(qpp[0]), short(qpp[1])))
1524 if qupdate:
1508 if qupdate:
1525 self.ui.status(_("queue directory updating\n"))
1509 self.ui.status(_("queue directory updating\n"))
1526 r = self.qrepo()
1510 r = self.qrepo()
1527 if not r:
1511 if not r:
1528 self.ui.warn(_("Unable to load queue repository\n"))
1512 self.ui.warn(_("Unable to load queue repository\n"))
1529 return 1
1513 return 1
1530 hg.clean(r, qpp[0])
1514 hg.clean(r, qpp[0])
1531
1515
1532 def save(self, repo, msg=None):
1516 def save(self, repo, msg=None):
1533 if not self.applied:
1517 if not self.applied:
1534 self.ui.warn(_("save: no patches applied, exiting\n"))
1518 self.ui.warn(_("save: no patches applied, exiting\n"))
1535 return 1
1519 return 1
1536 if self.issaveline(self.applied[-1]):
1520 if self.issaveline(self.applied[-1]):
1537 self.ui.warn(_("status is already saved\n"))
1521 self.ui.warn(_("status is already saved\n"))
1538 return 1
1522 return 1
1539
1523
1540 if not msg:
1524 if not msg:
1541 msg = _("hg patches saved state")
1525 msg = _("hg patches saved state")
1542 else:
1526 else:
1543 msg = "hg patches: " + msg.rstrip('\r\n')
1527 msg = "hg patches: " + msg.rstrip('\r\n')
1544 r = self.qrepo()
1528 r = self.qrepo()
1545 if r:
1529 if r:
1546 pp = r.dirstate.parents()
1530 pp = r.dirstate.parents()
1547 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1531 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1548 msg += "\n\nPatch Data:\n"
1532 msg += "\n\nPatch Data:\n"
1549 msg += ''.join('%s\n' % x for x in self.applied)
1533 msg += ''.join('%s\n' % x for x in self.applied)
1550 msg += ''.join(':%s\n' % x for x in self.full_series)
1534 msg += ''.join(':%s\n' % x for x in self.full_series)
1551 n = repo.commit(msg, force=True)
1535 n = repo.commit(msg, force=True)
1552 if not n:
1536 if not n:
1553 self.ui.warn(_("repo commit failed\n"))
1537 self.ui.warn(_("repo commit failed\n"))
1554 return 1
1538 return 1
1555 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1539 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1556 self.applied_dirty = 1
1540 self.applied_dirty = 1
1557 self.removeundo(repo)
1541 self.removeundo(repo)
1558
1542
1559 def full_series_end(self):
1543 def full_series_end(self):
1560 if self.applied:
1544 if self.applied:
1561 p = self.applied[-1].name
1545 p = self.applied[-1].name
1562 end = self.find_series(p)
1546 end = self.find_series(p)
1563 if end is None:
1547 if end is None:
1564 return len(self.full_series)
1548 return len(self.full_series)
1565 return end + 1
1549 return end + 1
1566 return 0
1550 return 0
1567
1551
1568 def series_end(self, all_patches=False):
1552 def series_end(self, all_patches=False):
1569 """If all_patches is False, return the index of the next pushable patch
1553 """If all_patches is False, return the index of the next pushable patch
1570 in the series, or the series length. If all_patches is True, return the
1554 in the series, or the series length. If all_patches is True, return the
1571 index of the first patch past the last applied one.
1555 index of the first patch past the last applied one.
1572 """
1556 """
1573 end = 0
1557 end = 0
1574 def next(start):
1558 def next(start):
1575 if all_patches or start >= len(self.series):
1559 if all_patches or start >= len(self.series):
1576 return start
1560 return start
1577 for i in xrange(start, len(self.series)):
1561 for i in xrange(start, len(self.series)):
1578 p, reason = self.pushable(i)
1562 p, reason = self.pushable(i)
1579 if p:
1563 if p:
1580 break
1564 break
1581 self.explain_pushable(i)
1565 self.explain_pushable(i)
1582 return i
1566 return i
1583 if self.applied:
1567 if self.applied:
1584 p = self.applied[-1].name
1568 p = self.applied[-1].name
1585 try:
1569 try:
1586 end = self.series.index(p)
1570 end = self.series.index(p)
1587 except ValueError:
1571 except ValueError:
1588 return 0
1572 return 0
1589 return next(end + 1)
1573 return next(end + 1)
1590 return next(end)
1574 return next(end)
1591
1575
1592 def appliedname(self, index):
1576 def appliedname(self, index):
1593 pname = self.applied[index].name
1577 pname = self.applied[index].name
1594 if not self.ui.verbose:
1578 if not self.ui.verbose:
1595 p = pname
1579 p = pname
1596 else:
1580 else:
1597 p = str(self.series.index(pname)) + " " + pname
1581 p = str(self.series.index(pname)) + " " + pname
1598 return p
1582 return p
1599
1583
1600 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1584 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1601 force=None, git=False):
1585 force=None, git=False):
1602 def checkseries(patchname):
1586 def checkseries(patchname):
1603 if patchname in self.series:
1587 if patchname in self.series:
1604 raise util.Abort(_('patch %s is already in the series file')
1588 raise util.Abort(_('patch %s is already in the series file')
1605 % patchname)
1589 % patchname)
1606 def checkfile(patchname):
1590 def checkfile(patchname):
1607 if not force and os.path.exists(self.join(patchname)):
1591 if not force and os.path.exists(self.join(patchname)):
1608 raise util.Abort(_('patch "%s" already exists')
1592 raise util.Abort(_('patch "%s" already exists')
1609 % patchname)
1593 % patchname)
1610
1594
1611 if rev:
1595 if rev:
1612 if files:
1596 if files:
1613 raise util.Abort(_('option "-r" not valid when importing '
1597 raise util.Abort(_('option "-r" not valid when importing '
1614 'files'))
1598 'files'))
1615 rev = cmdutil.revrange(repo, rev)
1599 rev = cmdutil.revrange(repo, rev)
1616 rev.sort(reverse=True)
1600 rev.sort(reverse=True)
1617 if (len(files) > 1 or len(rev) > 1) and patchname:
1601 if (len(files) > 1 or len(rev) > 1) and patchname:
1618 raise util.Abort(_('option "-n" not valid when importing multiple '
1602 raise util.Abort(_('option "-n" not valid when importing multiple '
1619 'patches'))
1603 'patches'))
1620 added = []
1604 added = []
1621 if rev:
1605 if rev:
1622 # If mq patches are applied, we can only import revisions
1606 # If mq patches are applied, we can only import revisions
1623 # that form a linear path to qbase.
1607 # that form a linear path to qbase.
1624 # Otherwise, they should form a linear path to a head.
1608 # Otherwise, they should form a linear path to a head.
1625 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1609 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1626 if len(heads) > 1:
1610 if len(heads) > 1:
1627 raise util.Abort(_('revision %d is the root of more than one '
1611 raise util.Abort(_('revision %d is the root of more than one '
1628 'branch') % rev[-1])
1612 'branch') % rev[-1])
1629 if self.applied:
1613 if self.applied:
1630 base = repo.changelog.node(rev[0])
1614 base = repo.changelog.node(rev[0])
1631 if base in [n.node for n in self.applied]:
1615 if base in [n.node for n in self.applied]:
1632 raise util.Abort(_('revision %d is already managed')
1616 raise util.Abort(_('revision %d is already managed')
1633 % rev[0])
1617 % rev[0])
1634 if heads != [self.applied[-1].node]:
1618 if heads != [self.applied[-1].node]:
1635 raise util.Abort(_('revision %d is not the parent of '
1619 raise util.Abort(_('revision %d is not the parent of '
1636 'the queue') % rev[0])
1620 'the queue') % rev[0])
1637 base = repo.changelog.rev(self.applied[0].node)
1621 base = repo.changelog.rev(self.applied[0].node)
1638 lastparent = repo.changelog.parentrevs(base)[0]
1622 lastparent = repo.changelog.parentrevs(base)[0]
1639 else:
1623 else:
1640 if heads != [repo.changelog.node(rev[0])]:
1624 if heads != [repo.changelog.node(rev[0])]:
1641 raise util.Abort(_('revision %d has unmanaged children')
1625 raise util.Abort(_('revision %d has unmanaged children')
1642 % rev[0])
1626 % rev[0])
1643 lastparent = None
1627 lastparent = None
1644
1628
1645 diffopts = self.diffopts({'git': git})
1629 diffopts = self.diffopts({'git': git})
1646 for r in rev:
1630 for r in rev:
1647 p1, p2 = repo.changelog.parentrevs(r)
1631 p1, p2 = repo.changelog.parentrevs(r)
1648 n = repo.changelog.node(r)
1632 n = repo.changelog.node(r)
1649 if p2 != nullrev:
1633 if p2 != nullrev:
1650 raise util.Abort(_('cannot import merge revision %d') % r)
1634 raise util.Abort(_('cannot import merge revision %d') % r)
1651 if lastparent and lastparent != r:
1635 if lastparent and lastparent != r:
1652 raise util.Abort(_('revision %d is not the parent of %d')
1636 raise util.Abort(_('revision %d is not the parent of %d')
1653 % (r, lastparent))
1637 % (r, lastparent))
1654 lastparent = p1
1638 lastparent = p1
1655
1639
1656 if not patchname:
1640 if not patchname:
1657 patchname = normname('%d.diff' % r)
1641 patchname = normname('%d.diff' % r)
1658 self.check_reserved_name(patchname)
1642 self.check_reserved_name(patchname)
1659 checkseries(patchname)
1643 checkseries(patchname)
1660 checkfile(patchname)
1644 checkfile(patchname)
1661 self.full_series.insert(0, patchname)
1645 self.full_series.insert(0, patchname)
1662
1646
1663 patchf = self.opener(patchname, "w")
1647 patchf = self.opener(patchname, "w")
1664 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1648 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1665 patchf.close()
1649 patchf.close()
1666
1650
1667 se = statusentry(n, patchname)
1651 se = statusentry(n, patchname)
1668 self.applied.insert(0, se)
1652 self.applied.insert(0, se)
1669
1653
1670 added.append(patchname)
1654 added.append(patchname)
1671 patchname = None
1655 patchname = None
1672 self.parse_series()
1656 self.parse_series()
1673 self.applied_dirty = 1
1657 self.applied_dirty = 1
1674
1658
1675 for i, filename in enumerate(files):
1659 for i, filename in enumerate(files):
1676 if existing:
1660 if existing:
1677 if filename == '-':
1661 if filename == '-':
1678 raise util.Abort(_('-e is incompatible with import from -'))
1662 raise util.Abort(_('-e is incompatible with import from -'))
1679 if not patchname:
1663 if not patchname:
1680 patchname = normname(filename)
1664 patchname = normname(filename)
1681 self.check_reserved_name(patchname)
1665 self.check_reserved_name(patchname)
1682 if not os.path.isfile(self.join(patchname)):
1666 if not os.path.isfile(self.join(patchname)):
1683 raise util.Abort(_("patch %s does not exist") % patchname)
1667 raise util.Abort(_("patch %s does not exist") % patchname)
1684 else:
1668 else:
1685 try:
1669 try:
1686 if filename == '-':
1670 if filename == '-':
1687 if not patchname:
1671 if not patchname:
1688 raise util.Abort(
1672 raise util.Abort(
1689 _('need --name to import a patch from -'))
1673 _('need --name to import a patch from -'))
1690 text = sys.stdin.read()
1674 text = sys.stdin.read()
1691 else:
1675 else:
1692 text = url.open(self.ui, filename).read()
1676 text = url.open(self.ui, filename).read()
1693 except (OSError, IOError):
1677 except (OSError, IOError):
1694 raise util.Abort(_("unable to read %s") % filename)
1678 raise util.Abort(_("unable to read %s") % filename)
1695 if not patchname:
1679 if not patchname:
1696 patchname = normname(os.path.basename(filename))
1680 patchname = normname(os.path.basename(filename))
1697 self.check_reserved_name(patchname)
1681 self.check_reserved_name(patchname)
1698 checkfile(patchname)
1682 checkfile(patchname)
1699 patchf = self.opener(patchname, "w")
1683 patchf = self.opener(patchname, "w")
1700 patchf.write(text)
1684 patchf.write(text)
1701 if not force:
1685 if not force:
1702 checkseries(patchname)
1686 checkseries(patchname)
1703 if patchname not in self.series:
1687 if patchname not in self.series:
1704 index = self.full_series_end() + i
1688 index = self.full_series_end() + i
1705 self.full_series[index:index] = [patchname]
1689 self.full_series[index:index] = [patchname]
1706 self.parse_series()
1690 self.parse_series()
1707 self.ui.warn(_("adding %s to series file\n") % patchname)
1691 self.ui.warn(_("adding %s to series file\n") % patchname)
1708 added.append(patchname)
1692 added.append(patchname)
1709 patchname = None
1693 patchname = None
1710 self.series_dirty = 1
1694 self.series_dirty = 1
1711 qrepo = self.qrepo()
1695 qrepo = self.qrepo()
1712 if qrepo:
1696 if qrepo:
1713 qrepo.add(added)
1697 qrepo.add(added)
1714
1698
1715 def delete(ui, repo, *patches, **opts):
1699 def delete(ui, repo, *patches, **opts):
1716 """remove patches from queue
1700 """remove patches from queue
1717
1701
1718 The patches must not be applied, and at least one patch is required. With
1702 The patches must not be applied, and at least one patch is required. With
1719 -k/--keep, the patch files are preserved in the patch directory.
1703 -k/--keep, the patch files are preserved in the patch directory.
1720
1704
1721 To stop managing a patch and move it into permanent history,
1705 To stop managing a patch and move it into permanent history,
1722 use the qfinish command."""
1706 use the qfinish command."""
1723 q = repo.mq
1707 q = repo.mq
1724 q.delete(repo, patches, opts)
1708 q.delete(repo, patches, opts)
1725 q.save_dirty()
1709 q.save_dirty()
1726 return 0
1710 return 0
1727
1711
1728 def applied(ui, repo, patch=None, **opts):
1712 def applied(ui, repo, patch=None, **opts):
1729 """print the patches already applied"""
1713 """print the patches already applied"""
1730
1714
1731 q = repo.mq
1715 q = repo.mq
1732 l = len(q.applied)
1716 l = len(q.applied)
1733
1717
1734 if patch:
1718 if patch:
1735 if patch not in q.series:
1719 if patch not in q.series:
1736 raise util.Abort(_("patch %s is not in series file") % patch)
1720 raise util.Abort(_("patch %s is not in series file") % patch)
1737 end = q.series.index(patch) + 1
1721 end = q.series.index(patch) + 1
1738 else:
1722 else:
1739 end = q.series_end(True)
1723 end = q.series_end(True)
1740
1724
1741 if opts.get('last') and not end:
1725 if opts.get('last') and not end:
1742 ui.write(_("no patches applied\n"))
1726 ui.write(_("no patches applied\n"))
1743 return 1
1727 return 1
1744 elif opts.get('last') and end == 1:
1728 elif opts.get('last') and end == 1:
1745 ui.write(_("only one patch applied\n"))
1729 ui.write(_("only one patch applied\n"))
1746 return 1
1730 return 1
1747 elif opts.get('last'):
1731 elif opts.get('last'):
1748 start = end - 2
1732 start = end - 2
1749 end = 1
1733 end = 1
1750 else:
1734 else:
1751 start = 0
1735 start = 0
1752
1736
1753 return q.qseries(repo, length=end, start=start, status='A',
1737 return q.qseries(repo, length=end, start=start, status='A',
1754 summary=opts.get('summary'))
1738 summary=opts.get('summary'))
1755
1739
1756 def unapplied(ui, repo, patch=None, **opts):
1740 def unapplied(ui, repo, patch=None, **opts):
1757 """print the patches not yet applied"""
1741 """print the patches not yet applied"""
1758
1742
1759 q = repo.mq
1743 q = repo.mq
1760 if patch:
1744 if patch:
1761 if patch not in q.series:
1745 if patch not in q.series:
1762 raise util.Abort(_("patch %s is not in series file") % patch)
1746 raise util.Abort(_("patch %s is not in series file") % patch)
1763 start = q.series.index(patch) + 1
1747 start = q.series.index(patch) + 1
1764 else:
1748 else:
1765 start = q.series_end(True)
1749 start = q.series_end(True)
1766
1750
1767 if start == len(q.series) and opts.get('first'):
1751 if start == len(q.series) and opts.get('first'):
1768 ui.write(_("all patches applied\n"))
1752 ui.write(_("all patches applied\n"))
1769 return 1
1753 return 1
1770
1754
1771 length = opts.get('first') and 1 or None
1755 length = opts.get('first') and 1 or None
1772 return q.qseries(repo, start=start, length=length, status='U',
1756 return q.qseries(repo, start=start, length=length, status='U',
1773 summary=opts.get('summary'))
1757 summary=opts.get('summary'))
1774
1758
1775 def qimport(ui, repo, *filename, **opts):
1759 def qimport(ui, repo, *filename, **opts):
1776 """import a patch
1760 """import a patch
1777
1761
1778 The patch is inserted into the series after the last applied
1762 The patch is inserted into the series after the last applied
1779 patch. If no patches have been applied, qimport prepends the patch
1763 patch. If no patches have been applied, qimport prepends the patch
1780 to the series.
1764 to the series.
1781
1765
1782 The patch will have the same name as its source file unless you
1766 The patch will have the same name as its source file unless you
1783 give it a new one with -n/--name.
1767 give it a new one with -n/--name.
1784
1768
1785 You can register an existing patch inside the patch directory with
1769 You can register an existing patch inside the patch directory with
1786 the -e/--existing flag.
1770 the -e/--existing flag.
1787
1771
1788 With -f/--force, an existing patch of the same name will be
1772 With -f/--force, an existing patch of the same name will be
1789 overwritten.
1773 overwritten.
1790
1774
1791 An existing changeset may be placed under mq control with -r/--rev
1775 An existing changeset may be placed under mq control with -r/--rev
1792 (e.g. qimport --rev tip -n patch will place tip under mq control).
1776 (e.g. qimport --rev tip -n patch will place tip under mq control).
1793 With -g/--git, patches imported with --rev will use the git diff
1777 With -g/--git, patches imported with --rev will use the git diff
1794 format. See the diffs help topic for information on why this is
1778 format. See the diffs help topic for information on why this is
1795 important for preserving rename/copy information and permission
1779 important for preserving rename/copy information and permission
1796 changes.
1780 changes.
1797
1781
1798 To import a patch from standard input, pass - as the patch file.
1782 To import a patch from standard input, pass - as the patch file.
1799 When importing from standard input, a patch name must be specified
1783 When importing from standard input, a patch name must be specified
1800 using the --name flag.
1784 using the --name flag.
1801 """
1785 """
1802 q = repo.mq
1786 q = repo.mq
1803 q.qimport(repo, filename, patchname=opts['name'],
1787 q.qimport(repo, filename, patchname=opts['name'],
1804 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1788 existing=opts['existing'], force=opts['force'], rev=opts['rev'],
1805 git=opts['git'])
1789 git=opts['git'])
1806 q.save_dirty()
1790 q.save_dirty()
1807
1791
1808 if opts.get('push') and not opts.get('rev'):
1792 if opts.get('push') and not opts.get('rev'):
1809 return q.push(repo, None)
1793 return q.push(repo, None)
1810 return 0
1794 return 0
1811
1795
1812 def qinit(ui, repo, create):
1796 def qinit(ui, repo, create):
1813 """initialize a new queue repository
1797 """initialize a new queue repository
1814
1798
1815 This command also creates a series file for ordering patches, and
1799 This command also creates a series file for ordering patches, and
1816 an mq-specific .hgignore file in the queue repository, to exclude
1800 an mq-specific .hgignore file in the queue repository, to exclude
1817 the status and guards files (these contain mostly transient state)."""
1801 the status and guards files (these contain mostly transient state)."""
1818 q = repo.mq
1802 q = repo.mq
1819 r = q.init(repo, create)
1803 r = q.init(repo, create)
1820 q.save_dirty()
1804 q.save_dirty()
1821 if r:
1805 if r:
1822 if not os.path.exists(r.wjoin('.hgignore')):
1806 if not os.path.exists(r.wjoin('.hgignore')):
1823 fp = r.wopener('.hgignore', 'w')
1807 fp = r.wopener('.hgignore', 'w')
1824 fp.write('^\\.hg\n')
1808 fp.write('^\\.hg\n')
1825 fp.write('^\\.mq\n')
1809 fp.write('^\\.mq\n')
1826 fp.write('syntax: glob\n')
1810 fp.write('syntax: glob\n')
1827 fp.write('status\n')
1811 fp.write('status\n')
1828 fp.write('guards\n')
1812 fp.write('guards\n')
1829 fp.close()
1813 fp.close()
1830 if not os.path.exists(r.wjoin('series')):
1814 if not os.path.exists(r.wjoin('series')):
1831 r.wopener('series', 'w').close()
1815 r.wopener('series', 'w').close()
1832 r.add(['.hgignore', 'series'])
1816 r.add(['.hgignore', 'series'])
1833 commands.add(ui, r)
1817 commands.add(ui, r)
1834 return 0
1818 return 0
1835
1819
1836 def init(ui, repo, **opts):
1820 def init(ui, repo, **opts):
1837 """init a new queue repository (DEPRECATED)
1821 """init a new queue repository (DEPRECATED)
1838
1822
1839 The queue repository is unversioned by default. If
1823 The queue repository is unversioned by default. If
1840 -c/--create-repo is specified, qinit will create a separate nested
1824 -c/--create-repo is specified, qinit will create a separate nested
1841 repository for patches (qinit -c may also be run later to convert
1825 repository for patches (qinit -c may also be run later to convert
1842 an unversioned patch repository into a versioned one). You can use
1826 an unversioned patch repository into a versioned one). You can use
1843 qcommit to commit changes to this queue repository.
1827 qcommit to commit changes to this queue repository.
1844
1828
1845 This command is deprecated. Without -c, it's implied by other relevant
1829 This command is deprecated. Without -c, it's implied by other relevant
1846 commands. With -c, use hg init --mq instead."""
1830 commands. With -c, use hg init --mq instead."""
1847 return qinit(ui, repo, create=opts['create_repo'])
1831 return qinit(ui, repo, create=opts['create_repo'])
1848
1832
1849 def clone(ui, source, dest=None, **opts):
1833 def clone(ui, source, dest=None, **opts):
1850 '''clone main and patch repository at same time
1834 '''clone main and patch repository at same time
1851
1835
1852 If source is local, destination will have no patches applied. If
1836 If source is local, destination will have no patches applied. If
1853 source is remote, this command can not check if patches are
1837 source is remote, this command can not check if patches are
1854 applied in source, so cannot guarantee that patches are not
1838 applied in source, so cannot guarantee that patches are not
1855 applied in destination. If you clone remote repository, be sure
1839 applied in destination. If you clone remote repository, be sure
1856 before that it has no patches applied.
1840 before that it has no patches applied.
1857
1841
1858 Source patch repository is looked for in <src>/.hg/patches by
1842 Source patch repository is looked for in <src>/.hg/patches by
1859 default. Use -p <url> to change.
1843 default. Use -p <url> to change.
1860
1844
1861 The patch directory must be a nested Mercurial repository, as
1845 The patch directory must be a nested Mercurial repository, as
1862 would be created by init --mq.
1846 would be created by init --mq.
1863 '''
1847 '''
1864 def patchdir(repo):
1848 def patchdir(repo):
1865 url = repo.url()
1849 url = repo.url()
1866 if url.endswith('/'):
1850 if url.endswith('/'):
1867 url = url[:-1]
1851 url = url[:-1]
1868 return url + '/.hg/patches'
1852 return url + '/.hg/patches'
1869 if dest is None:
1853 if dest is None:
1870 dest = hg.defaultdest(source)
1854 dest = hg.defaultdest(source)
1871 sr = hg.repository(cmdutil.remoteui(ui, opts), ui.expandpath(source))
1855 sr = hg.repository(cmdutil.remoteui(ui, opts), ui.expandpath(source))
1872 if opts['patches']:
1856 if opts['patches']:
1873 patchespath = ui.expandpath(opts['patches'])
1857 patchespath = ui.expandpath(opts['patches'])
1874 else:
1858 else:
1875 patchespath = patchdir(sr)
1859 patchespath = patchdir(sr)
1876 try:
1860 try:
1877 hg.repository(ui, patchespath)
1861 hg.repository(ui, patchespath)
1878 except error.RepoError:
1862 except error.RepoError:
1879 raise util.Abort(_('versioned patch repository not found'
1863 raise util.Abort(_('versioned patch repository not found'
1880 ' (see init --mq)'))
1864 ' (see init --mq)'))
1881 qbase, destrev = None, None
1865 qbase, destrev = None, None
1882 if sr.local():
1866 if sr.local():
1883 if sr.mq.applied:
1867 if sr.mq.applied:
1884 qbase = sr.mq.applied[0].node
1868 qbase = sr.mq.applied[0].node
1885 if not hg.islocal(dest):
1869 if not hg.islocal(dest):
1886 heads = set(sr.heads())
1870 heads = set(sr.heads())
1887 destrev = list(heads.difference(sr.heads(qbase)))
1871 destrev = list(heads.difference(sr.heads(qbase)))
1888 destrev.append(sr.changelog.parents(qbase)[0])
1872 destrev.append(sr.changelog.parents(qbase)[0])
1889 elif sr.capable('lookup'):
1873 elif sr.capable('lookup'):
1890 try:
1874 try:
1891 qbase = sr.lookup('qbase')
1875 qbase = sr.lookup('qbase')
1892 except error.RepoError:
1876 except error.RepoError:
1893 pass
1877 pass
1894 ui.note(_('cloning main repository\n'))
1878 ui.note(_('cloning main repository\n'))
1895 sr, dr = hg.clone(ui, sr.url(), dest,
1879 sr, dr = hg.clone(ui, sr.url(), dest,
1896 pull=opts['pull'],
1880 pull=opts['pull'],
1897 rev=destrev,
1881 rev=destrev,
1898 update=False,
1882 update=False,
1899 stream=opts['uncompressed'])
1883 stream=opts['uncompressed'])
1900 ui.note(_('cloning patch repository\n'))
1884 ui.note(_('cloning patch repository\n'))
1901 hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1885 hg.clone(ui, opts['patches'] or patchdir(sr), patchdir(dr),
1902 pull=opts['pull'], update=not opts['noupdate'],
1886 pull=opts['pull'], update=not opts['noupdate'],
1903 stream=opts['uncompressed'])
1887 stream=opts['uncompressed'])
1904 if dr.local():
1888 if dr.local():
1905 if qbase:
1889 if qbase:
1906 ui.note(_('stripping applied patches from destination '
1890 ui.note(_('stripping applied patches from destination '
1907 'repository\n'))
1891 'repository\n'))
1908 dr.mq.strip(dr, qbase, update=False, backup=None)
1892 dr.mq.strip(dr, qbase, update=False, backup=None)
1909 if not opts['noupdate']:
1893 if not opts['noupdate']:
1910 ui.note(_('updating destination repository\n'))
1894 ui.note(_('updating destination repository\n'))
1911 hg.update(dr, dr.changelog.tip())
1895 hg.update(dr, dr.changelog.tip())
1912
1896
1913 def commit(ui, repo, *pats, **opts):
1897 def commit(ui, repo, *pats, **opts):
1914 """commit changes in the queue repository (DEPRECATED)
1898 """commit changes in the queue repository (DEPRECATED)
1915
1899
1916 This command is deprecated; use hg commit --mq instead."""
1900 This command is deprecated; use hg commit --mq instead."""
1917 q = repo.mq
1901 q = repo.mq
1918 r = q.qrepo()
1902 r = q.qrepo()
1919 if not r:
1903 if not r:
1920 raise util.Abort('no queue repository')
1904 raise util.Abort('no queue repository')
1921 commands.commit(r.ui, r, *pats, **opts)
1905 commands.commit(r.ui, r, *pats, **opts)
1922
1906
1923 def series(ui, repo, **opts):
1907 def series(ui, repo, **opts):
1924 """print the entire series file"""
1908 """print the entire series file"""
1925 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1909 repo.mq.qseries(repo, missing=opts['missing'], summary=opts['summary'])
1926 return 0
1910 return 0
1927
1911
1928 def top(ui, repo, **opts):
1912 def top(ui, repo, **opts):
1929 """print the name of the current patch"""
1913 """print the name of the current patch"""
1930 q = repo.mq
1914 q = repo.mq
1931 t = q.applied and q.series_end(True) or 0
1915 t = q.applied and q.series_end(True) or 0
1932 if t:
1916 if t:
1933 return q.qseries(repo, start=t - 1, length=1, status='A',
1917 return q.qseries(repo, start=t - 1, length=1, status='A',
1934 summary=opts.get('summary'))
1918 summary=opts.get('summary'))
1935 else:
1919 else:
1936 ui.write(_("no patches applied\n"))
1920 ui.write(_("no patches applied\n"))
1937 return 1
1921 return 1
1938
1922
1939 def next(ui, repo, **opts):
1923 def next(ui, repo, **opts):
1940 """print the name of the next patch"""
1924 """print the name of the next patch"""
1941 q = repo.mq
1925 q = repo.mq
1942 end = q.series_end()
1926 end = q.series_end()
1943 if end == len(q.series):
1927 if end == len(q.series):
1944 ui.write(_("all patches applied\n"))
1928 ui.write(_("all patches applied\n"))
1945 return 1
1929 return 1
1946 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1930 return q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
1947
1931
1948 def prev(ui, repo, **opts):
1932 def prev(ui, repo, **opts):
1949 """print the name of the previous patch"""
1933 """print the name of the previous patch"""
1950 q = repo.mq
1934 q = repo.mq
1951 l = len(q.applied)
1935 l = len(q.applied)
1952 if l == 1:
1936 if l == 1:
1953 ui.write(_("only one patch applied\n"))
1937 ui.write(_("only one patch applied\n"))
1954 return 1
1938 return 1
1955 if not l:
1939 if not l:
1956 ui.write(_("no patches applied\n"))
1940 ui.write(_("no patches applied\n"))
1957 return 1
1941 return 1
1958 return q.qseries(repo, start=l - 2, length=1, status='A',
1942 return q.qseries(repo, start=l - 2, length=1, status='A',
1959 summary=opts.get('summary'))
1943 summary=opts.get('summary'))
1960
1944
1961 def setupheaderopts(ui, opts):
1945 def setupheaderopts(ui, opts):
1962 if not opts.get('user') and opts.get('currentuser'):
1946 if not opts.get('user') and opts.get('currentuser'):
1963 opts['user'] = ui.username()
1947 opts['user'] = ui.username()
1964 if not opts.get('date') and opts.get('currentdate'):
1948 if not opts.get('date') and opts.get('currentdate'):
1965 opts['date'] = "%d %d" % util.makedate()
1949 opts['date'] = "%d %d" % util.makedate()
1966
1950
1967 def new(ui, repo, patch, *args, **opts):
1951 def new(ui, repo, patch, *args, **opts):
1968 """create a new patch
1952 """create a new patch
1969
1953
1970 qnew creates a new patch on top of the currently-applied patch (if
1954 qnew creates a new patch on top of the currently-applied patch (if
1971 any). The patch will be initialized with any outstanding changes
1955 any). The patch will be initialized with any outstanding changes
1972 in the working directory. You may also use -I/--include,
1956 in the working directory. You may also use -I/--include,
1973 -X/--exclude, and/or a list of files after the patch name to add
1957 -X/--exclude, and/or a list of files after the patch name to add
1974 only changes to matching files to the new patch, leaving the rest
1958 only changes to matching files to the new patch, leaving the rest
1975 as uncommitted modifications.
1959 as uncommitted modifications.
1976
1960
1977 -u/--user and -d/--date can be used to set the (given) user and
1961 -u/--user and -d/--date can be used to set the (given) user and
1978 date, respectively. -U/--currentuser and -D/--currentdate set user
1962 date, respectively. -U/--currentuser and -D/--currentdate set user
1979 to current user and date to current date.
1963 to current user and date to current date.
1980
1964
1981 -e/--edit, -m/--message or -l/--logfile set the patch header as
1965 -e/--edit, -m/--message or -l/--logfile set the patch header as
1982 well as the commit message. If none is specified, the header is
1966 well as the commit message. If none is specified, the header is
1983 empty and the commit message is '[mq]: PATCH'.
1967 empty and the commit message is '[mq]: PATCH'.
1984
1968
1985 Use the -g/--git option to keep the patch in the git extended diff
1969 Use the -g/--git option to keep the patch in the git extended diff
1986 format. Read the diffs help topic for more information on why this
1970 format. Read the diffs help topic for more information on why this
1987 is important for preserving permission changes and copy/rename
1971 is important for preserving permission changes and copy/rename
1988 information.
1972 information.
1989 """
1973 """
1990 msg = cmdutil.logmessage(opts)
1974 msg = cmdutil.logmessage(opts)
1991 def getmsg():
1975 def getmsg():
1992 return ui.edit(msg, ui.username())
1976 return ui.edit(msg, ui.username())
1993 q = repo.mq
1977 q = repo.mq
1994 opts['msg'] = msg
1978 opts['msg'] = msg
1995 if opts.get('edit'):
1979 if opts.get('edit'):
1996 opts['msg'] = getmsg
1980 opts['msg'] = getmsg
1997 else:
1981 else:
1998 opts['msg'] = msg
1982 opts['msg'] = msg
1999 setupheaderopts(ui, opts)
1983 setupheaderopts(ui, opts)
2000 q.new(repo, patch, *args, **opts)
1984 q.new(repo, patch, *args, **opts)
2001 q.save_dirty()
1985 q.save_dirty()
2002 return 0
1986 return 0
2003
1987
2004 def refresh(ui, repo, *pats, **opts):
1988 def refresh(ui, repo, *pats, **opts):
2005 """update the current patch
1989 """update the current patch
2006
1990
2007 If any file patterns are provided, the refreshed patch will
1991 If any file patterns are provided, the refreshed patch will
2008 contain only the modifications that match those patterns; the
1992 contain only the modifications that match those patterns; the
2009 remaining modifications will remain in the working directory.
1993 remaining modifications will remain in the working directory.
2010
1994
2011 If -s/--short is specified, files currently included in the patch
1995 If -s/--short is specified, files currently included in the patch
2012 will be refreshed just like matched files and remain in the patch.
1996 will be refreshed just like matched files and remain in the patch.
2013
1997
2014 hg add/remove/copy/rename work as usual, though you might want to
1998 hg add/remove/copy/rename work as usual, though you might want to
2015 use git-style patches (-g/--git or [diff] git=1) to track copies
1999 use git-style patches (-g/--git or [diff] git=1) to track copies
2016 and renames. See the diffs help topic for more information on the
2000 and renames. See the diffs help topic for more information on the
2017 git diff format.
2001 git diff format.
2018 """
2002 """
2019 q = repo.mq
2003 q = repo.mq
2020 message = cmdutil.logmessage(opts)
2004 message = cmdutil.logmessage(opts)
2021 if opts['edit']:
2005 if opts['edit']:
2022 if not q.applied:
2006 if not q.applied:
2023 ui.write(_("no patches applied\n"))
2007 ui.write(_("no patches applied\n"))
2024 return 1
2008 return 1
2025 if message:
2009 if message:
2026 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2010 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2027 patch = q.applied[-1].name
2011 patch = q.applied[-1].name
2028 ph = patchheader(q.join(patch), q.plainmode)
2012 ph = patchheader(q.join(patch), q.plainmode)
2029 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2013 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2030 setupheaderopts(ui, opts)
2014 setupheaderopts(ui, opts)
2031 ret = q.refresh(repo, pats, msg=message, **opts)
2015 ret = q.refresh(repo, pats, msg=message, **opts)
2032 q.save_dirty()
2016 q.save_dirty()
2033 return ret
2017 return ret
2034
2018
2035 def diff(ui, repo, *pats, **opts):
2019 def diff(ui, repo, *pats, **opts):
2036 """diff of the current patch and subsequent modifications
2020 """diff of the current patch and subsequent modifications
2037
2021
2038 Shows a diff which includes the current patch as well as any
2022 Shows a diff which includes the current patch as well as any
2039 changes which have been made in the working directory since the
2023 changes which have been made in the working directory since the
2040 last refresh (thus showing what the current patch would become
2024 last refresh (thus showing what the current patch would become
2041 after a qrefresh).
2025 after a qrefresh).
2042
2026
2043 Use :hg:`diff` if you only want to see the changes made since the
2027 Use :hg:`diff` if you only want to see the changes made since the
2044 last qrefresh, or :hg:`export qtip` if you want to see changes
2028 last qrefresh, or :hg:`export qtip` if you want to see changes
2045 made by the current patch without including changes made since the
2029 made by the current patch without including changes made since the
2046 qrefresh.
2030 qrefresh.
2047 """
2031 """
2048 repo.mq.diff(repo, pats, opts)
2032 repo.mq.diff(repo, pats, opts)
2049 return 0
2033 return 0
2050
2034
2051 def fold(ui, repo, *files, **opts):
2035 def fold(ui, repo, *files, **opts):
2052 """fold the named patches into the current patch
2036 """fold the named patches into the current patch
2053
2037
2054 Patches must not yet be applied. Each patch will be successively
2038 Patches must not yet be applied. Each patch will be successively
2055 applied to the current patch in the order given. If all the
2039 applied to the current patch in the order given. If all the
2056 patches apply successfully, the current patch will be refreshed
2040 patches apply successfully, the current patch will be refreshed
2057 with the new cumulative patch, and the folded patches will be
2041 with the new cumulative patch, and the folded patches will be
2058 deleted. With -k/--keep, the folded patch files will not be
2042 deleted. With -k/--keep, the folded patch files will not be
2059 removed afterwards.
2043 removed afterwards.
2060
2044
2061 The header for each folded patch will be concatenated with the
2045 The header for each folded patch will be concatenated with the
2062 current patch header, separated by a line of '* * *'."""
2046 current patch header, separated by a line of '* * *'."""
2063
2047
2064 q = repo.mq
2048 q = repo.mq
2065
2049
2066 if not files:
2050 if not files:
2067 raise util.Abort(_('qfold requires at least one patch name'))
2051 raise util.Abort(_('qfold requires at least one patch name'))
2068 if not q.check_toppatch(repo)[0]:
2052 if not q.check_toppatch(repo)[0]:
2069 raise util.Abort(_('No patches applied'))
2053 raise util.Abort(_('No patches applied'))
2070 q.check_localchanges(repo)
2054 q.check_localchanges(repo)
2071
2055
2072 message = cmdutil.logmessage(opts)
2056 message = cmdutil.logmessage(opts)
2073 if opts['edit']:
2057 if opts['edit']:
2074 if message:
2058 if message:
2075 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2059 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2076
2060
2077 parent = q.lookup('qtip')
2061 parent = q.lookup('qtip')
2078 patches = []
2062 patches = []
2079 messages = []
2063 messages = []
2080 for f in files:
2064 for f in files:
2081 p = q.lookup(f)
2065 p = q.lookup(f)
2082 if p in patches or p == parent:
2066 if p in patches or p == parent:
2083 ui.warn(_('Skipping already folded patch %s') % p)
2067 ui.warn(_('Skipping already folded patch %s') % p)
2084 if q.isapplied(p):
2068 if q.isapplied(p):
2085 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2069 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2086 patches.append(p)
2070 patches.append(p)
2087
2071
2088 for p in patches:
2072 for p in patches:
2089 if not message:
2073 if not message:
2090 ph = patchheader(q.join(p), q.plainmode)
2074 ph = patchheader(q.join(p), q.plainmode)
2091 if ph.message:
2075 if ph.message:
2092 messages.append(ph.message)
2076 messages.append(ph.message)
2093 pf = q.join(p)
2077 pf = q.join(p)
2094 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2078 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2095 if not patchsuccess:
2079 if not patchsuccess:
2096 raise util.Abort(_('Error folding patch %s') % p)
2080 raise util.Abort(_('Error folding patch %s') % p)
2097 patch.updatedir(ui, repo, files)
2081 patch.updatedir(ui, repo, files)
2098
2082
2099 if not message:
2083 if not message:
2100 ph = patchheader(q.join(parent), q.plainmode)
2084 ph = patchheader(q.join(parent), q.plainmode)
2101 message, user = ph.message, ph.user
2085 message, user = ph.message, ph.user
2102 for msg in messages:
2086 for msg in messages:
2103 message.append('* * *')
2087 message.append('* * *')
2104 message.extend(msg)
2088 message.extend(msg)
2105 message = '\n'.join(message)
2089 message = '\n'.join(message)
2106
2090
2107 if opts['edit']:
2091 if opts['edit']:
2108 message = ui.edit(message, user or ui.username())
2092 message = ui.edit(message, user or ui.username())
2109
2093
2110 diffopts = q.patchopts(q.diffopts(), *patches)
2094 diffopts = q.patchopts(q.diffopts(), *patches)
2111 q.refresh(repo, msg=message, git=diffopts.git)
2095 q.refresh(repo, msg=message, git=diffopts.git)
2112 q.delete(repo, patches, opts)
2096 q.delete(repo, patches, opts)
2113 q.save_dirty()
2097 q.save_dirty()
2114
2098
2115 def goto(ui, repo, patch, **opts):
2099 def goto(ui, repo, patch, **opts):
2116 '''push or pop patches until named patch is at top of stack'''
2100 '''push or pop patches until named patch is at top of stack'''
2117 q = repo.mq
2101 q = repo.mq
2118 patch = q.lookup(patch)
2102 patch = q.lookup(patch)
2119 if q.isapplied(patch):
2103 if q.isapplied(patch):
2120 ret = q.pop(repo, patch, force=opts['force'])
2104 ret = q.pop(repo, patch, force=opts['force'])
2121 else:
2105 else:
2122 ret = q.push(repo, patch, force=opts['force'])
2106 ret = q.push(repo, patch, force=opts['force'])
2123 q.save_dirty()
2107 q.save_dirty()
2124 return ret
2108 return ret
2125
2109
2126 def guard(ui, repo, *args, **opts):
2110 def guard(ui, repo, *args, **opts):
2127 '''set or print guards for a patch
2111 '''set or print guards for a patch
2128
2112
2129 Guards control whether a patch can be pushed. A patch with no
2113 Guards control whether a patch can be pushed. A patch with no
2130 guards is always pushed. A patch with a positive guard ("+foo") is
2114 guards is always pushed. A patch with a positive guard ("+foo") is
2131 pushed only if the qselect command has activated it. A patch with
2115 pushed only if the qselect command has activated it. A patch with
2132 a negative guard ("-foo") is never pushed if the qselect command
2116 a negative guard ("-foo") is never pushed if the qselect command
2133 has activated it.
2117 has activated it.
2134
2118
2135 With no arguments, print the currently active guards.
2119 With no arguments, print the currently active guards.
2136 With arguments, set guards for the named patch.
2120 With arguments, set guards for the named patch.
2137 NOTE: Specifying negative guards now requires '--'.
2121 NOTE: Specifying negative guards now requires '--'.
2138
2122
2139 To set guards on another patch::
2123 To set guards on another patch::
2140
2124
2141 hg qguard other.patch -- +2.6.17 -stable
2125 hg qguard other.patch -- +2.6.17 -stable
2142 '''
2126 '''
2143 def status(idx):
2127 def status(idx):
2144 guards = q.series_guards[idx] or ['unguarded']
2128 guards = q.series_guards[idx] or ['unguarded']
2145 ui.write('%s: ' % ui.label(q.series[idx], 'qguard.patch'))
2129 ui.write('%s: ' % ui.label(q.series[idx], 'qguard.patch'))
2146 for i, guard in enumerate(guards):
2130 for i, guard in enumerate(guards):
2147 if guard.startswith('+'):
2131 if guard.startswith('+'):
2148 ui.write(guard, label='qguard.positive')
2132 ui.write(guard, label='qguard.positive')
2149 elif guard.startswith('-'):
2133 elif guard.startswith('-'):
2150 ui.write(guard, label='qguard.negative')
2134 ui.write(guard, label='qguard.negative')
2151 else:
2135 else:
2152 ui.write(guard, label='qguard.unguarded')
2136 ui.write(guard, label='qguard.unguarded')
2153 if i != len(guards) - 1:
2137 if i != len(guards) - 1:
2154 ui.write(' ')
2138 ui.write(' ')
2155 ui.write('\n')
2139 ui.write('\n')
2156 q = repo.mq
2140 q = repo.mq
2157 patch = None
2141 patch = None
2158 args = list(args)
2142 args = list(args)
2159 if opts['list']:
2143 if opts['list']:
2160 if args or opts['none']:
2144 if args or opts['none']:
2161 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2145 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2162 for i in xrange(len(q.series)):
2146 for i in xrange(len(q.series)):
2163 status(i)
2147 status(i)
2164 return
2148 return
2165 if not args or args[0][0:1] in '-+':
2149 if not args or args[0][0:1] in '-+':
2166 if not q.applied:
2150 if not q.applied:
2167 raise util.Abort(_('no patches applied'))
2151 raise util.Abort(_('no patches applied'))
2168 patch = q.applied[-1].name
2152 patch = q.applied[-1].name
2169 if patch is None and args[0][0:1] not in '-+':
2153 if patch is None and args[0][0:1] not in '-+':
2170 patch = args.pop(0)
2154 patch = args.pop(0)
2171 if patch is None:
2155 if patch is None:
2172 raise util.Abort(_('no patch to work with'))
2156 raise util.Abort(_('no patch to work with'))
2173 if args or opts['none']:
2157 if args or opts['none']:
2174 idx = q.find_series(patch)
2158 idx = q.find_series(patch)
2175 if idx is None:
2159 if idx is None:
2176 raise util.Abort(_('no patch named %s') % patch)
2160 raise util.Abort(_('no patch named %s') % patch)
2177 q.set_guards(idx, args)
2161 q.set_guards(idx, args)
2178 q.save_dirty()
2162 q.save_dirty()
2179 else:
2163 else:
2180 status(q.series.index(q.lookup(patch)))
2164 status(q.series.index(q.lookup(patch)))
2181
2165
2182 def header(ui, repo, patch=None):
2166 def header(ui, repo, patch=None):
2183 """print the header of the topmost or specified patch"""
2167 """print the header of the topmost or specified patch"""
2184 q = repo.mq
2168 q = repo.mq
2185
2169
2186 if patch:
2170 if patch:
2187 patch = q.lookup(patch)
2171 patch = q.lookup(patch)
2188 else:
2172 else:
2189 if not q.applied:
2173 if not q.applied:
2190 ui.write(_('no patches applied\n'))
2174 ui.write(_('no patches applied\n'))
2191 return 1
2175 return 1
2192 patch = q.lookup('qtip')
2176 patch = q.lookup('qtip')
2193 ph = patchheader(q.join(patch), q.plainmode)
2177 ph = patchheader(q.join(patch), q.plainmode)
2194
2178
2195 ui.write('\n'.join(ph.message) + '\n')
2179 ui.write('\n'.join(ph.message) + '\n')
2196
2180
2197 def lastsavename(path):
2181 def lastsavename(path):
2198 (directory, base) = os.path.split(path)
2182 (directory, base) = os.path.split(path)
2199 names = os.listdir(directory)
2183 names = os.listdir(directory)
2200 namere = re.compile("%s.([0-9]+)" % base)
2184 namere = re.compile("%s.([0-9]+)" % base)
2201 maxindex = None
2185 maxindex = None
2202 maxname = None
2186 maxname = None
2203 for f in names:
2187 for f in names:
2204 m = namere.match(f)
2188 m = namere.match(f)
2205 if m:
2189 if m:
2206 index = int(m.group(1))
2190 index = int(m.group(1))
2207 if maxindex is None or index > maxindex:
2191 if maxindex is None or index > maxindex:
2208 maxindex = index
2192 maxindex = index
2209 maxname = f
2193 maxname = f
2210 if maxname:
2194 if maxname:
2211 return (os.path.join(directory, maxname), maxindex)
2195 return (os.path.join(directory, maxname), maxindex)
2212 return (None, None)
2196 return (None, None)
2213
2197
2214 def savename(path):
2198 def savename(path):
2215 (last, index) = lastsavename(path)
2199 (last, index) = lastsavename(path)
2216 if last is None:
2200 if last is None:
2217 index = 0
2201 index = 0
2218 newpath = path + ".%d" % (index + 1)
2202 newpath = path + ".%d" % (index + 1)
2219 return newpath
2203 return newpath
2220
2204
2221 def push(ui, repo, patch=None, **opts):
2205 def push(ui, repo, patch=None, **opts):
2222 """push the next patch onto the stack
2206 """push the next patch onto the stack
2223
2207
2224 When -f/--force is applied, all local changes in patched files
2208 When -f/--force is applied, all local changes in patched files
2225 will be lost.
2209 will be lost.
2226 """
2210 """
2227 q = repo.mq
2211 q = repo.mq
2228 mergeq = None
2212 mergeq = None
2229
2213
2230 if opts['merge']:
2214 if opts['merge']:
2231 if opts['name']:
2215 if opts['name']:
2232 newpath = repo.join(opts['name'])
2216 newpath = repo.join(opts['name'])
2233 else:
2217 else:
2234 newpath, i = lastsavename(q.path)
2218 newpath, i = lastsavename(q.path)
2235 if not newpath:
2219 if not newpath:
2236 ui.warn(_("no saved queues found, please use -n\n"))
2220 ui.warn(_("no saved queues found, please use -n\n"))
2237 return 1
2221 return 1
2238 mergeq = queue(ui, repo.join(""), newpath)
2222 mergeq = queue(ui, repo.join(""), newpath)
2239 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2223 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2240 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2224 ret = q.push(repo, patch, force=opts['force'], list=opts['list'],
2241 mergeq=mergeq, all=opts.get('all'))
2225 mergeq=mergeq, all=opts.get('all'))
2242 return ret
2226 return ret
2243
2227
2244 def pop(ui, repo, patch=None, **opts):
2228 def pop(ui, repo, patch=None, **opts):
2245 """pop the current patch off the stack
2229 """pop the current patch off the stack
2246
2230
2247 By default, pops off the top of the patch stack. If given a patch
2231 By default, pops off the top of the patch stack. If given a patch
2248 name, keeps popping off patches until the named patch is at the
2232 name, keeps popping off patches until the named patch is at the
2249 top of the stack.
2233 top of the stack.
2250 """
2234 """
2251 localupdate = True
2235 localupdate = True
2252 if opts['name']:
2236 if opts['name']:
2253 q = queue(ui, repo.join(""), repo.join(opts['name']))
2237 q = queue(ui, repo.join(""), repo.join(opts['name']))
2254 ui.warn(_('using patch queue: %s\n') % q.path)
2238 ui.warn(_('using patch queue: %s\n') % q.path)
2255 localupdate = False
2239 localupdate = False
2256 else:
2240 else:
2257 q = repo.mq
2241 q = repo.mq
2258 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2242 ret = q.pop(repo, patch, force=opts['force'], update=localupdate,
2259 all=opts['all'])
2243 all=opts['all'])
2260 q.save_dirty()
2244 q.save_dirty()
2261 return ret
2245 return ret
2262
2246
2263 def rename(ui, repo, patch, name=None, **opts):
2247 def rename(ui, repo, patch, name=None, **opts):
2264 """rename a patch
2248 """rename a patch
2265
2249
2266 With one argument, renames the current patch to PATCH1.
2250 With one argument, renames the current patch to PATCH1.
2267 With two arguments, renames PATCH1 to PATCH2."""
2251 With two arguments, renames PATCH1 to PATCH2."""
2268
2252
2269 q = repo.mq
2253 q = repo.mq
2270
2254
2271 if not name:
2255 if not name:
2272 name = patch
2256 name = patch
2273 patch = None
2257 patch = None
2274
2258
2275 if patch:
2259 if patch:
2276 patch = q.lookup(patch)
2260 patch = q.lookup(patch)
2277 else:
2261 else:
2278 if not q.applied:
2262 if not q.applied:
2279 ui.write(_('no patches applied\n'))
2263 ui.write(_('no patches applied\n'))
2280 return
2264 return
2281 patch = q.lookup('qtip')
2265 patch = q.lookup('qtip')
2282 absdest = q.join(name)
2266 absdest = q.join(name)
2283 if os.path.isdir(absdest):
2267 if os.path.isdir(absdest):
2284 name = normname(os.path.join(name, os.path.basename(patch)))
2268 name = normname(os.path.join(name, os.path.basename(patch)))
2285 absdest = q.join(name)
2269 absdest = q.join(name)
2286 if os.path.exists(absdest):
2270 if os.path.exists(absdest):
2287 raise util.Abort(_('%s already exists') % absdest)
2271 raise util.Abort(_('%s already exists') % absdest)
2288
2272
2289 if name in q.series:
2273 if name in q.series:
2290 raise util.Abort(
2274 raise util.Abort(
2291 _('A patch named %s already exists in the series file') % name)
2275 _('A patch named %s already exists in the series file') % name)
2292
2276
2293 ui.note(_('renaming %s to %s\n') % (patch, name))
2277 ui.note(_('renaming %s to %s\n') % (patch, name))
2294 i = q.find_series(patch)
2278 i = q.find_series(patch)
2295 guards = q.guard_re.findall(q.full_series[i])
2279 guards = q.guard_re.findall(q.full_series[i])
2296 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2280 q.full_series[i] = name + ''.join([' #' + g for g in guards])
2297 q.parse_series()
2281 q.parse_series()
2298 q.series_dirty = 1
2282 q.series_dirty = 1
2299
2283
2300 info = q.isapplied(patch)
2284 info = q.isapplied(patch)
2301 if info:
2285 if info:
2302 q.applied[info[0]] = statusentry(info[1], name)
2286 q.applied[info[0]] = statusentry(info[1], name)
2303 q.applied_dirty = 1
2287 q.applied_dirty = 1
2304
2288
2305 util.rename(q.join(patch), absdest)
2289 util.rename(q.join(patch), absdest)
2306 r = q.qrepo()
2290 r = q.qrepo()
2307 if r:
2291 if r:
2308 wlock = r.wlock()
2292 wlock = r.wlock()
2309 try:
2293 try:
2310 if r.dirstate[patch] == 'a':
2294 if r.dirstate[patch] == 'a':
2311 r.dirstate.forget(patch)
2295 r.dirstate.forget(patch)
2312 r.dirstate.add(name)
2296 r.dirstate.add(name)
2313 else:
2297 else:
2314 if r.dirstate[name] == 'r':
2298 if r.dirstate[name] == 'r':
2315 r.undelete([name])
2299 r.undelete([name])
2316 r.copy(patch, name)
2300 r.copy(patch, name)
2317 r.remove([patch], False)
2301 r.remove([patch], False)
2318 finally:
2302 finally:
2319 wlock.release()
2303 wlock.release()
2320
2304
2321 q.save_dirty()
2305 q.save_dirty()
2322
2306
2323 def restore(ui, repo, rev, **opts):
2307 def restore(ui, repo, rev, **opts):
2324 """restore the queue state saved by a revision (DEPRECATED)
2308 """restore the queue state saved by a revision (DEPRECATED)
2325
2309
2326 This command is deprecated, use rebase --mq instead."""
2310 This command is deprecated, use rebase --mq instead."""
2327 rev = repo.lookup(rev)
2311 rev = repo.lookup(rev)
2328 q = repo.mq
2312 q = repo.mq
2329 q.restore(repo, rev, delete=opts['delete'],
2313 q.restore(repo, rev, delete=opts['delete'],
2330 qupdate=opts['update'])
2314 qupdate=opts['update'])
2331 q.save_dirty()
2315 q.save_dirty()
2332 return 0
2316 return 0
2333
2317
2334 def save(ui, repo, **opts):
2318 def save(ui, repo, **opts):
2335 """save current queue state (DEPRECATED)
2319 """save current queue state (DEPRECATED)
2336
2320
2337 This command is deprecated, use rebase --mq instead."""
2321 This command is deprecated, use rebase --mq instead."""
2338 q = repo.mq
2322 q = repo.mq
2339 message = cmdutil.logmessage(opts)
2323 message = cmdutil.logmessage(opts)
2340 ret = q.save(repo, msg=message)
2324 ret = q.save(repo, msg=message)
2341 if ret:
2325 if ret:
2342 return ret
2326 return ret
2343 q.save_dirty()
2327 q.save_dirty()
2344 if opts['copy']:
2328 if opts['copy']:
2345 path = q.path
2329 path = q.path
2346 if opts['name']:
2330 if opts['name']:
2347 newpath = os.path.join(q.basepath, opts['name'])
2331 newpath = os.path.join(q.basepath, opts['name'])
2348 if os.path.exists(newpath):
2332 if os.path.exists(newpath):
2349 if not os.path.isdir(newpath):
2333 if not os.path.isdir(newpath):
2350 raise util.Abort(_('destination %s exists and is not '
2334 raise util.Abort(_('destination %s exists and is not '
2351 'a directory') % newpath)
2335 'a directory') % newpath)
2352 if not opts['force']:
2336 if not opts['force']:
2353 raise util.Abort(_('destination %s exists, '
2337 raise util.Abort(_('destination %s exists, '
2354 'use -f to force') % newpath)
2338 'use -f to force') % newpath)
2355 else:
2339 else:
2356 newpath = savename(path)
2340 newpath = savename(path)
2357 ui.warn(_("copy %s to %s\n") % (path, newpath))
2341 ui.warn(_("copy %s to %s\n") % (path, newpath))
2358 util.copyfiles(path, newpath)
2342 util.copyfiles(path, newpath)
2359 if opts['empty']:
2343 if opts['empty']:
2360 try:
2344 try:
2361 os.unlink(q.join(q.status_path))
2345 os.unlink(q.join(q.status_path))
2362 except:
2346 except:
2363 pass
2347 pass
2364 return 0
2348 return 0
2365
2349
2366 def strip(ui, repo, rev, **opts):
2350 def strip(ui, repo, rev, **opts):
2367 """strip a revision and all its descendants from the repository
2351 """strip a revision and all its descendants from the repository
2368
2352
2369 If one of the working directory's parent revisions is stripped, the
2353 If one of the working directory's parent revisions is stripped, the
2370 working directory will be updated to the parent of the stripped
2354 working directory will be updated to the parent of the stripped
2371 revision.
2355 revision.
2372 """
2356 """
2373 backup = 'all'
2357 backup = 'all'
2374 if opts['backup']:
2358 if opts['backup']:
2375 backup = 'strip'
2359 backup = 'strip'
2376 elif opts['nobackup']:
2360 elif opts['nobackup']:
2377 backup = 'none'
2361 backup = 'none'
2378
2362
2379 rev = repo.lookup(rev)
2363 rev = repo.lookup(rev)
2380 p = repo.dirstate.parents()
2364 p = repo.dirstate.parents()
2381 cl = repo.changelog
2365 cl = repo.changelog
2382 update = True
2366 update = True
2383 if p[0] == nullid:
2367 if p[0] == nullid:
2384 update = False
2368 update = False
2385 elif p[1] == nullid and rev != cl.ancestor(p[0], rev):
2369 elif p[1] == nullid and rev != cl.ancestor(p[0], rev):
2386 update = False
2370 update = False
2387 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2371 elif rev not in (cl.ancestor(p[0], rev), cl.ancestor(p[1], rev)):
2388 update = False
2372 update = False
2389
2373
2390 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2374 repo.mq.strip(repo, rev, backup=backup, update=update, force=opts['force'])
2391 return 0
2375 return 0
2392
2376
2393 def select(ui, repo, *args, **opts):
2377 def select(ui, repo, *args, **opts):
2394 '''set or print guarded patches to push
2378 '''set or print guarded patches to push
2395
2379
2396 Use the qguard command to set or print guards on patch, then use
2380 Use the qguard command to set or print guards on patch, then use
2397 qselect to tell mq which guards to use. A patch will be pushed if
2381 qselect to tell mq which guards to use. A patch will be pushed if
2398 it has no guards or any positive guards match the currently
2382 it has no guards or any positive guards match the currently
2399 selected guard, but will not be pushed if any negative guards
2383 selected guard, but will not be pushed if any negative guards
2400 match the current guard. For example::
2384 match the current guard. For example::
2401
2385
2402 qguard foo.patch -stable (negative guard)
2386 qguard foo.patch -stable (negative guard)
2403 qguard bar.patch +stable (positive guard)
2387 qguard bar.patch +stable (positive guard)
2404 qselect stable
2388 qselect stable
2405
2389
2406 This activates the "stable" guard. mq will skip foo.patch (because
2390 This activates the "stable" guard. mq will skip foo.patch (because
2407 it has a negative match) but push bar.patch (because it has a
2391 it has a negative match) but push bar.patch (because it has a
2408 positive match).
2392 positive match).
2409
2393
2410 With no arguments, prints the currently active guards.
2394 With no arguments, prints the currently active guards.
2411 With one argument, sets the active guard.
2395 With one argument, sets the active guard.
2412
2396
2413 Use -n/--none to deactivate guards (no other arguments needed).
2397 Use -n/--none to deactivate guards (no other arguments needed).
2414 When no guards are active, patches with positive guards are
2398 When no guards are active, patches with positive guards are
2415 skipped and patches with negative guards are pushed.
2399 skipped and patches with negative guards are pushed.
2416
2400
2417 qselect can change the guards on applied patches. It does not pop
2401 qselect can change the guards on applied patches. It does not pop
2418 guarded patches by default. Use --pop to pop back to the last
2402 guarded patches by default. Use --pop to pop back to the last
2419 applied patch that is not guarded. Use --reapply (which implies
2403 applied patch that is not guarded. Use --reapply (which implies
2420 --pop) to push back to the current patch afterwards, but skip
2404 --pop) to push back to the current patch afterwards, but skip
2421 guarded patches.
2405 guarded patches.
2422
2406
2423 Use -s/--series to print a list of all guards in the series file
2407 Use -s/--series to print a list of all guards in the series file
2424 (no other arguments needed). Use -v for more information.'''
2408 (no other arguments needed). Use -v for more information.'''
2425
2409
2426 q = repo.mq
2410 q = repo.mq
2427 guards = q.active()
2411 guards = q.active()
2428 if args or opts['none']:
2412 if args or opts['none']:
2429 old_unapplied = q.unapplied(repo)
2413 old_unapplied = q.unapplied(repo)
2430 old_guarded = [i for i in xrange(len(q.applied)) if
2414 old_guarded = [i for i in xrange(len(q.applied)) if
2431 not q.pushable(i)[0]]
2415 not q.pushable(i)[0]]
2432 q.set_active(args)
2416 q.set_active(args)
2433 q.save_dirty()
2417 q.save_dirty()
2434 if not args:
2418 if not args:
2435 ui.status(_('guards deactivated\n'))
2419 ui.status(_('guards deactivated\n'))
2436 if not opts['pop'] and not opts['reapply']:
2420 if not opts['pop'] and not opts['reapply']:
2437 unapplied = q.unapplied(repo)
2421 unapplied = q.unapplied(repo)
2438 guarded = [i for i in xrange(len(q.applied))
2422 guarded = [i for i in xrange(len(q.applied))
2439 if not q.pushable(i)[0]]
2423 if not q.pushable(i)[0]]
2440 if len(unapplied) != len(old_unapplied):
2424 if len(unapplied) != len(old_unapplied):
2441 ui.status(_('number of unguarded, unapplied patches has '
2425 ui.status(_('number of unguarded, unapplied patches has '
2442 'changed from %d to %d\n') %
2426 'changed from %d to %d\n') %
2443 (len(old_unapplied), len(unapplied)))
2427 (len(old_unapplied), len(unapplied)))
2444 if len(guarded) != len(old_guarded):
2428 if len(guarded) != len(old_guarded):
2445 ui.status(_('number of guarded, applied patches has changed '
2429 ui.status(_('number of guarded, applied patches has changed '
2446 'from %d to %d\n') %
2430 'from %d to %d\n') %
2447 (len(old_guarded), len(guarded)))
2431 (len(old_guarded), len(guarded)))
2448 elif opts['series']:
2432 elif opts['series']:
2449 guards = {}
2433 guards = {}
2450 noguards = 0
2434 noguards = 0
2451 for gs in q.series_guards:
2435 for gs in q.series_guards:
2452 if not gs:
2436 if not gs:
2453 noguards += 1
2437 noguards += 1
2454 for g in gs:
2438 for g in gs:
2455 guards.setdefault(g, 0)
2439 guards.setdefault(g, 0)
2456 guards[g] += 1
2440 guards[g] += 1
2457 if ui.verbose:
2441 if ui.verbose:
2458 guards['NONE'] = noguards
2442 guards['NONE'] = noguards
2459 guards = guards.items()
2443 guards = guards.items()
2460 guards.sort(key=lambda x: x[0][1:])
2444 guards.sort(key=lambda x: x[0][1:])
2461 if guards:
2445 if guards:
2462 ui.note(_('guards in series file:\n'))
2446 ui.note(_('guards in series file:\n'))
2463 for guard, count in guards:
2447 for guard, count in guards:
2464 ui.note('%2d ' % count)
2448 ui.note('%2d ' % count)
2465 ui.write(guard, '\n')
2449 ui.write(guard, '\n')
2466 else:
2450 else:
2467 ui.note(_('no guards in series file\n'))
2451 ui.note(_('no guards in series file\n'))
2468 else:
2452 else:
2469 if guards:
2453 if guards:
2470 ui.note(_('active guards:\n'))
2454 ui.note(_('active guards:\n'))
2471 for g in guards:
2455 for g in guards:
2472 ui.write(g, '\n')
2456 ui.write(g, '\n')
2473 else:
2457 else:
2474 ui.write(_('no active guards\n'))
2458 ui.write(_('no active guards\n'))
2475 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2459 reapply = opts['reapply'] and q.applied and q.appliedname(-1)
2476 popped = False
2460 popped = False
2477 if opts['pop'] or opts['reapply']:
2461 if opts['pop'] or opts['reapply']:
2478 for i in xrange(len(q.applied)):
2462 for i in xrange(len(q.applied)):
2479 pushable, reason = q.pushable(i)
2463 pushable, reason = q.pushable(i)
2480 if not pushable:
2464 if not pushable:
2481 ui.status(_('popping guarded patches\n'))
2465 ui.status(_('popping guarded patches\n'))
2482 popped = True
2466 popped = True
2483 if i == 0:
2467 if i == 0:
2484 q.pop(repo, all=True)
2468 q.pop(repo, all=True)
2485 else:
2469 else:
2486 q.pop(repo, i - 1)
2470 q.pop(repo, i - 1)
2487 break
2471 break
2488 if popped:
2472 if popped:
2489 try:
2473 try:
2490 if reapply:
2474 if reapply:
2491 ui.status(_('reapplying unguarded patches\n'))
2475 ui.status(_('reapplying unguarded patches\n'))
2492 q.push(repo, reapply)
2476 q.push(repo, reapply)
2493 finally:
2477 finally:
2494 q.save_dirty()
2478 q.save_dirty()
2495
2479
2496 def finish(ui, repo, *revrange, **opts):
2480 def finish(ui, repo, *revrange, **opts):
2497 """move applied patches into repository history
2481 """move applied patches into repository history
2498
2482
2499 Finishes the specified revisions (corresponding to applied
2483 Finishes the specified revisions (corresponding to applied
2500 patches) by moving them out of mq control into regular repository
2484 patches) by moving them out of mq control into regular repository
2501 history.
2485 history.
2502
2486
2503 Accepts a revision range or the -a/--applied option. If --applied
2487 Accepts a revision range or the -a/--applied option. If --applied
2504 is specified, all applied mq revisions are removed from mq
2488 is specified, all applied mq revisions are removed from mq
2505 control. Otherwise, the given revisions must be at the base of the
2489 control. Otherwise, the given revisions must be at the base of the
2506 stack of applied patches.
2490 stack of applied patches.
2507
2491
2508 This can be especially useful if your changes have been applied to
2492 This can be especially useful if your changes have been applied to
2509 an upstream repository, or if you are about to push your changes
2493 an upstream repository, or if you are about to push your changes
2510 to upstream.
2494 to upstream.
2511 """
2495 """
2512 if not opts['applied'] and not revrange:
2496 if not opts['applied'] and not revrange:
2513 raise util.Abort(_('no revisions specified'))
2497 raise util.Abort(_('no revisions specified'))
2514 elif opts['applied']:
2498 elif opts['applied']:
2515 revrange = ('qbase:qtip',) + revrange
2499 revrange = ('qbase:qtip',) + revrange
2516
2500
2517 q = repo.mq
2501 q = repo.mq
2518 if not q.applied:
2502 if not q.applied:
2519 ui.status(_('no patches applied\n'))
2503 ui.status(_('no patches applied\n'))
2520 return 0
2504 return 0
2521
2505
2522 revs = cmdutil.revrange(repo, revrange)
2506 revs = cmdutil.revrange(repo, revrange)
2523 q.finish(repo, revs)
2507 q.finish(repo, revs)
2524 q.save_dirty()
2508 q.save_dirty()
2525 return 0
2509 return 0
2526
2510
2527 def reposetup(ui, repo):
2511 def reposetup(ui, repo):
2528 class mqrepo(repo.__class__):
2512 class mqrepo(repo.__class__):
2529 @util.propertycache
2513 @util.propertycache
2530 def mq(self):
2514 def mq(self):
2531 return queue(self.ui, self.join(""))
2515 return queue(self.ui, self.join(""))
2532
2516
2533 def abort_if_wdir_patched(self, errmsg, force=False):
2517 def abort_if_wdir_patched(self, errmsg, force=False):
2534 if self.mq.applied and not force:
2518 if self.mq.applied and not force:
2535 parent = self.dirstate.parents()[0]
2519 parent = self.dirstate.parents()[0]
2536 if parent in [s.node for s in self.mq.applied]:
2520 if parent in [s.node for s in self.mq.applied]:
2537 raise util.Abort(errmsg)
2521 raise util.Abort(errmsg)
2538
2522
2539 def commit(self, text="", user=None, date=None, match=None,
2523 def commit(self, text="", user=None, date=None, match=None,
2540 force=False, editor=False, extra={}):
2524 force=False, editor=False, extra={}):
2541 self.abort_if_wdir_patched(
2525 self.abort_if_wdir_patched(
2542 _('cannot commit over an applied mq patch'),
2526 _('cannot commit over an applied mq patch'),
2543 force)
2527 force)
2544
2528
2545 return super(mqrepo, self).commit(text, user, date, match, force,
2529 return super(mqrepo, self).commit(text, user, date, match, force,
2546 editor, extra)
2530 editor, extra)
2547
2531
2548 def push(self, remote, force=False, revs=None):
2532 def push(self, remote, force=False, revs=None):
2549 if self.mq.applied and not force and not revs:
2533 if self.mq.applied and not force and not revs:
2550 raise util.Abort(_('source has mq patches applied'))
2534 raise util.Abort(_('source has mq patches applied'))
2551 return super(mqrepo, self).push(remote, force, revs)
2535 return super(mqrepo, self).push(remote, force, revs)
2552
2536
2553 def _findtags(self):
2537 def _findtags(self):
2554 '''augment tags from base class with patch tags'''
2538 '''augment tags from base class with patch tags'''
2555 result = super(mqrepo, self)._findtags()
2539 result = super(mqrepo, self)._findtags()
2556
2540
2557 q = self.mq
2541 q = self.mq
2558 if not q.applied:
2542 if not q.applied:
2559 return result
2543 return result
2560
2544
2561 mqtags = [(patch.node, patch.name) for patch in q.applied]
2545 mqtags = [(patch.node, patch.name) for patch in q.applied]
2562
2546
2563 if mqtags[-1][0] not in self.changelog.nodemap:
2547 if mqtags[-1][0] not in self.changelog.nodemap:
2564 self.ui.warn(_('mq status file refers to unknown node %s\n')
2548 self.ui.warn(_('mq status file refers to unknown node %s\n')
2565 % short(mqtags[-1][0]))
2549 % short(mqtags[-1][0]))
2566 return result
2550 return result
2567
2551
2568 mqtags.append((mqtags[-1][0], 'qtip'))
2552 mqtags.append((mqtags[-1][0], 'qtip'))
2569 mqtags.append((mqtags[0][0], 'qbase'))
2553 mqtags.append((mqtags[0][0], 'qbase'))
2570 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2554 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
2571 tags = result[0]
2555 tags = result[0]
2572 for patch in mqtags:
2556 for patch in mqtags:
2573 if patch[1] in tags:
2557 if patch[1] in tags:
2574 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2558 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
2575 % patch[1])
2559 % patch[1])
2576 else:
2560 else:
2577 tags[patch[1]] = patch[0]
2561 tags[patch[1]] = patch[0]
2578
2562
2579 return result
2563 return result
2580
2564
2581 def _branchtags(self, partial, lrev):
2565 def _branchtags(self, partial, lrev):
2582 q = self.mq
2566 q = self.mq
2583 if not q.applied:
2567 if not q.applied:
2584 return super(mqrepo, self)._branchtags(partial, lrev)
2568 return super(mqrepo, self)._branchtags(partial, lrev)
2585
2569
2586 cl = self.changelog
2570 cl = self.changelog
2587 qbasenode = q.applied[0].node
2571 qbasenode = q.applied[0].node
2588 if qbasenode not in cl.nodemap:
2572 if qbasenode not in cl.nodemap:
2589 self.ui.warn(_('mq status file refers to unknown node %s\n')
2573 self.ui.warn(_('mq status file refers to unknown node %s\n')
2590 % short(qbasenode))
2574 % short(qbasenode))
2591 return super(mqrepo, self)._branchtags(partial, lrev)
2575 return super(mqrepo, self)._branchtags(partial, lrev)
2592
2576
2593 qbase = cl.rev(qbasenode)
2577 qbase = cl.rev(qbasenode)
2594 start = lrev + 1
2578 start = lrev + 1
2595 if start < qbase:
2579 if start < qbase:
2596 # update the cache (excluding the patches) and save it
2580 # update the cache (excluding the patches) and save it
2597 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
2581 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
2598 self._updatebranchcache(partial, ctxgen)
2582 self._updatebranchcache(partial, ctxgen)
2599 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
2583 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
2600 start = qbase
2584 start = qbase
2601 # if start = qbase, the cache is as updated as it should be.
2585 # if start = qbase, the cache is as updated as it should be.
2602 # if start > qbase, the cache includes (part of) the patches.
2586 # if start > qbase, the cache includes (part of) the patches.
2603 # we might as well use it, but we won't save it.
2587 # we might as well use it, but we won't save it.
2604
2588
2605 # update the cache up to the tip
2589 # update the cache up to the tip
2606 ctxgen = (self[r] for r in xrange(start, len(cl)))
2590 ctxgen = (self[r] for r in xrange(start, len(cl)))
2607 self._updatebranchcache(partial, ctxgen)
2591 self._updatebranchcache(partial, ctxgen)
2608
2592
2609 return partial
2593 return partial
2610
2594
2611 if repo.local():
2595 if repo.local():
2612 repo.__class__ = mqrepo
2596 repo.__class__ = mqrepo
2613
2597
2614 def mqimport(orig, ui, repo, *args, **kwargs):
2598 def mqimport(orig, ui, repo, *args, **kwargs):
2615 if (hasattr(repo, 'abort_if_wdir_patched')
2599 if (hasattr(repo, 'abort_if_wdir_patched')
2616 and not kwargs.get('no_commit', False)):
2600 and not kwargs.get('no_commit', False)):
2617 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2601 repo.abort_if_wdir_patched(_('cannot import over an applied patch'),
2618 kwargs.get('force'))
2602 kwargs.get('force'))
2619 return orig(ui, repo, *args, **kwargs)
2603 return orig(ui, repo, *args, **kwargs)
2620
2604
2621 def mqinit(orig, ui, *args, **kwargs):
2605 def mqinit(orig, ui, *args, **kwargs):
2622 mq = kwargs.pop('mq', None)
2606 mq = kwargs.pop('mq', None)
2623
2607
2624 if not mq:
2608 if not mq:
2625 return orig(ui, *args, **kwargs)
2609 return orig(ui, *args, **kwargs)
2626
2610
2627 if args:
2611 if args:
2628 repopath = args[0]
2612 repopath = args[0]
2629 if not hg.islocal(repopath):
2613 if not hg.islocal(repopath):
2630 raise util.Abort(_('only a local queue repository '
2614 raise util.Abort(_('only a local queue repository '
2631 'may be initialized'))
2615 'may be initialized'))
2632 else:
2616 else:
2633 repopath = cmdutil.findrepo(os.getcwd())
2617 repopath = cmdutil.findrepo(os.getcwd())
2634 if not repopath:
2618 if not repopath:
2635 raise util.Abort(_('There is no Mercurial repository here '
2619 raise util.Abort(_('There is no Mercurial repository here '
2636 '(.hg not found)'))
2620 '(.hg not found)'))
2637 repo = hg.repository(ui, repopath)
2621 repo = hg.repository(ui, repopath)
2638 return qinit(ui, repo, True)
2622 return qinit(ui, repo, True)
2639
2623
2640 def mqcommand(orig, ui, repo, *args, **kwargs):
2624 def mqcommand(orig, ui, repo, *args, **kwargs):
2641 """Add --mq option to operate on patch repository instead of main"""
2625 """Add --mq option to operate on patch repository instead of main"""
2642
2626
2643 # some commands do not like getting unknown options
2627 # some commands do not like getting unknown options
2644 mq = kwargs.pop('mq', None)
2628 mq = kwargs.pop('mq', None)
2645
2629
2646 if not mq:
2630 if not mq:
2647 return orig(ui, repo, *args, **kwargs)
2631 return orig(ui, repo, *args, **kwargs)
2648
2632
2649 q = repo.mq
2633 q = repo.mq
2650 r = q.qrepo()
2634 r = q.qrepo()
2651 if not r:
2635 if not r:
2652 raise util.Abort('no queue repository')
2636 raise util.Abort('no queue repository')
2653 return orig(r.ui, r, *args, **kwargs)
2637 return orig(r.ui, r, *args, **kwargs)
2654
2638
2655 def uisetup(ui):
2639 def uisetup(ui):
2656 mqopt = [('', 'mq', None, _("operate on patch repository"))]
2640 mqopt = [('', 'mq', None, _("operate on patch repository"))]
2657
2641
2658 extensions.wrapcommand(commands.table, 'import', mqimport)
2642 extensions.wrapcommand(commands.table, 'import', mqimport)
2659
2643
2660 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
2644 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
2661 entry[1].extend(mqopt)
2645 entry[1].extend(mqopt)
2662
2646
2663 norepo = commands.norepo.split(" ")
2647 norepo = commands.norepo.split(" ")
2664 for cmd in commands.table.keys():
2648 for cmd in commands.table.keys():
2665 cmd = cmdutil.parsealiases(cmd)[0]
2649 cmd = cmdutil.parsealiases(cmd)[0]
2666 if cmd in norepo:
2650 if cmd in norepo:
2667 continue
2651 continue
2668 entry = extensions.wrapcommand(commands.table, cmd, mqcommand)
2652 entry = extensions.wrapcommand(commands.table, cmd, mqcommand)
2669 entry[1].extend(mqopt)
2653 entry[1].extend(mqopt)
2670
2654
2671 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2655 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
2672
2656
2673 cmdtable = {
2657 cmdtable = {
2674 "qapplied":
2658 "qapplied":
2675 (applied,
2659 (applied,
2676 [('1', 'last', None, _('show only the last patch'))] + seriesopts,
2660 [('1', 'last', None, _('show only the last patch'))] + seriesopts,
2677 _('hg qapplied [-1] [-s] [PATCH]')),
2661 _('hg qapplied [-1] [-s] [PATCH]')),
2678 "qclone":
2662 "qclone":
2679 (clone,
2663 (clone,
2680 [('', 'pull', None, _('use pull protocol to copy metadata')),
2664 [('', 'pull', None, _('use pull protocol to copy metadata')),
2681 ('U', 'noupdate', None, _('do not update the new working directories')),
2665 ('U', 'noupdate', None, _('do not update the new working directories')),
2682 ('', 'uncompressed', None,
2666 ('', 'uncompressed', None,
2683 _('use uncompressed transfer (fast over LAN)')),
2667 _('use uncompressed transfer (fast over LAN)')),
2684 ('p', 'patches', '', _('location of source patch repository')),
2668 ('p', 'patches', '', _('location of source patch repository')),
2685 ] + commands.remoteopts,
2669 ] + commands.remoteopts,
2686 _('hg qclone [OPTION]... SOURCE [DEST]')),
2670 _('hg qclone [OPTION]... SOURCE [DEST]')),
2687 "qcommit|qci":
2671 "qcommit|qci":
2688 (commit,
2672 (commit,
2689 commands.table["^commit|ci"][1],
2673 commands.table["^commit|ci"][1],
2690 _('hg qcommit [OPTION]... [FILE]...')),
2674 _('hg qcommit [OPTION]... [FILE]...')),
2691 "^qdiff":
2675 "^qdiff":
2692 (diff,
2676 (diff,
2693 commands.diffopts + commands.diffopts2 + commands.walkopts,
2677 commands.diffopts + commands.diffopts2 + commands.walkopts,
2694 _('hg qdiff [OPTION]... [FILE]...')),
2678 _('hg qdiff [OPTION]... [FILE]...')),
2695 "qdelete|qremove|qrm":
2679 "qdelete|qremove|qrm":
2696 (delete,
2680 (delete,
2697 [('k', 'keep', None, _('keep patch file')),
2681 [('k', 'keep', None, _('keep patch file')),
2698 ('r', 'rev', [], _('stop managing a revision (DEPRECATED)'))],
2682 ('r', 'rev', [], _('stop managing a revision (DEPRECATED)'))],
2699 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2683 _('hg qdelete [-k] [-r REV]... [PATCH]...')),
2700 'qfold':
2684 'qfold':
2701 (fold,
2685 (fold,
2702 [('e', 'edit', None, _('edit patch header')),
2686 [('e', 'edit', None, _('edit patch header')),
2703 ('k', 'keep', None, _('keep folded patch files')),
2687 ('k', 'keep', None, _('keep folded patch files')),
2704 ] + commands.commitopts,
2688 ] + commands.commitopts,
2705 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2689 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...')),
2706 'qgoto':
2690 'qgoto':
2707 (goto,
2691 (goto,
2708 [('f', 'force', None, _('overwrite any local changes'))],
2692 [('f', 'force', None, _('overwrite any local changes'))],
2709 _('hg qgoto [OPTION]... PATCH')),
2693 _('hg qgoto [OPTION]... PATCH')),
2710 'qguard':
2694 'qguard':
2711 (guard,
2695 (guard,
2712 [('l', 'list', None, _('list all patches and guards')),
2696 [('l', 'list', None, _('list all patches and guards')),
2713 ('n', 'none', None, _('drop all guards'))],
2697 ('n', 'none', None, _('drop all guards'))],
2714 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]')),
2698 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]')),
2715 'qheader': (header, [], _('hg qheader [PATCH]')),
2699 'qheader': (header, [], _('hg qheader [PATCH]')),
2716 "qimport":
2700 "qimport":
2717 (qimport,
2701 (qimport,
2718 [('e', 'existing', None, _('import file in patch directory')),
2702 [('e', 'existing', None, _('import file in patch directory')),
2719 ('n', 'name', '', _('name of patch file')),
2703 ('n', 'name', '', _('name of patch file')),
2720 ('f', 'force', None, _('overwrite existing files')),
2704 ('f', 'force', None, _('overwrite existing files')),
2721 ('r', 'rev', [], _('place existing revisions under mq control')),
2705 ('r', 'rev', [], _('place existing revisions under mq control')),
2722 ('g', 'git', None, _('use git extended diff format')),
2706 ('g', 'git', None, _('use git extended diff format')),
2723 ('P', 'push', None, _('qpush after importing'))],
2707 ('P', 'push', None, _('qpush after importing'))],
2724 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...')),
2708 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...')),
2725 "^qinit":
2709 "^qinit":
2726 (init,
2710 (init,
2727 [('c', 'create-repo', None, _('create queue repository'))],
2711 [('c', 'create-repo', None, _('create queue repository'))],
2728 _('hg qinit [-c]')),
2712 _('hg qinit [-c]')),
2729 "^qnew":
2713 "^qnew":
2730 (new,
2714 (new,
2731 [('e', 'edit', None, _('edit commit message')),
2715 [('e', 'edit', None, _('edit commit message')),
2732 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2716 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2733 ('g', 'git', None, _('use git extended diff format')),
2717 ('g', 'git', None, _('use git extended diff format')),
2734 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2718 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2735 ('u', 'user', '', _('add "From: <given user>" to patch')),
2719 ('u', 'user', '', _('add "From: <given user>" to patch')),
2736 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2720 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2737 ('d', 'date', '', _('add "Date: <given date>" to patch'))
2721 ('d', 'date', '', _('add "Date: <given date>" to patch'))
2738 ] + commands.walkopts + commands.commitopts,
2722 ] + commands.walkopts + commands.commitopts,
2739 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...')),
2723 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...')),
2740 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2724 "qnext": (next, [] + seriesopts, _('hg qnext [-s]')),
2741 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2725 "qprev": (prev, [] + seriesopts, _('hg qprev [-s]')),
2742 "^qpop":
2726 "^qpop":
2743 (pop,
2727 (pop,
2744 [('a', 'all', None, _('pop all patches')),
2728 [('a', 'all', None, _('pop all patches')),
2745 ('n', 'name', '', _('queue name to pop (DEPRECATED)')),
2729 ('n', 'name', '', _('queue name to pop (DEPRECATED)')),
2746 ('f', 'force', None, _('forget any local changes to patched files'))],
2730 ('f', 'force', None, _('forget any local changes to patched files'))],
2747 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2731 _('hg qpop [-a] [-n NAME] [-f] [PATCH | INDEX]')),
2748 "^qpush":
2732 "^qpush":
2749 (push,
2733 (push,
2750 [('f', 'force', None, _('apply if the patch has rejects')),
2734 [('f', 'force', None, _('apply if the patch has rejects')),
2751 ('l', 'list', None, _('list patch name in commit text')),
2735 ('l', 'list', None, _('list patch name in commit text')),
2752 ('a', 'all', None, _('apply all patches')),
2736 ('a', 'all', None, _('apply all patches')),
2753 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2737 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2754 ('n', 'name', '', _('merge queue name (DEPRECATED)'))],
2738 ('n', 'name', '', _('merge queue name (DEPRECATED)'))],
2755 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2739 _('hg qpush [-f] [-l] [-a] [-m] [-n NAME] [PATCH | INDEX]')),
2756 "^qrefresh":
2740 "^qrefresh":
2757 (refresh,
2741 (refresh,
2758 [('e', 'edit', None, _('edit commit message')),
2742 [('e', 'edit', None, _('edit commit message')),
2759 ('g', 'git', None, _('use git extended diff format')),
2743 ('g', 'git', None, _('use git extended diff format')),
2760 ('s', 'short', None,
2744 ('s', 'short', None,
2761 _('refresh only files already in the patch and specified files')),
2745 _('refresh only files already in the patch and specified files')),
2762 ('U', 'currentuser', None,
2746 ('U', 'currentuser', None,
2763 _('add/update author field in patch with current user')),
2747 _('add/update author field in patch with current user')),
2764 ('u', 'user', '',
2748 ('u', 'user', '',
2765 _('add/update author field in patch with given user')),
2749 _('add/update author field in patch with given user')),
2766 ('D', 'currentdate', None,
2750 ('D', 'currentdate', None,
2767 _('add/update date field in patch with current date')),
2751 _('add/update date field in patch with current date')),
2768 ('d', 'date', '',
2752 ('d', 'date', '',
2769 _('add/update date field in patch with given date'))
2753 _('add/update date field in patch with given date'))
2770 ] + commands.walkopts + commands.commitopts,
2754 ] + commands.walkopts + commands.commitopts,
2771 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2755 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...')),
2772 'qrename|qmv':
2756 'qrename|qmv':
2773 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2757 (rename, [], _('hg qrename PATCH1 [PATCH2]')),
2774 "qrestore":
2758 "qrestore":
2775 (restore,
2759 (restore,
2776 [('d', 'delete', None, _('delete save entry')),
2760 [('d', 'delete', None, _('delete save entry')),
2777 ('u', 'update', None, _('update queue working directory'))],
2761 ('u', 'update', None, _('update queue working directory'))],
2778 _('hg qrestore [-d] [-u] REV')),
2762 _('hg qrestore [-d] [-u] REV')),
2779 "qsave":
2763 "qsave":
2780 (save,
2764 (save,
2781 [('c', 'copy', None, _('copy patch directory')),
2765 [('c', 'copy', None, _('copy patch directory')),
2782 ('n', 'name', '', _('copy directory name')),
2766 ('n', 'name', '', _('copy directory name')),
2783 ('e', 'empty', None, _('clear queue status file')),
2767 ('e', 'empty', None, _('clear queue status file')),
2784 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2768 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2785 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2769 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]')),
2786 "qselect":
2770 "qselect":
2787 (select,
2771 (select,
2788 [('n', 'none', None, _('disable all guards')),
2772 [('n', 'none', None, _('disable all guards')),
2789 ('s', 'series', None, _('list all guards in series file')),
2773 ('s', 'series', None, _('list all guards in series file')),
2790 ('', 'pop', None, _('pop to before first guarded applied patch')),
2774 ('', 'pop', None, _('pop to before first guarded applied patch')),
2791 ('', 'reapply', None, _('pop, then reapply patches'))],
2775 ('', 'reapply', None, _('pop, then reapply patches'))],
2792 _('hg qselect [OPTION]... [GUARD]...')),
2776 _('hg qselect [OPTION]... [GUARD]...')),
2793 "qseries":
2777 "qseries":
2794 (series,
2778 (series,
2795 [('m', 'missing', None, _('print patches not in series')),
2779 [('m', 'missing', None, _('print patches not in series')),
2796 ] + seriesopts,
2780 ] + seriesopts,
2797 _('hg qseries [-ms]')),
2781 _('hg qseries [-ms]')),
2798 "strip":
2782 "strip":
2799 (strip,
2783 (strip,
2800 [('f', 'force', None, _('force removal with local changes')),
2784 [('f', 'force', None, _('force removal with local changes')),
2801 ('b', 'backup', None, _('bundle unrelated changesets')),
2785 ('b', 'backup', None, _('bundle unrelated changesets')),
2802 ('n', 'nobackup', None, _('no backups'))],
2786 ('n', 'nobackup', None, _('no backups'))],
2803 _('hg strip [-f] [-b] [-n] REV')),
2787 _('hg strip [-f] [-b] [-n] REV')),
2804 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2788 "qtop": (top, [] + seriesopts, _('hg qtop [-s]')),
2805 "qunapplied":
2789 "qunapplied":
2806 (unapplied,
2790 (unapplied,
2807 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2791 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
2808 _('hg qunapplied [-1] [-s] [PATCH]')),
2792 _('hg qunapplied [-1] [-s] [PATCH]')),
2809 "qfinish":
2793 "qfinish":
2810 (finish,
2794 (finish,
2811 [('a', 'applied', None, _('finish all applied changesets'))],
2795 [('a', 'applied', None, _('finish all applied changesets'))],
2812 _('hg qfinish [-a] [REV]...')),
2796 _('hg qfinish [-a] [REV]...')),
2813 }
2797 }
2814
2798
2815 colortable = {'qguard.negative': 'red',
2799 colortable = {'qguard.negative': 'red',
2816 'qguard.positive': 'yellow',
2800 'qguard.positive': 'yellow',
2817 'qguard.unguarded': 'green',
2801 'qguard.unguarded': 'green',
2818 'qseries.applied': 'blue bold underline',
2802 'qseries.applied': 'blue bold underline',
2819 'qseries.guarded': 'black bold',
2803 'qseries.guarded': 'black bold',
2820 'qseries.missing': 'red bold',
2804 'qseries.missing': 'red bold',
2821 'qseries.unapplied': 'black bold'}
2805 'qseries.unapplied': 'black bold'}
@@ -1,1261 +1,1285 b''
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, nullid, nullrev, short
8 from node import hex, nullid, nullrev, short
9 from i18n import _
9 from i18n import _
10 import os, sys, errno, re, glob, tempfile
10 import os, sys, errno, re, glob, tempfile
11 import mdiff, bdiff, util, templater, patch, error, encoding, templatekw
11 import mdiff, bdiff, util, templater, patch, error, encoding, templatekw
12 import match as _match
12 import match as _match
13
13
14 revrangesep = ':'
14 revrangesep = ':'
15
15
16 def parsealiases(cmd):
16 def parsealiases(cmd):
17 return cmd.lstrip("^").split("|")
17 return cmd.lstrip("^").split("|")
18
18
19 def findpossible(cmd, table, strict=False):
19 def findpossible(cmd, table, strict=False):
20 """
20 """
21 Return cmd -> (aliases, command table entry)
21 Return cmd -> (aliases, command table entry)
22 for each matching command.
22 for each matching command.
23 Return debug commands (or their aliases) only if no normal command matches.
23 Return debug commands (or their aliases) only if no normal command matches.
24 """
24 """
25 choice = {}
25 choice = {}
26 debugchoice = {}
26 debugchoice = {}
27 for e in table.keys():
27 for e in table.keys():
28 aliases = parsealiases(e)
28 aliases = parsealiases(e)
29 found = None
29 found = None
30 if cmd in aliases:
30 if cmd in aliases:
31 found = cmd
31 found = cmd
32 elif not strict:
32 elif not strict:
33 for a in aliases:
33 for a in aliases:
34 if a.startswith(cmd):
34 if a.startswith(cmd):
35 found = a
35 found = a
36 break
36 break
37 if found is not None:
37 if found is not None:
38 if aliases[0].startswith("debug") or found.startswith("debug"):
38 if aliases[0].startswith("debug") or found.startswith("debug"):
39 debugchoice[found] = (aliases, table[e])
39 debugchoice[found] = (aliases, table[e])
40 else:
40 else:
41 choice[found] = (aliases, table[e])
41 choice[found] = (aliases, table[e])
42
42
43 if not choice and debugchoice:
43 if not choice and debugchoice:
44 choice = debugchoice
44 choice = debugchoice
45
45
46 return choice
46 return choice
47
47
48 def findcmd(cmd, table, strict=True):
48 def findcmd(cmd, table, strict=True):
49 """Return (aliases, command table entry) for command string."""
49 """Return (aliases, command table entry) for command string."""
50 choice = findpossible(cmd, table, strict)
50 choice = findpossible(cmd, table, strict)
51
51
52 if cmd in choice:
52 if cmd in choice:
53 return choice[cmd]
53 return choice[cmd]
54
54
55 if len(choice) > 1:
55 if len(choice) > 1:
56 clist = choice.keys()
56 clist = choice.keys()
57 clist.sort()
57 clist.sort()
58 raise error.AmbiguousCommand(cmd, clist)
58 raise error.AmbiguousCommand(cmd, clist)
59
59
60 if choice:
60 if choice:
61 return choice.values()[0]
61 return choice.values()[0]
62
62
63 raise error.UnknownCommand(cmd)
63 raise error.UnknownCommand(cmd)
64
64
65 def findrepo(p):
65 def findrepo(p):
66 while not os.path.isdir(os.path.join(p, ".hg")):
66 while not os.path.isdir(os.path.join(p, ".hg")):
67 oldp, p = p, os.path.dirname(p)
67 oldp, p = p, os.path.dirname(p)
68 if p == oldp:
68 if p == oldp:
69 return None
69 return None
70
70
71 return p
71 return p
72
72
73 def bail_if_changed(repo):
73 def bail_if_changed(repo):
74 if repo.dirstate.parents()[1] != nullid:
74 if repo.dirstate.parents()[1] != nullid:
75 raise util.Abort(_('outstanding uncommitted merge'))
75 raise util.Abort(_('outstanding uncommitted merge'))
76 modified, added, removed, deleted = repo.status()[:4]
76 modified, added, removed, deleted = repo.status()[:4]
77 if modified or added or removed or deleted:
77 if modified or added or removed or deleted:
78 raise util.Abort(_("outstanding uncommitted changes"))
78 raise util.Abort(_("outstanding uncommitted changes"))
79
79
80 def logmessage(opts):
80 def logmessage(opts):
81 """ get the log message according to -m and -l option """
81 """ get the log message according to -m and -l option """
82 message = opts.get('message')
82 message = opts.get('message')
83 logfile = opts.get('logfile')
83 logfile = opts.get('logfile')
84
84
85 if message and logfile:
85 if message and logfile:
86 raise util.Abort(_('options --message and --logfile are mutually '
86 raise util.Abort(_('options --message and --logfile are mutually '
87 'exclusive'))
87 'exclusive'))
88 if not message and logfile:
88 if not message and logfile:
89 try:
89 try:
90 if logfile == '-':
90 if logfile == '-':
91 message = sys.stdin.read()
91 message = sys.stdin.read()
92 else:
92 else:
93 message = open(logfile).read()
93 message = open(logfile).read()
94 except IOError, inst:
94 except IOError, inst:
95 raise util.Abort(_("can't read commit message '%s': %s") %
95 raise util.Abort(_("can't read commit message '%s': %s") %
96 (logfile, inst.strerror))
96 (logfile, inst.strerror))
97 return message
97 return message
98
98
99 def loglimit(opts):
99 def loglimit(opts):
100 """get the log limit according to option -l/--limit"""
100 """get the log limit according to option -l/--limit"""
101 limit = opts.get('limit')
101 limit = opts.get('limit')
102 if limit:
102 if limit:
103 try:
103 try:
104 limit = int(limit)
104 limit = int(limit)
105 except ValueError:
105 except ValueError:
106 raise util.Abort(_('limit must be a positive integer'))
106 raise util.Abort(_('limit must be a positive integer'))
107 if limit <= 0:
107 if limit <= 0:
108 raise util.Abort(_('limit must be positive'))
108 raise util.Abort(_('limit must be positive'))
109 else:
109 else:
110 limit = None
110 limit = None
111 return limit
111 return limit
112
112
113 def remoteui(src, opts):
113 def remoteui(src, opts):
114 'build a remote ui from ui or repo and opts'
114 'build a remote ui from ui or repo and opts'
115 if hasattr(src, 'baseui'): # looks like a repository
115 if hasattr(src, 'baseui'): # looks like a repository
116 dst = src.baseui.copy() # drop repo-specific config
116 dst = src.baseui.copy() # drop repo-specific config
117 src = src.ui # copy target options from repo
117 src = src.ui # copy target options from repo
118 else: # assume it's a global ui object
118 else: # assume it's a global ui object
119 dst = src.copy() # keep all global options
119 dst = src.copy() # keep all global options
120
120
121 # copy ssh-specific options
121 # copy ssh-specific options
122 for o in 'ssh', 'remotecmd':
122 for o in 'ssh', 'remotecmd':
123 v = opts.get(o) or src.config('ui', o)
123 v = opts.get(o) or src.config('ui', o)
124 if v:
124 if v:
125 dst.setconfig("ui", o, v)
125 dst.setconfig("ui", o, v)
126
126
127 # copy bundle-specific options
127 # copy bundle-specific options
128 r = src.config('bundle', 'mainreporoot')
128 r = src.config('bundle', 'mainreporoot')
129 if r:
129 if r:
130 dst.setconfig('bundle', 'mainreporoot', r)
130 dst.setconfig('bundle', 'mainreporoot', r)
131
131
132 # copy auth and http_proxy section settings
132 # copy auth and http_proxy section settings
133 for sect in ('auth', 'http_proxy'):
133 for sect in ('auth', 'http_proxy'):
134 for key, val in src.configitems(sect):
134 for key, val in src.configitems(sect):
135 dst.setconfig(sect, key, val)
135 dst.setconfig(sect, key, val)
136
136
137 return dst
137 return dst
138
138
139 def revpair(repo, revs):
139 def revpair(repo, revs):
140 '''return pair of nodes, given list of revisions. second item can
140 '''return pair of nodes, given list of revisions. second item can
141 be None, meaning use working dir.'''
141 be None, meaning use working dir.'''
142
142
143 def revfix(repo, val, defval):
143 def revfix(repo, val, defval):
144 if not val and val != 0 and defval is not None:
144 if not val and val != 0 and defval is not None:
145 val = defval
145 val = defval
146 return repo.lookup(val)
146 return repo.lookup(val)
147
147
148 if not revs:
148 if not revs:
149 return repo.dirstate.parents()[0], None
149 return repo.dirstate.parents()[0], None
150 end = None
150 end = None
151 if len(revs) == 1:
151 if len(revs) == 1:
152 if revrangesep in revs[0]:
152 if revrangesep in revs[0]:
153 start, end = revs[0].split(revrangesep, 1)
153 start, end = revs[0].split(revrangesep, 1)
154 start = revfix(repo, start, 0)
154 start = revfix(repo, start, 0)
155 end = revfix(repo, end, len(repo) - 1)
155 end = revfix(repo, end, len(repo) - 1)
156 else:
156 else:
157 start = revfix(repo, revs[0], None)
157 start = revfix(repo, revs[0], None)
158 elif len(revs) == 2:
158 elif len(revs) == 2:
159 if revrangesep in revs[0] or revrangesep in revs[1]:
159 if revrangesep in revs[0] or revrangesep in revs[1]:
160 raise util.Abort(_('too many revisions specified'))
160 raise util.Abort(_('too many revisions specified'))
161 start = revfix(repo, revs[0], None)
161 start = revfix(repo, revs[0], None)
162 end = revfix(repo, revs[1], None)
162 end = revfix(repo, revs[1], None)
163 else:
163 else:
164 raise util.Abort(_('too many revisions specified'))
164 raise util.Abort(_('too many revisions specified'))
165 return start, end
165 return start, end
166
166
167 def revrange(repo, revs):
167 def revrange(repo, revs):
168 """Yield revision as strings from a list of revision specifications."""
168 """Yield revision as strings from a list of revision specifications."""
169
169
170 def revfix(repo, val, defval):
170 def revfix(repo, val, defval):
171 if not val and val != 0 and defval is not None:
171 if not val and val != 0 and defval is not None:
172 return defval
172 return defval
173 return repo.changelog.rev(repo.lookup(val))
173 return repo.changelog.rev(repo.lookup(val))
174
174
175 seen, l = set(), []
175 seen, l = set(), []
176 for spec in revs:
176 for spec in revs:
177 if revrangesep in spec:
177 if revrangesep in spec:
178 start, end = spec.split(revrangesep, 1)
178 start, end = spec.split(revrangesep, 1)
179 start = revfix(repo, start, 0)
179 start = revfix(repo, start, 0)
180 end = revfix(repo, end, len(repo) - 1)
180 end = revfix(repo, end, len(repo) - 1)
181 step = start > end and -1 or 1
181 step = start > end and -1 or 1
182 for rev in xrange(start, end + step, step):
182 for rev in xrange(start, end + step, step):
183 if rev in seen:
183 if rev in seen:
184 continue
184 continue
185 seen.add(rev)
185 seen.add(rev)
186 l.append(rev)
186 l.append(rev)
187 else:
187 else:
188 rev = revfix(repo, spec, None)
188 rev = revfix(repo, spec, None)
189 if rev in seen:
189 if rev in seen:
190 continue
190 continue
191 seen.add(rev)
191 seen.add(rev)
192 l.append(rev)
192 l.append(rev)
193
193
194 return l
194 return l
195
195
196 def make_filename(repo, pat, node,
196 def make_filename(repo, pat, node,
197 total=None, seqno=None, revwidth=None, pathname=None):
197 total=None, seqno=None, revwidth=None, pathname=None):
198 node_expander = {
198 node_expander = {
199 'H': lambda: hex(node),
199 'H': lambda: hex(node),
200 'R': lambda: str(repo.changelog.rev(node)),
200 'R': lambda: str(repo.changelog.rev(node)),
201 'h': lambda: short(node),
201 'h': lambda: short(node),
202 }
202 }
203 expander = {
203 expander = {
204 '%': lambda: '%',
204 '%': lambda: '%',
205 'b': lambda: os.path.basename(repo.root),
205 'b': lambda: os.path.basename(repo.root),
206 }
206 }
207
207
208 try:
208 try:
209 if node:
209 if node:
210 expander.update(node_expander)
210 expander.update(node_expander)
211 if node:
211 if node:
212 expander['r'] = (lambda:
212 expander['r'] = (lambda:
213 str(repo.changelog.rev(node)).zfill(revwidth or 0))
213 str(repo.changelog.rev(node)).zfill(revwidth or 0))
214 if total is not None:
214 if total is not None:
215 expander['N'] = lambda: str(total)
215 expander['N'] = lambda: str(total)
216 if seqno is not None:
216 if seqno is not None:
217 expander['n'] = lambda: str(seqno)
217 expander['n'] = lambda: str(seqno)
218 if total is not None and seqno is not None:
218 if total is not None and seqno is not None:
219 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
219 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
220 if pathname is not None:
220 if pathname is not None:
221 expander['s'] = lambda: os.path.basename(pathname)
221 expander['s'] = lambda: os.path.basename(pathname)
222 expander['d'] = lambda: os.path.dirname(pathname) or '.'
222 expander['d'] = lambda: os.path.dirname(pathname) or '.'
223 expander['p'] = lambda: pathname
223 expander['p'] = lambda: pathname
224
224
225 newname = []
225 newname = []
226 patlen = len(pat)
226 patlen = len(pat)
227 i = 0
227 i = 0
228 while i < patlen:
228 while i < patlen:
229 c = pat[i]
229 c = pat[i]
230 if c == '%':
230 if c == '%':
231 i += 1
231 i += 1
232 c = pat[i]
232 c = pat[i]
233 c = expander[c]()
233 c = expander[c]()
234 newname.append(c)
234 newname.append(c)
235 i += 1
235 i += 1
236 return ''.join(newname)
236 return ''.join(newname)
237 except KeyError, inst:
237 except KeyError, inst:
238 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
238 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
239 inst.args[0])
239 inst.args[0])
240
240
241 def make_file(repo, pat, node=None,
241 def make_file(repo, pat, node=None,
242 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
242 total=None, seqno=None, revwidth=None, mode='wb', pathname=None):
243
243
244 writable = 'w' in mode or 'a' in mode
244 writable = 'w' in mode or 'a' in mode
245
245
246 if not pat or pat == '-':
246 if not pat or pat == '-':
247 return writable and sys.stdout or sys.stdin
247 return writable and sys.stdout or sys.stdin
248 if hasattr(pat, 'write') and writable:
248 if hasattr(pat, 'write') and writable:
249 return pat
249 return pat
250 if hasattr(pat, 'read') and 'r' in mode:
250 if hasattr(pat, 'read') and 'r' in mode:
251 return pat
251 return pat
252 return open(make_filename(repo, pat, node, total, seqno, revwidth,
252 return open(make_filename(repo, pat, node, total, seqno, revwidth,
253 pathname),
253 pathname),
254 mode)
254 mode)
255
255
256 def expandpats(pats):
256 def expandpats(pats):
257 if not util.expandglobs:
257 if not util.expandglobs:
258 return list(pats)
258 return list(pats)
259 ret = []
259 ret = []
260 for p in pats:
260 for p in pats:
261 kind, name = _match._patsplit(p, None)
261 kind, name = _match._patsplit(p, None)
262 if kind is None:
262 if kind is None:
263 try:
263 try:
264 globbed = glob.glob(name)
264 globbed = glob.glob(name)
265 except re.error:
265 except re.error:
266 globbed = [name]
266 globbed = [name]
267 if globbed:
267 if globbed:
268 ret.extend(globbed)
268 ret.extend(globbed)
269 continue
269 continue
270 ret.append(p)
270 ret.append(p)
271 return ret
271 return ret
272
272
273 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
273 def match(repo, pats=[], opts={}, globbed=False, default='relpath'):
274 if not globbed and default == 'relpath':
274 if not globbed and default == 'relpath':
275 pats = expandpats(pats or [])
275 pats = expandpats(pats or [])
276 m = _match.match(repo.root, repo.getcwd(), pats,
276 m = _match.match(repo.root, repo.getcwd(), pats,
277 opts.get('include'), opts.get('exclude'), default)
277 opts.get('include'), opts.get('exclude'), default)
278 def badfn(f, msg):
278 def badfn(f, msg):
279 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
279 repo.ui.warn("%s: %s\n" % (m.rel(f), msg))
280 m.bad = badfn
280 m.bad = badfn
281 return m
281 return m
282
282
283 def matchall(repo):
283 def matchall(repo):
284 return _match.always(repo.root, repo.getcwd())
284 return _match.always(repo.root, repo.getcwd())
285
285
286 def matchfiles(repo, files):
286 def matchfiles(repo, files):
287 return _match.exact(repo.root, repo.getcwd(), files)
287 return _match.exact(repo.root, repo.getcwd(), files)
288
288
289 def findrenames(repo, added, removed, threshold):
289 def findrenames(repo, added, removed, threshold):
290 '''find renamed files -- yields (before, after, score) tuples'''
290 '''find renamed files -- yields (before, after, score) tuples'''
291 copies = {}
291 copies = {}
292 ctx = repo['.']
292 ctx = repo['.']
293 for i, r in enumerate(removed):
293 for i, r in enumerate(removed):
294 repo.ui.progress(_('searching'), i, total=len(removed))
294 repo.ui.progress(_('searching'), i, total=len(removed))
295 if r not in ctx:
295 if r not in ctx:
296 continue
296 continue
297 fctx = ctx.filectx(r)
297 fctx = ctx.filectx(r)
298
298
299 # lazily load text
299 # lazily load text
300 @util.cachefunc
300 @util.cachefunc
301 def data():
301 def data():
302 orig = fctx.data()
302 orig = fctx.data()
303 return orig, mdiff.splitnewlines(orig)
303 return orig, mdiff.splitnewlines(orig)
304
304
305 def score(text):
305 def score(text):
306 if not len(text):
306 if not len(text):
307 return 0.0
307 return 0.0
308 if not fctx.cmp(text):
308 if not fctx.cmp(text):
309 return 1.0
309 return 1.0
310 if threshold == 1.0:
310 if threshold == 1.0:
311 return 0.0
311 return 0.0
312 orig, lines = data()
312 orig, lines = data()
313 # bdiff.blocks() returns blocks of matching lines
313 # bdiff.blocks() returns blocks of matching lines
314 # count the number of bytes in each
314 # count the number of bytes in each
315 equal = 0
315 equal = 0
316 matches = bdiff.blocks(text, orig)
316 matches = bdiff.blocks(text, orig)
317 for x1, x2, y1, y2 in matches:
317 for x1, x2, y1, y2 in matches:
318 for line in lines[y1:y2]:
318 for line in lines[y1:y2]:
319 equal += len(line)
319 equal += len(line)
320
320
321 lengths = len(text) + len(orig)
321 lengths = len(text) + len(orig)
322 return equal * 2.0 / lengths
322 return equal * 2.0 / lengths
323
323
324 for a in added:
324 for a in added:
325 bestscore = copies.get(a, (None, threshold))[1]
325 bestscore = copies.get(a, (None, threshold))[1]
326 myscore = score(repo.wread(a))
326 myscore = score(repo.wread(a))
327 if myscore >= bestscore:
327 if myscore >= bestscore:
328 copies[a] = (r, myscore)
328 copies[a] = (r, myscore)
329 repo.ui.progress(_('searching'), None)
329 repo.ui.progress(_('searching'), None)
330
330
331 for dest, v in copies.iteritems():
331 for dest, v in copies.iteritems():
332 source, score = v
332 source, score = v
333 yield source, dest, score
333 yield source, dest, score
334
334
335 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
335 def addremove(repo, pats=[], opts={}, dry_run=None, similarity=None):
336 if dry_run is None:
336 if dry_run is None:
337 dry_run = opts.get('dry_run')
337 dry_run = opts.get('dry_run')
338 if similarity is None:
338 if similarity is None:
339 similarity = float(opts.get('similarity') or 0)
339 similarity = float(opts.get('similarity') or 0)
340 # we'd use status here, except handling of symlinks and ignore is tricky
340 # we'd use status here, except handling of symlinks and ignore is tricky
341 added, unknown, deleted, removed = [], [], [], []
341 added, unknown, deleted, removed = [], [], [], []
342 audit_path = util.path_auditor(repo.root)
342 audit_path = util.path_auditor(repo.root)
343 m = match(repo, pats, opts)
343 m = match(repo, pats, opts)
344 for abs in repo.walk(m):
344 for abs in repo.walk(m):
345 target = repo.wjoin(abs)
345 target = repo.wjoin(abs)
346 good = True
346 good = True
347 try:
347 try:
348 audit_path(abs)
348 audit_path(abs)
349 except:
349 except:
350 good = False
350 good = False
351 rel = m.rel(abs)
351 rel = m.rel(abs)
352 exact = m.exact(abs)
352 exact = m.exact(abs)
353 if good and abs not in repo.dirstate:
353 if good and abs not in repo.dirstate:
354 unknown.append(abs)
354 unknown.append(abs)
355 if repo.ui.verbose or not exact:
355 if repo.ui.verbose or not exact:
356 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
356 repo.ui.status(_('adding %s\n') % ((pats and rel) or abs))
357 elif repo.dirstate[abs] != 'r' and (not good or not util.lexists(target)
357 elif repo.dirstate[abs] != 'r' and (not good or not util.lexists(target)
358 or (os.path.isdir(target) and not os.path.islink(target))):
358 or (os.path.isdir(target) and not os.path.islink(target))):
359 deleted.append(abs)
359 deleted.append(abs)
360 if repo.ui.verbose or not exact:
360 if repo.ui.verbose or not exact:
361 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
361 repo.ui.status(_('removing %s\n') % ((pats and rel) or abs))
362 # for finding renames
362 # for finding renames
363 elif repo.dirstate[abs] == 'r':
363 elif repo.dirstate[abs] == 'r':
364 removed.append(abs)
364 removed.append(abs)
365 elif repo.dirstate[abs] == 'a':
365 elif repo.dirstate[abs] == 'a':
366 added.append(abs)
366 added.append(abs)
367 copies = {}
367 copies = {}
368 if similarity > 0:
368 if similarity > 0:
369 for old, new, score in findrenames(repo, added + unknown,
369 for old, new, score in findrenames(repo, added + unknown,
370 removed + deleted, similarity):
370 removed + deleted, similarity):
371 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
371 if repo.ui.verbose or not m.exact(old) or not m.exact(new):
372 repo.ui.status(_('recording removal of %s as rename to %s '
372 repo.ui.status(_('recording removal of %s as rename to %s '
373 '(%d%% similar)\n') %
373 '(%d%% similar)\n') %
374 (m.rel(old), m.rel(new), score * 100))
374 (m.rel(old), m.rel(new), score * 100))
375 copies[new] = old
375 copies[new] = old
376
376
377 if not dry_run:
377 if not dry_run:
378 wlock = repo.wlock()
378 wlock = repo.wlock()
379 try:
379 try:
380 repo.remove(deleted)
380 repo.remove(deleted)
381 repo.add(unknown)
381 repo.add(unknown)
382 for new, old in copies.iteritems():
382 for new, old in copies.iteritems():
383 repo.copy(old, new)
383 repo.copy(old, new)
384 finally:
384 finally:
385 wlock.release()
385 wlock.release()
386
386
387 def copy(ui, repo, pats, opts, rename=False):
387 def copy(ui, repo, pats, opts, rename=False):
388 # called with the repo lock held
388 # called with the repo lock held
389 #
389 #
390 # hgsep => pathname that uses "/" to separate directories
390 # hgsep => pathname that uses "/" to separate directories
391 # ossep => pathname that uses os.sep to separate directories
391 # ossep => pathname that uses os.sep to separate directories
392 cwd = repo.getcwd()
392 cwd = repo.getcwd()
393 targets = {}
393 targets = {}
394 after = opts.get("after")
394 after = opts.get("after")
395 dryrun = opts.get("dry_run")
395 dryrun = opts.get("dry_run")
396
396
397 def walkpat(pat):
397 def walkpat(pat):
398 srcs = []
398 srcs = []
399 m = match(repo, [pat], opts, globbed=True)
399 m = match(repo, [pat], opts, globbed=True)
400 for abs in repo.walk(m):
400 for abs in repo.walk(m):
401 state = repo.dirstate[abs]
401 state = repo.dirstate[abs]
402 rel = m.rel(abs)
402 rel = m.rel(abs)
403 exact = m.exact(abs)
403 exact = m.exact(abs)
404 if state in '?r':
404 if state in '?r':
405 if exact and state == '?':
405 if exact and state == '?':
406 ui.warn(_('%s: not copying - file is not managed\n') % rel)
406 ui.warn(_('%s: not copying - file is not managed\n') % rel)
407 if exact and state == 'r':
407 if exact and state == 'r':
408 ui.warn(_('%s: not copying - file has been marked for'
408 ui.warn(_('%s: not copying - file has been marked for'
409 ' remove\n') % rel)
409 ' remove\n') % rel)
410 continue
410 continue
411 # abs: hgsep
411 # abs: hgsep
412 # rel: ossep
412 # rel: ossep
413 srcs.append((abs, rel, exact))
413 srcs.append((abs, rel, exact))
414 return srcs
414 return srcs
415
415
416 # abssrc: hgsep
416 # abssrc: hgsep
417 # relsrc: ossep
417 # relsrc: ossep
418 # otarget: ossep
418 # otarget: ossep
419 def copyfile(abssrc, relsrc, otarget, exact):
419 def copyfile(abssrc, relsrc, otarget, exact):
420 abstarget = util.canonpath(repo.root, cwd, otarget)
420 abstarget = util.canonpath(repo.root, cwd, otarget)
421 reltarget = repo.pathto(abstarget, cwd)
421 reltarget = repo.pathto(abstarget, cwd)
422 target = repo.wjoin(abstarget)
422 target = repo.wjoin(abstarget)
423 src = repo.wjoin(abssrc)
423 src = repo.wjoin(abssrc)
424 state = repo.dirstate[abstarget]
424 state = repo.dirstate[abstarget]
425
425
426 # check for collisions
426 # check for collisions
427 prevsrc = targets.get(abstarget)
427 prevsrc = targets.get(abstarget)
428 if prevsrc is not None:
428 if prevsrc is not None:
429 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
429 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
430 (reltarget, repo.pathto(abssrc, cwd),
430 (reltarget, repo.pathto(abssrc, cwd),
431 repo.pathto(prevsrc, cwd)))
431 repo.pathto(prevsrc, cwd)))
432 return
432 return
433
433
434 # check for overwrites
434 # check for overwrites
435 exists = os.path.exists(target)
435 exists = os.path.exists(target)
436 if not after and exists or after and state in 'mn':
436 if not after and exists or after and state in 'mn':
437 if not opts['force']:
437 if not opts['force']:
438 ui.warn(_('%s: not overwriting - file exists\n') %
438 ui.warn(_('%s: not overwriting - file exists\n') %
439 reltarget)
439 reltarget)
440 return
440 return
441
441
442 if after:
442 if after:
443 if not exists:
443 if not exists:
444 return
444 return
445 elif not dryrun:
445 elif not dryrun:
446 try:
446 try:
447 if exists:
447 if exists:
448 os.unlink(target)
448 os.unlink(target)
449 targetdir = os.path.dirname(target) or '.'
449 targetdir = os.path.dirname(target) or '.'
450 if not os.path.isdir(targetdir):
450 if not os.path.isdir(targetdir):
451 os.makedirs(targetdir)
451 os.makedirs(targetdir)
452 util.copyfile(src, target)
452 util.copyfile(src, target)
453 except IOError, inst:
453 except IOError, inst:
454 if inst.errno == errno.ENOENT:
454 if inst.errno == errno.ENOENT:
455 ui.warn(_('%s: deleted in working copy\n') % relsrc)
455 ui.warn(_('%s: deleted in working copy\n') % relsrc)
456 else:
456 else:
457 ui.warn(_('%s: cannot copy - %s\n') %
457 ui.warn(_('%s: cannot copy - %s\n') %
458 (relsrc, inst.strerror))
458 (relsrc, inst.strerror))
459 return True # report a failure
459 return True # report a failure
460
460
461 if ui.verbose or not exact:
461 if ui.verbose or not exact:
462 if rename:
462 if rename:
463 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
463 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
464 else:
464 else:
465 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
465 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
466
466
467 targets[abstarget] = abssrc
467 targets[abstarget] = abssrc
468
468
469 # fix up dirstate
469 # fix up dirstate
470 origsrc = repo.dirstate.copied(abssrc) or abssrc
470 origsrc = repo.dirstate.copied(abssrc) or abssrc
471 if abstarget == origsrc: # copying back a copy?
471 if abstarget == origsrc: # copying back a copy?
472 if state not in 'mn' and not dryrun:
472 if state not in 'mn' and not dryrun:
473 repo.dirstate.normallookup(abstarget)
473 repo.dirstate.normallookup(abstarget)
474 else:
474 else:
475 if repo.dirstate[origsrc] == 'a' and origsrc == abssrc:
475 if repo.dirstate[origsrc] == 'a' and origsrc == abssrc:
476 if not ui.quiet:
476 if not ui.quiet:
477 ui.warn(_("%s has not been committed yet, so no copy "
477 ui.warn(_("%s has not been committed yet, so no copy "
478 "data will be stored for %s.\n")
478 "data will be stored for %s.\n")
479 % (repo.pathto(origsrc, cwd), reltarget))
479 % (repo.pathto(origsrc, cwd), reltarget))
480 if repo.dirstate[abstarget] in '?r' and not dryrun:
480 if repo.dirstate[abstarget] in '?r' and not dryrun:
481 repo.add([abstarget])
481 repo.add([abstarget])
482 elif not dryrun:
482 elif not dryrun:
483 repo.copy(origsrc, abstarget)
483 repo.copy(origsrc, abstarget)
484
484
485 if rename and not dryrun:
485 if rename and not dryrun:
486 repo.remove([abssrc], not after)
486 repo.remove([abssrc], not after)
487
487
488 # pat: ossep
488 # pat: ossep
489 # dest ossep
489 # dest ossep
490 # srcs: list of (hgsep, hgsep, ossep, bool)
490 # srcs: list of (hgsep, hgsep, ossep, bool)
491 # return: function that takes hgsep and returns ossep
491 # return: function that takes hgsep and returns ossep
492 def targetpathfn(pat, dest, srcs):
492 def targetpathfn(pat, dest, srcs):
493 if os.path.isdir(pat):
493 if os.path.isdir(pat):
494 abspfx = util.canonpath(repo.root, cwd, pat)
494 abspfx = util.canonpath(repo.root, cwd, pat)
495 abspfx = util.localpath(abspfx)
495 abspfx = util.localpath(abspfx)
496 if destdirexists:
496 if destdirexists:
497 striplen = len(os.path.split(abspfx)[0])
497 striplen = len(os.path.split(abspfx)[0])
498 else:
498 else:
499 striplen = len(abspfx)
499 striplen = len(abspfx)
500 if striplen:
500 if striplen:
501 striplen += len(os.sep)
501 striplen += len(os.sep)
502 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
502 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
503 elif destdirexists:
503 elif destdirexists:
504 res = lambda p: os.path.join(dest,
504 res = lambda p: os.path.join(dest,
505 os.path.basename(util.localpath(p)))
505 os.path.basename(util.localpath(p)))
506 else:
506 else:
507 res = lambda p: dest
507 res = lambda p: dest
508 return res
508 return res
509
509
510 # pat: ossep
510 # pat: ossep
511 # dest ossep
511 # dest ossep
512 # srcs: list of (hgsep, hgsep, ossep, bool)
512 # srcs: list of (hgsep, hgsep, ossep, bool)
513 # return: function that takes hgsep and returns ossep
513 # return: function that takes hgsep and returns ossep
514 def targetpathafterfn(pat, dest, srcs):
514 def targetpathafterfn(pat, dest, srcs):
515 if _match.patkind(pat):
515 if _match.patkind(pat):
516 # a mercurial pattern
516 # a mercurial pattern
517 res = lambda p: os.path.join(dest,
517 res = lambda p: os.path.join(dest,
518 os.path.basename(util.localpath(p)))
518 os.path.basename(util.localpath(p)))
519 else:
519 else:
520 abspfx = util.canonpath(repo.root, cwd, pat)
520 abspfx = util.canonpath(repo.root, cwd, pat)
521 if len(abspfx) < len(srcs[0][0]):
521 if len(abspfx) < len(srcs[0][0]):
522 # A directory. Either the target path contains the last
522 # A directory. Either the target path contains the last
523 # component of the source path or it does not.
523 # component of the source path or it does not.
524 def evalpath(striplen):
524 def evalpath(striplen):
525 score = 0
525 score = 0
526 for s in srcs:
526 for s in srcs:
527 t = os.path.join(dest, util.localpath(s[0])[striplen:])
527 t = os.path.join(dest, util.localpath(s[0])[striplen:])
528 if os.path.exists(t):
528 if os.path.exists(t):
529 score += 1
529 score += 1
530 return score
530 return score
531
531
532 abspfx = util.localpath(abspfx)
532 abspfx = util.localpath(abspfx)
533 striplen = len(abspfx)
533 striplen = len(abspfx)
534 if striplen:
534 if striplen:
535 striplen += len(os.sep)
535 striplen += len(os.sep)
536 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
536 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
537 score = evalpath(striplen)
537 score = evalpath(striplen)
538 striplen1 = len(os.path.split(abspfx)[0])
538 striplen1 = len(os.path.split(abspfx)[0])
539 if striplen1:
539 if striplen1:
540 striplen1 += len(os.sep)
540 striplen1 += len(os.sep)
541 if evalpath(striplen1) > score:
541 if evalpath(striplen1) > score:
542 striplen = striplen1
542 striplen = striplen1
543 res = lambda p: os.path.join(dest,
543 res = lambda p: os.path.join(dest,
544 util.localpath(p)[striplen:])
544 util.localpath(p)[striplen:])
545 else:
545 else:
546 # a file
546 # a file
547 if destdirexists:
547 if destdirexists:
548 res = lambda p: os.path.join(dest,
548 res = lambda p: os.path.join(dest,
549 os.path.basename(util.localpath(p)))
549 os.path.basename(util.localpath(p)))
550 else:
550 else:
551 res = lambda p: dest
551 res = lambda p: dest
552 return res
552 return res
553
553
554
554
555 pats = expandpats(pats)
555 pats = expandpats(pats)
556 if not pats:
556 if not pats:
557 raise util.Abort(_('no source or destination specified'))
557 raise util.Abort(_('no source or destination specified'))
558 if len(pats) == 1:
558 if len(pats) == 1:
559 raise util.Abort(_('no destination specified'))
559 raise util.Abort(_('no destination specified'))
560 dest = pats.pop()
560 dest = pats.pop()
561 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
561 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
562 if not destdirexists:
562 if not destdirexists:
563 if len(pats) > 1 or _match.patkind(pats[0]):
563 if len(pats) > 1 or _match.patkind(pats[0]):
564 raise util.Abort(_('with multiple sources, destination must be an '
564 raise util.Abort(_('with multiple sources, destination must be an '
565 'existing directory'))
565 'existing directory'))
566 if util.endswithsep(dest):
566 if util.endswithsep(dest):
567 raise util.Abort(_('destination %s is not a directory') % dest)
567 raise util.Abort(_('destination %s is not a directory') % dest)
568
568
569 tfn = targetpathfn
569 tfn = targetpathfn
570 if after:
570 if after:
571 tfn = targetpathafterfn
571 tfn = targetpathafterfn
572 copylist = []
572 copylist = []
573 for pat in pats:
573 for pat in pats:
574 srcs = walkpat(pat)
574 srcs = walkpat(pat)
575 if not srcs:
575 if not srcs:
576 continue
576 continue
577 copylist.append((tfn(pat, dest, srcs), srcs))
577 copylist.append((tfn(pat, dest, srcs), srcs))
578 if not copylist:
578 if not copylist:
579 raise util.Abort(_('no files to copy'))
579 raise util.Abort(_('no files to copy'))
580
580
581 errors = 0
581 errors = 0
582 for targetpath, srcs in copylist:
582 for targetpath, srcs in copylist:
583 for abssrc, relsrc, exact in srcs:
583 for abssrc, relsrc, exact in srcs:
584 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
584 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
585 errors += 1
585 errors += 1
586
586
587 if errors:
587 if errors:
588 ui.warn(_('(consider using --after)\n'))
588 ui.warn(_('(consider using --after)\n'))
589
589
590 return errors
590 return errors
591
591
592 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
592 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
593 runargs=None, appendpid=False):
593 runargs=None, appendpid=False):
594 '''Run a command as a service.'''
594 '''Run a command as a service.'''
595
595
596 if opts['daemon'] and not opts['daemon_pipefds']:
596 if opts['daemon'] and not opts['daemon_pipefds']:
597 # Signal child process startup with file removal
597 # Signal child process startup with file removal
598 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
598 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
599 os.close(lockfd)
599 os.close(lockfd)
600 try:
600 try:
601 if not runargs:
601 if not runargs:
602 runargs = util.hgcmd() + sys.argv[1:]
602 runargs = util.hgcmd() + sys.argv[1:]
603 runargs.append('--daemon-pipefds=%s' % lockpath)
603 runargs.append('--daemon-pipefds=%s' % lockpath)
604 # Don't pass --cwd to the child process, because we've already
604 # Don't pass --cwd to the child process, because we've already
605 # changed directory.
605 # changed directory.
606 for i in xrange(1, len(runargs)):
606 for i in xrange(1, len(runargs)):
607 if runargs[i].startswith('--cwd='):
607 if runargs[i].startswith('--cwd='):
608 del runargs[i]
608 del runargs[i]
609 break
609 break
610 elif runargs[i].startswith('--cwd'):
610 elif runargs[i].startswith('--cwd'):
611 del runargs[i:i + 2]
611 del runargs[i:i + 2]
612 break
612 break
613 def condfn():
613 def condfn():
614 return not os.path.exists(lockpath)
614 return not os.path.exists(lockpath)
615 pid = util.rundetached(runargs, condfn)
615 pid = util.rundetached(runargs, condfn)
616 if pid < 0:
616 if pid < 0:
617 raise util.Abort(_('child process failed to start'))
617 raise util.Abort(_('child process failed to start'))
618 finally:
618 finally:
619 try:
619 try:
620 os.unlink(lockpath)
620 os.unlink(lockpath)
621 except OSError, e:
621 except OSError, e:
622 if e.errno != errno.ENOENT:
622 if e.errno != errno.ENOENT:
623 raise
623 raise
624 if parentfn:
624 if parentfn:
625 return parentfn(pid)
625 return parentfn(pid)
626 else:
626 else:
627 return
627 return
628
628
629 if initfn:
629 if initfn:
630 initfn()
630 initfn()
631
631
632 if opts['pid_file']:
632 if opts['pid_file']:
633 mode = appendpid and 'a' or 'w'
633 mode = appendpid and 'a' or 'w'
634 fp = open(opts['pid_file'], mode)
634 fp = open(opts['pid_file'], mode)
635 fp.write(str(os.getpid()) + '\n')
635 fp.write(str(os.getpid()) + '\n')
636 fp.close()
636 fp.close()
637
637
638 if opts['daemon_pipefds']:
638 if opts['daemon_pipefds']:
639 lockpath = opts['daemon_pipefds']
639 lockpath = opts['daemon_pipefds']
640 try:
640 try:
641 os.setsid()
641 os.setsid()
642 except AttributeError:
642 except AttributeError:
643 pass
643 pass
644 os.unlink(lockpath)
644 os.unlink(lockpath)
645 util.hidewindow()
645 util.hidewindow()
646 sys.stdout.flush()
646 sys.stdout.flush()
647 sys.stderr.flush()
647 sys.stderr.flush()
648
648
649 nullfd = os.open(util.nulldev, os.O_RDWR)
649 nullfd = os.open(util.nulldev, os.O_RDWR)
650 logfilefd = nullfd
650 logfilefd = nullfd
651 if logfile:
651 if logfile:
652 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
652 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
653 os.dup2(nullfd, 0)
653 os.dup2(nullfd, 0)
654 os.dup2(logfilefd, 1)
654 os.dup2(logfilefd, 1)
655 os.dup2(logfilefd, 2)
655 os.dup2(logfilefd, 2)
656 if nullfd not in (0, 1, 2):
656 if nullfd not in (0, 1, 2):
657 os.close(nullfd)
657 os.close(nullfd)
658 if logfile and logfilefd not in (0, 1, 2):
658 if logfile and logfilefd not in (0, 1, 2):
659 os.close(logfilefd)
659 os.close(logfilefd)
660
660
661 if runfn:
661 if runfn:
662 return runfn()
662 return runfn()
663
663
664 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
664 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
665 opts=None):
665 opts=None):
666 '''export changesets as hg patches.'''
666 '''export changesets as hg patches.'''
667
667
668 total = len(revs)
668 total = len(revs)
669 revwidth = max([len(str(rev)) for rev in revs])
669 revwidth = max([len(str(rev)) for rev in revs])
670
670
671 def single(rev, seqno, fp):
671 def single(rev, seqno, fp):
672 ctx = repo[rev]
672 ctx = repo[rev]
673 node = ctx.node()
673 node = ctx.node()
674 parents = [p.node() for p in ctx.parents() if p]
674 parents = [p.node() for p in ctx.parents() if p]
675 branch = ctx.branch()
675 branch = ctx.branch()
676 if switch_parent:
676 if switch_parent:
677 parents.reverse()
677 parents.reverse()
678 prev = (parents and parents[0]) or nullid
678 prev = (parents and parents[0]) or nullid
679
679
680 if not fp:
680 if not fp:
681 fp = make_file(repo, template, node, total=total, seqno=seqno,
681 fp = make_file(repo, template, node, total=total, seqno=seqno,
682 revwidth=revwidth, mode='ab')
682 revwidth=revwidth, mode='ab')
683 if fp != sys.stdout and hasattr(fp, 'name'):
683 if fp != sys.stdout and hasattr(fp, 'name'):
684 repo.ui.note("%s\n" % fp.name)
684 repo.ui.note("%s\n" % fp.name)
685
685
686 fp.write("# HG changeset patch\n")
686 fp.write("# HG changeset patch\n")
687 fp.write("# User %s\n" % ctx.user())
687 fp.write("# User %s\n" % ctx.user())
688 fp.write("# Date %d %d\n" % ctx.date())
688 fp.write("# Date %d %d\n" % ctx.date())
689 if branch and (branch != 'default'):
689 if branch and (branch != 'default'):
690 fp.write("# Branch %s\n" % branch)
690 fp.write("# Branch %s\n" % branch)
691 fp.write("# Node ID %s\n" % hex(node))
691 fp.write("# Node ID %s\n" % hex(node))
692 fp.write("# Parent %s\n" % hex(prev))
692 fp.write("# Parent %s\n" % hex(prev))
693 if len(parents) > 1:
693 if len(parents) > 1:
694 fp.write("# Parent %s\n" % hex(parents[1]))
694 fp.write("# Parent %s\n" % hex(parents[1]))
695 fp.write(ctx.description().rstrip())
695 fp.write(ctx.description().rstrip())
696 fp.write("\n\n")
696 fp.write("\n\n")
697
697
698 for chunk in patch.diff(repo, prev, node, opts=opts):
698 for chunk in patch.diff(repo, prev, node, opts=opts):
699 fp.write(chunk)
699 fp.write(chunk)
700
700
701 for seqno, rev in enumerate(revs):
701 for seqno, rev in enumerate(revs):
702 single(rev, seqno + 1, fp)
702 single(rev, seqno + 1, fp)
703
703
704 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
705 changes=None, stat=False, fp=None):
706 '''show diff or diffstat.'''
707 if fp is None:
708 write = ui.write
709 else:
710 def write(s, **kw):
711 fp.write(s)
712
713 if stat:
714 diffopts.context = 0
715 width = 80
716 if not ui.plain():
717 width = util.termwidth()
718 chunks = patch.diff(repo, node1, node2, match, changes, diffopts)
719 for chunk, label in patch.diffstatui(util.iterlines(chunks),
720 width=width,
721 git=diffopts.git):
722 write(chunk, label=label)
723 else:
724 for chunk, label in patch.diffui(repo, node1, node2, match,
725 changes, diffopts):
726 write(chunk, label=label)
727
704 class changeset_printer(object):
728 class changeset_printer(object):
705 '''show changeset information when templating not requested.'''
729 '''show changeset information when templating not requested.'''
706
730
707 def __init__(self, ui, repo, patch, diffopts, buffered):
731 def __init__(self, ui, repo, patch, diffopts, buffered):
708 self.ui = ui
732 self.ui = ui
709 self.repo = repo
733 self.repo = repo
710 self.buffered = buffered
734 self.buffered = buffered
711 self.patch = patch
735 self.patch = patch
712 self.diffopts = diffopts
736 self.diffopts = diffopts
713 self.header = {}
737 self.header = {}
714 self.hunk = {}
738 self.hunk = {}
715 self.lastheader = None
739 self.lastheader = None
716 self.footer = None
740 self.footer = None
717
741
718 def flush(self, rev):
742 def flush(self, rev):
719 if rev in self.header:
743 if rev in self.header:
720 h = self.header[rev]
744 h = self.header[rev]
721 if h != self.lastheader:
745 if h != self.lastheader:
722 self.lastheader = h
746 self.lastheader = h
723 self.ui.write(h)
747 self.ui.write(h)
724 del self.header[rev]
748 del self.header[rev]
725 if rev in self.hunk:
749 if rev in self.hunk:
726 self.ui.write(self.hunk[rev])
750 self.ui.write(self.hunk[rev])
727 del self.hunk[rev]
751 del self.hunk[rev]
728 return 1
752 return 1
729 return 0
753 return 0
730
754
731 def close(self):
755 def close(self):
732 if self.footer:
756 if self.footer:
733 self.ui.write(self.footer)
757 self.ui.write(self.footer)
734
758
735 def show(self, ctx, copies=None, **props):
759 def show(self, ctx, copies=None, **props):
736 if self.buffered:
760 if self.buffered:
737 self.ui.pushbuffer()
761 self.ui.pushbuffer()
738 self._show(ctx, copies, props)
762 self._show(ctx, copies, props)
739 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
763 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
740 else:
764 else:
741 self._show(ctx, copies, props)
765 self._show(ctx, copies, props)
742
766
743 def _show(self, ctx, copies, props):
767 def _show(self, ctx, copies, props):
744 '''show a single changeset or file revision'''
768 '''show a single changeset or file revision'''
745 changenode = ctx.node()
769 changenode = ctx.node()
746 rev = ctx.rev()
770 rev = ctx.rev()
747
771
748 if self.ui.quiet:
772 if self.ui.quiet:
749 self.ui.write("%d:%s\n" % (rev, short(changenode)),
773 self.ui.write("%d:%s\n" % (rev, short(changenode)),
750 label='log.node')
774 label='log.node')
751 return
775 return
752
776
753 log = self.repo.changelog
777 log = self.repo.changelog
754 date = util.datestr(ctx.date())
778 date = util.datestr(ctx.date())
755
779
756 hexfunc = self.ui.debugflag and hex or short
780 hexfunc = self.ui.debugflag and hex or short
757
781
758 parents = [(p, hexfunc(log.node(p)))
782 parents = [(p, hexfunc(log.node(p)))
759 for p in self._meaningful_parentrevs(log, rev)]
783 for p in self._meaningful_parentrevs(log, rev)]
760
784
761 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
785 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
762 label='log.changeset')
786 label='log.changeset')
763
787
764 branch = ctx.branch()
788 branch = ctx.branch()
765 # don't show the default branch name
789 # don't show the default branch name
766 if branch != 'default':
790 if branch != 'default':
767 branch = encoding.tolocal(branch)
791 branch = encoding.tolocal(branch)
768 self.ui.write(_("branch: %s\n") % branch,
792 self.ui.write(_("branch: %s\n") % branch,
769 label='log.branch')
793 label='log.branch')
770 for tag in self.repo.nodetags(changenode):
794 for tag in self.repo.nodetags(changenode):
771 self.ui.write(_("tag: %s\n") % tag,
795 self.ui.write(_("tag: %s\n") % tag,
772 label='log.tag')
796 label='log.tag')
773 for parent in parents:
797 for parent in parents:
774 self.ui.write(_("parent: %d:%s\n") % parent,
798 self.ui.write(_("parent: %d:%s\n") % parent,
775 label='log.parent')
799 label='log.parent')
776
800
777 if self.ui.debugflag:
801 if self.ui.debugflag:
778 mnode = ctx.manifestnode()
802 mnode = ctx.manifestnode()
779 self.ui.write(_("manifest: %d:%s\n") %
803 self.ui.write(_("manifest: %d:%s\n") %
780 (self.repo.manifest.rev(mnode), hex(mnode)),
804 (self.repo.manifest.rev(mnode), hex(mnode)),
781 label='ui.debug log.manifest')
805 label='ui.debug log.manifest')
782 self.ui.write(_("user: %s\n") % ctx.user(),
806 self.ui.write(_("user: %s\n") % ctx.user(),
783 label='log.user')
807 label='log.user')
784 self.ui.write(_("date: %s\n") % date,
808 self.ui.write(_("date: %s\n") % date,
785 label='log.date')
809 label='log.date')
786
810
787 if self.ui.debugflag:
811 if self.ui.debugflag:
788 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
812 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
789 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
813 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
790 files):
814 files):
791 if value:
815 if value:
792 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
816 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
793 label='ui.debug log.files')
817 label='ui.debug log.files')
794 elif ctx.files() and self.ui.verbose:
818 elif ctx.files() and self.ui.verbose:
795 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
819 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
796 label='ui.note log.files')
820 label='ui.note log.files')
797 if copies and self.ui.verbose:
821 if copies and self.ui.verbose:
798 copies = ['%s (%s)' % c for c in copies]
822 copies = ['%s (%s)' % c for c in copies]
799 self.ui.write(_("copies: %s\n") % ' '.join(copies),
823 self.ui.write(_("copies: %s\n") % ' '.join(copies),
800 label='ui.note log.copies')
824 label='ui.note log.copies')
801
825
802 extra = ctx.extra()
826 extra = ctx.extra()
803 if extra and self.ui.debugflag:
827 if extra and self.ui.debugflag:
804 for key, value in sorted(extra.items()):
828 for key, value in sorted(extra.items()):
805 self.ui.write(_("extra: %s=%s\n")
829 self.ui.write(_("extra: %s=%s\n")
806 % (key, value.encode('string_escape')),
830 % (key, value.encode('string_escape')),
807 label='ui.debug log.extra')
831 label='ui.debug log.extra')
808
832
809 description = ctx.description().strip()
833 description = ctx.description().strip()
810 if description:
834 if description:
811 if self.ui.verbose:
835 if self.ui.verbose:
812 self.ui.write(_("description:\n"),
836 self.ui.write(_("description:\n"),
813 label='ui.note log.description')
837 label='ui.note log.description')
814 self.ui.write(description,
838 self.ui.write(description,
815 label='ui.note log.description')
839 label='ui.note log.description')
816 self.ui.write("\n\n")
840 self.ui.write("\n\n")
817 else:
841 else:
818 self.ui.write(_("summary: %s\n") %
842 self.ui.write(_("summary: %s\n") %
819 description.splitlines()[0],
843 description.splitlines()[0],
820 label='log.summary')
844 label='log.summary')
821 self.ui.write("\n")
845 self.ui.write("\n")
822
846
823 self.showpatch(changenode)
847 self.showpatch(changenode)
824
848
825 def showpatch(self, node):
849 def showpatch(self, node):
826 if self.patch:
850 if self.patch:
827 prev = self.repo.changelog.parents(node)[0]
851 prev = self.repo.changelog.parents(node)[0]
828 chunks = patch.diffui(self.repo, prev, node, match=self.patch,
852 chunks = patch.diffui(self.repo, prev, node, match=self.patch,
829 opts=patch.diffopts(self.ui, self.diffopts))
853 opts=patch.diffopts(self.ui, self.diffopts))
830 for chunk, label in chunks:
854 for chunk, label in chunks:
831 self.ui.write(chunk, label=label)
855 self.ui.write(chunk, label=label)
832 self.ui.write("\n")
856 self.ui.write("\n")
833
857
834 def _meaningful_parentrevs(self, log, rev):
858 def _meaningful_parentrevs(self, log, rev):
835 """Return list of meaningful (or all if debug) parentrevs for rev.
859 """Return list of meaningful (or all if debug) parentrevs for rev.
836
860
837 For merges (two non-nullrev revisions) both parents are meaningful.
861 For merges (two non-nullrev revisions) both parents are meaningful.
838 Otherwise the first parent revision is considered meaningful if it
862 Otherwise the first parent revision is considered meaningful if it
839 is not the preceding revision.
863 is not the preceding revision.
840 """
864 """
841 parents = log.parentrevs(rev)
865 parents = log.parentrevs(rev)
842 if not self.ui.debugflag and parents[1] == nullrev:
866 if not self.ui.debugflag and parents[1] == nullrev:
843 if parents[0] >= rev - 1:
867 if parents[0] >= rev - 1:
844 parents = []
868 parents = []
845 else:
869 else:
846 parents = [parents[0]]
870 parents = [parents[0]]
847 return parents
871 return parents
848
872
849
873
850 class changeset_templater(changeset_printer):
874 class changeset_templater(changeset_printer):
851 '''format changeset information.'''
875 '''format changeset information.'''
852
876
853 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
877 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
854 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
878 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
855 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
879 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
856 defaulttempl = {
880 defaulttempl = {
857 'parent': '{rev}:{node|formatnode} ',
881 'parent': '{rev}:{node|formatnode} ',
858 'manifest': '{rev}:{node|formatnode}',
882 'manifest': '{rev}:{node|formatnode}',
859 'file_copy': '{name} ({source})',
883 'file_copy': '{name} ({source})',
860 'extra': '{key}={value|stringescape}'
884 'extra': '{key}={value|stringescape}'
861 }
885 }
862 # filecopy is preserved for compatibility reasons
886 # filecopy is preserved for compatibility reasons
863 defaulttempl['filecopy'] = defaulttempl['file_copy']
887 defaulttempl['filecopy'] = defaulttempl['file_copy']
864 self.t = templater.templater(mapfile, {'formatnode': formatnode},
888 self.t = templater.templater(mapfile, {'formatnode': formatnode},
865 cache=defaulttempl)
889 cache=defaulttempl)
866 self.cache = {}
890 self.cache = {}
867
891
868 def use_template(self, t):
892 def use_template(self, t):
869 '''set template string to use'''
893 '''set template string to use'''
870 self.t.cache['changeset'] = t
894 self.t.cache['changeset'] = t
871
895
872 def _meaningful_parentrevs(self, ctx):
896 def _meaningful_parentrevs(self, ctx):
873 """Return list of meaningful (or all if debug) parentrevs for rev.
897 """Return list of meaningful (or all if debug) parentrevs for rev.
874 """
898 """
875 parents = ctx.parents()
899 parents = ctx.parents()
876 if len(parents) > 1:
900 if len(parents) > 1:
877 return parents
901 return parents
878 if self.ui.debugflag:
902 if self.ui.debugflag:
879 return [parents[0], self.repo['null']]
903 return [parents[0], self.repo['null']]
880 if parents[0].rev() >= ctx.rev() - 1:
904 if parents[0].rev() >= ctx.rev() - 1:
881 return []
905 return []
882 return parents
906 return parents
883
907
884 def _show(self, ctx, copies, props):
908 def _show(self, ctx, copies, props):
885 '''show a single changeset or file revision'''
909 '''show a single changeset or file revision'''
886
910
887 showlist = templatekw.showlist
911 showlist = templatekw.showlist
888
912
889 # showparents() behaviour depends on ui trace level which
913 # showparents() behaviour depends on ui trace level which
890 # causes unexpected behaviours at templating level and makes
914 # causes unexpected behaviours at templating level and makes
891 # it harder to extract it in a standalone function. Its
915 # it harder to extract it in a standalone function. Its
892 # behaviour cannot be changed so leave it here for now.
916 # behaviour cannot be changed so leave it here for now.
893 def showparents(**args):
917 def showparents(**args):
894 ctx = args['ctx']
918 ctx = args['ctx']
895 parents = [[('rev', p.rev()), ('node', p.hex())]
919 parents = [[('rev', p.rev()), ('node', p.hex())]
896 for p in self._meaningful_parentrevs(ctx)]
920 for p in self._meaningful_parentrevs(ctx)]
897 return showlist('parent', parents, **args)
921 return showlist('parent', parents, **args)
898
922
899 props = props.copy()
923 props = props.copy()
900 props.update(templatekw.keywords)
924 props.update(templatekw.keywords)
901 props['parents'] = showparents
925 props['parents'] = showparents
902 props['templ'] = self.t
926 props['templ'] = self.t
903 props['ctx'] = ctx
927 props['ctx'] = ctx
904 props['repo'] = self.repo
928 props['repo'] = self.repo
905 props['revcache'] = {'copies': copies}
929 props['revcache'] = {'copies': copies}
906 props['cache'] = self.cache
930 props['cache'] = self.cache
907
931
908 # find correct templates for current mode
932 # find correct templates for current mode
909
933
910 tmplmodes = [
934 tmplmodes = [
911 (True, None),
935 (True, None),
912 (self.ui.verbose, 'verbose'),
936 (self.ui.verbose, 'verbose'),
913 (self.ui.quiet, 'quiet'),
937 (self.ui.quiet, 'quiet'),
914 (self.ui.debugflag, 'debug'),
938 (self.ui.debugflag, 'debug'),
915 ]
939 ]
916
940
917 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
941 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
918 for mode, postfix in tmplmodes:
942 for mode, postfix in tmplmodes:
919 for type in types:
943 for type in types:
920 cur = postfix and ('%s_%s' % (type, postfix)) or type
944 cur = postfix and ('%s_%s' % (type, postfix)) or type
921 if mode and cur in self.t:
945 if mode and cur in self.t:
922 types[type] = cur
946 types[type] = cur
923
947
924 try:
948 try:
925
949
926 # write header
950 # write header
927 if types['header']:
951 if types['header']:
928 h = templater.stringify(self.t(types['header'], **props))
952 h = templater.stringify(self.t(types['header'], **props))
929 if self.buffered:
953 if self.buffered:
930 self.header[ctx.rev()] = h
954 self.header[ctx.rev()] = h
931 else:
955 else:
932 self.ui.write(h)
956 self.ui.write(h)
933
957
934 # write changeset metadata, then patch if requested
958 # write changeset metadata, then patch if requested
935 key = types['changeset']
959 key = types['changeset']
936 self.ui.write(templater.stringify(self.t(key, **props)))
960 self.ui.write(templater.stringify(self.t(key, **props)))
937 self.showpatch(ctx.node())
961 self.showpatch(ctx.node())
938
962
939 if types['footer']:
963 if types['footer']:
940 if not self.footer:
964 if not self.footer:
941 self.footer = templater.stringify(self.t(types['footer'],
965 self.footer = templater.stringify(self.t(types['footer'],
942 **props))
966 **props))
943
967
944 except KeyError, inst:
968 except KeyError, inst:
945 msg = _("%s: no key named '%s'")
969 msg = _("%s: no key named '%s'")
946 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
970 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
947 except SyntaxError, inst:
971 except SyntaxError, inst:
948 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
972 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
949
973
950 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
974 def show_changeset(ui, repo, opts, buffered=False, matchfn=False):
951 """show one changeset using template or regular display.
975 """show one changeset using template or regular display.
952
976
953 Display format will be the first non-empty hit of:
977 Display format will be the first non-empty hit of:
954 1. option 'template'
978 1. option 'template'
955 2. option 'style'
979 2. option 'style'
956 3. [ui] setting 'logtemplate'
980 3. [ui] setting 'logtemplate'
957 4. [ui] setting 'style'
981 4. [ui] setting 'style'
958 If all of these values are either the unset or the empty string,
982 If all of these values are either the unset or the empty string,
959 regular display via changeset_printer() is done.
983 regular display via changeset_printer() is done.
960 """
984 """
961 # options
985 # options
962 patch = False
986 patch = False
963 if opts.get('patch'):
987 if opts.get('patch'):
964 patch = matchfn or matchall(repo)
988 patch = matchfn or matchall(repo)
965
989
966 tmpl = opts.get('template')
990 tmpl = opts.get('template')
967 style = None
991 style = None
968 if tmpl:
992 if tmpl:
969 tmpl = templater.parsestring(tmpl, quoted=False)
993 tmpl = templater.parsestring(tmpl, quoted=False)
970 else:
994 else:
971 style = opts.get('style')
995 style = opts.get('style')
972
996
973 # ui settings
997 # ui settings
974 if not (tmpl or style):
998 if not (tmpl or style):
975 tmpl = ui.config('ui', 'logtemplate')
999 tmpl = ui.config('ui', 'logtemplate')
976 if tmpl:
1000 if tmpl:
977 tmpl = templater.parsestring(tmpl)
1001 tmpl = templater.parsestring(tmpl)
978 else:
1002 else:
979 style = util.expandpath(ui.config('ui', 'style', ''))
1003 style = util.expandpath(ui.config('ui', 'style', ''))
980
1004
981 if not (tmpl or style):
1005 if not (tmpl or style):
982 return changeset_printer(ui, repo, patch, opts, buffered)
1006 return changeset_printer(ui, repo, patch, opts, buffered)
983
1007
984 mapfile = None
1008 mapfile = None
985 if style and not tmpl:
1009 if style and not tmpl:
986 mapfile = style
1010 mapfile = style
987 if not os.path.split(mapfile)[0]:
1011 if not os.path.split(mapfile)[0]:
988 mapname = (templater.templatepath('map-cmdline.' + mapfile)
1012 mapname = (templater.templatepath('map-cmdline.' + mapfile)
989 or templater.templatepath(mapfile))
1013 or templater.templatepath(mapfile))
990 if mapname:
1014 if mapname:
991 mapfile = mapname
1015 mapfile = mapname
992
1016
993 try:
1017 try:
994 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
1018 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
995 except SyntaxError, inst:
1019 except SyntaxError, inst:
996 raise util.Abort(inst.args[0])
1020 raise util.Abort(inst.args[0])
997 if tmpl:
1021 if tmpl:
998 t.use_template(tmpl)
1022 t.use_template(tmpl)
999 return t
1023 return t
1000
1024
1001 def finddate(ui, repo, date):
1025 def finddate(ui, repo, date):
1002 """Find the tipmost changeset that matches the given date spec"""
1026 """Find the tipmost changeset that matches the given date spec"""
1003
1027
1004 df = util.matchdate(date)
1028 df = util.matchdate(date)
1005 m = matchall(repo)
1029 m = matchall(repo)
1006 results = {}
1030 results = {}
1007
1031
1008 def prep(ctx, fns):
1032 def prep(ctx, fns):
1009 d = ctx.date()
1033 d = ctx.date()
1010 if df(d[0]):
1034 if df(d[0]):
1011 results[ctx.rev()] = d
1035 results[ctx.rev()] = d
1012
1036
1013 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1037 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1014 rev = ctx.rev()
1038 rev = ctx.rev()
1015 if rev in results:
1039 if rev in results:
1016 ui.status(_("Found revision %s from %s\n") %
1040 ui.status(_("Found revision %s from %s\n") %
1017 (rev, util.datestr(results[rev])))
1041 (rev, util.datestr(results[rev])))
1018 return str(rev)
1042 return str(rev)
1019
1043
1020 raise util.Abort(_("revision matching date not found"))
1044 raise util.Abort(_("revision matching date not found"))
1021
1045
1022 def walkchangerevs(repo, match, opts, prepare):
1046 def walkchangerevs(repo, match, opts, prepare):
1023 '''Iterate over files and the revs in which they changed.
1047 '''Iterate over files and the revs in which they changed.
1024
1048
1025 Callers most commonly need to iterate backwards over the history
1049 Callers most commonly need to iterate backwards over the history
1026 in which they are interested. Doing so has awful (quadratic-looking)
1050 in which they are interested. Doing so has awful (quadratic-looking)
1027 performance, so we use iterators in a "windowed" way.
1051 performance, so we use iterators in a "windowed" way.
1028
1052
1029 We walk a window of revisions in the desired order. Within the
1053 We walk a window of revisions in the desired order. Within the
1030 window, we first walk forwards to gather data, then in the desired
1054 window, we first walk forwards to gather data, then in the desired
1031 order (usually backwards) to display it.
1055 order (usually backwards) to display it.
1032
1056
1033 This function returns an iterator yielding contexts. Before
1057 This function returns an iterator yielding contexts. Before
1034 yielding each context, the iterator will first call the prepare
1058 yielding each context, the iterator will first call the prepare
1035 function on each context in the window in forward order.'''
1059 function on each context in the window in forward order.'''
1036
1060
1037 def increasing_windows(start, end, windowsize=8, sizelimit=512):
1061 def increasing_windows(start, end, windowsize=8, sizelimit=512):
1038 if start < end:
1062 if start < end:
1039 while start < end:
1063 while start < end:
1040 yield start, min(windowsize, end - start)
1064 yield start, min(windowsize, end - start)
1041 start += windowsize
1065 start += windowsize
1042 if windowsize < sizelimit:
1066 if windowsize < sizelimit:
1043 windowsize *= 2
1067 windowsize *= 2
1044 else:
1068 else:
1045 while start > end:
1069 while start > end:
1046 yield start, min(windowsize, start - end - 1)
1070 yield start, min(windowsize, start - end - 1)
1047 start -= windowsize
1071 start -= windowsize
1048 if windowsize < sizelimit:
1072 if windowsize < sizelimit:
1049 windowsize *= 2
1073 windowsize *= 2
1050
1074
1051 follow = opts.get('follow') or opts.get('follow_first')
1075 follow = opts.get('follow') or opts.get('follow_first')
1052
1076
1053 if not len(repo):
1077 if not len(repo):
1054 return []
1078 return []
1055
1079
1056 if follow:
1080 if follow:
1057 defrange = '%s:0' % repo['.'].rev()
1081 defrange = '%s:0' % repo['.'].rev()
1058 else:
1082 else:
1059 defrange = '-1:0'
1083 defrange = '-1:0'
1060 revs = revrange(repo, opts['rev'] or [defrange])
1084 revs = revrange(repo, opts['rev'] or [defrange])
1061 wanted = set()
1085 wanted = set()
1062 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1086 slowpath = match.anypats() or (match.files() and opts.get('removed'))
1063 fncache = {}
1087 fncache = {}
1064 change = util.cachefunc(repo.changectx)
1088 change = util.cachefunc(repo.changectx)
1065
1089
1066 if not slowpath and not match.files():
1090 if not slowpath and not match.files():
1067 # No files, no patterns. Display all revs.
1091 # No files, no patterns. Display all revs.
1068 wanted = set(revs)
1092 wanted = set(revs)
1069 copies = []
1093 copies = []
1070
1094
1071 if not slowpath:
1095 if not slowpath:
1072 # Only files, no patterns. Check the history of each file.
1096 # Only files, no patterns. Check the history of each file.
1073 def filerevgen(filelog, node):
1097 def filerevgen(filelog, node):
1074 cl_count = len(repo)
1098 cl_count = len(repo)
1075 if node is None:
1099 if node is None:
1076 last = len(filelog) - 1
1100 last = len(filelog) - 1
1077 else:
1101 else:
1078 last = filelog.rev(node)
1102 last = filelog.rev(node)
1079 for i, window in increasing_windows(last, nullrev):
1103 for i, window in increasing_windows(last, nullrev):
1080 revs = []
1104 revs = []
1081 for j in xrange(i - window, i + 1):
1105 for j in xrange(i - window, i + 1):
1082 n = filelog.node(j)
1106 n = filelog.node(j)
1083 revs.append((filelog.linkrev(j),
1107 revs.append((filelog.linkrev(j),
1084 follow and filelog.renamed(n)))
1108 follow and filelog.renamed(n)))
1085 for rev in reversed(revs):
1109 for rev in reversed(revs):
1086 # only yield rev for which we have the changelog, it can
1110 # only yield rev for which we have the changelog, it can
1087 # happen while doing "hg log" during a pull or commit
1111 # happen while doing "hg log" during a pull or commit
1088 if rev[0] < cl_count:
1112 if rev[0] < cl_count:
1089 yield rev
1113 yield rev
1090 def iterfiles():
1114 def iterfiles():
1091 for filename in match.files():
1115 for filename in match.files():
1092 yield filename, None
1116 yield filename, None
1093 for filename_node in copies:
1117 for filename_node in copies:
1094 yield filename_node
1118 yield filename_node
1095 minrev, maxrev = min(revs), max(revs)
1119 minrev, maxrev = min(revs), max(revs)
1096 for file_, node in iterfiles():
1120 for file_, node in iterfiles():
1097 filelog = repo.file(file_)
1121 filelog = repo.file(file_)
1098 if not len(filelog):
1122 if not len(filelog):
1099 if node is None:
1123 if node is None:
1100 # A zero count may be a directory or deleted file, so
1124 # A zero count may be a directory or deleted file, so
1101 # try to find matching entries on the slow path.
1125 # try to find matching entries on the slow path.
1102 if follow:
1126 if follow:
1103 raise util.Abort(
1127 raise util.Abort(
1104 _('cannot follow nonexistent file: "%s"') % file_)
1128 _('cannot follow nonexistent file: "%s"') % file_)
1105 slowpath = True
1129 slowpath = True
1106 break
1130 break
1107 else:
1131 else:
1108 continue
1132 continue
1109 for rev, copied in filerevgen(filelog, node):
1133 for rev, copied in filerevgen(filelog, node):
1110 if rev <= maxrev:
1134 if rev <= maxrev:
1111 if rev < minrev:
1135 if rev < minrev:
1112 break
1136 break
1113 fncache.setdefault(rev, [])
1137 fncache.setdefault(rev, [])
1114 fncache[rev].append(file_)
1138 fncache[rev].append(file_)
1115 wanted.add(rev)
1139 wanted.add(rev)
1116 if copied:
1140 if copied:
1117 copies.append(copied)
1141 copies.append(copied)
1118 if slowpath:
1142 if slowpath:
1119 if follow:
1143 if follow:
1120 raise util.Abort(_('can only follow copies/renames for explicit '
1144 raise util.Abort(_('can only follow copies/renames for explicit '
1121 'filenames'))
1145 'filenames'))
1122
1146
1123 # The slow path checks files modified in every changeset.
1147 # The slow path checks files modified in every changeset.
1124 def changerevgen():
1148 def changerevgen():
1125 for i, window in increasing_windows(len(repo) - 1, nullrev):
1149 for i, window in increasing_windows(len(repo) - 1, nullrev):
1126 for j in xrange(i - window, i + 1):
1150 for j in xrange(i - window, i + 1):
1127 yield change(j)
1151 yield change(j)
1128
1152
1129 for ctx in changerevgen():
1153 for ctx in changerevgen():
1130 matches = filter(match, ctx.files())
1154 matches = filter(match, ctx.files())
1131 if matches:
1155 if matches:
1132 fncache[ctx.rev()] = matches
1156 fncache[ctx.rev()] = matches
1133 wanted.add(ctx.rev())
1157 wanted.add(ctx.rev())
1134
1158
1135 class followfilter(object):
1159 class followfilter(object):
1136 def __init__(self, onlyfirst=False):
1160 def __init__(self, onlyfirst=False):
1137 self.startrev = nullrev
1161 self.startrev = nullrev
1138 self.roots = set()
1162 self.roots = set()
1139 self.onlyfirst = onlyfirst
1163 self.onlyfirst = onlyfirst
1140
1164
1141 def match(self, rev):
1165 def match(self, rev):
1142 def realparents(rev):
1166 def realparents(rev):
1143 if self.onlyfirst:
1167 if self.onlyfirst:
1144 return repo.changelog.parentrevs(rev)[0:1]
1168 return repo.changelog.parentrevs(rev)[0:1]
1145 else:
1169 else:
1146 return filter(lambda x: x != nullrev,
1170 return filter(lambda x: x != nullrev,
1147 repo.changelog.parentrevs(rev))
1171 repo.changelog.parentrevs(rev))
1148
1172
1149 if self.startrev == nullrev:
1173 if self.startrev == nullrev:
1150 self.startrev = rev
1174 self.startrev = rev
1151 return True
1175 return True
1152
1176
1153 if rev > self.startrev:
1177 if rev > self.startrev:
1154 # forward: all descendants
1178 # forward: all descendants
1155 if not self.roots:
1179 if not self.roots:
1156 self.roots.add(self.startrev)
1180 self.roots.add(self.startrev)
1157 for parent in realparents(rev):
1181 for parent in realparents(rev):
1158 if parent in self.roots:
1182 if parent in self.roots:
1159 self.roots.add(rev)
1183 self.roots.add(rev)
1160 return True
1184 return True
1161 else:
1185 else:
1162 # backwards: all parents
1186 # backwards: all parents
1163 if not self.roots:
1187 if not self.roots:
1164 self.roots.update(realparents(self.startrev))
1188 self.roots.update(realparents(self.startrev))
1165 if rev in self.roots:
1189 if rev in self.roots:
1166 self.roots.remove(rev)
1190 self.roots.remove(rev)
1167 self.roots.update(realparents(rev))
1191 self.roots.update(realparents(rev))
1168 return True
1192 return True
1169
1193
1170 return False
1194 return False
1171
1195
1172 # it might be worthwhile to do this in the iterator if the rev range
1196 # it might be worthwhile to do this in the iterator if the rev range
1173 # is descending and the prune args are all within that range
1197 # is descending and the prune args are all within that range
1174 for rev in opts.get('prune', ()):
1198 for rev in opts.get('prune', ()):
1175 rev = repo.changelog.rev(repo.lookup(rev))
1199 rev = repo.changelog.rev(repo.lookup(rev))
1176 ff = followfilter()
1200 ff = followfilter()
1177 stop = min(revs[0], revs[-1])
1201 stop = min(revs[0], revs[-1])
1178 for x in xrange(rev, stop - 1, -1):
1202 for x in xrange(rev, stop - 1, -1):
1179 if ff.match(x):
1203 if ff.match(x):
1180 wanted.discard(x)
1204 wanted.discard(x)
1181
1205
1182 def iterate():
1206 def iterate():
1183 if follow and not match.files():
1207 if follow and not match.files():
1184 ff = followfilter(onlyfirst=opts.get('follow_first'))
1208 ff = followfilter(onlyfirst=opts.get('follow_first'))
1185 def want(rev):
1209 def want(rev):
1186 return ff.match(rev) and rev in wanted
1210 return ff.match(rev) and rev in wanted
1187 else:
1211 else:
1188 def want(rev):
1212 def want(rev):
1189 return rev in wanted
1213 return rev in wanted
1190
1214
1191 for i, window in increasing_windows(0, len(revs)):
1215 for i, window in increasing_windows(0, len(revs)):
1192 change = util.cachefunc(repo.changectx)
1216 change = util.cachefunc(repo.changectx)
1193 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1217 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1194 for rev in sorted(nrevs):
1218 for rev in sorted(nrevs):
1195 fns = fncache.get(rev)
1219 fns = fncache.get(rev)
1196 ctx = change(rev)
1220 ctx = change(rev)
1197 if not fns:
1221 if not fns:
1198 def fns_generator():
1222 def fns_generator():
1199 for f in ctx.files():
1223 for f in ctx.files():
1200 if match(f):
1224 if match(f):
1201 yield f
1225 yield f
1202 fns = fns_generator()
1226 fns = fns_generator()
1203 prepare(ctx, fns)
1227 prepare(ctx, fns)
1204 for rev in nrevs:
1228 for rev in nrevs:
1205 yield change(rev)
1229 yield change(rev)
1206 return iterate()
1230 return iterate()
1207
1231
1208 def commit(ui, repo, commitfunc, pats, opts):
1232 def commit(ui, repo, commitfunc, pats, opts):
1209 '''commit the specified files or all outstanding changes'''
1233 '''commit the specified files or all outstanding changes'''
1210 date = opts.get('date')
1234 date = opts.get('date')
1211 if date:
1235 if date:
1212 opts['date'] = util.parsedate(date)
1236 opts['date'] = util.parsedate(date)
1213 message = logmessage(opts)
1237 message = logmessage(opts)
1214
1238
1215 # extract addremove carefully -- this function can be called from a command
1239 # extract addremove carefully -- this function can be called from a command
1216 # that doesn't support addremove
1240 # that doesn't support addremove
1217 if opts.get('addremove'):
1241 if opts.get('addremove'):
1218 addremove(repo, pats, opts)
1242 addremove(repo, pats, opts)
1219
1243
1220 return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
1244 return commitfunc(ui, repo, message, match(repo, pats, opts), opts)
1221
1245
1222 def commiteditor(repo, ctx, subs):
1246 def commiteditor(repo, ctx, subs):
1223 if ctx.description():
1247 if ctx.description():
1224 return ctx.description()
1248 return ctx.description()
1225 return commitforceeditor(repo, ctx, subs)
1249 return commitforceeditor(repo, ctx, subs)
1226
1250
1227 def commitforceeditor(repo, ctx, subs):
1251 def commitforceeditor(repo, ctx, subs):
1228 edittext = []
1252 edittext = []
1229 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1253 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1230 if ctx.description():
1254 if ctx.description():
1231 edittext.append(ctx.description())
1255 edittext.append(ctx.description())
1232 edittext.append("")
1256 edittext.append("")
1233 edittext.append("") # Empty line between message and comments.
1257 edittext.append("") # Empty line between message and comments.
1234 edittext.append(_("HG: Enter commit message."
1258 edittext.append(_("HG: Enter commit message."
1235 " Lines beginning with 'HG:' are removed."))
1259 " Lines beginning with 'HG:' are removed."))
1236 edittext.append(_("HG: Leave message empty to abort commit."))
1260 edittext.append(_("HG: Leave message empty to abort commit."))
1237 edittext.append("HG: --")
1261 edittext.append("HG: --")
1238 edittext.append(_("HG: user: %s") % ctx.user())
1262 edittext.append(_("HG: user: %s") % ctx.user())
1239 if ctx.p2():
1263 if ctx.p2():
1240 edittext.append(_("HG: branch merge"))
1264 edittext.append(_("HG: branch merge"))
1241 if ctx.branch():
1265 if ctx.branch():
1242 edittext.append(_("HG: branch '%s'")
1266 edittext.append(_("HG: branch '%s'")
1243 % encoding.tolocal(ctx.branch()))
1267 % encoding.tolocal(ctx.branch()))
1244 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1268 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1245 edittext.extend([_("HG: added %s") % f for f in added])
1269 edittext.extend([_("HG: added %s") % f for f in added])
1246 edittext.extend([_("HG: changed %s") % f for f in modified])
1270 edittext.extend([_("HG: changed %s") % f for f in modified])
1247 edittext.extend([_("HG: removed %s") % f for f in removed])
1271 edittext.extend([_("HG: removed %s") % f for f in removed])
1248 if not added and not modified and not removed:
1272 if not added and not modified and not removed:
1249 edittext.append(_("HG: no files changed"))
1273 edittext.append(_("HG: no files changed"))
1250 edittext.append("")
1274 edittext.append("")
1251 # run editor in the repository root
1275 # run editor in the repository root
1252 olddir = os.getcwd()
1276 olddir = os.getcwd()
1253 os.chdir(repo.root)
1277 os.chdir(repo.root)
1254 text = repo.ui.edit("\n".join(edittext), ctx.user())
1278 text = repo.ui.edit("\n".join(edittext), ctx.user())
1255 text = re.sub("(?m)^HG:.*\n", "", text)
1279 text = re.sub("(?m)^HG:.*\n", "", text)
1256 os.chdir(olddir)
1280 os.chdir(olddir)
1257
1281
1258 if not text.strip():
1282 if not text.strip():
1259 raise util.Abort(_("empty commit message"))
1283 raise util.Abort(_("empty commit message"))
1260
1284
1261 return text
1285 return text
@@ -1,3934 +1,3920 b''
1 # commands.py - command processing for mercurial
1 # commands.py - command processing for mercurial
2 #
2 #
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from node import hex, nullid, nullrev, short
8 from node import hex, nullid, nullrev, short
9 from lock import release
9 from lock import release
10 from i18n import _, gettext
10 from i18n import _, gettext
11 import os, re, sys, difflib, time, tempfile
11 import os, re, sys, difflib, time, tempfile
12 import hg, util, revlog, bundlerepo, extensions, copies, error
12 import hg, util, revlog, bundlerepo, extensions, copies, error
13 import patch, help, mdiff, url, encoding, templatekw
13 import patch, help, mdiff, url, encoding, templatekw
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 import merge as mergemod
15 import merge as mergemod
16 import minirst
16 import minirst
17
17
18 # Commands start here, listed alphabetically
18 # Commands start here, listed alphabetically
19
19
20 def add(ui, repo, *pats, **opts):
20 def add(ui, repo, *pats, **opts):
21 """add the specified files on the next commit
21 """add the specified files on the next commit
22
22
23 Schedule files to be version controlled and added to the
23 Schedule files to be version controlled and added to the
24 repository.
24 repository.
25
25
26 The files will be added to the repository at the next commit. To
26 The files will be added to the repository at the next commit. To
27 undo an add before that, see hg forget.
27 undo an add before that, see hg forget.
28
28
29 If no names are given, add all files to the repository.
29 If no names are given, add all files to the repository.
30
30
31 .. container:: verbose
31 .. container:: verbose
32
32
33 An example showing how new (unknown) files are added
33 An example showing how new (unknown) files are added
34 automatically by :hg:`add`::
34 automatically by :hg:`add`::
35
35
36 $ ls
36 $ ls
37 foo.c
37 foo.c
38 $ hg status
38 $ hg status
39 ? foo.c
39 ? foo.c
40 $ hg add
40 $ hg add
41 adding foo.c
41 adding foo.c
42 $ hg status
42 $ hg status
43 A foo.c
43 A foo.c
44 """
44 """
45
45
46 bad = []
46 bad = []
47 names = []
47 names = []
48 m = cmdutil.match(repo, pats, opts)
48 m = cmdutil.match(repo, pats, opts)
49 oldbad = m.bad
49 oldbad = m.bad
50 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
50 m.bad = lambda x, y: bad.append(x) or oldbad(x, y)
51
51
52 for f in repo.walk(m):
52 for f in repo.walk(m):
53 exact = m.exact(f)
53 exact = m.exact(f)
54 if exact or f not in repo.dirstate:
54 if exact or f not in repo.dirstate:
55 names.append(f)
55 names.append(f)
56 if ui.verbose or not exact:
56 if ui.verbose or not exact:
57 ui.status(_('adding %s\n') % m.rel(f))
57 ui.status(_('adding %s\n') % m.rel(f))
58 if not opts.get('dry_run'):
58 if not opts.get('dry_run'):
59 bad += [f for f in repo.add(names) if f in m.files()]
59 bad += [f for f in repo.add(names) if f in m.files()]
60 return bad and 1 or 0
60 return bad and 1 or 0
61
61
62 def addremove(ui, repo, *pats, **opts):
62 def addremove(ui, repo, *pats, **opts):
63 """add all new files, delete all missing files
63 """add all new files, delete all missing files
64
64
65 Add all new files and remove all missing files from the
65 Add all new files and remove all missing files from the
66 repository.
66 repository.
67
67
68 New files are ignored if they match any of the patterns in
68 New files are ignored if they match any of the patterns in
69 .hgignore. As with add, these changes take effect at the next
69 .hgignore. As with add, these changes take effect at the next
70 commit.
70 commit.
71
71
72 Use the -s/--similarity option to detect renamed files. With a
72 Use the -s/--similarity option to detect renamed files. With a
73 parameter greater than 0, this compares every removed file with
73 parameter greater than 0, this compares every removed file with
74 every added file and records those similar enough as renames. This
74 every added file and records those similar enough as renames. This
75 option takes a percentage between 0 (disabled) and 100 (files must
75 option takes a percentage between 0 (disabled) and 100 (files must
76 be identical) as its parameter. Detecting renamed files this way
76 be identical) as its parameter. Detecting renamed files this way
77 can be expensive.
77 can be expensive.
78 """
78 """
79 try:
79 try:
80 sim = float(opts.get('similarity') or 0)
80 sim = float(opts.get('similarity') or 0)
81 except ValueError:
81 except ValueError:
82 raise util.Abort(_('similarity must be a number'))
82 raise util.Abort(_('similarity must be a number'))
83 if sim < 0 or sim > 100:
83 if sim < 0 or sim > 100:
84 raise util.Abort(_('similarity must be between 0 and 100'))
84 raise util.Abort(_('similarity must be between 0 and 100'))
85 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
85 return cmdutil.addremove(repo, pats, opts, similarity=sim / 100.0)
86
86
87 def annotate(ui, repo, *pats, **opts):
87 def annotate(ui, repo, *pats, **opts):
88 """show changeset information by line for each file
88 """show changeset information by line for each file
89
89
90 List changes in files, showing the revision id responsible for
90 List changes in files, showing the revision id responsible for
91 each line
91 each line
92
92
93 This command is useful for discovering when a change was made and
93 This command is useful for discovering when a change was made and
94 by whom.
94 by whom.
95
95
96 Without the -a/--text option, annotate will avoid processing files
96 Without the -a/--text option, annotate will avoid processing files
97 it detects as binary. With -a, annotate will annotate the file
97 it detects as binary. With -a, annotate will annotate the file
98 anyway, although the results will probably be neither useful
98 anyway, although the results will probably be neither useful
99 nor desirable.
99 nor desirable.
100 """
100 """
101 if opts.get('follow'):
101 if opts.get('follow'):
102 # --follow is deprecated and now just an alias for -f/--file
102 # --follow is deprecated and now just an alias for -f/--file
103 # to mimic the behavior of Mercurial before version 1.5
103 # to mimic the behavior of Mercurial before version 1.5
104 opts['file'] = 1
104 opts['file'] = 1
105
105
106 datefunc = ui.quiet and util.shortdate or util.datestr
106 datefunc = ui.quiet and util.shortdate or util.datestr
107 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
107 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
108
108
109 if not pats:
109 if not pats:
110 raise util.Abort(_('at least one filename or pattern is required'))
110 raise util.Abort(_('at least one filename or pattern is required'))
111
111
112 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
112 opmap = [('user', lambda x: ui.shortuser(x[0].user())),
113 ('number', lambda x: str(x[0].rev())),
113 ('number', lambda x: str(x[0].rev())),
114 ('changeset', lambda x: short(x[0].node())),
114 ('changeset', lambda x: short(x[0].node())),
115 ('date', getdate),
115 ('date', getdate),
116 ('file', lambda x: x[0].path()),
116 ('file', lambda x: x[0].path()),
117 ]
117 ]
118
118
119 if (not opts.get('user') and not opts.get('changeset')
119 if (not opts.get('user') and not opts.get('changeset')
120 and not opts.get('date') and not opts.get('file')):
120 and not opts.get('date') and not opts.get('file')):
121 opts['number'] = 1
121 opts['number'] = 1
122
122
123 linenumber = opts.get('line_number') is not None
123 linenumber = opts.get('line_number') is not None
124 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
124 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
125 raise util.Abort(_('at least one of -n/-c is required for -l'))
125 raise util.Abort(_('at least one of -n/-c is required for -l'))
126
126
127 funcmap = [func for op, func in opmap if opts.get(op)]
127 funcmap = [func for op, func in opmap if opts.get(op)]
128 if linenumber:
128 if linenumber:
129 lastfunc = funcmap[-1]
129 lastfunc = funcmap[-1]
130 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
130 funcmap[-1] = lambda x: "%s:%s" % (lastfunc(x), x[1])
131
131
132 ctx = repo[opts.get('rev')]
132 ctx = repo[opts.get('rev')]
133 m = cmdutil.match(repo, pats, opts)
133 m = cmdutil.match(repo, pats, opts)
134 follow = not opts.get('no_follow')
134 follow = not opts.get('no_follow')
135 for abs in ctx.walk(m):
135 for abs in ctx.walk(m):
136 fctx = ctx[abs]
136 fctx = ctx[abs]
137 if not opts.get('text') and util.binary(fctx.data()):
137 if not opts.get('text') and util.binary(fctx.data()):
138 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
138 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
139 continue
139 continue
140
140
141 lines = fctx.annotate(follow=follow, linenumber=linenumber)
141 lines = fctx.annotate(follow=follow, linenumber=linenumber)
142 pieces = []
142 pieces = []
143
143
144 for f in funcmap:
144 for f in funcmap:
145 l = [f(n) for n, dummy in lines]
145 l = [f(n) for n, dummy in lines]
146 if l:
146 if l:
147 ml = max(map(len, l))
147 ml = max(map(len, l))
148 pieces.append(["%*s" % (ml, x) for x in l])
148 pieces.append(["%*s" % (ml, x) for x in l])
149
149
150 if pieces:
150 if pieces:
151 for p, l in zip(zip(*pieces), lines):
151 for p, l in zip(zip(*pieces), lines):
152 ui.write("%s: %s" % (" ".join(p), l[1]))
152 ui.write("%s: %s" % (" ".join(p), l[1]))
153
153
154 def archive(ui, repo, dest, **opts):
154 def archive(ui, repo, dest, **opts):
155 '''create an unversioned archive of a repository revision
155 '''create an unversioned archive of a repository revision
156
156
157 By default, the revision used is the parent of the working
157 By default, the revision used is the parent of the working
158 directory; use -r/--rev to specify a different revision.
158 directory; use -r/--rev to specify a different revision.
159
159
160 The archive type is automatically detected based on file
160 The archive type is automatically detected based on file
161 extension (or override using -t/--type).
161 extension (or override using -t/--type).
162
162
163 Valid types are:
163 Valid types are:
164
164
165 :``files``: a directory full of files (default)
165 :``files``: a directory full of files (default)
166 :``tar``: tar archive, uncompressed
166 :``tar``: tar archive, uncompressed
167 :``tbz2``: tar archive, compressed using bzip2
167 :``tbz2``: tar archive, compressed using bzip2
168 :``tgz``: tar archive, compressed using gzip
168 :``tgz``: tar archive, compressed using gzip
169 :``uzip``: zip archive, uncompressed
169 :``uzip``: zip archive, uncompressed
170 :``zip``: zip archive, compressed using deflate
170 :``zip``: zip archive, compressed using deflate
171
171
172 The exact name of the destination archive or directory is given
172 The exact name of the destination archive or directory is given
173 using a format string; see :hg:`help export` for details.
173 using a format string; see :hg:`help export` for details.
174
174
175 Each member added to an archive file has a directory prefix
175 Each member added to an archive file has a directory prefix
176 prepended. Use -p/--prefix to specify a format string for the
176 prepended. Use -p/--prefix to specify a format string for the
177 prefix. The default is the basename of the archive, with suffixes
177 prefix. The default is the basename of the archive, with suffixes
178 removed.
178 removed.
179 '''
179 '''
180
180
181 ctx = repo[opts.get('rev')]
181 ctx = repo[opts.get('rev')]
182 if not ctx:
182 if not ctx:
183 raise util.Abort(_('no working directory: please specify a revision'))
183 raise util.Abort(_('no working directory: please specify a revision'))
184 node = ctx.node()
184 node = ctx.node()
185 dest = cmdutil.make_filename(repo, dest, node)
185 dest = cmdutil.make_filename(repo, dest, node)
186 if os.path.realpath(dest) == repo.root:
186 if os.path.realpath(dest) == repo.root:
187 raise util.Abort(_('repository root cannot be destination'))
187 raise util.Abort(_('repository root cannot be destination'))
188
188
189 def guess_type():
189 def guess_type():
190 exttypes = {
190 exttypes = {
191 'tar': ['.tar'],
191 'tar': ['.tar'],
192 'tbz2': ['.tbz2', '.tar.bz2'],
192 'tbz2': ['.tbz2', '.tar.bz2'],
193 'tgz': ['.tgz', '.tar.gz'],
193 'tgz': ['.tgz', '.tar.gz'],
194 'zip': ['.zip'],
194 'zip': ['.zip'],
195 }
195 }
196
196
197 for type, extensions in exttypes.items():
197 for type, extensions in exttypes.items():
198 if util.any(dest.endswith(ext) for ext in extensions):
198 if util.any(dest.endswith(ext) for ext in extensions):
199 return type
199 return type
200 return None
200 return None
201
201
202 kind = opts.get('type') or guess_type() or 'files'
202 kind = opts.get('type') or guess_type() or 'files'
203 prefix = opts.get('prefix')
203 prefix = opts.get('prefix')
204
204
205 if dest == '-':
205 if dest == '-':
206 if kind == 'files':
206 if kind == 'files':
207 raise util.Abort(_('cannot archive plain files to stdout'))
207 raise util.Abort(_('cannot archive plain files to stdout'))
208 dest = sys.stdout
208 dest = sys.stdout
209 if not prefix:
209 if not prefix:
210 prefix = os.path.basename(repo.root) + '-%h'
210 prefix = os.path.basename(repo.root) + '-%h'
211
211
212 prefix = cmdutil.make_filename(repo, prefix, node)
212 prefix = cmdutil.make_filename(repo, prefix, node)
213 matchfn = cmdutil.match(repo, [], opts)
213 matchfn = cmdutil.match(repo, [], opts)
214 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
214 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
215 matchfn, prefix)
215 matchfn, prefix)
216
216
217 def backout(ui, repo, node=None, rev=None, **opts):
217 def backout(ui, repo, node=None, rev=None, **opts):
218 '''reverse effect of earlier changeset
218 '''reverse effect of earlier changeset
219
219
220 Commit the backed out changes as a new changeset. The new
220 Commit the backed out changes as a new changeset. The new
221 changeset is a child of the backed out changeset.
221 changeset is a child of the backed out changeset.
222
222
223 If you backout a changeset other than the tip, a new head is
223 If you backout a changeset other than the tip, a new head is
224 created. This head will be the new tip and you should merge this
224 created. This head will be the new tip and you should merge this
225 backout changeset with another head.
225 backout changeset with another head.
226
226
227 The --merge option remembers the parent of the working directory
227 The --merge option remembers the parent of the working directory
228 before starting the backout, then merges the new head with that
228 before starting the backout, then merges the new head with that
229 changeset afterwards. This saves you from doing the merge by hand.
229 changeset afterwards. This saves you from doing the merge by hand.
230 The result of this merge is not committed, as with a normal merge.
230 The result of this merge is not committed, as with a normal merge.
231
231
232 See :hg:`help dates` for a list of formats valid for -d/--date.
232 See :hg:`help dates` for a list of formats valid for -d/--date.
233 '''
233 '''
234 if rev and node:
234 if rev and node:
235 raise util.Abort(_("please specify just one revision"))
235 raise util.Abort(_("please specify just one revision"))
236
236
237 if not rev:
237 if not rev:
238 rev = node
238 rev = node
239
239
240 if not rev:
240 if not rev:
241 raise util.Abort(_("please specify a revision to backout"))
241 raise util.Abort(_("please specify a revision to backout"))
242
242
243 date = opts.get('date')
243 date = opts.get('date')
244 if date:
244 if date:
245 opts['date'] = util.parsedate(date)
245 opts['date'] = util.parsedate(date)
246
246
247 cmdutil.bail_if_changed(repo)
247 cmdutil.bail_if_changed(repo)
248 node = repo.lookup(rev)
248 node = repo.lookup(rev)
249
249
250 op1, op2 = repo.dirstate.parents()
250 op1, op2 = repo.dirstate.parents()
251 a = repo.changelog.ancestor(op1, node)
251 a = repo.changelog.ancestor(op1, node)
252 if a != node:
252 if a != node:
253 raise util.Abort(_('cannot backout change on a different branch'))
253 raise util.Abort(_('cannot backout change on a different branch'))
254
254
255 p1, p2 = repo.changelog.parents(node)
255 p1, p2 = repo.changelog.parents(node)
256 if p1 == nullid:
256 if p1 == nullid:
257 raise util.Abort(_('cannot backout a change with no parents'))
257 raise util.Abort(_('cannot backout a change with no parents'))
258 if p2 != nullid:
258 if p2 != nullid:
259 if not opts.get('parent'):
259 if not opts.get('parent'):
260 raise util.Abort(_('cannot backout a merge changeset without '
260 raise util.Abort(_('cannot backout a merge changeset without '
261 '--parent'))
261 '--parent'))
262 p = repo.lookup(opts['parent'])
262 p = repo.lookup(opts['parent'])
263 if p not in (p1, p2):
263 if p not in (p1, p2):
264 raise util.Abort(_('%s is not a parent of %s') %
264 raise util.Abort(_('%s is not a parent of %s') %
265 (short(p), short(node)))
265 (short(p), short(node)))
266 parent = p
266 parent = p
267 else:
267 else:
268 if opts.get('parent'):
268 if opts.get('parent'):
269 raise util.Abort(_('cannot use --parent on non-merge changeset'))
269 raise util.Abort(_('cannot use --parent on non-merge changeset'))
270 parent = p1
270 parent = p1
271
271
272 # the backout should appear on the same branch
272 # the backout should appear on the same branch
273 branch = repo.dirstate.branch()
273 branch = repo.dirstate.branch()
274 hg.clean(repo, node, show_stats=False)
274 hg.clean(repo, node, show_stats=False)
275 repo.dirstate.setbranch(branch)
275 repo.dirstate.setbranch(branch)
276 revert_opts = opts.copy()
276 revert_opts = opts.copy()
277 revert_opts['date'] = None
277 revert_opts['date'] = None
278 revert_opts['all'] = True
278 revert_opts['all'] = True
279 revert_opts['rev'] = hex(parent)
279 revert_opts['rev'] = hex(parent)
280 revert_opts['no_backup'] = None
280 revert_opts['no_backup'] = None
281 revert(ui, repo, **revert_opts)
281 revert(ui, repo, **revert_opts)
282 commit_opts = opts.copy()
282 commit_opts = opts.copy()
283 commit_opts['addremove'] = False
283 commit_opts['addremove'] = False
284 if not commit_opts['message'] and not commit_opts['logfile']:
284 if not commit_opts['message'] and not commit_opts['logfile']:
285 # we don't translate commit messages
285 # we don't translate commit messages
286 commit_opts['message'] = "Backed out changeset %s" % short(node)
286 commit_opts['message'] = "Backed out changeset %s" % short(node)
287 commit_opts['force_editor'] = True
287 commit_opts['force_editor'] = True
288 commit(ui, repo, **commit_opts)
288 commit(ui, repo, **commit_opts)
289 def nice(node):
289 def nice(node):
290 return '%d:%s' % (repo.changelog.rev(node), short(node))
290 return '%d:%s' % (repo.changelog.rev(node), short(node))
291 ui.status(_('changeset %s backs out changeset %s\n') %
291 ui.status(_('changeset %s backs out changeset %s\n') %
292 (nice(repo.changelog.tip()), nice(node)))
292 (nice(repo.changelog.tip()), nice(node)))
293 if op1 != node:
293 if op1 != node:
294 hg.clean(repo, op1, show_stats=False)
294 hg.clean(repo, op1, show_stats=False)
295 if opts.get('merge'):
295 if opts.get('merge'):
296 ui.status(_('merging with changeset %s\n')
296 ui.status(_('merging with changeset %s\n')
297 % nice(repo.changelog.tip()))
297 % nice(repo.changelog.tip()))
298 hg.merge(repo, hex(repo.changelog.tip()))
298 hg.merge(repo, hex(repo.changelog.tip()))
299 else:
299 else:
300 ui.status(_('the backout changeset is a new head - '
300 ui.status(_('the backout changeset is a new head - '
301 'do not forget to merge\n'))
301 'do not forget to merge\n'))
302 ui.status(_('(use "backout --merge" '
302 ui.status(_('(use "backout --merge" '
303 'if you want to auto-merge)\n'))
303 'if you want to auto-merge)\n'))
304
304
305 def bisect(ui, repo, rev=None, extra=None, command=None,
305 def bisect(ui, repo, rev=None, extra=None, command=None,
306 reset=None, good=None, bad=None, skip=None, noupdate=None):
306 reset=None, good=None, bad=None, skip=None, noupdate=None):
307 """subdivision search of changesets
307 """subdivision search of changesets
308
308
309 This command helps to find changesets which introduce problems. To
309 This command helps to find changesets which introduce problems. To
310 use, mark the earliest changeset you know exhibits the problem as
310 use, mark the earliest changeset you know exhibits the problem as
311 bad, then mark the latest changeset which is free from the problem
311 bad, then mark the latest changeset which is free from the problem
312 as good. Bisect will update your working directory to a revision
312 as good. Bisect will update your working directory to a revision
313 for testing (unless the -U/--noupdate option is specified). Once
313 for testing (unless the -U/--noupdate option is specified). Once
314 you have performed tests, mark the working directory as good or
314 you have performed tests, mark the working directory as good or
315 bad, and bisect will either update to another candidate changeset
315 bad, and bisect will either update to another candidate changeset
316 or announce that it has found the bad revision.
316 or announce that it has found the bad revision.
317
317
318 As a shortcut, you can also use the revision argument to mark a
318 As a shortcut, you can also use the revision argument to mark a
319 revision as good or bad without checking it out first.
319 revision as good or bad without checking it out first.
320
320
321 If you supply a command, it will be used for automatic bisection.
321 If you supply a command, it will be used for automatic bisection.
322 Its exit status will be used to mark revisions as good or bad:
322 Its exit status will be used to mark revisions as good or bad:
323 status 0 means good, 125 means to skip the revision, 127
323 status 0 means good, 125 means to skip the revision, 127
324 (command not found) will abort the bisection, and any other
324 (command not found) will abort the bisection, and any other
325 non-zero exit status means the revision is bad.
325 non-zero exit status means the revision is bad.
326 """
326 """
327 def print_result(nodes, good):
327 def print_result(nodes, good):
328 displayer = cmdutil.show_changeset(ui, repo, {})
328 displayer = cmdutil.show_changeset(ui, repo, {})
329 if len(nodes) == 1:
329 if len(nodes) == 1:
330 # narrowed it down to a single revision
330 # narrowed it down to a single revision
331 if good:
331 if good:
332 ui.write(_("The first good revision is:\n"))
332 ui.write(_("The first good revision is:\n"))
333 else:
333 else:
334 ui.write(_("The first bad revision is:\n"))
334 ui.write(_("The first bad revision is:\n"))
335 displayer.show(repo[nodes[0]])
335 displayer.show(repo[nodes[0]])
336 else:
336 else:
337 # multiple possible revisions
337 # multiple possible revisions
338 if good:
338 if good:
339 ui.write(_("Due to skipped revisions, the first "
339 ui.write(_("Due to skipped revisions, the first "
340 "good revision could be any of:\n"))
340 "good revision could be any of:\n"))
341 else:
341 else:
342 ui.write(_("Due to skipped revisions, the first "
342 ui.write(_("Due to skipped revisions, the first "
343 "bad revision could be any of:\n"))
343 "bad revision could be any of:\n"))
344 for n in nodes:
344 for n in nodes:
345 displayer.show(repo[n])
345 displayer.show(repo[n])
346 displayer.close()
346 displayer.close()
347
347
348 def check_state(state, interactive=True):
348 def check_state(state, interactive=True):
349 if not state['good'] or not state['bad']:
349 if not state['good'] or not state['bad']:
350 if (good or bad or skip or reset) and interactive:
350 if (good or bad or skip or reset) and interactive:
351 return
351 return
352 if not state['good']:
352 if not state['good']:
353 raise util.Abort(_('cannot bisect (no known good revisions)'))
353 raise util.Abort(_('cannot bisect (no known good revisions)'))
354 else:
354 else:
355 raise util.Abort(_('cannot bisect (no known bad revisions)'))
355 raise util.Abort(_('cannot bisect (no known bad revisions)'))
356 return True
356 return True
357
357
358 # backward compatibility
358 # backward compatibility
359 if rev in "good bad reset init".split():
359 if rev in "good bad reset init".split():
360 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
360 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
361 cmd, rev, extra = rev, extra, None
361 cmd, rev, extra = rev, extra, None
362 if cmd == "good":
362 if cmd == "good":
363 good = True
363 good = True
364 elif cmd == "bad":
364 elif cmd == "bad":
365 bad = True
365 bad = True
366 else:
366 else:
367 reset = True
367 reset = True
368 elif extra or good + bad + skip + reset + bool(command) > 1:
368 elif extra or good + bad + skip + reset + bool(command) > 1:
369 raise util.Abort(_('incompatible arguments'))
369 raise util.Abort(_('incompatible arguments'))
370
370
371 if reset:
371 if reset:
372 p = repo.join("bisect.state")
372 p = repo.join("bisect.state")
373 if os.path.exists(p):
373 if os.path.exists(p):
374 os.unlink(p)
374 os.unlink(p)
375 return
375 return
376
376
377 state = hbisect.load_state(repo)
377 state = hbisect.load_state(repo)
378
378
379 if command:
379 if command:
380 changesets = 1
380 changesets = 1
381 try:
381 try:
382 while changesets:
382 while changesets:
383 # update state
383 # update state
384 status = util.system(command)
384 status = util.system(command)
385 if status == 125:
385 if status == 125:
386 transition = "skip"
386 transition = "skip"
387 elif status == 0:
387 elif status == 0:
388 transition = "good"
388 transition = "good"
389 # status < 0 means process was killed
389 # status < 0 means process was killed
390 elif status == 127:
390 elif status == 127:
391 raise util.Abort(_("failed to execute %s") % command)
391 raise util.Abort(_("failed to execute %s") % command)
392 elif status < 0:
392 elif status < 0:
393 raise util.Abort(_("%s killed") % command)
393 raise util.Abort(_("%s killed") % command)
394 else:
394 else:
395 transition = "bad"
395 transition = "bad"
396 ctx = repo[rev or '.']
396 ctx = repo[rev or '.']
397 state[transition].append(ctx.node())
397 state[transition].append(ctx.node())
398 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
398 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
399 check_state(state, interactive=False)
399 check_state(state, interactive=False)
400 # bisect
400 # bisect
401 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
401 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
402 # update to next check
402 # update to next check
403 cmdutil.bail_if_changed(repo)
403 cmdutil.bail_if_changed(repo)
404 hg.clean(repo, nodes[0], show_stats=False)
404 hg.clean(repo, nodes[0], show_stats=False)
405 finally:
405 finally:
406 hbisect.save_state(repo, state)
406 hbisect.save_state(repo, state)
407 return print_result(nodes, good)
407 return print_result(nodes, good)
408
408
409 # update state
409 # update state
410 node = repo.lookup(rev or '.')
410 node = repo.lookup(rev or '.')
411 if good or bad or skip:
411 if good or bad or skip:
412 if good:
412 if good:
413 state['good'].append(node)
413 state['good'].append(node)
414 elif bad:
414 elif bad:
415 state['bad'].append(node)
415 state['bad'].append(node)
416 elif skip:
416 elif skip:
417 state['skip'].append(node)
417 state['skip'].append(node)
418 hbisect.save_state(repo, state)
418 hbisect.save_state(repo, state)
419
419
420 if not check_state(state):
420 if not check_state(state):
421 return
421 return
422
422
423 # actually bisect
423 # actually bisect
424 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
424 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
425 if changesets == 0:
425 if changesets == 0:
426 print_result(nodes, good)
426 print_result(nodes, good)
427 else:
427 else:
428 assert len(nodes) == 1 # only a single node can be tested next
428 assert len(nodes) == 1 # only a single node can be tested next
429 node = nodes[0]
429 node = nodes[0]
430 # compute the approximate number of remaining tests
430 # compute the approximate number of remaining tests
431 tests, size = 0, 2
431 tests, size = 0, 2
432 while size <= changesets:
432 while size <= changesets:
433 tests, size = tests + 1, size * 2
433 tests, size = tests + 1, size * 2
434 rev = repo.changelog.rev(node)
434 rev = repo.changelog.rev(node)
435 ui.write(_("Testing changeset %d:%s "
435 ui.write(_("Testing changeset %d:%s "
436 "(%d changesets remaining, ~%d tests)\n")
436 "(%d changesets remaining, ~%d tests)\n")
437 % (rev, short(node), changesets, tests))
437 % (rev, short(node), changesets, tests))
438 if not noupdate:
438 if not noupdate:
439 cmdutil.bail_if_changed(repo)
439 cmdutil.bail_if_changed(repo)
440 return hg.clean(repo, node)
440 return hg.clean(repo, node)
441
441
442 def branch(ui, repo, label=None, **opts):
442 def branch(ui, repo, label=None, **opts):
443 """set or show the current branch name
443 """set or show the current branch name
444
444
445 With no argument, show the current branch name. With one argument,
445 With no argument, show the current branch name. With one argument,
446 set the working directory branch name (the branch will not exist
446 set the working directory branch name (the branch will not exist
447 in the repository until the next commit). Standard practice
447 in the repository until the next commit). Standard practice
448 recommends that primary development take place on the 'default'
448 recommends that primary development take place on the 'default'
449 branch.
449 branch.
450
450
451 Unless -f/--force is specified, branch will not let you set a
451 Unless -f/--force is specified, branch will not let you set a
452 branch name that already exists, even if it's inactive.
452 branch name that already exists, even if it's inactive.
453
453
454 Use -C/--clean to reset the working directory branch to that of
454 Use -C/--clean to reset the working directory branch to that of
455 the parent of the working directory, negating a previous branch
455 the parent of the working directory, negating a previous branch
456 change.
456 change.
457
457
458 Use the command :hg:`update` to switch to an existing branch. Use
458 Use the command :hg:`update` to switch to an existing branch. Use
459 :hg:`commit --close-branch` to mark this branch as closed.
459 :hg:`commit --close-branch` to mark this branch as closed.
460 """
460 """
461
461
462 if opts.get('clean'):
462 if opts.get('clean'):
463 label = repo[None].parents()[0].branch()
463 label = repo[None].parents()[0].branch()
464 repo.dirstate.setbranch(label)
464 repo.dirstate.setbranch(label)
465 ui.status(_('reset working directory to branch %s\n') % label)
465 ui.status(_('reset working directory to branch %s\n') % label)
466 elif label:
466 elif label:
467 utflabel = encoding.fromlocal(label)
467 utflabel = encoding.fromlocal(label)
468 if not opts.get('force') and utflabel in repo.branchtags():
468 if not opts.get('force') and utflabel in repo.branchtags():
469 if label not in [p.branch() for p in repo.parents()]:
469 if label not in [p.branch() for p in repo.parents()]:
470 raise util.Abort(_('a branch of the same name already exists'
470 raise util.Abort(_('a branch of the same name already exists'
471 " (use 'hg update' to switch to it)"))
471 " (use 'hg update' to switch to it)"))
472 repo.dirstate.setbranch(utflabel)
472 repo.dirstate.setbranch(utflabel)
473 ui.status(_('marked working directory as branch %s\n') % label)
473 ui.status(_('marked working directory as branch %s\n') % label)
474 else:
474 else:
475 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
475 ui.write("%s\n" % encoding.tolocal(repo.dirstate.branch()))
476
476
477 def branches(ui, repo, active=False, closed=False):
477 def branches(ui, repo, active=False, closed=False):
478 """list repository named branches
478 """list repository named branches
479
479
480 List the repository's named branches, indicating which ones are
480 List the repository's named branches, indicating which ones are
481 inactive. If -c/--closed is specified, also list branches which have
481 inactive. If -c/--closed is specified, also list branches which have
482 been marked closed (see hg commit --close-branch).
482 been marked closed (see hg commit --close-branch).
483
483
484 If -a/--active is specified, only show active branches. A branch
484 If -a/--active is specified, only show active branches. A branch
485 is considered active if it contains repository heads.
485 is considered active if it contains repository heads.
486
486
487 Use the command :hg:`update` to switch to an existing branch.
487 Use the command :hg:`update` to switch to an existing branch.
488 """
488 """
489
489
490 hexfunc = ui.debugflag and hex or short
490 hexfunc = ui.debugflag and hex or short
491 activebranches = [repo[n].branch() for n in repo.heads()]
491 activebranches = [repo[n].branch() for n in repo.heads()]
492 def testactive(tag, node):
492 def testactive(tag, node):
493 realhead = tag in activebranches
493 realhead = tag in activebranches
494 open = node in repo.branchheads(tag, closed=False)
494 open = node in repo.branchheads(tag, closed=False)
495 return realhead and open
495 return realhead and open
496 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
496 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
497 for tag, node in repo.branchtags().items()],
497 for tag, node in repo.branchtags().items()],
498 reverse=True)
498 reverse=True)
499
499
500 for isactive, node, tag in branches:
500 for isactive, node, tag in branches:
501 if (not active) or isactive:
501 if (not active) or isactive:
502 encodedtag = encoding.tolocal(tag)
502 encodedtag = encoding.tolocal(tag)
503 if ui.quiet:
503 if ui.quiet:
504 ui.write("%s\n" % encodedtag)
504 ui.write("%s\n" % encodedtag)
505 else:
505 else:
506 hn = repo.lookup(node)
506 hn = repo.lookup(node)
507 if isactive:
507 if isactive:
508 notice = ''
508 notice = ''
509 elif hn not in repo.branchheads(tag, closed=False):
509 elif hn not in repo.branchheads(tag, closed=False):
510 if not closed:
510 if not closed:
511 continue
511 continue
512 notice = _(' (closed)')
512 notice = _(' (closed)')
513 else:
513 else:
514 notice = _(' (inactive)')
514 notice = _(' (inactive)')
515 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
515 rev = str(node).rjust(31 - encoding.colwidth(encodedtag))
516 data = encodedtag, rev, hexfunc(hn), notice
516 data = encodedtag, rev, hexfunc(hn), notice
517 ui.write("%s %s:%s%s\n" % data)
517 ui.write("%s %s:%s%s\n" % data)
518
518
519 def bundle(ui, repo, fname, dest=None, **opts):
519 def bundle(ui, repo, fname, dest=None, **opts):
520 """create a changegroup file
520 """create a changegroup file
521
521
522 Generate a compressed changegroup file collecting changesets not
522 Generate a compressed changegroup file collecting changesets not
523 known to be in another repository.
523 known to be in another repository.
524
524
525 If you omit the destination repository, then hg assumes the
525 If you omit the destination repository, then hg assumes the
526 destination will have all the nodes you specify with --base
526 destination will have all the nodes you specify with --base
527 parameters. To create a bundle containing all changesets, use
527 parameters. To create a bundle containing all changesets, use
528 -a/--all (or --base null).
528 -a/--all (or --base null).
529
529
530 You can change compression method with the -t/--type option.
530 You can change compression method with the -t/--type option.
531 The available compression methods are: none, bzip2, and
531 The available compression methods are: none, bzip2, and
532 gzip (by default, bundles are compressed using bzip2).
532 gzip (by default, bundles are compressed using bzip2).
533
533
534 The bundle file can then be transferred using conventional means
534 The bundle file can then be transferred using conventional means
535 and applied to another repository with the unbundle or pull
535 and applied to another repository with the unbundle or pull
536 command. This is useful when direct push and pull are not
536 command. This is useful when direct push and pull are not
537 available or when exporting an entire repository is undesirable.
537 available or when exporting an entire repository is undesirable.
538
538
539 Applying bundles preserves all changeset contents including
539 Applying bundles preserves all changeset contents including
540 permissions, copy/rename information, and revision history.
540 permissions, copy/rename information, and revision history.
541 """
541 """
542 revs = opts.get('rev') or None
542 revs = opts.get('rev') or None
543 if revs:
543 if revs:
544 revs = [repo.lookup(rev) for rev in revs]
544 revs = [repo.lookup(rev) for rev in revs]
545 if opts.get('all'):
545 if opts.get('all'):
546 base = ['null']
546 base = ['null']
547 else:
547 else:
548 base = opts.get('base')
548 base = opts.get('base')
549 if base:
549 if base:
550 if dest:
550 if dest:
551 raise util.Abort(_("--base is incompatible with specifying "
551 raise util.Abort(_("--base is incompatible with specifying "
552 "a destination"))
552 "a destination"))
553 base = [repo.lookup(rev) for rev in base]
553 base = [repo.lookup(rev) for rev in base]
554 # create the right base
554 # create the right base
555 # XXX: nodesbetween / changegroup* should be "fixed" instead
555 # XXX: nodesbetween / changegroup* should be "fixed" instead
556 o = []
556 o = []
557 has = set((nullid,))
557 has = set((nullid,))
558 for n in base:
558 for n in base:
559 has.update(repo.changelog.reachable(n))
559 has.update(repo.changelog.reachable(n))
560 if revs:
560 if revs:
561 visit = list(revs)
561 visit = list(revs)
562 has.difference_update(revs)
562 has.difference_update(revs)
563 else:
563 else:
564 visit = repo.changelog.heads()
564 visit = repo.changelog.heads()
565 seen = {}
565 seen = {}
566 while visit:
566 while visit:
567 n = visit.pop(0)
567 n = visit.pop(0)
568 parents = [p for p in repo.changelog.parents(n) if p not in has]
568 parents = [p for p in repo.changelog.parents(n) if p not in has]
569 if len(parents) == 0:
569 if len(parents) == 0:
570 if n not in has:
570 if n not in has:
571 o.append(n)
571 o.append(n)
572 else:
572 else:
573 for p in parents:
573 for p in parents:
574 if p not in seen:
574 if p not in seen:
575 seen[p] = 1
575 seen[p] = 1
576 visit.append(p)
576 visit.append(p)
577 else:
577 else:
578 dest = ui.expandpath(dest or 'default-push', dest or 'default')
578 dest = ui.expandpath(dest or 'default-push', dest or 'default')
579 dest, branches = hg.parseurl(dest, opts.get('branch'))
579 dest, branches = hg.parseurl(dest, opts.get('branch'))
580 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
580 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
581 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
581 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
582 o = repo.findoutgoing(other, force=opts.get('force'))
582 o = repo.findoutgoing(other, force=opts.get('force'))
583
583
584 if not o:
584 if not o:
585 ui.status(_("no changes found\n"))
585 ui.status(_("no changes found\n"))
586 return
586 return
587
587
588 if revs:
588 if revs:
589 cg = repo.changegroupsubset(o, revs, 'bundle')
589 cg = repo.changegroupsubset(o, revs, 'bundle')
590 else:
590 else:
591 cg = repo.changegroup(o, 'bundle')
591 cg = repo.changegroup(o, 'bundle')
592
592
593 bundletype = opts.get('type', 'bzip2').lower()
593 bundletype = opts.get('type', 'bzip2').lower()
594 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
594 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
595 bundletype = btypes.get(bundletype)
595 bundletype = btypes.get(bundletype)
596 if bundletype not in changegroup.bundletypes:
596 if bundletype not in changegroup.bundletypes:
597 raise util.Abort(_('unknown bundle type specified with --type'))
597 raise util.Abort(_('unknown bundle type specified with --type'))
598
598
599 changegroup.writebundle(cg, fname, bundletype)
599 changegroup.writebundle(cg, fname, bundletype)
600
600
601 def cat(ui, repo, file1, *pats, **opts):
601 def cat(ui, repo, file1, *pats, **opts):
602 """output the current or given revision of files
602 """output the current or given revision of files
603
603
604 Print the specified files as they were at the given revision. If
604 Print the specified files as they were at the given revision. If
605 no revision is given, the parent of the working directory is used,
605 no revision is given, the parent of the working directory is used,
606 or tip if no revision is checked out.
606 or tip if no revision is checked out.
607
607
608 Output may be to a file, in which case the name of the file is
608 Output may be to a file, in which case the name of the file is
609 given using a format string. The formatting rules are the same as
609 given using a format string. The formatting rules are the same as
610 for the export command, with the following additions:
610 for the export command, with the following additions:
611
611
612 :``%s``: basename of file being printed
612 :``%s``: basename of file being printed
613 :``%d``: dirname of file being printed, or '.' if in repository root
613 :``%d``: dirname of file being printed, or '.' if in repository root
614 :``%p``: root-relative path name of file being printed
614 :``%p``: root-relative path name of file being printed
615 """
615 """
616 ctx = repo[opts.get('rev')]
616 ctx = repo[opts.get('rev')]
617 err = 1
617 err = 1
618 m = cmdutil.match(repo, (file1,) + pats, opts)
618 m = cmdutil.match(repo, (file1,) + pats, opts)
619 for abs in ctx.walk(m):
619 for abs in ctx.walk(m):
620 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
620 fp = cmdutil.make_file(repo, opts.get('output'), ctx.node(), pathname=abs)
621 data = ctx[abs].data()
621 data = ctx[abs].data()
622 if opts.get('decode'):
622 if opts.get('decode'):
623 data = repo.wwritedata(abs, data)
623 data = repo.wwritedata(abs, data)
624 fp.write(data)
624 fp.write(data)
625 err = 0
625 err = 0
626 return err
626 return err
627
627
628 def clone(ui, source, dest=None, **opts):
628 def clone(ui, source, dest=None, **opts):
629 """make a copy of an existing repository
629 """make a copy of an existing repository
630
630
631 Create a copy of an existing repository in a new directory.
631 Create a copy of an existing repository in a new directory.
632
632
633 If no destination directory name is specified, it defaults to the
633 If no destination directory name is specified, it defaults to the
634 basename of the source.
634 basename of the source.
635
635
636 The location of the source is added to the new repository's
636 The location of the source is added to the new repository's
637 .hg/hgrc file, as the default to be used for future pulls.
637 .hg/hgrc file, as the default to be used for future pulls.
638
638
639 See :hg:`help urls` for valid source format details.
639 See :hg:`help urls` for valid source format details.
640
640
641 It is possible to specify an ``ssh://`` URL as the destination, but no
641 It is possible to specify an ``ssh://`` URL as the destination, but no
642 .hg/hgrc and working directory will be created on the remote side.
642 .hg/hgrc and working directory will be created on the remote side.
643 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
643 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
644
644
645 A set of changesets (tags, or branch names) to pull may be specified
645 A set of changesets (tags, or branch names) to pull may be specified
646 by listing each changeset (tag, or branch name) with -r/--rev.
646 by listing each changeset (tag, or branch name) with -r/--rev.
647 If -r/--rev is used, the cloned repository will contain only a subset
647 If -r/--rev is used, the cloned repository will contain only a subset
648 of the changesets of the source repository. Only the set of changesets
648 of the changesets of the source repository. Only the set of changesets
649 defined by all -r/--rev options (including all their ancestors)
649 defined by all -r/--rev options (including all their ancestors)
650 will be pulled into the destination repository.
650 will be pulled into the destination repository.
651 No subsequent changesets (including subsequent tags) will be present
651 No subsequent changesets (including subsequent tags) will be present
652 in the destination.
652 in the destination.
653
653
654 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
654 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
655 local source repositories.
655 local source repositories.
656
656
657 For efficiency, hardlinks are used for cloning whenever the source
657 For efficiency, hardlinks are used for cloning whenever the source
658 and destination are on the same filesystem (note this applies only
658 and destination are on the same filesystem (note this applies only
659 to the repository data, not to the working directory). Some
659 to the repository data, not to the working directory). Some
660 filesystems, such as AFS, implement hardlinking incorrectly, but
660 filesystems, such as AFS, implement hardlinking incorrectly, but
661 do not report errors. In these cases, use the --pull option to
661 do not report errors. In these cases, use the --pull option to
662 avoid hardlinking.
662 avoid hardlinking.
663
663
664 In some cases, you can clone repositories and the working directory
664 In some cases, you can clone repositories and the working directory
665 using full hardlinks with ::
665 using full hardlinks with ::
666
666
667 $ cp -al REPO REPOCLONE
667 $ cp -al REPO REPOCLONE
668
668
669 This is the fastest way to clone, but it is not always safe. The
669 This is the fastest way to clone, but it is not always safe. The
670 operation is not atomic (making sure REPO is not modified during
670 operation is not atomic (making sure REPO is not modified during
671 the operation is up to you) and you have to make sure your editor
671 the operation is up to you) and you have to make sure your editor
672 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
672 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
673 this is not compatible with certain extensions that place their
673 this is not compatible with certain extensions that place their
674 metadata under the .hg directory, such as mq.
674 metadata under the .hg directory, such as mq.
675
675
676 Mercurial will update the working directory to the first applicable
676 Mercurial will update the working directory to the first applicable
677 revision from this list:
677 revision from this list:
678
678
679 a) null if -U or the source repository has no changesets
679 a) null if -U or the source repository has no changesets
680 b) if -u . and the source repository is local, the first parent of
680 b) if -u . and the source repository is local, the first parent of
681 the source repository's working directory
681 the source repository's working directory
682 c) the changeset specified with -u (if a branch name, this means the
682 c) the changeset specified with -u (if a branch name, this means the
683 latest head of that branch)
683 latest head of that branch)
684 d) the changeset specified with -r
684 d) the changeset specified with -r
685 e) the tipmost head specified with -b
685 e) the tipmost head specified with -b
686 f) the tipmost head specified with the url#branch source syntax
686 f) the tipmost head specified with the url#branch source syntax
687 g) the tipmost head of the default branch
687 g) the tipmost head of the default branch
688 h) tip
688 h) tip
689 """
689 """
690 if opts.get('noupdate') and opts.get('updaterev'):
690 if opts.get('noupdate') and opts.get('updaterev'):
691 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
691 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
692
692
693 hg.clone(cmdutil.remoteui(ui, opts), source, dest,
693 hg.clone(cmdutil.remoteui(ui, opts), source, dest,
694 pull=opts.get('pull'),
694 pull=opts.get('pull'),
695 stream=opts.get('uncompressed'),
695 stream=opts.get('uncompressed'),
696 rev=opts.get('rev'),
696 rev=opts.get('rev'),
697 update=opts.get('updaterev') or not opts.get('noupdate'),
697 update=opts.get('updaterev') or not opts.get('noupdate'),
698 branch=opts.get('branch'))
698 branch=opts.get('branch'))
699
699
700 def commit(ui, repo, *pats, **opts):
700 def commit(ui, repo, *pats, **opts):
701 """commit the specified files or all outstanding changes
701 """commit the specified files or all outstanding changes
702
702
703 Commit changes to the given files into the repository. Unlike a
703 Commit changes to the given files into the repository. Unlike a
704 centralized RCS, this operation is a local operation. See hg push
704 centralized RCS, this operation is a local operation. See hg push
705 for a way to actively distribute your changes.
705 for a way to actively distribute your changes.
706
706
707 If a list of files is omitted, all changes reported by :hg:`status`
707 If a list of files is omitted, all changes reported by :hg:`status`
708 will be committed.
708 will be committed.
709
709
710 If you are committing the result of a merge, do not provide any
710 If you are committing the result of a merge, do not provide any
711 filenames or -I/-X filters.
711 filenames or -I/-X filters.
712
712
713 If no commit message is specified, the configured editor is
713 If no commit message is specified, the configured editor is
714 started to prompt you for a message.
714 started to prompt you for a message.
715
715
716 See :hg:`help dates` for a list of formats valid for -d/--date.
716 See :hg:`help dates` for a list of formats valid for -d/--date.
717 """
717 """
718 extra = {}
718 extra = {}
719 if opts.get('close_branch'):
719 if opts.get('close_branch'):
720 extra['close'] = 1
720 extra['close'] = 1
721 e = cmdutil.commiteditor
721 e = cmdutil.commiteditor
722 if opts.get('force_editor'):
722 if opts.get('force_editor'):
723 e = cmdutil.commitforceeditor
723 e = cmdutil.commitforceeditor
724
724
725 def commitfunc(ui, repo, message, match, opts):
725 def commitfunc(ui, repo, message, match, opts):
726 return repo.commit(message, opts.get('user'), opts.get('date'), match,
726 return repo.commit(message, opts.get('user'), opts.get('date'), match,
727 editor=e, extra=extra)
727 editor=e, extra=extra)
728
728
729 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
729 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
730 if not node:
730 if not node:
731 ui.status(_("nothing changed\n"))
731 ui.status(_("nothing changed\n"))
732 return
732 return
733 cl = repo.changelog
733 cl = repo.changelog
734 rev = cl.rev(node)
734 rev = cl.rev(node)
735 parents = cl.parentrevs(rev)
735 parents = cl.parentrevs(rev)
736 if rev - 1 in parents:
736 if rev - 1 in parents:
737 # one of the parents was the old tip
737 # one of the parents was the old tip
738 pass
738 pass
739 elif (parents == (nullrev, nullrev) or
739 elif (parents == (nullrev, nullrev) or
740 len(cl.heads(cl.node(parents[0]))) > 1 and
740 len(cl.heads(cl.node(parents[0]))) > 1 and
741 (parents[1] == nullrev or len(cl.heads(cl.node(parents[1]))) > 1)):
741 (parents[1] == nullrev or len(cl.heads(cl.node(parents[1]))) > 1)):
742 ui.status(_('created new head\n'))
742 ui.status(_('created new head\n'))
743
743
744 if ui.debugflag:
744 if ui.debugflag:
745 ui.write(_('committed changeset %d:%s\n') % (rev, hex(node)))
745 ui.write(_('committed changeset %d:%s\n') % (rev, hex(node)))
746 elif ui.verbose:
746 elif ui.verbose:
747 ui.write(_('committed changeset %d:%s\n') % (rev, short(node)))
747 ui.write(_('committed changeset %d:%s\n') % (rev, short(node)))
748
748
749 def copy(ui, repo, *pats, **opts):
749 def copy(ui, repo, *pats, **opts):
750 """mark files as copied for the next commit
750 """mark files as copied for the next commit
751
751
752 Mark dest as having copies of source files. If dest is a
752 Mark dest as having copies of source files. If dest is a
753 directory, copies are put in that directory. If dest is a file,
753 directory, copies are put in that directory. If dest is a file,
754 the source must be a single file.
754 the source must be a single file.
755
755
756 By default, this command copies the contents of files as they
756 By default, this command copies the contents of files as they
757 exist in the working directory. If invoked with -A/--after, the
757 exist in the working directory. If invoked with -A/--after, the
758 operation is recorded, but no copying is performed.
758 operation is recorded, but no copying is performed.
759
759
760 This command takes effect with the next commit. To undo a copy
760 This command takes effect with the next commit. To undo a copy
761 before that, see hg revert.
761 before that, see hg revert.
762 """
762 """
763 wlock = repo.wlock(False)
763 wlock = repo.wlock(False)
764 try:
764 try:
765 return cmdutil.copy(ui, repo, pats, opts)
765 return cmdutil.copy(ui, repo, pats, opts)
766 finally:
766 finally:
767 wlock.release()
767 wlock.release()
768
768
769 def debugancestor(ui, repo, *args):
769 def debugancestor(ui, repo, *args):
770 """find the ancestor revision of two revisions in a given index"""
770 """find the ancestor revision of two revisions in a given index"""
771 if len(args) == 3:
771 if len(args) == 3:
772 index, rev1, rev2 = args
772 index, rev1, rev2 = args
773 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
773 r = revlog.revlog(util.opener(os.getcwd(), audit=False), index)
774 lookup = r.lookup
774 lookup = r.lookup
775 elif len(args) == 2:
775 elif len(args) == 2:
776 if not repo:
776 if not repo:
777 raise util.Abort(_("There is no Mercurial repository here "
777 raise util.Abort(_("There is no Mercurial repository here "
778 "(.hg not found)"))
778 "(.hg not found)"))
779 rev1, rev2 = args
779 rev1, rev2 = args
780 r = repo.changelog
780 r = repo.changelog
781 lookup = repo.lookup
781 lookup = repo.lookup
782 else:
782 else:
783 raise util.Abort(_('either two or three arguments required'))
783 raise util.Abort(_('either two or three arguments required'))
784 a = r.ancestor(lookup(rev1), lookup(rev2))
784 a = r.ancestor(lookup(rev1), lookup(rev2))
785 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
785 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
786
786
787 def debugcommands(ui, cmd='', *args):
787 def debugcommands(ui, cmd='', *args):
788 for cmd, vals in sorted(table.iteritems()):
788 for cmd, vals in sorted(table.iteritems()):
789 cmd = cmd.split('|')[0].strip('^')
789 cmd = cmd.split('|')[0].strip('^')
790 opts = ', '.join([i[1] for i in vals[1]])
790 opts = ', '.join([i[1] for i in vals[1]])
791 ui.write('%s: %s\n' % (cmd, opts))
791 ui.write('%s: %s\n' % (cmd, opts))
792
792
793 def debugcomplete(ui, cmd='', **opts):
793 def debugcomplete(ui, cmd='', **opts):
794 """returns the completion list associated with the given command"""
794 """returns the completion list associated with the given command"""
795
795
796 if opts.get('options'):
796 if opts.get('options'):
797 options = []
797 options = []
798 otables = [globalopts]
798 otables = [globalopts]
799 if cmd:
799 if cmd:
800 aliases, entry = cmdutil.findcmd(cmd, table, False)
800 aliases, entry = cmdutil.findcmd(cmd, table, False)
801 otables.append(entry[1])
801 otables.append(entry[1])
802 for t in otables:
802 for t in otables:
803 for o in t:
803 for o in t:
804 if "(DEPRECATED)" in o[3]:
804 if "(DEPRECATED)" in o[3]:
805 continue
805 continue
806 if o[0]:
806 if o[0]:
807 options.append('-%s' % o[0])
807 options.append('-%s' % o[0])
808 options.append('--%s' % o[1])
808 options.append('--%s' % o[1])
809 ui.write("%s\n" % "\n".join(options))
809 ui.write("%s\n" % "\n".join(options))
810 return
810 return
811
811
812 cmdlist = cmdutil.findpossible(cmd, table)
812 cmdlist = cmdutil.findpossible(cmd, table)
813 if ui.verbose:
813 if ui.verbose:
814 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
814 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
815 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
815 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
816
816
817 def debugfsinfo(ui, path = "."):
817 def debugfsinfo(ui, path = "."):
818 open('.debugfsinfo', 'w').write('')
818 open('.debugfsinfo', 'w').write('')
819 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
819 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
820 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
820 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
821 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
821 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
822 and 'yes' or 'no'))
822 and 'yes' or 'no'))
823 os.unlink('.debugfsinfo')
823 os.unlink('.debugfsinfo')
824
824
825 def debugrebuildstate(ui, repo, rev="tip"):
825 def debugrebuildstate(ui, repo, rev="tip"):
826 """rebuild the dirstate as it would look like for the given revision"""
826 """rebuild the dirstate as it would look like for the given revision"""
827 ctx = repo[rev]
827 ctx = repo[rev]
828 wlock = repo.wlock()
828 wlock = repo.wlock()
829 try:
829 try:
830 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
830 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
831 finally:
831 finally:
832 wlock.release()
832 wlock.release()
833
833
834 def debugcheckstate(ui, repo):
834 def debugcheckstate(ui, repo):
835 """validate the correctness of the current dirstate"""
835 """validate the correctness of the current dirstate"""
836 parent1, parent2 = repo.dirstate.parents()
836 parent1, parent2 = repo.dirstate.parents()
837 m1 = repo[parent1].manifest()
837 m1 = repo[parent1].manifest()
838 m2 = repo[parent2].manifest()
838 m2 = repo[parent2].manifest()
839 errors = 0
839 errors = 0
840 for f in repo.dirstate:
840 for f in repo.dirstate:
841 state = repo.dirstate[f]
841 state = repo.dirstate[f]
842 if state in "nr" and f not in m1:
842 if state in "nr" and f not in m1:
843 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
843 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
844 errors += 1
844 errors += 1
845 if state in "a" and f in m1:
845 if state in "a" and f in m1:
846 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
846 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
847 errors += 1
847 errors += 1
848 if state in "m" and f not in m1 and f not in m2:
848 if state in "m" and f not in m1 and f not in m2:
849 ui.warn(_("%s in state %s, but not in either manifest\n") %
849 ui.warn(_("%s in state %s, but not in either manifest\n") %
850 (f, state))
850 (f, state))
851 errors += 1
851 errors += 1
852 for f in m1:
852 for f in m1:
853 state = repo.dirstate[f]
853 state = repo.dirstate[f]
854 if state not in "nrm":
854 if state not in "nrm":
855 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
855 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
856 errors += 1
856 errors += 1
857 if errors:
857 if errors:
858 error = _(".hg/dirstate inconsistent with current parent's manifest")
858 error = _(".hg/dirstate inconsistent with current parent's manifest")
859 raise util.Abort(error)
859 raise util.Abort(error)
860
860
861 def showconfig(ui, repo, *values, **opts):
861 def showconfig(ui, repo, *values, **opts):
862 """show combined config settings from all hgrc files
862 """show combined config settings from all hgrc files
863
863
864 With no arguments, print names and values of all config items.
864 With no arguments, print names and values of all config items.
865
865
866 With one argument of the form section.name, print just the value
866 With one argument of the form section.name, print just the value
867 of that config item.
867 of that config item.
868
868
869 With multiple arguments, print names and values of all config
869 With multiple arguments, print names and values of all config
870 items with matching section names.
870 items with matching section names.
871
871
872 With --debug, the source (filename and line number) is printed
872 With --debug, the source (filename and line number) is printed
873 for each config item.
873 for each config item.
874 """
874 """
875
875
876 for f in util.rcpath():
876 for f in util.rcpath():
877 ui.debug(_('read config from: %s\n') % f)
877 ui.debug(_('read config from: %s\n') % f)
878 untrusted = bool(opts.get('untrusted'))
878 untrusted = bool(opts.get('untrusted'))
879 if values:
879 if values:
880 if len([v for v in values if '.' in v]) > 1:
880 if len([v for v in values if '.' in v]) > 1:
881 raise util.Abort(_('only one config item permitted'))
881 raise util.Abort(_('only one config item permitted'))
882 for section, name, value in ui.walkconfig(untrusted=untrusted):
882 for section, name, value in ui.walkconfig(untrusted=untrusted):
883 sectname = section + '.' + name
883 sectname = section + '.' + name
884 if values:
884 if values:
885 for v in values:
885 for v in values:
886 if v == section:
886 if v == section:
887 ui.debug('%s: ' %
887 ui.debug('%s: ' %
888 ui.configsource(section, name, untrusted))
888 ui.configsource(section, name, untrusted))
889 ui.write('%s=%s\n' % (sectname, value))
889 ui.write('%s=%s\n' % (sectname, value))
890 elif v == sectname:
890 elif v == sectname:
891 ui.debug('%s: ' %
891 ui.debug('%s: ' %
892 ui.configsource(section, name, untrusted))
892 ui.configsource(section, name, untrusted))
893 ui.write(value, '\n')
893 ui.write(value, '\n')
894 else:
894 else:
895 ui.debug('%s: ' %
895 ui.debug('%s: ' %
896 ui.configsource(section, name, untrusted))
896 ui.configsource(section, name, untrusted))
897 ui.write('%s=%s\n' % (sectname, value))
897 ui.write('%s=%s\n' % (sectname, value))
898
898
899 def debugsetparents(ui, repo, rev1, rev2=None):
899 def debugsetparents(ui, repo, rev1, rev2=None):
900 """manually set the parents of the current working directory
900 """manually set the parents of the current working directory
901
901
902 This is useful for writing repository conversion tools, but should
902 This is useful for writing repository conversion tools, but should
903 be used with care.
903 be used with care.
904 """
904 """
905
905
906 if not rev2:
906 if not rev2:
907 rev2 = hex(nullid)
907 rev2 = hex(nullid)
908
908
909 wlock = repo.wlock()
909 wlock = repo.wlock()
910 try:
910 try:
911 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
911 repo.dirstate.setparents(repo.lookup(rev1), repo.lookup(rev2))
912 finally:
912 finally:
913 wlock.release()
913 wlock.release()
914
914
915 def debugstate(ui, repo, nodates=None):
915 def debugstate(ui, repo, nodates=None):
916 """show the contents of the current dirstate"""
916 """show the contents of the current dirstate"""
917 timestr = ""
917 timestr = ""
918 showdate = not nodates
918 showdate = not nodates
919 for file_, ent in sorted(repo.dirstate._map.iteritems()):
919 for file_, ent in sorted(repo.dirstate._map.iteritems()):
920 if showdate:
920 if showdate:
921 if ent[3] == -1:
921 if ent[3] == -1:
922 # Pad or slice to locale representation
922 # Pad or slice to locale representation
923 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
923 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
924 time.localtime(0)))
924 time.localtime(0)))
925 timestr = 'unset'
925 timestr = 'unset'
926 timestr = (timestr[:locale_len] +
926 timestr = (timestr[:locale_len] +
927 ' ' * (locale_len - len(timestr)))
927 ' ' * (locale_len - len(timestr)))
928 else:
928 else:
929 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
929 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
930 time.localtime(ent[3]))
930 time.localtime(ent[3]))
931 if ent[1] & 020000:
931 if ent[1] & 020000:
932 mode = 'lnk'
932 mode = 'lnk'
933 else:
933 else:
934 mode = '%3o' % (ent[1] & 0777)
934 mode = '%3o' % (ent[1] & 0777)
935 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
935 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
936 for f in repo.dirstate.copies():
936 for f in repo.dirstate.copies():
937 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
937 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
938
938
939 def debugsub(ui, repo, rev=None):
939 def debugsub(ui, repo, rev=None):
940 if rev == '':
940 if rev == '':
941 rev = None
941 rev = None
942 for k, v in sorted(repo[rev].substate.items()):
942 for k, v in sorted(repo[rev].substate.items()):
943 ui.write('path %s\n' % k)
943 ui.write('path %s\n' % k)
944 ui.write(' source %s\n' % v[0])
944 ui.write(' source %s\n' % v[0])
945 ui.write(' revision %s\n' % v[1])
945 ui.write(' revision %s\n' % v[1])
946
946
947 def debugdata(ui, file_, rev):
947 def debugdata(ui, file_, rev):
948 """dump the contents of a data file revision"""
948 """dump the contents of a data file revision"""
949 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
949 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_[:-2] + ".i")
950 try:
950 try:
951 ui.write(r.revision(r.lookup(rev)))
951 ui.write(r.revision(r.lookup(rev)))
952 except KeyError:
952 except KeyError:
953 raise util.Abort(_('invalid revision identifier %s') % rev)
953 raise util.Abort(_('invalid revision identifier %s') % rev)
954
954
955 def debugdate(ui, date, range=None, **opts):
955 def debugdate(ui, date, range=None, **opts):
956 """parse and display a date"""
956 """parse and display a date"""
957 if opts["extended"]:
957 if opts["extended"]:
958 d = util.parsedate(date, util.extendeddateformats)
958 d = util.parsedate(date, util.extendeddateformats)
959 else:
959 else:
960 d = util.parsedate(date)
960 d = util.parsedate(date)
961 ui.write("internal: %s %s\n" % d)
961 ui.write("internal: %s %s\n" % d)
962 ui.write("standard: %s\n" % util.datestr(d))
962 ui.write("standard: %s\n" % util.datestr(d))
963 if range:
963 if range:
964 m = util.matchdate(range)
964 m = util.matchdate(range)
965 ui.write("match: %s\n" % m(d[0]))
965 ui.write("match: %s\n" % m(d[0]))
966
966
967 def debugindex(ui, file_):
967 def debugindex(ui, file_):
968 """dump the contents of an index file"""
968 """dump the contents of an index file"""
969 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
969 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
970 ui.write(" rev offset length base linkrev"
970 ui.write(" rev offset length base linkrev"
971 " nodeid p1 p2\n")
971 " nodeid p1 p2\n")
972 for i in r:
972 for i in r:
973 node = r.node(i)
973 node = r.node(i)
974 try:
974 try:
975 pp = r.parents(node)
975 pp = r.parents(node)
976 except:
976 except:
977 pp = [nullid, nullid]
977 pp = [nullid, nullid]
978 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
978 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
979 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
979 i, r.start(i), r.length(i), r.base(i), r.linkrev(i),
980 short(node), short(pp[0]), short(pp[1])))
980 short(node), short(pp[0]), short(pp[1])))
981
981
982 def debugindexdot(ui, file_):
982 def debugindexdot(ui, file_):
983 """dump an index DAG as a graphviz dot file"""
983 """dump an index DAG as a graphviz dot file"""
984 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
984 r = revlog.revlog(util.opener(os.getcwd(), audit=False), file_)
985 ui.write("digraph G {\n")
985 ui.write("digraph G {\n")
986 for i in r:
986 for i in r:
987 node = r.node(i)
987 node = r.node(i)
988 pp = r.parents(node)
988 pp = r.parents(node)
989 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
989 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
990 if pp[1] != nullid:
990 if pp[1] != nullid:
991 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
991 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
992 ui.write("}\n")
992 ui.write("}\n")
993
993
994 def debuginstall(ui):
994 def debuginstall(ui):
995 '''test Mercurial installation'''
995 '''test Mercurial installation'''
996
996
997 def writetemp(contents):
997 def writetemp(contents):
998 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
998 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
999 f = os.fdopen(fd, "wb")
999 f = os.fdopen(fd, "wb")
1000 f.write(contents)
1000 f.write(contents)
1001 f.close()
1001 f.close()
1002 return name
1002 return name
1003
1003
1004 problems = 0
1004 problems = 0
1005
1005
1006 # encoding
1006 # encoding
1007 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1007 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1008 try:
1008 try:
1009 encoding.fromlocal("test")
1009 encoding.fromlocal("test")
1010 except util.Abort, inst:
1010 except util.Abort, inst:
1011 ui.write(" %s\n" % inst)
1011 ui.write(" %s\n" % inst)
1012 ui.write(_(" (check that your locale is properly set)\n"))
1012 ui.write(_(" (check that your locale is properly set)\n"))
1013 problems += 1
1013 problems += 1
1014
1014
1015 # compiled modules
1015 # compiled modules
1016 ui.status(_("Checking extensions...\n"))
1016 ui.status(_("Checking extensions...\n"))
1017 try:
1017 try:
1018 import bdiff, mpatch, base85
1018 import bdiff, mpatch, base85
1019 except Exception, inst:
1019 except Exception, inst:
1020 ui.write(" %s\n" % inst)
1020 ui.write(" %s\n" % inst)
1021 ui.write(_(" One or more extensions could not be found"))
1021 ui.write(_(" One or more extensions could not be found"))
1022 ui.write(_(" (check that you compiled the extensions)\n"))
1022 ui.write(_(" (check that you compiled the extensions)\n"))
1023 problems += 1
1023 problems += 1
1024
1024
1025 # templates
1025 # templates
1026 ui.status(_("Checking templates...\n"))
1026 ui.status(_("Checking templates...\n"))
1027 try:
1027 try:
1028 import templater
1028 import templater
1029 templater.templater(templater.templatepath("map-cmdline.default"))
1029 templater.templater(templater.templatepath("map-cmdline.default"))
1030 except Exception, inst:
1030 except Exception, inst:
1031 ui.write(" %s\n" % inst)
1031 ui.write(" %s\n" % inst)
1032 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1032 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1033 problems += 1
1033 problems += 1
1034
1034
1035 # patch
1035 # patch
1036 ui.status(_("Checking patch...\n"))
1036 ui.status(_("Checking patch...\n"))
1037 patchproblems = 0
1037 patchproblems = 0
1038 a = "1\n2\n3\n4\n"
1038 a = "1\n2\n3\n4\n"
1039 b = "1\n2\n3\ninsert\n4\n"
1039 b = "1\n2\n3\ninsert\n4\n"
1040 fa = writetemp(a)
1040 fa = writetemp(a)
1041 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1041 d = mdiff.unidiff(a, None, b, None, os.path.basename(fa),
1042 os.path.basename(fa))
1042 os.path.basename(fa))
1043 fd = writetemp(d)
1043 fd = writetemp(d)
1044
1044
1045 files = {}
1045 files = {}
1046 try:
1046 try:
1047 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1047 patch.patch(fd, ui, cwd=os.path.dirname(fa), files=files)
1048 except util.Abort, e:
1048 except util.Abort, e:
1049 ui.write(_(" patch call failed:\n"))
1049 ui.write(_(" patch call failed:\n"))
1050 ui.write(" " + str(e) + "\n")
1050 ui.write(" " + str(e) + "\n")
1051 patchproblems += 1
1051 patchproblems += 1
1052 else:
1052 else:
1053 if list(files) != [os.path.basename(fa)]:
1053 if list(files) != [os.path.basename(fa)]:
1054 ui.write(_(" unexpected patch output!\n"))
1054 ui.write(_(" unexpected patch output!\n"))
1055 patchproblems += 1
1055 patchproblems += 1
1056 a = open(fa).read()
1056 a = open(fa).read()
1057 if a != b:
1057 if a != b:
1058 ui.write(_(" patch test failed!\n"))
1058 ui.write(_(" patch test failed!\n"))
1059 patchproblems += 1
1059 patchproblems += 1
1060
1060
1061 if patchproblems:
1061 if patchproblems:
1062 if ui.config('ui', 'patch'):
1062 if ui.config('ui', 'patch'):
1063 ui.write(_(" (Current patch tool may be incompatible with patch,"
1063 ui.write(_(" (Current patch tool may be incompatible with patch,"
1064 " or misconfigured. Please check your .hgrc file)\n"))
1064 " or misconfigured. Please check your .hgrc file)\n"))
1065 else:
1065 else:
1066 ui.write(_(" Internal patcher failure, please report this error"
1066 ui.write(_(" Internal patcher failure, please report this error"
1067 " to http://mercurial.selenic.com/bts/\n"))
1067 " to http://mercurial.selenic.com/bts/\n"))
1068 problems += patchproblems
1068 problems += patchproblems
1069
1069
1070 os.unlink(fa)
1070 os.unlink(fa)
1071 os.unlink(fd)
1071 os.unlink(fd)
1072
1072
1073 # editor
1073 # editor
1074 ui.status(_("Checking commit editor...\n"))
1074 ui.status(_("Checking commit editor...\n"))
1075 editor = ui.geteditor()
1075 editor = ui.geteditor()
1076 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1076 cmdpath = util.find_exe(editor) or util.find_exe(editor.split()[0])
1077 if not cmdpath:
1077 if not cmdpath:
1078 if editor == 'vi':
1078 if editor == 'vi':
1079 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1079 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1080 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1080 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1081 else:
1081 else:
1082 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1082 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1083 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1083 ui.write(_(" (specify a commit editor in your .hgrc file)\n"))
1084 problems += 1
1084 problems += 1
1085
1085
1086 # check username
1086 # check username
1087 ui.status(_("Checking username...\n"))
1087 ui.status(_("Checking username...\n"))
1088 try:
1088 try:
1089 user = ui.username()
1089 user = ui.username()
1090 except util.Abort, e:
1090 except util.Abort, e:
1091 ui.write(" %s\n" % e)
1091 ui.write(" %s\n" % e)
1092 ui.write(_(" (specify a username in your .hgrc file)\n"))
1092 ui.write(_(" (specify a username in your .hgrc file)\n"))
1093 problems += 1
1093 problems += 1
1094
1094
1095 if not problems:
1095 if not problems:
1096 ui.status(_("No problems detected\n"))
1096 ui.status(_("No problems detected\n"))
1097 else:
1097 else:
1098 ui.write(_("%s problems detected,"
1098 ui.write(_("%s problems detected,"
1099 " please check your install!\n") % problems)
1099 " please check your install!\n") % problems)
1100
1100
1101 return problems
1101 return problems
1102
1102
1103 def debugrename(ui, repo, file1, *pats, **opts):
1103 def debugrename(ui, repo, file1, *pats, **opts):
1104 """dump rename information"""
1104 """dump rename information"""
1105
1105
1106 ctx = repo[opts.get('rev')]
1106 ctx = repo[opts.get('rev')]
1107 m = cmdutil.match(repo, (file1,) + pats, opts)
1107 m = cmdutil.match(repo, (file1,) + pats, opts)
1108 for abs in ctx.walk(m):
1108 for abs in ctx.walk(m):
1109 fctx = ctx[abs]
1109 fctx = ctx[abs]
1110 o = fctx.filelog().renamed(fctx.filenode())
1110 o = fctx.filelog().renamed(fctx.filenode())
1111 rel = m.rel(abs)
1111 rel = m.rel(abs)
1112 if o:
1112 if o:
1113 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1113 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1114 else:
1114 else:
1115 ui.write(_("%s not renamed\n") % rel)
1115 ui.write(_("%s not renamed\n") % rel)
1116
1116
1117 def debugwalk(ui, repo, *pats, **opts):
1117 def debugwalk(ui, repo, *pats, **opts):
1118 """show how files match on given patterns"""
1118 """show how files match on given patterns"""
1119 m = cmdutil.match(repo, pats, opts)
1119 m = cmdutil.match(repo, pats, opts)
1120 items = list(repo.walk(m))
1120 items = list(repo.walk(m))
1121 if not items:
1121 if not items:
1122 return
1122 return
1123 fmt = 'f %%-%ds %%-%ds %%s' % (
1123 fmt = 'f %%-%ds %%-%ds %%s' % (
1124 max([len(abs) for abs in items]),
1124 max([len(abs) for abs in items]),
1125 max([len(m.rel(abs)) for abs in items]))
1125 max([len(m.rel(abs)) for abs in items]))
1126 for abs in items:
1126 for abs in items:
1127 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1127 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
1128 ui.write("%s\n" % line.rstrip())
1128 ui.write("%s\n" % line.rstrip())
1129
1129
1130 def diff(ui, repo, *pats, **opts):
1130 def diff(ui, repo, *pats, **opts):
1131 """diff repository (or selected files)
1131 """diff repository (or selected files)
1132
1132
1133 Show differences between revisions for the specified files.
1133 Show differences between revisions for the specified files.
1134
1134
1135 Differences between files are shown using the unified diff format.
1135 Differences between files are shown using the unified diff format.
1136
1136
1137 NOTE: diff may generate unexpected results for merges, as it will
1137 NOTE: diff may generate unexpected results for merges, as it will
1138 default to comparing against the working directory's first parent
1138 default to comparing against the working directory's first parent
1139 changeset if no revisions are specified.
1139 changeset if no revisions are specified.
1140
1140
1141 When two revision arguments are given, then changes are shown
1141 When two revision arguments are given, then changes are shown
1142 between those revisions. If only one revision is specified then
1142 between those revisions. If only one revision is specified then
1143 that revision is compared to the working directory, and, when no
1143 that revision is compared to the working directory, and, when no
1144 revisions are specified, the working directory files are compared
1144 revisions are specified, the working directory files are compared
1145 to its parent.
1145 to its parent.
1146
1146
1147 Alternatively you can specify -c/--change with a revision to see
1147 Alternatively you can specify -c/--change with a revision to see
1148 the changes in that changeset relative to its first parent.
1148 the changes in that changeset relative to its first parent.
1149
1149
1150 Without the -a/--text option, diff will avoid generating diffs of
1150 Without the -a/--text option, diff will avoid generating diffs of
1151 files it detects as binary. With -a, diff will generate a diff
1151 files it detects as binary. With -a, diff will generate a diff
1152 anyway, probably with undesirable results.
1152 anyway, probably with undesirable results.
1153
1153
1154 Use the -g/--git option to generate diffs in the git extended diff
1154 Use the -g/--git option to generate diffs in the git extended diff
1155 format. For more information, read :hg:`help diffs`.
1155 format. For more information, read :hg:`help diffs`.
1156 """
1156 """
1157
1157
1158 revs = opts.get('rev')
1158 revs = opts.get('rev')
1159 change = opts.get('change')
1159 change = opts.get('change')
1160 stat = opts.get('stat')
1160 stat = opts.get('stat')
1161 reverse = opts.get('reverse')
1161 reverse = opts.get('reverse')
1162
1162
1163 if revs and change:
1163 if revs and change:
1164 msg = _('cannot specify --rev and --change at the same time')
1164 msg = _('cannot specify --rev and --change at the same time')
1165 raise util.Abort(msg)
1165 raise util.Abort(msg)
1166 elif change:
1166 elif change:
1167 node2 = repo.lookup(change)
1167 node2 = repo.lookup(change)
1168 node1 = repo[node2].parents()[0].node()
1168 node1 = repo[node2].parents()[0].node()
1169 else:
1169 else:
1170 node1, node2 = cmdutil.revpair(repo, revs)
1170 node1, node2 = cmdutil.revpair(repo, revs)
1171
1171
1172 if reverse:
1172 if reverse:
1173 node1, node2 = node2, node1
1173 node1, node2 = node2, node1
1174
1174
1175 if stat:
1176 opts['unified'] = '0'
1177 diffopts = patch.diffopts(ui, opts)
1175 diffopts = patch.diffopts(ui, opts)
1178
1179 m = cmdutil.match(repo, pats, opts)
1176 m = cmdutil.match(repo, pats, opts)
1180 if stat:
1177 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat)
1181 it = patch.diff(repo, node1, node2, match=m, opts=diffopts)
1182 width = 80
1183 if not ui.plain():
1184 width = util.termwidth()
1185 for chunk, label in patch.diffstatui(util.iterlines(it), width=width,
1186 git=diffopts.git):
1187 ui.write(chunk, label=label)
1188 else:
1189 it = patch.diffui(repo, node1, node2, match=m, opts=diffopts)
1190 for chunk, label in it:
1191 ui.write(chunk, label=label)
1192
1178
1193 def export(ui, repo, *changesets, **opts):
1179 def export(ui, repo, *changesets, **opts):
1194 """dump the header and diffs for one or more changesets
1180 """dump the header and diffs for one or more changesets
1195
1181
1196 Print the changeset header and diffs for one or more revisions.
1182 Print the changeset header and diffs for one or more revisions.
1197
1183
1198 The information shown in the changeset header is: author, date,
1184 The information shown in the changeset header is: author, date,
1199 branch name (if non-default), changeset hash, parent(s) and commit
1185 branch name (if non-default), changeset hash, parent(s) and commit
1200 comment.
1186 comment.
1201
1187
1202 NOTE: export may generate unexpected diff output for merge
1188 NOTE: export may generate unexpected diff output for merge
1203 changesets, as it will compare the merge changeset against its
1189 changesets, as it will compare the merge changeset against its
1204 first parent only.
1190 first parent only.
1205
1191
1206 Output may be to a file, in which case the name of the file is
1192 Output may be to a file, in which case the name of the file is
1207 given using a format string. The formatting rules are as follows:
1193 given using a format string. The formatting rules are as follows:
1208
1194
1209 :``%%``: literal "%" character
1195 :``%%``: literal "%" character
1210 :``%H``: changeset hash (40 bytes of hexadecimal)
1196 :``%H``: changeset hash (40 bytes of hexadecimal)
1211 :``%N``: number of patches being generated
1197 :``%N``: number of patches being generated
1212 :``%R``: changeset revision number
1198 :``%R``: changeset revision number
1213 :``%b``: basename of the exporting repository
1199 :``%b``: basename of the exporting repository
1214 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1200 :``%h``: short-form changeset hash (12 bytes of hexadecimal)
1215 :``%n``: zero-padded sequence number, starting at 1
1201 :``%n``: zero-padded sequence number, starting at 1
1216 :``%r``: zero-padded changeset revision number
1202 :``%r``: zero-padded changeset revision number
1217
1203
1218 Without the -a/--text option, export will avoid generating diffs
1204 Without the -a/--text option, export will avoid generating diffs
1219 of files it detects as binary. With -a, export will generate a
1205 of files it detects as binary. With -a, export will generate a
1220 diff anyway, probably with undesirable results.
1206 diff anyway, probably with undesirable results.
1221
1207
1222 Use the -g/--git option to generate diffs in the git extended diff
1208 Use the -g/--git option to generate diffs in the git extended diff
1223 format. See :hg:`help diffs` for more information.
1209 format. See :hg:`help diffs` for more information.
1224
1210
1225 With the --switch-parent option, the diff will be against the
1211 With the --switch-parent option, the diff will be against the
1226 second parent. It can be useful to review a merge.
1212 second parent. It can be useful to review a merge.
1227 """
1213 """
1228 changesets += tuple(opts.get('rev', []))
1214 changesets += tuple(opts.get('rev', []))
1229 if not changesets:
1215 if not changesets:
1230 raise util.Abort(_("export requires at least one changeset"))
1216 raise util.Abort(_("export requires at least one changeset"))
1231 revs = cmdutil.revrange(repo, changesets)
1217 revs = cmdutil.revrange(repo, changesets)
1232 if len(revs) > 1:
1218 if len(revs) > 1:
1233 ui.note(_('exporting patches:\n'))
1219 ui.note(_('exporting patches:\n'))
1234 else:
1220 else:
1235 ui.note(_('exporting patch:\n'))
1221 ui.note(_('exporting patch:\n'))
1236 cmdutil.export(repo, revs, template=opts.get('output'),
1222 cmdutil.export(repo, revs, template=opts.get('output'),
1237 switch_parent=opts.get('switch_parent'),
1223 switch_parent=opts.get('switch_parent'),
1238 opts=patch.diffopts(ui, opts))
1224 opts=patch.diffopts(ui, opts))
1239
1225
1240 def forget(ui, repo, *pats, **opts):
1226 def forget(ui, repo, *pats, **opts):
1241 """forget the specified files on the next commit
1227 """forget the specified files on the next commit
1242
1228
1243 Mark the specified files so they will no longer be tracked
1229 Mark the specified files so they will no longer be tracked
1244 after the next commit.
1230 after the next commit.
1245
1231
1246 This only removes files from the current branch, not from the
1232 This only removes files from the current branch, not from the
1247 entire project history, and it does not delete them from the
1233 entire project history, and it does not delete them from the
1248 working directory.
1234 working directory.
1249
1235
1250 To undo a forget before the next commit, see hg add.
1236 To undo a forget before the next commit, see hg add.
1251 """
1237 """
1252
1238
1253 if not pats:
1239 if not pats:
1254 raise util.Abort(_('no files specified'))
1240 raise util.Abort(_('no files specified'))
1255
1241
1256 m = cmdutil.match(repo, pats, opts)
1242 m = cmdutil.match(repo, pats, opts)
1257 s = repo.status(match=m, clean=True)
1243 s = repo.status(match=m, clean=True)
1258 forget = sorted(s[0] + s[1] + s[3] + s[6])
1244 forget = sorted(s[0] + s[1] + s[3] + s[6])
1259
1245
1260 for f in m.files():
1246 for f in m.files():
1261 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1247 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
1262 ui.warn(_('not removing %s: file is already untracked\n')
1248 ui.warn(_('not removing %s: file is already untracked\n')
1263 % m.rel(f))
1249 % m.rel(f))
1264
1250
1265 for f in forget:
1251 for f in forget:
1266 if ui.verbose or not m.exact(f):
1252 if ui.verbose or not m.exact(f):
1267 ui.status(_('removing %s\n') % m.rel(f))
1253 ui.status(_('removing %s\n') % m.rel(f))
1268
1254
1269 repo.remove(forget, unlink=False)
1255 repo.remove(forget, unlink=False)
1270
1256
1271 def grep(ui, repo, pattern, *pats, **opts):
1257 def grep(ui, repo, pattern, *pats, **opts):
1272 """search for a pattern in specified files and revisions
1258 """search for a pattern in specified files and revisions
1273
1259
1274 Search revisions of files for a regular expression.
1260 Search revisions of files for a regular expression.
1275
1261
1276 This command behaves differently than Unix grep. It only accepts
1262 This command behaves differently than Unix grep. It only accepts
1277 Python/Perl regexps. It searches repository history, not the
1263 Python/Perl regexps. It searches repository history, not the
1278 working directory. It always prints the revision number in which a
1264 working directory. It always prints the revision number in which a
1279 match appears.
1265 match appears.
1280
1266
1281 By default, grep only prints output for the first revision of a
1267 By default, grep only prints output for the first revision of a
1282 file in which it finds a match. To get it to print every revision
1268 file in which it finds a match. To get it to print every revision
1283 that contains a change in match status ("-" for a match that
1269 that contains a change in match status ("-" for a match that
1284 becomes a non-match, or "+" for a non-match that becomes a match),
1270 becomes a non-match, or "+" for a non-match that becomes a match),
1285 use the --all flag.
1271 use the --all flag.
1286 """
1272 """
1287 reflags = 0
1273 reflags = 0
1288 if opts.get('ignore_case'):
1274 if opts.get('ignore_case'):
1289 reflags |= re.I
1275 reflags |= re.I
1290 try:
1276 try:
1291 regexp = re.compile(pattern, reflags)
1277 regexp = re.compile(pattern, reflags)
1292 except Exception, inst:
1278 except Exception, inst:
1293 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1279 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
1294 return None
1280 return None
1295 sep, eol = ':', '\n'
1281 sep, eol = ':', '\n'
1296 if opts.get('print0'):
1282 if opts.get('print0'):
1297 sep = eol = '\0'
1283 sep = eol = '\0'
1298
1284
1299 getfile = util.lrucachefunc(repo.file)
1285 getfile = util.lrucachefunc(repo.file)
1300
1286
1301 def matchlines(body):
1287 def matchlines(body):
1302 begin = 0
1288 begin = 0
1303 linenum = 0
1289 linenum = 0
1304 while True:
1290 while True:
1305 match = regexp.search(body, begin)
1291 match = regexp.search(body, begin)
1306 if not match:
1292 if not match:
1307 break
1293 break
1308 mstart, mend = match.span()
1294 mstart, mend = match.span()
1309 linenum += body.count('\n', begin, mstart) + 1
1295 linenum += body.count('\n', begin, mstart) + 1
1310 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1296 lstart = body.rfind('\n', begin, mstart) + 1 or begin
1311 begin = body.find('\n', mend) + 1 or len(body)
1297 begin = body.find('\n', mend) + 1 or len(body)
1312 lend = begin - 1
1298 lend = begin - 1
1313 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1299 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
1314
1300
1315 class linestate(object):
1301 class linestate(object):
1316 def __init__(self, line, linenum, colstart, colend):
1302 def __init__(self, line, linenum, colstart, colend):
1317 self.line = line
1303 self.line = line
1318 self.linenum = linenum
1304 self.linenum = linenum
1319 self.colstart = colstart
1305 self.colstart = colstart
1320 self.colend = colend
1306 self.colend = colend
1321
1307
1322 def __hash__(self):
1308 def __hash__(self):
1323 return hash((self.linenum, self.line))
1309 return hash((self.linenum, self.line))
1324
1310
1325 def __eq__(self, other):
1311 def __eq__(self, other):
1326 return self.line == other.line
1312 return self.line == other.line
1327
1313
1328 matches = {}
1314 matches = {}
1329 copies = {}
1315 copies = {}
1330 def grepbody(fn, rev, body):
1316 def grepbody(fn, rev, body):
1331 matches[rev].setdefault(fn, [])
1317 matches[rev].setdefault(fn, [])
1332 m = matches[rev][fn]
1318 m = matches[rev][fn]
1333 for lnum, cstart, cend, line in matchlines(body):
1319 for lnum, cstart, cend, line in matchlines(body):
1334 s = linestate(line, lnum, cstart, cend)
1320 s = linestate(line, lnum, cstart, cend)
1335 m.append(s)
1321 m.append(s)
1336
1322
1337 def difflinestates(a, b):
1323 def difflinestates(a, b):
1338 sm = difflib.SequenceMatcher(None, a, b)
1324 sm = difflib.SequenceMatcher(None, a, b)
1339 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1325 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
1340 if tag == 'insert':
1326 if tag == 'insert':
1341 for i in xrange(blo, bhi):
1327 for i in xrange(blo, bhi):
1342 yield ('+', b[i])
1328 yield ('+', b[i])
1343 elif tag == 'delete':
1329 elif tag == 'delete':
1344 for i in xrange(alo, ahi):
1330 for i in xrange(alo, ahi):
1345 yield ('-', a[i])
1331 yield ('-', a[i])
1346 elif tag == 'replace':
1332 elif tag == 'replace':
1347 for i in xrange(alo, ahi):
1333 for i in xrange(alo, ahi):
1348 yield ('-', a[i])
1334 yield ('-', a[i])
1349 for i in xrange(blo, bhi):
1335 for i in xrange(blo, bhi):
1350 yield ('+', b[i])
1336 yield ('+', b[i])
1351
1337
1352 def display(fn, ctx, pstates, states):
1338 def display(fn, ctx, pstates, states):
1353 rev = ctx.rev()
1339 rev = ctx.rev()
1354 datefunc = ui.quiet and util.shortdate or util.datestr
1340 datefunc = ui.quiet and util.shortdate or util.datestr
1355 found = False
1341 found = False
1356 filerevmatches = {}
1342 filerevmatches = {}
1357 if opts.get('all'):
1343 if opts.get('all'):
1358 iter = difflinestates(pstates, states)
1344 iter = difflinestates(pstates, states)
1359 else:
1345 else:
1360 iter = [('', l) for l in states]
1346 iter = [('', l) for l in states]
1361 for change, l in iter:
1347 for change, l in iter:
1362 cols = [fn, str(rev)]
1348 cols = [fn, str(rev)]
1363 before, match, after = None, None, None
1349 before, match, after = None, None, None
1364 if opts.get('line_number'):
1350 if opts.get('line_number'):
1365 cols.append(str(l.linenum))
1351 cols.append(str(l.linenum))
1366 if opts.get('all'):
1352 if opts.get('all'):
1367 cols.append(change)
1353 cols.append(change)
1368 if opts.get('user'):
1354 if opts.get('user'):
1369 cols.append(ui.shortuser(ctx.user()))
1355 cols.append(ui.shortuser(ctx.user()))
1370 if opts.get('date'):
1356 if opts.get('date'):
1371 cols.append(datefunc(ctx.date()))
1357 cols.append(datefunc(ctx.date()))
1372 if opts.get('files_with_matches'):
1358 if opts.get('files_with_matches'):
1373 c = (fn, rev)
1359 c = (fn, rev)
1374 if c in filerevmatches:
1360 if c in filerevmatches:
1375 continue
1361 continue
1376 filerevmatches[c] = 1
1362 filerevmatches[c] = 1
1377 else:
1363 else:
1378 before = l.line[:l.colstart]
1364 before = l.line[:l.colstart]
1379 match = l.line[l.colstart:l.colend]
1365 match = l.line[l.colstart:l.colend]
1380 after = l.line[l.colend:]
1366 after = l.line[l.colend:]
1381 ui.write(sep.join(cols))
1367 ui.write(sep.join(cols))
1382 if before is not None:
1368 if before is not None:
1383 ui.write(sep + before)
1369 ui.write(sep + before)
1384 ui.write(match, label='grep.match')
1370 ui.write(match, label='grep.match')
1385 ui.write(after)
1371 ui.write(after)
1386 ui.write(eol)
1372 ui.write(eol)
1387 found = True
1373 found = True
1388 return found
1374 return found
1389
1375
1390 skip = {}
1376 skip = {}
1391 revfiles = {}
1377 revfiles = {}
1392 matchfn = cmdutil.match(repo, pats, opts)
1378 matchfn = cmdutil.match(repo, pats, opts)
1393 found = False
1379 found = False
1394 follow = opts.get('follow')
1380 follow = opts.get('follow')
1395
1381
1396 def prep(ctx, fns):
1382 def prep(ctx, fns):
1397 rev = ctx.rev()
1383 rev = ctx.rev()
1398 pctx = ctx.parents()[0]
1384 pctx = ctx.parents()[0]
1399 parent = pctx.rev()
1385 parent = pctx.rev()
1400 matches.setdefault(rev, {})
1386 matches.setdefault(rev, {})
1401 matches.setdefault(parent, {})
1387 matches.setdefault(parent, {})
1402 files = revfiles.setdefault(rev, [])
1388 files = revfiles.setdefault(rev, [])
1403 for fn in fns:
1389 for fn in fns:
1404 flog = getfile(fn)
1390 flog = getfile(fn)
1405 try:
1391 try:
1406 fnode = ctx.filenode(fn)
1392 fnode = ctx.filenode(fn)
1407 except error.LookupError:
1393 except error.LookupError:
1408 continue
1394 continue
1409
1395
1410 copied = flog.renamed(fnode)
1396 copied = flog.renamed(fnode)
1411 copy = follow and copied and copied[0]
1397 copy = follow and copied and copied[0]
1412 if copy:
1398 if copy:
1413 copies.setdefault(rev, {})[fn] = copy
1399 copies.setdefault(rev, {})[fn] = copy
1414 if fn in skip:
1400 if fn in skip:
1415 if copy:
1401 if copy:
1416 skip[copy] = True
1402 skip[copy] = True
1417 continue
1403 continue
1418 files.append(fn)
1404 files.append(fn)
1419
1405
1420 if fn not in matches[rev]:
1406 if fn not in matches[rev]:
1421 grepbody(fn, rev, flog.read(fnode))
1407 grepbody(fn, rev, flog.read(fnode))
1422
1408
1423 pfn = copy or fn
1409 pfn = copy or fn
1424 if pfn not in matches[parent]:
1410 if pfn not in matches[parent]:
1425 try:
1411 try:
1426 fnode = pctx.filenode(pfn)
1412 fnode = pctx.filenode(pfn)
1427 grepbody(pfn, parent, flog.read(fnode))
1413 grepbody(pfn, parent, flog.read(fnode))
1428 except error.LookupError:
1414 except error.LookupError:
1429 pass
1415 pass
1430
1416
1431 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1417 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
1432 rev = ctx.rev()
1418 rev = ctx.rev()
1433 parent = ctx.parents()[0].rev()
1419 parent = ctx.parents()[0].rev()
1434 for fn in sorted(revfiles.get(rev, [])):
1420 for fn in sorted(revfiles.get(rev, [])):
1435 states = matches[rev][fn]
1421 states = matches[rev][fn]
1436 copy = copies.get(rev, {}).get(fn)
1422 copy = copies.get(rev, {}).get(fn)
1437 if fn in skip:
1423 if fn in skip:
1438 if copy:
1424 if copy:
1439 skip[copy] = True
1425 skip[copy] = True
1440 continue
1426 continue
1441 pstates = matches.get(parent, {}).get(copy or fn, [])
1427 pstates = matches.get(parent, {}).get(copy or fn, [])
1442 if pstates or states:
1428 if pstates or states:
1443 r = display(fn, ctx, pstates, states)
1429 r = display(fn, ctx, pstates, states)
1444 found = found or r
1430 found = found or r
1445 if r and not opts.get('all'):
1431 if r and not opts.get('all'):
1446 skip[fn] = True
1432 skip[fn] = True
1447 if copy:
1433 if copy:
1448 skip[copy] = True
1434 skip[copy] = True
1449 del matches[rev]
1435 del matches[rev]
1450 del revfiles[rev]
1436 del revfiles[rev]
1451
1437
1452 def heads(ui, repo, *branchrevs, **opts):
1438 def heads(ui, repo, *branchrevs, **opts):
1453 """show current repository heads or show branch heads
1439 """show current repository heads or show branch heads
1454
1440
1455 With no arguments, show all repository branch heads.
1441 With no arguments, show all repository branch heads.
1456
1442
1457 Repository "heads" are changesets with no child changesets. They are
1443 Repository "heads" are changesets with no child changesets. They are
1458 where development generally takes place and are the usual targets
1444 where development generally takes place and are the usual targets
1459 for update and merge operations. Branch heads are changesets that have
1445 for update and merge operations. Branch heads are changesets that have
1460 no child changeset on the same branch.
1446 no child changeset on the same branch.
1461
1447
1462 If one or more REVs are given, only branch heads on the branches
1448 If one or more REVs are given, only branch heads on the branches
1463 associated with the specified changesets are shown.
1449 associated with the specified changesets are shown.
1464
1450
1465 If -c/--closed is specified, also show branch heads marked closed
1451 If -c/--closed is specified, also show branch heads marked closed
1466 (see hg commit --close-branch).
1452 (see hg commit --close-branch).
1467
1453
1468 If STARTREV is specified, only those heads that are descendants of
1454 If STARTREV is specified, only those heads that are descendants of
1469 STARTREV will be displayed.
1455 STARTREV will be displayed.
1470
1456
1471 If -t/--topo is specified, named branch mechanics will be ignored and only
1457 If -t/--topo is specified, named branch mechanics will be ignored and only
1472 changesets without children will be shown.
1458 changesets without children will be shown.
1473 """
1459 """
1474
1460
1475 if opts.get('rev'):
1461 if opts.get('rev'):
1476 start = repo.lookup(opts['rev'])
1462 start = repo.lookup(opts['rev'])
1477 else:
1463 else:
1478 start = None
1464 start = None
1479
1465
1480 if opts.get('topo'):
1466 if opts.get('topo'):
1481 heads = [repo[h] for h in repo.heads(start)]
1467 heads = [repo[h] for h in repo.heads(start)]
1482 else:
1468 else:
1483 heads = []
1469 heads = []
1484 for b, ls in repo.branchmap().iteritems():
1470 for b, ls in repo.branchmap().iteritems():
1485 if start is None:
1471 if start is None:
1486 heads += [repo[h] for h in ls]
1472 heads += [repo[h] for h in ls]
1487 continue
1473 continue
1488 startrev = repo.changelog.rev(start)
1474 startrev = repo.changelog.rev(start)
1489 descendants = set(repo.changelog.descendants(startrev))
1475 descendants = set(repo.changelog.descendants(startrev))
1490 descendants.add(startrev)
1476 descendants.add(startrev)
1491 rev = repo.changelog.rev
1477 rev = repo.changelog.rev
1492 heads += [repo[h] for h in ls if rev(h) in descendants]
1478 heads += [repo[h] for h in ls if rev(h) in descendants]
1493
1479
1494 if branchrevs:
1480 if branchrevs:
1495 decode, encode = encoding.fromlocal, encoding.tolocal
1481 decode, encode = encoding.fromlocal, encoding.tolocal
1496 branches = set(repo[decode(br)].branch() for br in branchrevs)
1482 branches = set(repo[decode(br)].branch() for br in branchrevs)
1497 heads = [h for h in heads if h.branch() in branches]
1483 heads = [h for h in heads if h.branch() in branches]
1498
1484
1499 if not opts.get('closed'):
1485 if not opts.get('closed'):
1500 heads = [h for h in heads if not h.extra().get('close')]
1486 heads = [h for h in heads if not h.extra().get('close')]
1501
1487
1502 if opts.get('active') and branchrevs:
1488 if opts.get('active') and branchrevs:
1503 dagheads = repo.heads(start)
1489 dagheads = repo.heads(start)
1504 heads = [h for h in heads if h.node() in dagheads]
1490 heads = [h for h in heads if h.node() in dagheads]
1505
1491
1506 if branchrevs:
1492 if branchrevs:
1507 haveheads = set(h.branch() for h in heads)
1493 haveheads = set(h.branch() for h in heads)
1508 if branches - haveheads:
1494 if branches - haveheads:
1509 headless = ', '.join(encode(b) for b in branches - haveheads)
1495 headless = ', '.join(encode(b) for b in branches - haveheads)
1510 msg = _('no open branch heads found on branches %s')
1496 msg = _('no open branch heads found on branches %s')
1511 if opts.get('rev'):
1497 if opts.get('rev'):
1512 msg += _(' (started at %s)' % opts['rev'])
1498 msg += _(' (started at %s)' % opts['rev'])
1513 ui.warn((msg + '\n') % headless)
1499 ui.warn((msg + '\n') % headless)
1514
1500
1515 if not heads:
1501 if not heads:
1516 return 1
1502 return 1
1517
1503
1518 heads = sorted(heads, key=lambda x: -x.rev())
1504 heads = sorted(heads, key=lambda x: -x.rev())
1519 displayer = cmdutil.show_changeset(ui, repo, opts)
1505 displayer = cmdutil.show_changeset(ui, repo, opts)
1520 for ctx in heads:
1506 for ctx in heads:
1521 displayer.show(ctx)
1507 displayer.show(ctx)
1522 displayer.close()
1508 displayer.close()
1523
1509
1524 def help_(ui, name=None, with_version=False, unknowncmd=False):
1510 def help_(ui, name=None, with_version=False, unknowncmd=False):
1525 """show help for a given topic or a help overview
1511 """show help for a given topic or a help overview
1526
1512
1527 With no arguments, print a list of commands with short help messages.
1513 With no arguments, print a list of commands with short help messages.
1528
1514
1529 Given a topic, extension, or command name, print help for that
1515 Given a topic, extension, or command name, print help for that
1530 topic."""
1516 topic."""
1531 option_lists = []
1517 option_lists = []
1532 textwidth = util.termwidth() - 2
1518 textwidth = util.termwidth() - 2
1533
1519
1534 def addglobalopts(aliases):
1520 def addglobalopts(aliases):
1535 if ui.verbose:
1521 if ui.verbose:
1536 option_lists.append((_("global options:"), globalopts))
1522 option_lists.append((_("global options:"), globalopts))
1537 if name == 'shortlist':
1523 if name == 'shortlist':
1538 option_lists.append((_('use "hg help" for the full list '
1524 option_lists.append((_('use "hg help" for the full list '
1539 'of commands'), ()))
1525 'of commands'), ()))
1540 else:
1526 else:
1541 if name == 'shortlist':
1527 if name == 'shortlist':
1542 msg = _('use "hg help" for the full list of commands '
1528 msg = _('use "hg help" for the full list of commands '
1543 'or "hg -v" for details')
1529 'or "hg -v" for details')
1544 elif aliases:
1530 elif aliases:
1545 msg = _('use "hg -v help%s" to show aliases and '
1531 msg = _('use "hg -v help%s" to show aliases and '
1546 'global options') % (name and " " + name or "")
1532 'global options') % (name and " " + name or "")
1547 else:
1533 else:
1548 msg = _('use "hg -v help %s" to show global options') % name
1534 msg = _('use "hg -v help %s" to show global options') % name
1549 option_lists.append((msg, ()))
1535 option_lists.append((msg, ()))
1550
1536
1551 def helpcmd(name):
1537 def helpcmd(name):
1552 if with_version:
1538 if with_version:
1553 version_(ui)
1539 version_(ui)
1554 ui.write('\n')
1540 ui.write('\n')
1555
1541
1556 try:
1542 try:
1557 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1543 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
1558 except error.AmbiguousCommand, inst:
1544 except error.AmbiguousCommand, inst:
1559 # py3k fix: except vars can't be used outside the scope of the
1545 # py3k fix: except vars can't be used outside the scope of the
1560 # except block, nor can be used inside a lambda. python issue4617
1546 # except block, nor can be used inside a lambda. python issue4617
1561 prefix = inst.args[0]
1547 prefix = inst.args[0]
1562 select = lambda c: c.lstrip('^').startswith(prefix)
1548 select = lambda c: c.lstrip('^').startswith(prefix)
1563 helplist(_('list of commands:\n\n'), select)
1549 helplist(_('list of commands:\n\n'), select)
1564 return
1550 return
1565
1551
1566 # check if it's an invalid alias and display its error if it is
1552 # check if it's an invalid alias and display its error if it is
1567 if getattr(entry[0], 'badalias', False):
1553 if getattr(entry[0], 'badalias', False):
1568 if not unknowncmd:
1554 if not unknowncmd:
1569 entry[0](ui)
1555 entry[0](ui)
1570 return
1556 return
1571
1557
1572 # synopsis
1558 # synopsis
1573 if len(entry) > 2:
1559 if len(entry) > 2:
1574 if entry[2].startswith('hg'):
1560 if entry[2].startswith('hg'):
1575 ui.write("%s\n" % entry[2])
1561 ui.write("%s\n" % entry[2])
1576 else:
1562 else:
1577 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1563 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
1578 else:
1564 else:
1579 ui.write('hg %s\n' % aliases[0])
1565 ui.write('hg %s\n' % aliases[0])
1580
1566
1581 # aliases
1567 # aliases
1582 if not ui.quiet and len(aliases) > 1:
1568 if not ui.quiet and len(aliases) > 1:
1583 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1569 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
1584
1570
1585 # description
1571 # description
1586 doc = gettext(entry[0].__doc__)
1572 doc = gettext(entry[0].__doc__)
1587 if not doc:
1573 if not doc:
1588 doc = _("(no help text available)")
1574 doc = _("(no help text available)")
1589 if hasattr(entry[0], 'definition'): # aliased command
1575 if hasattr(entry[0], 'definition'): # aliased command
1590 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1576 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
1591 if ui.quiet:
1577 if ui.quiet:
1592 doc = doc.splitlines()[0]
1578 doc = doc.splitlines()[0]
1593 keep = ui.verbose and ['verbose'] or []
1579 keep = ui.verbose and ['verbose'] or []
1594 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1580 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
1595 ui.write("\n%s\n" % formatted)
1581 ui.write("\n%s\n" % formatted)
1596 if pruned:
1582 if pruned:
1597 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1583 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
1598
1584
1599 if not ui.quiet:
1585 if not ui.quiet:
1600 # options
1586 # options
1601 if entry[1]:
1587 if entry[1]:
1602 option_lists.append((_("options:\n"), entry[1]))
1588 option_lists.append((_("options:\n"), entry[1]))
1603
1589
1604 addglobalopts(False)
1590 addglobalopts(False)
1605
1591
1606 def helplist(header, select=None):
1592 def helplist(header, select=None):
1607 h = {}
1593 h = {}
1608 cmds = {}
1594 cmds = {}
1609 for c, e in table.iteritems():
1595 for c, e in table.iteritems():
1610 f = c.split("|", 1)[0]
1596 f = c.split("|", 1)[0]
1611 if select and not select(f):
1597 if select and not select(f):
1612 continue
1598 continue
1613 if (not select and name != 'shortlist' and
1599 if (not select and name != 'shortlist' and
1614 e[0].__module__ != __name__):
1600 e[0].__module__ != __name__):
1615 continue
1601 continue
1616 if name == "shortlist" and not f.startswith("^"):
1602 if name == "shortlist" and not f.startswith("^"):
1617 continue
1603 continue
1618 f = f.lstrip("^")
1604 f = f.lstrip("^")
1619 if not ui.debugflag and f.startswith("debug"):
1605 if not ui.debugflag and f.startswith("debug"):
1620 continue
1606 continue
1621 doc = e[0].__doc__
1607 doc = e[0].__doc__
1622 if doc and 'DEPRECATED' in doc and not ui.verbose:
1608 if doc and 'DEPRECATED' in doc and not ui.verbose:
1623 continue
1609 continue
1624 doc = gettext(doc)
1610 doc = gettext(doc)
1625 if not doc:
1611 if not doc:
1626 doc = _("(no help text available)")
1612 doc = _("(no help text available)")
1627 h[f] = doc.splitlines()[0].rstrip()
1613 h[f] = doc.splitlines()[0].rstrip()
1628 cmds[f] = c.lstrip("^")
1614 cmds[f] = c.lstrip("^")
1629
1615
1630 if not h:
1616 if not h:
1631 ui.status(_('no commands defined\n'))
1617 ui.status(_('no commands defined\n'))
1632 return
1618 return
1633
1619
1634 ui.status(header)
1620 ui.status(header)
1635 fns = sorted(h)
1621 fns = sorted(h)
1636 m = max(map(len, fns))
1622 m = max(map(len, fns))
1637 for f in fns:
1623 for f in fns:
1638 if ui.verbose:
1624 if ui.verbose:
1639 commands = cmds[f].replace("|",", ")
1625 commands = cmds[f].replace("|",", ")
1640 ui.write(" %s:\n %s\n"%(commands, h[f]))
1626 ui.write(" %s:\n %s\n"%(commands, h[f]))
1641 else:
1627 else:
1642 ui.write(' %-*s %s\n' % (m, f, util.wrap(h[f], m + 4)))
1628 ui.write(' %-*s %s\n' % (m, f, util.wrap(h[f], m + 4)))
1643
1629
1644 if not ui.quiet:
1630 if not ui.quiet:
1645 addglobalopts(True)
1631 addglobalopts(True)
1646
1632
1647 def helptopic(name):
1633 def helptopic(name):
1648 for names, header, doc in help.helptable:
1634 for names, header, doc in help.helptable:
1649 if name in names:
1635 if name in names:
1650 break
1636 break
1651 else:
1637 else:
1652 raise error.UnknownCommand(name)
1638 raise error.UnknownCommand(name)
1653
1639
1654 # description
1640 # description
1655 if not doc:
1641 if not doc:
1656 doc = _("(no help text available)")
1642 doc = _("(no help text available)")
1657 if hasattr(doc, '__call__'):
1643 if hasattr(doc, '__call__'):
1658 doc = doc()
1644 doc = doc()
1659
1645
1660 ui.write("%s\n\n" % header)
1646 ui.write("%s\n\n" % header)
1661 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1647 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
1662
1648
1663 def helpext(name):
1649 def helpext(name):
1664 try:
1650 try:
1665 mod = extensions.find(name)
1651 mod = extensions.find(name)
1666 doc = gettext(mod.__doc__) or _('no help text available')
1652 doc = gettext(mod.__doc__) or _('no help text available')
1667 except KeyError:
1653 except KeyError:
1668 mod = None
1654 mod = None
1669 doc = extensions.disabledext(name)
1655 doc = extensions.disabledext(name)
1670 if not doc:
1656 if not doc:
1671 raise error.UnknownCommand(name)
1657 raise error.UnknownCommand(name)
1672
1658
1673 if '\n' not in doc:
1659 if '\n' not in doc:
1674 head, tail = doc, ""
1660 head, tail = doc, ""
1675 else:
1661 else:
1676 head, tail = doc.split('\n', 1)
1662 head, tail = doc.split('\n', 1)
1677 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1663 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
1678 if tail:
1664 if tail:
1679 ui.write(minirst.format(tail, textwidth))
1665 ui.write(minirst.format(tail, textwidth))
1680 ui.status('\n\n')
1666 ui.status('\n\n')
1681
1667
1682 if mod:
1668 if mod:
1683 try:
1669 try:
1684 ct = mod.cmdtable
1670 ct = mod.cmdtable
1685 except AttributeError:
1671 except AttributeError:
1686 ct = {}
1672 ct = {}
1687 modcmds = set([c.split('|', 1)[0] for c in ct])
1673 modcmds = set([c.split('|', 1)[0] for c in ct])
1688 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1674 helplist(_('list of commands:\n\n'), modcmds.__contains__)
1689 else:
1675 else:
1690 ui.write(_('use "hg help extensions" for information on enabling '
1676 ui.write(_('use "hg help extensions" for information on enabling '
1691 'extensions\n'))
1677 'extensions\n'))
1692
1678
1693 def helpextcmd(name):
1679 def helpextcmd(name):
1694 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1680 cmd, ext, mod = extensions.disabledcmd(name, ui.config('ui', 'strict'))
1695 doc = gettext(mod.__doc__).splitlines()[0]
1681 doc = gettext(mod.__doc__).splitlines()[0]
1696
1682
1697 msg = help.listexts(_("'%s' is provided by the following "
1683 msg = help.listexts(_("'%s' is provided by the following "
1698 "extension:") % cmd, {ext: doc}, len(ext),
1684 "extension:") % cmd, {ext: doc}, len(ext),
1699 indent=4)
1685 indent=4)
1700 ui.write(minirst.format(msg, textwidth))
1686 ui.write(minirst.format(msg, textwidth))
1701 ui.write('\n\n')
1687 ui.write('\n\n')
1702 ui.write(_('use "hg help extensions" for information on enabling '
1688 ui.write(_('use "hg help extensions" for information on enabling '
1703 'extensions\n'))
1689 'extensions\n'))
1704
1690
1705 if name and name != 'shortlist':
1691 if name and name != 'shortlist':
1706 i = None
1692 i = None
1707 if unknowncmd:
1693 if unknowncmd:
1708 queries = (helpextcmd,)
1694 queries = (helpextcmd,)
1709 else:
1695 else:
1710 queries = (helptopic, helpcmd, helpext, helpextcmd)
1696 queries = (helptopic, helpcmd, helpext, helpextcmd)
1711 for f in queries:
1697 for f in queries:
1712 try:
1698 try:
1713 f(name)
1699 f(name)
1714 i = None
1700 i = None
1715 break
1701 break
1716 except error.UnknownCommand, inst:
1702 except error.UnknownCommand, inst:
1717 i = inst
1703 i = inst
1718 if i:
1704 if i:
1719 raise i
1705 raise i
1720
1706
1721 else:
1707 else:
1722 # program name
1708 # program name
1723 if ui.verbose or with_version:
1709 if ui.verbose or with_version:
1724 version_(ui)
1710 version_(ui)
1725 else:
1711 else:
1726 ui.status(_("Mercurial Distributed SCM\n"))
1712 ui.status(_("Mercurial Distributed SCM\n"))
1727 ui.status('\n')
1713 ui.status('\n')
1728
1714
1729 # list of commands
1715 # list of commands
1730 if name == "shortlist":
1716 if name == "shortlist":
1731 header = _('basic commands:\n\n')
1717 header = _('basic commands:\n\n')
1732 else:
1718 else:
1733 header = _('list of commands:\n\n')
1719 header = _('list of commands:\n\n')
1734
1720
1735 helplist(header)
1721 helplist(header)
1736 if name != 'shortlist':
1722 if name != 'shortlist':
1737 exts, maxlength = extensions.enabled()
1723 exts, maxlength = extensions.enabled()
1738 text = help.listexts(_('enabled extensions:'), exts, maxlength)
1724 text = help.listexts(_('enabled extensions:'), exts, maxlength)
1739 if text:
1725 if text:
1740 ui.write("\n%s\n" % minirst.format(text, textwidth))
1726 ui.write("\n%s\n" % minirst.format(text, textwidth))
1741
1727
1742 # list all option lists
1728 # list all option lists
1743 opt_output = []
1729 opt_output = []
1744 for title, options in option_lists:
1730 for title, options in option_lists:
1745 opt_output.append(("\n%s" % title, None))
1731 opt_output.append(("\n%s" % title, None))
1746 for shortopt, longopt, default, desc in options:
1732 for shortopt, longopt, default, desc in options:
1747 if _("DEPRECATED") in desc and not ui.verbose:
1733 if _("DEPRECATED") in desc and not ui.verbose:
1748 continue
1734 continue
1749 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1735 opt_output.append(("%2s%s" % (shortopt and "-%s" % shortopt,
1750 longopt and " --%s" % longopt),
1736 longopt and " --%s" % longopt),
1751 "%s%s" % (desc,
1737 "%s%s" % (desc,
1752 default
1738 default
1753 and _(" (default: %s)") % default
1739 and _(" (default: %s)") % default
1754 or "")))
1740 or "")))
1755
1741
1756 if not name:
1742 if not name:
1757 ui.write(_("\nadditional help topics:\n\n"))
1743 ui.write(_("\nadditional help topics:\n\n"))
1758 topics = []
1744 topics = []
1759 for names, header, doc in help.helptable:
1745 for names, header, doc in help.helptable:
1760 topics.append((sorted(names, key=len, reverse=True)[0], header))
1746 topics.append((sorted(names, key=len, reverse=True)[0], header))
1761 topics_len = max([len(s[0]) for s in topics])
1747 topics_len = max([len(s[0]) for s in topics])
1762 for t, desc in topics:
1748 for t, desc in topics:
1763 ui.write(" %-*s %s\n" % (topics_len, t, desc))
1749 ui.write(" %-*s %s\n" % (topics_len, t, desc))
1764
1750
1765 if opt_output:
1751 if opt_output:
1766 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1752 opts_len = max([len(line[0]) for line in opt_output if line[1]] or [0])
1767 for first, second in opt_output:
1753 for first, second in opt_output:
1768 if second:
1754 if second:
1769 second = util.wrap(second, opts_len + 3)
1755 second = util.wrap(second, opts_len + 3)
1770 ui.write(" %-*s %s\n" % (opts_len, first, second))
1756 ui.write(" %-*s %s\n" % (opts_len, first, second))
1771 else:
1757 else:
1772 ui.write("%s\n" % first)
1758 ui.write("%s\n" % first)
1773
1759
1774 def identify(ui, repo, source=None,
1760 def identify(ui, repo, source=None,
1775 rev=None, num=None, id=None, branch=None, tags=None):
1761 rev=None, num=None, id=None, branch=None, tags=None):
1776 """identify the working copy or specified revision
1762 """identify the working copy or specified revision
1777
1763
1778 With no revision, print a summary of the current state of the
1764 With no revision, print a summary of the current state of the
1779 repository.
1765 repository.
1780
1766
1781 Specifying a path to a repository root or Mercurial bundle will
1767 Specifying a path to a repository root or Mercurial bundle will
1782 cause lookup to operate on that repository/bundle.
1768 cause lookup to operate on that repository/bundle.
1783
1769
1784 This summary identifies the repository state using one or two
1770 This summary identifies the repository state using one or two
1785 parent hash identifiers, followed by a "+" if there are
1771 parent hash identifiers, followed by a "+" if there are
1786 uncommitted changes in the working directory, a list of tags for
1772 uncommitted changes in the working directory, a list of tags for
1787 this revision and a branch name for non-default branches.
1773 this revision and a branch name for non-default branches.
1788 """
1774 """
1789
1775
1790 if not repo and not source:
1776 if not repo and not source:
1791 raise util.Abort(_("There is no Mercurial repository here "
1777 raise util.Abort(_("There is no Mercurial repository here "
1792 "(.hg not found)"))
1778 "(.hg not found)"))
1793
1779
1794 hexfunc = ui.debugflag and hex or short
1780 hexfunc = ui.debugflag and hex or short
1795 default = not (num or id or branch or tags)
1781 default = not (num or id or branch or tags)
1796 output = []
1782 output = []
1797
1783
1798 revs = []
1784 revs = []
1799 if source:
1785 if source:
1800 source, branches = hg.parseurl(ui.expandpath(source))
1786 source, branches = hg.parseurl(ui.expandpath(source))
1801 repo = hg.repository(ui, source)
1787 repo = hg.repository(ui, source)
1802 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
1788 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
1803
1789
1804 if not repo.local():
1790 if not repo.local():
1805 if not rev and revs:
1791 if not rev and revs:
1806 rev = revs[0]
1792 rev = revs[0]
1807 if not rev:
1793 if not rev:
1808 rev = "tip"
1794 rev = "tip"
1809 if num or branch or tags:
1795 if num or branch or tags:
1810 raise util.Abort(
1796 raise util.Abort(
1811 "can't query remote revision number, branch, or tags")
1797 "can't query remote revision number, branch, or tags")
1812 output = [hexfunc(repo.lookup(rev))]
1798 output = [hexfunc(repo.lookup(rev))]
1813 elif not rev:
1799 elif not rev:
1814 ctx = repo[None]
1800 ctx = repo[None]
1815 parents = ctx.parents()
1801 parents = ctx.parents()
1816 changed = False
1802 changed = False
1817 if default or id or num:
1803 if default or id or num:
1818 changed = util.any(repo.status())
1804 changed = util.any(repo.status())
1819 if default or id:
1805 if default or id:
1820 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1806 output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p in parents]),
1821 (changed) and "+" or "")]
1807 (changed) and "+" or "")]
1822 if num:
1808 if num:
1823 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1809 output.append("%s%s" % ('+'.join([str(p.rev()) for p in parents]),
1824 (changed) and "+" or ""))
1810 (changed) and "+" or ""))
1825 else:
1811 else:
1826 ctx = repo[rev]
1812 ctx = repo[rev]
1827 if default or id:
1813 if default or id:
1828 output = [hexfunc(ctx.node())]
1814 output = [hexfunc(ctx.node())]
1829 if num:
1815 if num:
1830 output.append(str(ctx.rev()))
1816 output.append(str(ctx.rev()))
1831
1817
1832 if repo.local() and default and not ui.quiet:
1818 if repo.local() and default and not ui.quiet:
1833 b = encoding.tolocal(ctx.branch())
1819 b = encoding.tolocal(ctx.branch())
1834 if b != 'default':
1820 if b != 'default':
1835 output.append("(%s)" % b)
1821 output.append("(%s)" % b)
1836
1822
1837 # multiple tags for a single parent separated by '/'
1823 # multiple tags for a single parent separated by '/'
1838 t = "/".join(ctx.tags())
1824 t = "/".join(ctx.tags())
1839 if t:
1825 if t:
1840 output.append(t)
1826 output.append(t)
1841
1827
1842 if branch:
1828 if branch:
1843 output.append(encoding.tolocal(ctx.branch()))
1829 output.append(encoding.tolocal(ctx.branch()))
1844
1830
1845 if tags:
1831 if tags:
1846 output.extend(ctx.tags())
1832 output.extend(ctx.tags())
1847
1833
1848 ui.write("%s\n" % ' '.join(output))
1834 ui.write("%s\n" % ' '.join(output))
1849
1835
1850 def import_(ui, repo, patch1, *patches, **opts):
1836 def import_(ui, repo, patch1, *patches, **opts):
1851 """import an ordered set of patches
1837 """import an ordered set of patches
1852
1838
1853 Import a list of patches and commit them individually (unless
1839 Import a list of patches and commit them individually (unless
1854 --no-commit is specified).
1840 --no-commit is specified).
1855
1841
1856 If there are outstanding changes in the working directory, import
1842 If there are outstanding changes in the working directory, import
1857 will abort unless given the -f/--force flag.
1843 will abort unless given the -f/--force flag.
1858
1844
1859 You can import a patch straight from a mail message. Even patches
1845 You can import a patch straight from a mail message. Even patches
1860 as attachments work (to use the body part, it must have type
1846 as attachments work (to use the body part, it must have type
1861 text/plain or text/x-patch). From and Subject headers of email
1847 text/plain or text/x-patch). From and Subject headers of email
1862 message are used as default committer and commit message. All
1848 message are used as default committer and commit message. All
1863 text/plain body parts before first diff are added to commit
1849 text/plain body parts before first diff are added to commit
1864 message.
1850 message.
1865
1851
1866 If the imported patch was generated by hg export, user and
1852 If the imported patch was generated by hg export, user and
1867 description from patch override values from message headers and
1853 description from patch override values from message headers and
1868 body. Values given on command line with -m/--message and -u/--user
1854 body. Values given on command line with -m/--message and -u/--user
1869 override these.
1855 override these.
1870
1856
1871 If --exact is specified, import will set the working directory to
1857 If --exact is specified, import will set the working directory to
1872 the parent of each patch before applying it, and will abort if the
1858 the parent of each patch before applying it, and will abort if the
1873 resulting changeset has a different ID than the one recorded in
1859 resulting changeset has a different ID than the one recorded in
1874 the patch. This may happen due to character set problems or other
1860 the patch. This may happen due to character set problems or other
1875 deficiencies in the text patch format.
1861 deficiencies in the text patch format.
1876
1862
1877 With -s/--similarity, hg will attempt to discover renames and
1863 With -s/--similarity, hg will attempt to discover renames and
1878 copies in the patch in the same way as 'addremove'.
1864 copies in the patch in the same way as 'addremove'.
1879
1865
1880 To read a patch from standard input, use "-" as the patch name. If
1866 To read a patch from standard input, use "-" as the patch name. If
1881 a URL is specified, the patch will be downloaded from it.
1867 a URL is specified, the patch will be downloaded from it.
1882 See :hg:`help dates` for a list of formats valid for -d/--date.
1868 See :hg:`help dates` for a list of formats valid for -d/--date.
1883 """
1869 """
1884 patches = (patch1,) + patches
1870 patches = (patch1,) + patches
1885
1871
1886 date = opts.get('date')
1872 date = opts.get('date')
1887 if date:
1873 if date:
1888 opts['date'] = util.parsedate(date)
1874 opts['date'] = util.parsedate(date)
1889
1875
1890 try:
1876 try:
1891 sim = float(opts.get('similarity') or 0)
1877 sim = float(opts.get('similarity') or 0)
1892 except ValueError:
1878 except ValueError:
1893 raise util.Abort(_('similarity must be a number'))
1879 raise util.Abort(_('similarity must be a number'))
1894 if sim < 0 or sim > 100:
1880 if sim < 0 or sim > 100:
1895 raise util.Abort(_('similarity must be between 0 and 100'))
1881 raise util.Abort(_('similarity must be between 0 and 100'))
1896
1882
1897 if opts.get('exact') or not opts.get('force'):
1883 if opts.get('exact') or not opts.get('force'):
1898 cmdutil.bail_if_changed(repo)
1884 cmdutil.bail_if_changed(repo)
1899
1885
1900 d = opts["base"]
1886 d = opts["base"]
1901 strip = opts["strip"]
1887 strip = opts["strip"]
1902 wlock = lock = None
1888 wlock = lock = None
1903
1889
1904 def tryone(ui, hunk):
1890 def tryone(ui, hunk):
1905 tmpname, message, user, date, branch, nodeid, p1, p2 = \
1891 tmpname, message, user, date, branch, nodeid, p1, p2 = \
1906 patch.extract(ui, hunk)
1892 patch.extract(ui, hunk)
1907
1893
1908 if not tmpname:
1894 if not tmpname:
1909 return None
1895 return None
1910 commitid = _('to working directory')
1896 commitid = _('to working directory')
1911
1897
1912 try:
1898 try:
1913 cmdline_message = cmdutil.logmessage(opts)
1899 cmdline_message = cmdutil.logmessage(opts)
1914 if cmdline_message:
1900 if cmdline_message:
1915 # pickup the cmdline msg
1901 # pickup the cmdline msg
1916 message = cmdline_message
1902 message = cmdline_message
1917 elif message:
1903 elif message:
1918 # pickup the patch msg
1904 # pickup the patch msg
1919 message = message.strip()
1905 message = message.strip()
1920 else:
1906 else:
1921 # launch the editor
1907 # launch the editor
1922 message = None
1908 message = None
1923 ui.debug('message:\n%s\n' % message)
1909 ui.debug('message:\n%s\n' % message)
1924
1910
1925 wp = repo.parents()
1911 wp = repo.parents()
1926 if opts.get('exact'):
1912 if opts.get('exact'):
1927 if not nodeid or not p1:
1913 if not nodeid or not p1:
1928 raise util.Abort(_('not a Mercurial patch'))
1914 raise util.Abort(_('not a Mercurial patch'))
1929 p1 = repo.lookup(p1)
1915 p1 = repo.lookup(p1)
1930 p2 = repo.lookup(p2 or hex(nullid))
1916 p2 = repo.lookup(p2 or hex(nullid))
1931
1917
1932 if p1 != wp[0].node():
1918 if p1 != wp[0].node():
1933 hg.clean(repo, p1)
1919 hg.clean(repo, p1)
1934 repo.dirstate.setparents(p1, p2)
1920 repo.dirstate.setparents(p1, p2)
1935 elif p2:
1921 elif p2:
1936 try:
1922 try:
1937 p1 = repo.lookup(p1)
1923 p1 = repo.lookup(p1)
1938 p2 = repo.lookup(p2)
1924 p2 = repo.lookup(p2)
1939 if p1 == wp[0].node():
1925 if p1 == wp[0].node():
1940 repo.dirstate.setparents(p1, p2)
1926 repo.dirstate.setparents(p1, p2)
1941 except error.RepoError:
1927 except error.RepoError:
1942 pass
1928 pass
1943 if opts.get('exact') or opts.get('import_branch'):
1929 if opts.get('exact') or opts.get('import_branch'):
1944 repo.dirstate.setbranch(branch or 'default')
1930 repo.dirstate.setbranch(branch or 'default')
1945
1931
1946 files = {}
1932 files = {}
1947 try:
1933 try:
1948 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1934 patch.patch(tmpname, ui, strip=strip, cwd=repo.root,
1949 files=files, eolmode=None)
1935 files=files, eolmode=None)
1950 finally:
1936 finally:
1951 files = patch.updatedir(ui, repo, files,
1937 files = patch.updatedir(ui, repo, files,
1952 similarity=sim / 100.0)
1938 similarity=sim / 100.0)
1953 if not opts.get('no_commit'):
1939 if not opts.get('no_commit'):
1954 if opts.get('exact'):
1940 if opts.get('exact'):
1955 m = None
1941 m = None
1956 else:
1942 else:
1957 m = cmdutil.matchfiles(repo, files or [])
1943 m = cmdutil.matchfiles(repo, files or [])
1958 n = repo.commit(message, opts.get('user') or user,
1944 n = repo.commit(message, opts.get('user') or user,
1959 opts.get('date') or date, match=m,
1945 opts.get('date') or date, match=m,
1960 editor=cmdutil.commiteditor)
1946 editor=cmdutil.commiteditor)
1961 if opts.get('exact'):
1947 if opts.get('exact'):
1962 if hex(n) != nodeid:
1948 if hex(n) != nodeid:
1963 repo.rollback()
1949 repo.rollback()
1964 raise util.Abort(_('patch is damaged'
1950 raise util.Abort(_('patch is damaged'
1965 ' or loses information'))
1951 ' or loses information'))
1966 # Force a dirstate write so that the next transaction
1952 # Force a dirstate write so that the next transaction
1967 # backups an up-do-date file.
1953 # backups an up-do-date file.
1968 repo.dirstate.write()
1954 repo.dirstate.write()
1969 if n:
1955 if n:
1970 commitid = short(n)
1956 commitid = short(n)
1971
1957
1972 return commitid
1958 return commitid
1973 finally:
1959 finally:
1974 os.unlink(tmpname)
1960 os.unlink(tmpname)
1975
1961
1976 try:
1962 try:
1977 wlock = repo.wlock()
1963 wlock = repo.wlock()
1978 lock = repo.lock()
1964 lock = repo.lock()
1979 lastcommit = None
1965 lastcommit = None
1980 for p in patches:
1966 for p in patches:
1981 pf = os.path.join(d, p)
1967 pf = os.path.join(d, p)
1982
1968
1983 if pf == '-':
1969 if pf == '-':
1984 ui.status(_("applying patch from stdin\n"))
1970 ui.status(_("applying patch from stdin\n"))
1985 pf = sys.stdin
1971 pf = sys.stdin
1986 else:
1972 else:
1987 ui.status(_("applying %s\n") % p)
1973 ui.status(_("applying %s\n") % p)
1988 pf = url.open(ui, pf)
1974 pf = url.open(ui, pf)
1989
1975
1990 haspatch = False
1976 haspatch = False
1991 for hunk in patch.split(pf):
1977 for hunk in patch.split(pf):
1992 commitid = tryone(ui, hunk)
1978 commitid = tryone(ui, hunk)
1993 if commitid:
1979 if commitid:
1994 haspatch = True
1980 haspatch = True
1995 if lastcommit:
1981 if lastcommit:
1996 ui.status(_('applied %s\n') % lastcommit)
1982 ui.status(_('applied %s\n') % lastcommit)
1997 lastcommit = commitid
1983 lastcommit = commitid
1998
1984
1999 if not haspatch:
1985 if not haspatch:
2000 raise util.Abort(_('no diffs found'))
1986 raise util.Abort(_('no diffs found'))
2001
1987
2002 finally:
1988 finally:
2003 release(lock, wlock)
1989 release(lock, wlock)
2004
1990
2005 def incoming(ui, repo, source="default", **opts):
1991 def incoming(ui, repo, source="default", **opts):
2006 """show new changesets found in source
1992 """show new changesets found in source
2007
1993
2008 Show new changesets found in the specified path/URL or the default
1994 Show new changesets found in the specified path/URL or the default
2009 pull location. These are the changesets that would have been pulled
1995 pull location. These are the changesets that would have been pulled
2010 if a pull at the time you issued this command.
1996 if a pull at the time you issued this command.
2011
1997
2012 For remote repository, using --bundle avoids downloading the
1998 For remote repository, using --bundle avoids downloading the
2013 changesets twice if the incoming is followed by a pull.
1999 changesets twice if the incoming is followed by a pull.
2014
2000
2015 See pull for valid source format details.
2001 See pull for valid source format details.
2016 """
2002 """
2017 limit = cmdutil.loglimit(opts)
2003 limit = cmdutil.loglimit(opts)
2018 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2004 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2019 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2005 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2020 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2006 ui.status(_('comparing with %s\n') % url.hidepassword(source))
2021 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2007 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2022 if revs:
2008 if revs:
2023 revs = [other.lookup(rev) for rev in revs]
2009 revs = [other.lookup(rev) for rev in revs]
2024 common, incoming, rheads = repo.findcommonincoming(other, heads=revs,
2010 common, incoming, rheads = repo.findcommonincoming(other, heads=revs,
2025 force=opts["force"])
2011 force=opts["force"])
2026 if not incoming:
2012 if not incoming:
2027 try:
2013 try:
2028 os.unlink(opts["bundle"])
2014 os.unlink(opts["bundle"])
2029 except:
2015 except:
2030 pass
2016 pass
2031 ui.status(_("no changes found\n"))
2017 ui.status(_("no changes found\n"))
2032 return 1
2018 return 1
2033
2019
2034 cleanup = None
2020 cleanup = None
2035 try:
2021 try:
2036 fname = opts["bundle"]
2022 fname = opts["bundle"]
2037 if fname or not other.local():
2023 if fname or not other.local():
2038 # create a bundle (uncompressed if other repo is not local)
2024 # create a bundle (uncompressed if other repo is not local)
2039
2025
2040 if revs is None and other.capable('changegroupsubset'):
2026 if revs is None and other.capable('changegroupsubset'):
2041 revs = rheads
2027 revs = rheads
2042
2028
2043 if revs is None:
2029 if revs is None:
2044 cg = other.changegroup(incoming, "incoming")
2030 cg = other.changegroup(incoming, "incoming")
2045 else:
2031 else:
2046 cg = other.changegroupsubset(incoming, revs, 'incoming')
2032 cg = other.changegroupsubset(incoming, revs, 'incoming')
2047 bundletype = other.local() and "HG10BZ" or "HG10UN"
2033 bundletype = other.local() and "HG10BZ" or "HG10UN"
2048 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2034 fname = cleanup = changegroup.writebundle(cg, fname, bundletype)
2049 # keep written bundle?
2035 # keep written bundle?
2050 if opts["bundle"]:
2036 if opts["bundle"]:
2051 cleanup = None
2037 cleanup = None
2052 if not other.local():
2038 if not other.local():
2053 # use the created uncompressed bundlerepo
2039 # use the created uncompressed bundlerepo
2054 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2040 other = bundlerepo.bundlerepository(ui, repo.root, fname)
2055
2041
2056 o = other.changelog.nodesbetween(incoming, revs)[0]
2042 o = other.changelog.nodesbetween(incoming, revs)[0]
2057 if opts.get('newest_first'):
2043 if opts.get('newest_first'):
2058 o.reverse()
2044 o.reverse()
2059 displayer = cmdutil.show_changeset(ui, other, opts)
2045 displayer = cmdutil.show_changeset(ui, other, opts)
2060 count = 0
2046 count = 0
2061 for n in o:
2047 for n in o:
2062 if limit is not None and count >= limit:
2048 if limit is not None and count >= limit:
2063 break
2049 break
2064 parents = [p for p in other.changelog.parents(n) if p != nullid]
2050 parents = [p for p in other.changelog.parents(n) if p != nullid]
2065 if opts.get('no_merges') and len(parents) == 2:
2051 if opts.get('no_merges') and len(parents) == 2:
2066 continue
2052 continue
2067 count += 1
2053 count += 1
2068 displayer.show(other[n])
2054 displayer.show(other[n])
2069 displayer.close()
2055 displayer.close()
2070 finally:
2056 finally:
2071 if hasattr(other, 'close'):
2057 if hasattr(other, 'close'):
2072 other.close()
2058 other.close()
2073 if cleanup:
2059 if cleanup:
2074 os.unlink(cleanup)
2060 os.unlink(cleanup)
2075
2061
2076 def init(ui, dest=".", **opts):
2062 def init(ui, dest=".", **opts):
2077 """create a new repository in the given directory
2063 """create a new repository in the given directory
2078
2064
2079 Initialize a new repository in the given directory. If the given
2065 Initialize a new repository in the given directory. If the given
2080 directory does not exist, it will be created.
2066 directory does not exist, it will be created.
2081
2067
2082 If no directory is given, the current directory is used.
2068 If no directory is given, the current directory is used.
2083
2069
2084 It is possible to specify an ``ssh://`` URL as the destination.
2070 It is possible to specify an ``ssh://`` URL as the destination.
2085 See :hg:`help urls` for more information.
2071 See :hg:`help urls` for more information.
2086 """
2072 """
2087 hg.repository(cmdutil.remoteui(ui, opts), dest, create=1)
2073 hg.repository(cmdutil.remoteui(ui, opts), dest, create=1)
2088
2074
2089 def locate(ui, repo, *pats, **opts):
2075 def locate(ui, repo, *pats, **opts):
2090 """locate files matching specific patterns
2076 """locate files matching specific patterns
2091
2077
2092 Print files under Mercurial control in the working directory whose
2078 Print files under Mercurial control in the working directory whose
2093 names match the given patterns.
2079 names match the given patterns.
2094
2080
2095 By default, this command searches all directories in the working
2081 By default, this command searches all directories in the working
2096 directory. To search just the current directory and its
2082 directory. To search just the current directory and its
2097 subdirectories, use "--include .".
2083 subdirectories, use "--include .".
2098
2084
2099 If no patterns are given to match, this command prints the names
2085 If no patterns are given to match, this command prints the names
2100 of all files under Mercurial control in the working directory.
2086 of all files under Mercurial control in the working directory.
2101
2087
2102 If you want to feed the output of this command into the "xargs"
2088 If you want to feed the output of this command into the "xargs"
2103 command, use the -0 option to both this command and "xargs". This
2089 command, use the -0 option to both this command and "xargs". This
2104 will avoid the problem of "xargs" treating single filenames that
2090 will avoid the problem of "xargs" treating single filenames that
2105 contain whitespace as multiple filenames.
2091 contain whitespace as multiple filenames.
2106 """
2092 """
2107 end = opts.get('print0') and '\0' or '\n'
2093 end = opts.get('print0') and '\0' or '\n'
2108 rev = opts.get('rev') or None
2094 rev = opts.get('rev') or None
2109
2095
2110 ret = 1
2096 ret = 1
2111 m = cmdutil.match(repo, pats, opts, default='relglob')
2097 m = cmdutil.match(repo, pats, opts, default='relglob')
2112 m.bad = lambda x, y: False
2098 m.bad = lambda x, y: False
2113 for abs in repo[rev].walk(m):
2099 for abs in repo[rev].walk(m):
2114 if not rev and abs not in repo.dirstate:
2100 if not rev and abs not in repo.dirstate:
2115 continue
2101 continue
2116 if opts.get('fullpath'):
2102 if opts.get('fullpath'):
2117 ui.write(repo.wjoin(abs), end)
2103 ui.write(repo.wjoin(abs), end)
2118 else:
2104 else:
2119 ui.write(((pats and m.rel(abs)) or abs), end)
2105 ui.write(((pats and m.rel(abs)) or abs), end)
2120 ret = 0
2106 ret = 0
2121
2107
2122 return ret
2108 return ret
2123
2109
2124 def log(ui, repo, *pats, **opts):
2110 def log(ui, repo, *pats, **opts):
2125 """show revision history of entire repository or files
2111 """show revision history of entire repository or files
2126
2112
2127 Print the revision history of the specified files or the entire
2113 Print the revision history of the specified files or the entire
2128 project.
2114 project.
2129
2115
2130 File history is shown without following rename or copy history of
2116 File history is shown without following rename or copy history of
2131 files. Use -f/--follow with a filename to follow history across
2117 files. Use -f/--follow with a filename to follow history across
2132 renames and copies. --follow without a filename will only show
2118 renames and copies. --follow without a filename will only show
2133 ancestors or descendants of the starting revision. --follow-first
2119 ancestors or descendants of the starting revision. --follow-first
2134 only follows the first parent of merge revisions.
2120 only follows the first parent of merge revisions.
2135
2121
2136 If no revision range is specified, the default is tip:0 unless
2122 If no revision range is specified, the default is tip:0 unless
2137 --follow is set, in which case the working directory parent is
2123 --follow is set, in which case the working directory parent is
2138 used as the starting revision.
2124 used as the starting revision.
2139
2125
2140 See :hg:`help dates` for a list of formats valid for -d/--date.
2126 See :hg:`help dates` for a list of formats valid for -d/--date.
2141
2127
2142 By default this command prints revision number and changeset id,
2128 By default this command prints revision number and changeset id,
2143 tags, non-trivial parents, user, date and time, and a summary for
2129 tags, non-trivial parents, user, date and time, and a summary for
2144 each commit. When the -v/--verbose switch is used, the list of
2130 each commit. When the -v/--verbose switch is used, the list of
2145 changed files and full commit message are shown.
2131 changed files and full commit message are shown.
2146
2132
2147 NOTE: log -p/--patch may generate unexpected diff output for merge
2133 NOTE: log -p/--patch may generate unexpected diff output for merge
2148 changesets, as it will only compare the merge changeset against
2134 changesets, as it will only compare the merge changeset against
2149 its first parent. Also, only files different from BOTH parents
2135 its first parent. Also, only files different from BOTH parents
2150 will appear in files:.
2136 will appear in files:.
2151 """
2137 """
2152
2138
2153 matchfn = cmdutil.match(repo, pats, opts)
2139 matchfn = cmdutil.match(repo, pats, opts)
2154 limit = cmdutil.loglimit(opts)
2140 limit = cmdutil.loglimit(opts)
2155 count = 0
2141 count = 0
2156
2142
2157 endrev = None
2143 endrev = None
2158 if opts.get('copies') and opts.get('rev'):
2144 if opts.get('copies') and opts.get('rev'):
2159 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2145 endrev = max(cmdutil.revrange(repo, opts.get('rev'))) + 1
2160
2146
2161 df = False
2147 df = False
2162 if opts["date"]:
2148 if opts["date"]:
2163 df = util.matchdate(opts["date"])
2149 df = util.matchdate(opts["date"])
2164
2150
2165 branches = opts.get('branch', []) + opts.get('only_branch', [])
2151 branches = opts.get('branch', []) + opts.get('only_branch', [])
2166 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2152 opts['branch'] = [repo.lookupbranch(b) for b in branches]
2167
2153
2168 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
2154 displayer = cmdutil.show_changeset(ui, repo, opts, True, matchfn)
2169 def prep(ctx, fns):
2155 def prep(ctx, fns):
2170 rev = ctx.rev()
2156 rev = ctx.rev()
2171 parents = [p for p in repo.changelog.parentrevs(rev)
2157 parents = [p for p in repo.changelog.parentrevs(rev)
2172 if p != nullrev]
2158 if p != nullrev]
2173 if opts.get('no_merges') and len(parents) == 2:
2159 if opts.get('no_merges') and len(parents) == 2:
2174 return
2160 return
2175 if opts.get('only_merges') and len(parents) != 2:
2161 if opts.get('only_merges') and len(parents) != 2:
2176 return
2162 return
2177 if opts.get('branch') and ctx.branch() not in opts['branch']:
2163 if opts.get('branch') and ctx.branch() not in opts['branch']:
2178 return
2164 return
2179 if df and not df(ctx.date()[0]):
2165 if df and not df(ctx.date()[0]):
2180 return
2166 return
2181 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2167 if opts['user'] and not [k for k in opts['user'] if k in ctx.user()]:
2182 return
2168 return
2183 if opts.get('keyword'):
2169 if opts.get('keyword'):
2184 for k in [kw.lower() for kw in opts['keyword']]:
2170 for k in [kw.lower() for kw in opts['keyword']]:
2185 if (k in ctx.user().lower() or
2171 if (k in ctx.user().lower() or
2186 k in ctx.description().lower() or
2172 k in ctx.description().lower() or
2187 k in " ".join(ctx.files()).lower()):
2173 k in " ".join(ctx.files()).lower()):
2188 break
2174 break
2189 else:
2175 else:
2190 return
2176 return
2191
2177
2192 copies = None
2178 copies = None
2193 if opts.get('copies') and rev:
2179 if opts.get('copies') and rev:
2194 copies = []
2180 copies = []
2195 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2181 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
2196 for fn in ctx.files():
2182 for fn in ctx.files():
2197 rename = getrenamed(fn, rev)
2183 rename = getrenamed(fn, rev)
2198 if rename:
2184 if rename:
2199 copies.append((fn, rename[0]))
2185 copies.append((fn, rename[0]))
2200
2186
2201 displayer.show(ctx, copies=copies)
2187 displayer.show(ctx, copies=copies)
2202
2188
2203 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2189 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2204 if count == limit:
2190 if count == limit:
2205 break
2191 break
2206 if displayer.flush(ctx.rev()):
2192 if displayer.flush(ctx.rev()):
2207 count += 1
2193 count += 1
2208 displayer.close()
2194 displayer.close()
2209
2195
2210 def manifest(ui, repo, node=None, rev=None):
2196 def manifest(ui, repo, node=None, rev=None):
2211 """output the current or given revision of the project manifest
2197 """output the current or given revision of the project manifest
2212
2198
2213 Print a list of version controlled files for the given revision.
2199 Print a list of version controlled files for the given revision.
2214 If no revision is given, the first parent of the working directory
2200 If no revision is given, the first parent of the working directory
2215 is used, or the null revision if no revision is checked out.
2201 is used, or the null revision if no revision is checked out.
2216
2202
2217 With -v, print file permissions, symlink and executable bits.
2203 With -v, print file permissions, symlink and executable bits.
2218 With --debug, print file revision hashes.
2204 With --debug, print file revision hashes.
2219 """
2205 """
2220
2206
2221 if rev and node:
2207 if rev and node:
2222 raise util.Abort(_("please specify just one revision"))
2208 raise util.Abort(_("please specify just one revision"))
2223
2209
2224 if not node:
2210 if not node:
2225 node = rev
2211 node = rev
2226
2212
2227 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2213 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
2228 ctx = repo[node]
2214 ctx = repo[node]
2229 for f in ctx:
2215 for f in ctx:
2230 if ui.debugflag:
2216 if ui.debugflag:
2231 ui.write("%40s " % hex(ctx.manifest()[f]))
2217 ui.write("%40s " % hex(ctx.manifest()[f]))
2232 if ui.verbose:
2218 if ui.verbose:
2233 ui.write(decor[ctx.flags(f)])
2219 ui.write(decor[ctx.flags(f)])
2234 ui.write("%s\n" % f)
2220 ui.write("%s\n" % f)
2235
2221
2236 def merge(ui, repo, node=None, **opts):
2222 def merge(ui, repo, node=None, **opts):
2237 """merge working directory with another revision
2223 """merge working directory with another revision
2238
2224
2239 The current working directory is updated with all changes made in
2225 The current working directory is updated with all changes made in
2240 the requested revision since the last common predecessor revision.
2226 the requested revision since the last common predecessor revision.
2241
2227
2242 Files that changed between either parent are marked as changed for
2228 Files that changed between either parent are marked as changed for
2243 the next commit and a commit must be performed before any further
2229 the next commit and a commit must be performed before any further
2244 updates to the repository are allowed. The next commit will have
2230 updates to the repository are allowed. The next commit will have
2245 two parents.
2231 two parents.
2246
2232
2247 If no revision is specified, the working directory's parent is a
2233 If no revision is specified, the working directory's parent is a
2248 head revision, and the current branch contains exactly one other
2234 head revision, and the current branch contains exactly one other
2249 head, the other head is merged with by default. Otherwise, an
2235 head, the other head is merged with by default. Otherwise, an
2250 explicit revision with which to merge with must be provided.
2236 explicit revision with which to merge with must be provided.
2251 """
2237 """
2252
2238
2253 if opts.get('rev') and node:
2239 if opts.get('rev') and node:
2254 raise util.Abort(_("please specify just one revision"))
2240 raise util.Abort(_("please specify just one revision"))
2255 if not node:
2241 if not node:
2256 node = opts.get('rev')
2242 node = opts.get('rev')
2257
2243
2258 if not node:
2244 if not node:
2259 branch = repo.changectx(None).branch()
2245 branch = repo.changectx(None).branch()
2260 bheads = repo.branchheads(branch)
2246 bheads = repo.branchheads(branch)
2261 if len(bheads) > 2:
2247 if len(bheads) > 2:
2262 ui.warn(_("abort: branch '%s' has %d heads - "
2248 ui.warn(_("abort: branch '%s' has %d heads - "
2263 "please merge with an explicit rev\n")
2249 "please merge with an explicit rev\n")
2264 % (branch, len(bheads)))
2250 % (branch, len(bheads)))
2265 ui.status(_("(run 'hg heads .' to see heads)\n"))
2251 ui.status(_("(run 'hg heads .' to see heads)\n"))
2266 return False
2252 return False
2267
2253
2268 parent = repo.dirstate.parents()[0]
2254 parent = repo.dirstate.parents()[0]
2269 if len(bheads) == 1:
2255 if len(bheads) == 1:
2270 if len(repo.heads()) > 1:
2256 if len(repo.heads()) > 1:
2271 ui.warn(_("abort: branch '%s' has one head - "
2257 ui.warn(_("abort: branch '%s' has one head - "
2272 "please merge with an explicit rev\n" % branch))
2258 "please merge with an explicit rev\n" % branch))
2273 ui.status(_("(run 'hg heads' to see all heads)\n"))
2259 ui.status(_("(run 'hg heads' to see all heads)\n"))
2274 return False
2260 return False
2275 msg = _('there is nothing to merge')
2261 msg = _('there is nothing to merge')
2276 if parent != repo.lookup(repo[None].branch()):
2262 if parent != repo.lookup(repo[None].branch()):
2277 msg = _('%s - use "hg update" instead') % msg
2263 msg = _('%s - use "hg update" instead') % msg
2278 raise util.Abort(msg)
2264 raise util.Abort(msg)
2279
2265
2280 if parent not in bheads:
2266 if parent not in bheads:
2281 raise util.Abort(_('working dir not at a head rev - '
2267 raise util.Abort(_('working dir not at a head rev - '
2282 'use "hg update" or merge with an explicit rev'))
2268 'use "hg update" or merge with an explicit rev'))
2283 node = parent == bheads[0] and bheads[-1] or bheads[0]
2269 node = parent == bheads[0] and bheads[-1] or bheads[0]
2284
2270
2285 if opts.get('preview'):
2271 if opts.get('preview'):
2286 # find nodes that are ancestors of p2 but not of p1
2272 # find nodes that are ancestors of p2 but not of p1
2287 p1 = repo.lookup('.')
2273 p1 = repo.lookup('.')
2288 p2 = repo.lookup(node)
2274 p2 = repo.lookup(node)
2289 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2275 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
2290
2276
2291 displayer = cmdutil.show_changeset(ui, repo, opts)
2277 displayer = cmdutil.show_changeset(ui, repo, opts)
2292 for node in nodes:
2278 for node in nodes:
2293 displayer.show(repo[node])
2279 displayer.show(repo[node])
2294 displayer.close()
2280 displayer.close()
2295 return 0
2281 return 0
2296
2282
2297 return hg.merge(repo, node, force=opts.get('force'))
2283 return hg.merge(repo, node, force=opts.get('force'))
2298
2284
2299 def outgoing(ui, repo, dest=None, **opts):
2285 def outgoing(ui, repo, dest=None, **opts):
2300 """show changesets not found in the destination
2286 """show changesets not found in the destination
2301
2287
2302 Show changesets not found in the specified destination repository
2288 Show changesets not found in the specified destination repository
2303 or the default push location. These are the changesets that would
2289 or the default push location. These are the changesets that would
2304 be pushed if a push was requested.
2290 be pushed if a push was requested.
2305
2291
2306 See pull for details of valid destination formats.
2292 See pull for details of valid destination formats.
2307 """
2293 """
2308 limit = cmdutil.loglimit(opts)
2294 limit = cmdutil.loglimit(opts)
2309 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2295 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2310 dest, branches = hg.parseurl(dest, opts.get('branch'))
2296 dest, branches = hg.parseurl(dest, opts.get('branch'))
2311 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2297 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2312 if revs:
2298 if revs:
2313 revs = [repo.lookup(rev) for rev in revs]
2299 revs = [repo.lookup(rev) for rev in revs]
2314
2300
2315 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2301 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2316 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2302 ui.status(_('comparing with %s\n') % url.hidepassword(dest))
2317 o = repo.findoutgoing(other, force=opts.get('force'))
2303 o = repo.findoutgoing(other, force=opts.get('force'))
2318 if not o:
2304 if not o:
2319 ui.status(_("no changes found\n"))
2305 ui.status(_("no changes found\n"))
2320 return 1
2306 return 1
2321 o = repo.changelog.nodesbetween(o, revs)[0]
2307 o = repo.changelog.nodesbetween(o, revs)[0]
2322 if opts.get('newest_first'):
2308 if opts.get('newest_first'):
2323 o.reverse()
2309 o.reverse()
2324 displayer = cmdutil.show_changeset(ui, repo, opts)
2310 displayer = cmdutil.show_changeset(ui, repo, opts)
2325 count = 0
2311 count = 0
2326 for n in o:
2312 for n in o:
2327 if limit is not None and count >= limit:
2313 if limit is not None and count >= limit:
2328 break
2314 break
2329 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2315 parents = [p for p in repo.changelog.parents(n) if p != nullid]
2330 if opts.get('no_merges') and len(parents) == 2:
2316 if opts.get('no_merges') and len(parents) == 2:
2331 continue
2317 continue
2332 count += 1
2318 count += 1
2333 displayer.show(repo[n])
2319 displayer.show(repo[n])
2334 displayer.close()
2320 displayer.close()
2335
2321
2336 def parents(ui, repo, file_=None, **opts):
2322 def parents(ui, repo, file_=None, **opts):
2337 """show the parents of the working directory or revision
2323 """show the parents of the working directory or revision
2338
2324
2339 Print the working directory's parent revisions. If a revision is
2325 Print the working directory's parent revisions. If a revision is
2340 given via -r/--rev, the parent of that revision will be printed.
2326 given via -r/--rev, the parent of that revision will be printed.
2341 If a file argument is given, the revision in which the file was
2327 If a file argument is given, the revision in which the file was
2342 last changed (before the working directory revision or the
2328 last changed (before the working directory revision or the
2343 argument to --rev if given) is printed.
2329 argument to --rev if given) is printed.
2344 """
2330 """
2345 rev = opts.get('rev')
2331 rev = opts.get('rev')
2346 if rev:
2332 if rev:
2347 ctx = repo[rev]
2333 ctx = repo[rev]
2348 else:
2334 else:
2349 ctx = repo[None]
2335 ctx = repo[None]
2350
2336
2351 if file_:
2337 if file_:
2352 m = cmdutil.match(repo, (file_,), opts)
2338 m = cmdutil.match(repo, (file_,), opts)
2353 if m.anypats() or len(m.files()) != 1:
2339 if m.anypats() or len(m.files()) != 1:
2354 raise util.Abort(_('can only specify an explicit filename'))
2340 raise util.Abort(_('can only specify an explicit filename'))
2355 file_ = m.files()[0]
2341 file_ = m.files()[0]
2356 filenodes = []
2342 filenodes = []
2357 for cp in ctx.parents():
2343 for cp in ctx.parents():
2358 if not cp:
2344 if not cp:
2359 continue
2345 continue
2360 try:
2346 try:
2361 filenodes.append(cp.filenode(file_))
2347 filenodes.append(cp.filenode(file_))
2362 except error.LookupError:
2348 except error.LookupError:
2363 pass
2349 pass
2364 if not filenodes:
2350 if not filenodes:
2365 raise util.Abort(_("'%s' not found in manifest!") % file_)
2351 raise util.Abort(_("'%s' not found in manifest!") % file_)
2366 fl = repo.file(file_)
2352 fl = repo.file(file_)
2367 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2353 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
2368 else:
2354 else:
2369 p = [cp.node() for cp in ctx.parents()]
2355 p = [cp.node() for cp in ctx.parents()]
2370
2356
2371 displayer = cmdutil.show_changeset(ui, repo, opts)
2357 displayer = cmdutil.show_changeset(ui, repo, opts)
2372 for n in p:
2358 for n in p:
2373 if n != nullid:
2359 if n != nullid:
2374 displayer.show(repo[n])
2360 displayer.show(repo[n])
2375 displayer.close()
2361 displayer.close()
2376
2362
2377 def paths(ui, repo, search=None):
2363 def paths(ui, repo, search=None):
2378 """show aliases for remote repositories
2364 """show aliases for remote repositories
2379
2365
2380 Show definition of symbolic path name NAME. If no name is given,
2366 Show definition of symbolic path name NAME. If no name is given,
2381 show definition of all available names.
2367 show definition of all available names.
2382
2368
2383 Path names are defined in the [paths] section of
2369 Path names are defined in the [paths] section of
2384 ``/etc/mercurial/hgrc`` and ``$HOME/.hgrc``. If run inside a
2370 ``/etc/mercurial/hgrc`` and ``$HOME/.hgrc``. If run inside a
2385 repository, ``.hg/hgrc`` is used, too.
2371 repository, ``.hg/hgrc`` is used, too.
2386
2372
2387 The path names ``default`` and ``default-push`` have a special
2373 The path names ``default`` and ``default-push`` have a special
2388 meaning. When performing a push or pull operation, they are used
2374 meaning. When performing a push or pull operation, they are used
2389 as fallbacks if no location is specified on the command-line.
2375 as fallbacks if no location is specified on the command-line.
2390 When ``default-push`` is set, it will be used for push and
2376 When ``default-push`` is set, it will be used for push and
2391 ``default`` will be used for pull; otherwise ``default`` is used
2377 ``default`` will be used for pull; otherwise ``default`` is used
2392 as the fallback for both. When cloning a repository, the clone
2378 as the fallback for both. When cloning a repository, the clone
2393 source is written as ``default`` in ``.hg/hgrc``. Note that
2379 source is written as ``default`` in ``.hg/hgrc``. Note that
2394 ``default`` and ``default-push`` apply to all inbound (e.g.
2380 ``default`` and ``default-push`` apply to all inbound (e.g.
2395 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2381 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
2396 :hg:`bundle`) operations.
2382 :hg:`bundle`) operations.
2397
2383
2398 See :hg:`help urls` for more information.
2384 See :hg:`help urls` for more information.
2399 """
2385 """
2400 if search:
2386 if search:
2401 for name, path in ui.configitems("paths"):
2387 for name, path in ui.configitems("paths"):
2402 if name == search:
2388 if name == search:
2403 ui.write("%s\n" % url.hidepassword(path))
2389 ui.write("%s\n" % url.hidepassword(path))
2404 return
2390 return
2405 ui.warn(_("not found!\n"))
2391 ui.warn(_("not found!\n"))
2406 return 1
2392 return 1
2407 else:
2393 else:
2408 for name, path in ui.configitems("paths"):
2394 for name, path in ui.configitems("paths"):
2409 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2395 ui.write("%s = %s\n" % (name, url.hidepassword(path)))
2410
2396
2411 def postincoming(ui, repo, modheads, optupdate, checkout):
2397 def postincoming(ui, repo, modheads, optupdate, checkout):
2412 if modheads == 0:
2398 if modheads == 0:
2413 return
2399 return
2414 if optupdate:
2400 if optupdate:
2415 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2401 if (modheads <= 1 or len(repo.branchheads()) == 1) or checkout:
2416 return hg.update(repo, checkout)
2402 return hg.update(repo, checkout)
2417 else:
2403 else:
2418 ui.status(_("not updating, since new heads added\n"))
2404 ui.status(_("not updating, since new heads added\n"))
2419 if modheads > 1:
2405 if modheads > 1:
2420 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2406 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
2421 else:
2407 else:
2422 ui.status(_("(run 'hg update' to get a working copy)\n"))
2408 ui.status(_("(run 'hg update' to get a working copy)\n"))
2423
2409
2424 def pull(ui, repo, source="default", **opts):
2410 def pull(ui, repo, source="default", **opts):
2425 """pull changes from the specified source
2411 """pull changes from the specified source
2426
2412
2427 Pull changes from a remote repository to a local one.
2413 Pull changes from a remote repository to a local one.
2428
2414
2429 This finds all changes from the repository at the specified path
2415 This finds all changes from the repository at the specified path
2430 or URL and adds them to a local repository (the current one unless
2416 or URL and adds them to a local repository (the current one unless
2431 -R is specified). By default, this does not update the copy of the
2417 -R is specified). By default, this does not update the copy of the
2432 project in the working directory.
2418 project in the working directory.
2433
2419
2434 Use hg incoming if you want to see what would have been added by a
2420 Use hg incoming if you want to see what would have been added by a
2435 pull at the time you issued this command. If you then decide to
2421 pull at the time you issued this command. If you then decide to
2436 added those changes to the repository, you should use pull -r X
2422 added those changes to the repository, you should use pull -r X
2437 where X is the last changeset listed by hg incoming.
2423 where X is the last changeset listed by hg incoming.
2438
2424
2439 If SOURCE is omitted, the 'default' path will be used.
2425 If SOURCE is omitted, the 'default' path will be used.
2440 See :hg:`help urls` for more information.
2426 See :hg:`help urls` for more information.
2441 """
2427 """
2442 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2428 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
2443 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2429 other = hg.repository(cmdutil.remoteui(repo, opts), source)
2444 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2430 ui.status(_('pulling from %s\n') % url.hidepassword(source))
2445 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2431 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
2446 if revs:
2432 if revs:
2447 try:
2433 try:
2448 revs = [other.lookup(rev) for rev in revs]
2434 revs = [other.lookup(rev) for rev in revs]
2449 except error.CapabilityError:
2435 except error.CapabilityError:
2450 err = _("Other repository doesn't support revision lookup, "
2436 err = _("Other repository doesn't support revision lookup, "
2451 "so a rev cannot be specified.")
2437 "so a rev cannot be specified.")
2452 raise util.Abort(err)
2438 raise util.Abort(err)
2453
2439
2454 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2440 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
2455 if checkout:
2441 if checkout:
2456 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2442 checkout = str(repo.changelog.rev(other.lookup(checkout)))
2457 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2443 return postincoming(ui, repo, modheads, opts.get('update'), checkout)
2458
2444
2459 def push(ui, repo, dest=None, **opts):
2445 def push(ui, repo, dest=None, **opts):
2460 """push changes to the specified destination
2446 """push changes to the specified destination
2461
2447
2462 Push changes from the local repository to the specified destination.
2448 Push changes from the local repository to the specified destination.
2463
2449
2464 This is the symmetrical operation for pull. It moves changes from
2450 This is the symmetrical operation for pull. It moves changes from
2465 the current repository to a different one. If the destination is
2451 the current repository to a different one. If the destination is
2466 local this is identical to a pull in that directory from the
2452 local this is identical to a pull in that directory from the
2467 current one.
2453 current one.
2468
2454
2469 By default, push will refuse to run if it detects the result would
2455 By default, push will refuse to run if it detects the result would
2470 increase the number of remote heads. This generally indicates the
2456 increase the number of remote heads. This generally indicates the
2471 user forgot to pull and merge before pushing.
2457 user forgot to pull and merge before pushing.
2472
2458
2473 If -r/--rev is used, the named revision and all its ancestors will
2459 If -r/--rev is used, the named revision and all its ancestors will
2474 be pushed to the remote repository.
2460 be pushed to the remote repository.
2475
2461
2476 Please see :hg:`help urls` for important details about ``ssh://``
2462 Please see :hg:`help urls` for important details about ``ssh://``
2477 URLs. If DESTINATION is omitted, a default path will be used.
2463 URLs. If DESTINATION is omitted, a default path will be used.
2478 """
2464 """
2479 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2465 dest = ui.expandpath(dest or 'default-push', dest or 'default')
2480 dest, branches = hg.parseurl(dest, opts.get('branch'))
2466 dest, branches = hg.parseurl(dest, opts.get('branch'))
2481 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2467 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
2482 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2468 other = hg.repository(cmdutil.remoteui(repo, opts), dest)
2483 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2469 ui.status(_('pushing to %s\n') % url.hidepassword(dest))
2484 if revs:
2470 if revs:
2485 revs = [repo.lookup(rev) for rev in revs]
2471 revs = [repo.lookup(rev) for rev in revs]
2486
2472
2487 # push subrepos depth-first for coherent ordering
2473 # push subrepos depth-first for coherent ordering
2488 c = repo['']
2474 c = repo['']
2489 subs = c.substate # only repos that are committed
2475 subs = c.substate # only repos that are committed
2490 for s in sorted(subs):
2476 for s in sorted(subs):
2491 c.sub(s).push(opts.get('force'))
2477 c.sub(s).push(opts.get('force'))
2492
2478
2493 r = repo.push(other, opts.get('force'), revs=revs)
2479 r = repo.push(other, opts.get('force'), revs=revs)
2494 return r == 0
2480 return r == 0
2495
2481
2496 def recover(ui, repo):
2482 def recover(ui, repo):
2497 """roll back an interrupted transaction
2483 """roll back an interrupted transaction
2498
2484
2499 Recover from an interrupted commit or pull.
2485 Recover from an interrupted commit or pull.
2500
2486
2501 This command tries to fix the repository status after an
2487 This command tries to fix the repository status after an
2502 interrupted operation. It should only be necessary when Mercurial
2488 interrupted operation. It should only be necessary when Mercurial
2503 suggests it.
2489 suggests it.
2504 """
2490 """
2505 if repo.recover():
2491 if repo.recover():
2506 return hg.verify(repo)
2492 return hg.verify(repo)
2507 return 1
2493 return 1
2508
2494
2509 def remove(ui, repo, *pats, **opts):
2495 def remove(ui, repo, *pats, **opts):
2510 """remove the specified files on the next commit
2496 """remove the specified files on the next commit
2511
2497
2512 Schedule the indicated files for removal from the repository.
2498 Schedule the indicated files for removal from the repository.
2513
2499
2514 This only removes files from the current branch, not from the
2500 This only removes files from the current branch, not from the
2515 entire project history. -A/--after can be used to remove only
2501 entire project history. -A/--after can be used to remove only
2516 files that have already been deleted, -f/--force can be used to
2502 files that have already been deleted, -f/--force can be used to
2517 force deletion, and -Af can be used to remove files from the next
2503 force deletion, and -Af can be used to remove files from the next
2518 revision without deleting them from the working directory.
2504 revision without deleting them from the working directory.
2519
2505
2520 The following table details the behavior of remove for different
2506 The following table details the behavior of remove for different
2521 file states (columns) and option combinations (rows). The file
2507 file states (columns) and option combinations (rows). The file
2522 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2508 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
2523 reported by hg status). The actions are Warn, Remove (from branch)
2509 reported by hg status). The actions are Warn, Remove (from branch)
2524 and Delete (from disk)::
2510 and Delete (from disk)::
2525
2511
2526 A C M !
2512 A C M !
2527 none W RD W R
2513 none W RD W R
2528 -f R RD RD R
2514 -f R RD RD R
2529 -A W W W R
2515 -A W W W R
2530 -Af R R R R
2516 -Af R R R R
2531
2517
2532 This command schedules the files to be removed at the next commit.
2518 This command schedules the files to be removed at the next commit.
2533 To undo a remove before that, see hg revert.
2519 To undo a remove before that, see hg revert.
2534 """
2520 """
2535
2521
2536 after, force = opts.get('after'), opts.get('force')
2522 after, force = opts.get('after'), opts.get('force')
2537 if not pats and not after:
2523 if not pats and not after:
2538 raise util.Abort(_('no files specified'))
2524 raise util.Abort(_('no files specified'))
2539
2525
2540 m = cmdutil.match(repo, pats, opts)
2526 m = cmdutil.match(repo, pats, opts)
2541 s = repo.status(match=m, clean=True)
2527 s = repo.status(match=m, clean=True)
2542 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2528 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2543
2529
2544 for f in m.files():
2530 for f in m.files():
2545 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2531 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2546 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2532 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
2547
2533
2548 def warn(files, reason):
2534 def warn(files, reason):
2549 for f in files:
2535 for f in files:
2550 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2536 ui.warn(_('not removing %s: file %s (use -f to force removal)\n')
2551 % (m.rel(f), reason))
2537 % (m.rel(f), reason))
2552
2538
2553 if force:
2539 if force:
2554 remove, forget = modified + deleted + clean, added
2540 remove, forget = modified + deleted + clean, added
2555 elif after:
2541 elif after:
2556 remove, forget = deleted, []
2542 remove, forget = deleted, []
2557 warn(modified + added + clean, _('still exists'))
2543 warn(modified + added + clean, _('still exists'))
2558 else:
2544 else:
2559 remove, forget = deleted + clean, []
2545 remove, forget = deleted + clean, []
2560 warn(modified, _('is modified'))
2546 warn(modified, _('is modified'))
2561 warn(added, _('has been marked for add'))
2547 warn(added, _('has been marked for add'))
2562
2548
2563 for f in sorted(remove + forget):
2549 for f in sorted(remove + forget):
2564 if ui.verbose or not m.exact(f):
2550 if ui.verbose or not m.exact(f):
2565 ui.status(_('removing %s\n') % m.rel(f))
2551 ui.status(_('removing %s\n') % m.rel(f))
2566
2552
2567 repo.forget(forget)
2553 repo.forget(forget)
2568 repo.remove(remove, unlink=not after)
2554 repo.remove(remove, unlink=not after)
2569
2555
2570 def rename(ui, repo, *pats, **opts):
2556 def rename(ui, repo, *pats, **opts):
2571 """rename files; equivalent of copy + remove
2557 """rename files; equivalent of copy + remove
2572
2558
2573 Mark dest as copies of sources; mark sources for deletion. If dest
2559 Mark dest as copies of sources; mark sources for deletion. If dest
2574 is a directory, copies are put in that directory. If dest is a
2560 is a directory, copies are put in that directory. If dest is a
2575 file, there can only be one source.
2561 file, there can only be one source.
2576
2562
2577 By default, this command copies the contents of files as they
2563 By default, this command copies the contents of files as they
2578 exist in the working directory. If invoked with -A/--after, the
2564 exist in the working directory. If invoked with -A/--after, the
2579 operation is recorded, but no copying is performed.
2565 operation is recorded, but no copying is performed.
2580
2566
2581 This command takes effect at the next commit. To undo a rename
2567 This command takes effect at the next commit. To undo a rename
2582 before that, see hg revert.
2568 before that, see hg revert.
2583 """
2569 """
2584 wlock = repo.wlock(False)
2570 wlock = repo.wlock(False)
2585 try:
2571 try:
2586 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2572 return cmdutil.copy(ui, repo, pats, opts, rename=True)
2587 finally:
2573 finally:
2588 wlock.release()
2574 wlock.release()
2589
2575
2590 def resolve(ui, repo, *pats, **opts):
2576 def resolve(ui, repo, *pats, **opts):
2591 """various operations to help finish a merge
2577 """various operations to help finish a merge
2592
2578
2593 This command includes several actions that are often useful while
2579 This command includes several actions that are often useful while
2594 performing a merge, after running ``merge`` but before running
2580 performing a merge, after running ``merge`` but before running
2595 ``commit``. (It is only meaningful if your working directory has
2581 ``commit``. (It is only meaningful if your working directory has
2596 two parents.) It is most relevant for merges with unresolved
2582 two parents.) It is most relevant for merges with unresolved
2597 conflicts, which are typically a result of non-interactive merging with
2583 conflicts, which are typically a result of non-interactive merging with
2598 ``internal:merge`` or a command-line merge tool like ``diff3``.
2584 ``internal:merge`` or a command-line merge tool like ``diff3``.
2599
2585
2600 The available actions are:
2586 The available actions are:
2601
2587
2602 1) list files that were merged with conflicts (U, for unresolved)
2588 1) list files that were merged with conflicts (U, for unresolved)
2603 and without conflicts (R, for resolved): ``hg resolve -l``
2589 and without conflicts (R, for resolved): ``hg resolve -l``
2604 (this is like ``status`` for merges)
2590 (this is like ``status`` for merges)
2605 2) record that you have resolved conflicts in certain files:
2591 2) record that you have resolved conflicts in certain files:
2606 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2592 ``hg resolve -m [file ...]`` (default: mark all unresolved files)
2607 3) forget that you have resolved conflicts in certain files:
2593 3) forget that you have resolved conflicts in certain files:
2608 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2594 ``hg resolve -u [file ...]`` (default: unmark all resolved files)
2609 4) discard your current attempt(s) at resolving conflicts and
2595 4) discard your current attempt(s) at resolving conflicts and
2610 restart the merge from scratch: ``hg resolve file...``
2596 restart the merge from scratch: ``hg resolve file...``
2611 (or ``-a`` for all unresolved files)
2597 (or ``-a`` for all unresolved files)
2612
2598
2613 Note that Mercurial will not let you commit files with unresolved merge
2599 Note that Mercurial will not let you commit files with unresolved merge
2614 conflicts. You must use ``hg resolve -m ...`` before you can commit
2600 conflicts. You must use ``hg resolve -m ...`` before you can commit
2615 after a conflicting merge.
2601 after a conflicting merge.
2616 """
2602 """
2617
2603
2618 all, mark, unmark, show, nostatus = \
2604 all, mark, unmark, show, nostatus = \
2619 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2605 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
2620
2606
2621 if (show and (mark or unmark)) or (mark and unmark):
2607 if (show and (mark or unmark)) or (mark and unmark):
2622 raise util.Abort(_("too many options specified"))
2608 raise util.Abort(_("too many options specified"))
2623 if pats and all:
2609 if pats and all:
2624 raise util.Abort(_("can't specify --all and patterns"))
2610 raise util.Abort(_("can't specify --all and patterns"))
2625 if not (all or pats or show or mark or unmark):
2611 if not (all or pats or show or mark or unmark):
2626 raise util.Abort(_('no files or directories specified; '
2612 raise util.Abort(_('no files or directories specified; '
2627 'use --all to remerge all files'))
2613 'use --all to remerge all files'))
2628
2614
2629 ms = mergemod.mergestate(repo)
2615 ms = mergemod.mergestate(repo)
2630 m = cmdutil.match(repo, pats, opts)
2616 m = cmdutil.match(repo, pats, opts)
2631
2617
2632 for f in ms:
2618 for f in ms:
2633 if m(f):
2619 if m(f):
2634 if show:
2620 if show:
2635 if nostatus:
2621 if nostatus:
2636 ui.write("%s\n" % f)
2622 ui.write("%s\n" % f)
2637 else:
2623 else:
2638 ui.write("%s %s\n" % (ms[f].upper(), f),
2624 ui.write("%s %s\n" % (ms[f].upper(), f),
2639 label='resolve.' +
2625 label='resolve.' +
2640 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
2626 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
2641 elif mark:
2627 elif mark:
2642 ms.mark(f, "r")
2628 ms.mark(f, "r")
2643 elif unmark:
2629 elif unmark:
2644 ms.mark(f, "u")
2630 ms.mark(f, "u")
2645 else:
2631 else:
2646 wctx = repo[None]
2632 wctx = repo[None]
2647 mctx = wctx.parents()[-1]
2633 mctx = wctx.parents()[-1]
2648
2634
2649 # backup pre-resolve (merge uses .orig for its own purposes)
2635 # backup pre-resolve (merge uses .orig for its own purposes)
2650 a = repo.wjoin(f)
2636 a = repo.wjoin(f)
2651 util.copyfile(a, a + ".resolve")
2637 util.copyfile(a, a + ".resolve")
2652
2638
2653 # resolve file
2639 # resolve file
2654 ms.resolve(f, wctx, mctx)
2640 ms.resolve(f, wctx, mctx)
2655
2641
2656 # replace filemerge's .orig file with our resolve file
2642 # replace filemerge's .orig file with our resolve file
2657 util.rename(a + ".resolve", a + ".orig")
2643 util.rename(a + ".resolve", a + ".orig")
2658
2644
2659 def revert(ui, repo, *pats, **opts):
2645 def revert(ui, repo, *pats, **opts):
2660 """restore individual files or directories to an earlier state
2646 """restore individual files or directories to an earlier state
2661
2647
2662 (Use update -r to check out earlier revisions, revert does not
2648 (Use update -r to check out earlier revisions, revert does not
2663 change the working directory parents.)
2649 change the working directory parents.)
2664
2650
2665 With no revision specified, revert the named files or directories
2651 With no revision specified, revert the named files or directories
2666 to the contents they had in the parent of the working directory.
2652 to the contents they had in the parent of the working directory.
2667 This restores the contents of the affected files to an unmodified
2653 This restores the contents of the affected files to an unmodified
2668 state and unschedules adds, removes, copies, and renames. If the
2654 state and unschedules adds, removes, copies, and renames. If the
2669 working directory has two parents, you must explicitly specify a
2655 working directory has two parents, you must explicitly specify a
2670 revision.
2656 revision.
2671
2657
2672 Using the -r/--rev option, revert the given files or directories
2658 Using the -r/--rev option, revert the given files or directories
2673 to their contents as of a specific revision. This can be helpful
2659 to their contents as of a specific revision. This can be helpful
2674 to "roll back" some or all of an earlier change. See :hg:`help
2660 to "roll back" some or all of an earlier change. See :hg:`help
2675 dates` for a list of formats valid for -d/--date.
2661 dates` for a list of formats valid for -d/--date.
2676
2662
2677 Revert modifies the working directory. It does not commit any
2663 Revert modifies the working directory. It does not commit any
2678 changes, or change the parent of the working directory. If you
2664 changes, or change the parent of the working directory. If you
2679 revert to a revision other than the parent of the working
2665 revert to a revision other than the parent of the working
2680 directory, the reverted files will thus appear modified
2666 directory, the reverted files will thus appear modified
2681 afterwards.
2667 afterwards.
2682
2668
2683 If a file has been deleted, it is restored. If the executable mode
2669 If a file has been deleted, it is restored. If the executable mode
2684 of a file was changed, it is reset.
2670 of a file was changed, it is reset.
2685
2671
2686 If names are given, all files matching the names are reverted.
2672 If names are given, all files matching the names are reverted.
2687 If no arguments are given, no files are reverted.
2673 If no arguments are given, no files are reverted.
2688
2674
2689 Modified files are saved with a .orig suffix before reverting.
2675 Modified files are saved with a .orig suffix before reverting.
2690 To disable these backups, use --no-backup.
2676 To disable these backups, use --no-backup.
2691 """
2677 """
2692
2678
2693 if opts["date"]:
2679 if opts["date"]:
2694 if opts["rev"]:
2680 if opts["rev"]:
2695 raise util.Abort(_("you can't specify a revision and a date"))
2681 raise util.Abort(_("you can't specify a revision and a date"))
2696 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2682 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
2697
2683
2698 if not pats and not opts.get('all'):
2684 if not pats and not opts.get('all'):
2699 raise util.Abort(_('no files or directories specified; '
2685 raise util.Abort(_('no files or directories specified; '
2700 'use --all to revert the whole repo'))
2686 'use --all to revert the whole repo'))
2701
2687
2702 parent, p2 = repo.dirstate.parents()
2688 parent, p2 = repo.dirstate.parents()
2703 if not opts.get('rev') and p2 != nullid:
2689 if not opts.get('rev') and p2 != nullid:
2704 raise util.Abort(_('uncommitted merge - please provide a '
2690 raise util.Abort(_('uncommitted merge - please provide a '
2705 'specific revision'))
2691 'specific revision'))
2706 ctx = repo[opts.get('rev')]
2692 ctx = repo[opts.get('rev')]
2707 node = ctx.node()
2693 node = ctx.node()
2708 mf = ctx.manifest()
2694 mf = ctx.manifest()
2709 if node == parent:
2695 if node == parent:
2710 pmf = mf
2696 pmf = mf
2711 else:
2697 else:
2712 pmf = None
2698 pmf = None
2713
2699
2714 # need all matching names in dirstate and manifest of target rev,
2700 # need all matching names in dirstate and manifest of target rev,
2715 # so have to walk both. do not print errors if files exist in one
2701 # so have to walk both. do not print errors if files exist in one
2716 # but not other.
2702 # but not other.
2717
2703
2718 names = {}
2704 names = {}
2719
2705
2720 wlock = repo.wlock()
2706 wlock = repo.wlock()
2721 try:
2707 try:
2722 # walk dirstate.
2708 # walk dirstate.
2723
2709
2724 m = cmdutil.match(repo, pats, opts)
2710 m = cmdutil.match(repo, pats, opts)
2725 m.bad = lambda x, y: False
2711 m.bad = lambda x, y: False
2726 for abs in repo.walk(m):
2712 for abs in repo.walk(m):
2727 names[abs] = m.rel(abs), m.exact(abs)
2713 names[abs] = m.rel(abs), m.exact(abs)
2728
2714
2729 # walk target manifest.
2715 # walk target manifest.
2730
2716
2731 def badfn(path, msg):
2717 def badfn(path, msg):
2732 if path in names:
2718 if path in names:
2733 return
2719 return
2734 path_ = path + '/'
2720 path_ = path + '/'
2735 for f in names:
2721 for f in names:
2736 if f.startswith(path_):
2722 if f.startswith(path_):
2737 return
2723 return
2738 ui.warn("%s: %s\n" % (m.rel(path), msg))
2724 ui.warn("%s: %s\n" % (m.rel(path), msg))
2739
2725
2740 m = cmdutil.match(repo, pats, opts)
2726 m = cmdutil.match(repo, pats, opts)
2741 m.bad = badfn
2727 m.bad = badfn
2742 for abs in repo[node].walk(m):
2728 for abs in repo[node].walk(m):
2743 if abs not in names:
2729 if abs not in names:
2744 names[abs] = m.rel(abs), m.exact(abs)
2730 names[abs] = m.rel(abs), m.exact(abs)
2745
2731
2746 m = cmdutil.matchfiles(repo, names)
2732 m = cmdutil.matchfiles(repo, names)
2747 changes = repo.status(match=m)[:4]
2733 changes = repo.status(match=m)[:4]
2748 modified, added, removed, deleted = map(set, changes)
2734 modified, added, removed, deleted = map(set, changes)
2749
2735
2750 # if f is a rename, also revert the source
2736 # if f is a rename, also revert the source
2751 cwd = repo.getcwd()
2737 cwd = repo.getcwd()
2752 for f in added:
2738 for f in added:
2753 src = repo.dirstate.copied(f)
2739 src = repo.dirstate.copied(f)
2754 if src and src not in names and repo.dirstate[src] == 'r':
2740 if src and src not in names and repo.dirstate[src] == 'r':
2755 removed.add(src)
2741 removed.add(src)
2756 names[src] = (repo.pathto(src, cwd), True)
2742 names[src] = (repo.pathto(src, cwd), True)
2757
2743
2758 def removeforget(abs):
2744 def removeforget(abs):
2759 if repo.dirstate[abs] == 'a':
2745 if repo.dirstate[abs] == 'a':
2760 return _('forgetting %s\n')
2746 return _('forgetting %s\n')
2761 return _('removing %s\n')
2747 return _('removing %s\n')
2762
2748
2763 revert = ([], _('reverting %s\n'))
2749 revert = ([], _('reverting %s\n'))
2764 add = ([], _('adding %s\n'))
2750 add = ([], _('adding %s\n'))
2765 remove = ([], removeforget)
2751 remove = ([], removeforget)
2766 undelete = ([], _('undeleting %s\n'))
2752 undelete = ([], _('undeleting %s\n'))
2767
2753
2768 disptable = (
2754 disptable = (
2769 # dispatch table:
2755 # dispatch table:
2770 # file state
2756 # file state
2771 # action if in target manifest
2757 # action if in target manifest
2772 # action if not in target manifest
2758 # action if not in target manifest
2773 # make backup if in target manifest
2759 # make backup if in target manifest
2774 # make backup if not in target manifest
2760 # make backup if not in target manifest
2775 (modified, revert, remove, True, True),
2761 (modified, revert, remove, True, True),
2776 (added, revert, remove, True, False),
2762 (added, revert, remove, True, False),
2777 (removed, undelete, None, False, False),
2763 (removed, undelete, None, False, False),
2778 (deleted, revert, remove, False, False),
2764 (deleted, revert, remove, False, False),
2779 )
2765 )
2780
2766
2781 for abs, (rel, exact) in sorted(names.items()):
2767 for abs, (rel, exact) in sorted(names.items()):
2782 mfentry = mf.get(abs)
2768 mfentry = mf.get(abs)
2783 target = repo.wjoin(abs)
2769 target = repo.wjoin(abs)
2784 def handle(xlist, dobackup):
2770 def handle(xlist, dobackup):
2785 xlist[0].append(abs)
2771 xlist[0].append(abs)
2786 if dobackup and not opts.get('no_backup') and util.lexists(target):
2772 if dobackup and not opts.get('no_backup') and util.lexists(target):
2787 bakname = "%s.orig" % rel
2773 bakname = "%s.orig" % rel
2788 ui.note(_('saving current version of %s as %s\n') %
2774 ui.note(_('saving current version of %s as %s\n') %
2789 (rel, bakname))
2775 (rel, bakname))
2790 if not opts.get('dry_run'):
2776 if not opts.get('dry_run'):
2791 util.copyfile(target, bakname)
2777 util.copyfile(target, bakname)
2792 if ui.verbose or not exact:
2778 if ui.verbose or not exact:
2793 msg = xlist[1]
2779 msg = xlist[1]
2794 if not isinstance(msg, basestring):
2780 if not isinstance(msg, basestring):
2795 msg = msg(abs)
2781 msg = msg(abs)
2796 ui.status(msg % rel)
2782 ui.status(msg % rel)
2797 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2783 for table, hitlist, misslist, backuphit, backupmiss in disptable:
2798 if abs not in table:
2784 if abs not in table:
2799 continue
2785 continue
2800 # file has changed in dirstate
2786 # file has changed in dirstate
2801 if mfentry:
2787 if mfentry:
2802 handle(hitlist, backuphit)
2788 handle(hitlist, backuphit)
2803 elif misslist is not None:
2789 elif misslist is not None:
2804 handle(misslist, backupmiss)
2790 handle(misslist, backupmiss)
2805 break
2791 break
2806 else:
2792 else:
2807 if abs not in repo.dirstate:
2793 if abs not in repo.dirstate:
2808 if mfentry:
2794 if mfentry:
2809 handle(add, True)
2795 handle(add, True)
2810 elif exact:
2796 elif exact:
2811 ui.warn(_('file not managed: %s\n') % rel)
2797 ui.warn(_('file not managed: %s\n') % rel)
2812 continue
2798 continue
2813 # file has not changed in dirstate
2799 # file has not changed in dirstate
2814 if node == parent:
2800 if node == parent:
2815 if exact:
2801 if exact:
2816 ui.warn(_('no changes needed to %s\n') % rel)
2802 ui.warn(_('no changes needed to %s\n') % rel)
2817 continue
2803 continue
2818 if pmf is None:
2804 if pmf is None:
2819 # only need parent manifest in this unlikely case,
2805 # only need parent manifest in this unlikely case,
2820 # so do not read by default
2806 # so do not read by default
2821 pmf = repo[parent].manifest()
2807 pmf = repo[parent].manifest()
2822 if abs in pmf:
2808 if abs in pmf:
2823 if mfentry:
2809 if mfentry:
2824 # if version of file is same in parent and target
2810 # if version of file is same in parent and target
2825 # manifests, do nothing
2811 # manifests, do nothing
2826 if (pmf[abs] != mfentry or
2812 if (pmf[abs] != mfentry or
2827 pmf.flags(abs) != mf.flags(abs)):
2813 pmf.flags(abs) != mf.flags(abs)):
2828 handle(revert, False)
2814 handle(revert, False)
2829 else:
2815 else:
2830 handle(remove, False)
2816 handle(remove, False)
2831
2817
2832 if not opts.get('dry_run'):
2818 if not opts.get('dry_run'):
2833 def checkout(f):
2819 def checkout(f):
2834 fc = ctx[f]
2820 fc = ctx[f]
2835 repo.wwrite(f, fc.data(), fc.flags())
2821 repo.wwrite(f, fc.data(), fc.flags())
2836
2822
2837 audit_path = util.path_auditor(repo.root)
2823 audit_path = util.path_auditor(repo.root)
2838 for f in remove[0]:
2824 for f in remove[0]:
2839 if repo.dirstate[f] == 'a':
2825 if repo.dirstate[f] == 'a':
2840 repo.dirstate.forget(f)
2826 repo.dirstate.forget(f)
2841 continue
2827 continue
2842 audit_path(f)
2828 audit_path(f)
2843 try:
2829 try:
2844 util.unlink(repo.wjoin(f))
2830 util.unlink(repo.wjoin(f))
2845 except OSError:
2831 except OSError:
2846 pass
2832 pass
2847 repo.dirstate.remove(f)
2833 repo.dirstate.remove(f)
2848
2834
2849 normal = None
2835 normal = None
2850 if node == parent:
2836 if node == parent:
2851 # We're reverting to our parent. If possible, we'd like status
2837 # We're reverting to our parent. If possible, we'd like status
2852 # to report the file as clean. We have to use normallookup for
2838 # to report the file as clean. We have to use normallookup for
2853 # merges to avoid losing information about merged/dirty files.
2839 # merges to avoid losing information about merged/dirty files.
2854 if p2 != nullid:
2840 if p2 != nullid:
2855 normal = repo.dirstate.normallookup
2841 normal = repo.dirstate.normallookup
2856 else:
2842 else:
2857 normal = repo.dirstate.normal
2843 normal = repo.dirstate.normal
2858 for f in revert[0]:
2844 for f in revert[0]:
2859 checkout(f)
2845 checkout(f)
2860 if normal:
2846 if normal:
2861 normal(f)
2847 normal(f)
2862
2848
2863 for f in add[0]:
2849 for f in add[0]:
2864 checkout(f)
2850 checkout(f)
2865 repo.dirstate.add(f)
2851 repo.dirstate.add(f)
2866
2852
2867 normal = repo.dirstate.normallookup
2853 normal = repo.dirstate.normallookup
2868 if node == parent and p2 == nullid:
2854 if node == parent and p2 == nullid:
2869 normal = repo.dirstate.normal
2855 normal = repo.dirstate.normal
2870 for f in undelete[0]:
2856 for f in undelete[0]:
2871 checkout(f)
2857 checkout(f)
2872 normal(f)
2858 normal(f)
2873
2859
2874 finally:
2860 finally:
2875 wlock.release()
2861 wlock.release()
2876
2862
2877 def rollback(ui, repo, **opts):
2863 def rollback(ui, repo, **opts):
2878 """roll back the last transaction (dangerous)
2864 """roll back the last transaction (dangerous)
2879
2865
2880 This command should be used with care. There is only one level of
2866 This command should be used with care. There is only one level of
2881 rollback, and there is no way to undo a rollback. It will also
2867 rollback, and there is no way to undo a rollback. It will also
2882 restore the dirstate at the time of the last transaction, losing
2868 restore the dirstate at the time of the last transaction, losing
2883 any dirstate changes since that time. This command does not alter
2869 any dirstate changes since that time. This command does not alter
2884 the working directory.
2870 the working directory.
2885
2871
2886 Transactions are used to encapsulate the effects of all commands
2872 Transactions are used to encapsulate the effects of all commands
2887 that create new changesets or propagate existing changesets into a
2873 that create new changesets or propagate existing changesets into a
2888 repository. For example, the following commands are transactional,
2874 repository. For example, the following commands are transactional,
2889 and their effects can be rolled back:
2875 and their effects can be rolled back:
2890
2876
2891 - commit
2877 - commit
2892 - import
2878 - import
2893 - pull
2879 - pull
2894 - push (with this repository as the destination)
2880 - push (with this repository as the destination)
2895 - unbundle
2881 - unbundle
2896
2882
2897 This command is not intended for use on public repositories. Once
2883 This command is not intended for use on public repositories. Once
2898 changes are visible for pull by other users, rolling a transaction
2884 changes are visible for pull by other users, rolling a transaction
2899 back locally is ineffective (someone else may already have pulled
2885 back locally is ineffective (someone else may already have pulled
2900 the changes). Furthermore, a race is possible with readers of the
2886 the changes). Furthermore, a race is possible with readers of the
2901 repository; for example an in-progress pull from the repository
2887 repository; for example an in-progress pull from the repository
2902 may fail if a rollback is performed.
2888 may fail if a rollback is performed.
2903 """
2889 """
2904 repo.rollback(opts.get('dry_run'))
2890 repo.rollback(opts.get('dry_run'))
2905
2891
2906 def root(ui, repo):
2892 def root(ui, repo):
2907 """print the root (top) of the current working directory
2893 """print the root (top) of the current working directory
2908
2894
2909 Print the root directory of the current repository.
2895 Print the root directory of the current repository.
2910 """
2896 """
2911 ui.write(repo.root + "\n")
2897 ui.write(repo.root + "\n")
2912
2898
2913 def serve(ui, repo, **opts):
2899 def serve(ui, repo, **opts):
2914 """start stand-alone webserver
2900 """start stand-alone webserver
2915
2901
2916 Start a local HTTP repository browser and pull server.
2902 Start a local HTTP repository browser and pull server.
2917
2903
2918 By default, the server logs accesses to stdout and errors to
2904 By default, the server logs accesses to stdout and errors to
2919 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
2905 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
2920 files.
2906 files.
2921
2907
2922 To have the server choose a free port number to listen on, specify
2908 To have the server choose a free port number to listen on, specify
2923 a port number of 0; in this case, the server will print the port
2909 a port number of 0; in this case, the server will print the port
2924 number it uses.
2910 number it uses.
2925 """
2911 """
2926
2912
2927 if opts["stdio"]:
2913 if opts["stdio"]:
2928 if repo is None:
2914 if repo is None:
2929 raise error.RepoError(_("There is no Mercurial repository here"
2915 raise error.RepoError(_("There is no Mercurial repository here"
2930 " (.hg not found)"))
2916 " (.hg not found)"))
2931 s = sshserver.sshserver(ui, repo)
2917 s = sshserver.sshserver(ui, repo)
2932 s.serve_forever()
2918 s.serve_forever()
2933
2919
2934 # this way we can check if something was given in the command-line
2920 # this way we can check if something was given in the command-line
2935 if opts.get('port'):
2921 if opts.get('port'):
2936 opts['port'] = int(opts.get('port'))
2922 opts['port'] = int(opts.get('port'))
2937
2923
2938 baseui = repo and repo.baseui or ui
2924 baseui = repo and repo.baseui or ui
2939 optlist = ("name templates style address port prefix ipv6"
2925 optlist = ("name templates style address port prefix ipv6"
2940 " accesslog errorlog certificate encoding")
2926 " accesslog errorlog certificate encoding")
2941 for o in optlist.split():
2927 for o in optlist.split():
2942 val = opts.get(o, '')
2928 val = opts.get(o, '')
2943 if val in (None, ''): # should check against default options instead
2929 if val in (None, ''): # should check against default options instead
2944 continue
2930 continue
2945 baseui.setconfig("web", o, val)
2931 baseui.setconfig("web", o, val)
2946 if repo and repo.ui != baseui:
2932 if repo and repo.ui != baseui:
2947 repo.ui.setconfig("web", o, val)
2933 repo.ui.setconfig("web", o, val)
2948
2934
2949 o = opts.get('web_conf') or opts.get('webdir_conf')
2935 o = opts.get('web_conf') or opts.get('webdir_conf')
2950 if not o:
2936 if not o:
2951 if not repo:
2937 if not repo:
2952 raise error.RepoError(_("There is no Mercurial repository"
2938 raise error.RepoError(_("There is no Mercurial repository"
2953 " here (.hg not found)"))
2939 " here (.hg not found)"))
2954 o = repo.root
2940 o = repo.root
2955
2941
2956 app = hgweb.hgweb(o, baseui=ui)
2942 app = hgweb.hgweb(o, baseui=ui)
2957
2943
2958 class service(object):
2944 class service(object):
2959 def init(self):
2945 def init(self):
2960 util.set_signal_handler()
2946 util.set_signal_handler()
2961 self.httpd = hgweb.server.create_server(ui, app)
2947 self.httpd = hgweb.server.create_server(ui, app)
2962
2948
2963 if opts['port'] and not ui.verbose:
2949 if opts['port'] and not ui.verbose:
2964 return
2950 return
2965
2951
2966 if self.httpd.prefix:
2952 if self.httpd.prefix:
2967 prefix = self.httpd.prefix.strip('/') + '/'
2953 prefix = self.httpd.prefix.strip('/') + '/'
2968 else:
2954 else:
2969 prefix = ''
2955 prefix = ''
2970
2956
2971 port = ':%d' % self.httpd.port
2957 port = ':%d' % self.httpd.port
2972 if port == ':80':
2958 if port == ':80':
2973 port = ''
2959 port = ''
2974
2960
2975 bindaddr = self.httpd.addr
2961 bindaddr = self.httpd.addr
2976 if bindaddr == '0.0.0.0':
2962 if bindaddr == '0.0.0.0':
2977 bindaddr = '*'
2963 bindaddr = '*'
2978 elif ':' in bindaddr: # IPv6
2964 elif ':' in bindaddr: # IPv6
2979 bindaddr = '[%s]' % bindaddr
2965 bindaddr = '[%s]' % bindaddr
2980
2966
2981 fqaddr = self.httpd.fqaddr
2967 fqaddr = self.httpd.fqaddr
2982 if ':' in fqaddr:
2968 if ':' in fqaddr:
2983 fqaddr = '[%s]' % fqaddr
2969 fqaddr = '[%s]' % fqaddr
2984 if opts['port']:
2970 if opts['port']:
2985 write = ui.status
2971 write = ui.status
2986 else:
2972 else:
2987 write = ui.write
2973 write = ui.write
2988 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
2974 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
2989 (fqaddr, port, prefix, bindaddr, self.httpd.port))
2975 (fqaddr, port, prefix, bindaddr, self.httpd.port))
2990
2976
2991 def run(self):
2977 def run(self):
2992 self.httpd.serve_forever()
2978 self.httpd.serve_forever()
2993
2979
2994 service = service()
2980 service = service()
2995
2981
2996 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2982 cmdutil.service(opts, initfn=service.init, runfn=service.run)
2997
2983
2998 def status(ui, repo, *pats, **opts):
2984 def status(ui, repo, *pats, **opts):
2999 """show changed files in the working directory
2985 """show changed files in the working directory
3000
2986
3001 Show status of files in the repository. If names are given, only
2987 Show status of files in the repository. If names are given, only
3002 files that match are shown. Files that are clean or ignored or
2988 files that match are shown. Files that are clean or ignored or
3003 the source of a copy/move operation, are not listed unless
2989 the source of a copy/move operation, are not listed unless
3004 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
2990 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
3005 Unless options described with "show only ..." are given, the
2991 Unless options described with "show only ..." are given, the
3006 options -mardu are used.
2992 options -mardu are used.
3007
2993
3008 Option -q/--quiet hides untracked (unknown and ignored) files
2994 Option -q/--quiet hides untracked (unknown and ignored) files
3009 unless explicitly requested with -u/--unknown or -i/--ignored.
2995 unless explicitly requested with -u/--unknown or -i/--ignored.
3010
2996
3011 NOTE: status may appear to disagree with diff if permissions have
2997 NOTE: status may appear to disagree with diff if permissions have
3012 changed or a merge has occurred. The standard diff format does not
2998 changed or a merge has occurred. The standard diff format does not
3013 report permission changes and diff only reports changes relative
2999 report permission changes and diff only reports changes relative
3014 to one merge parent.
3000 to one merge parent.
3015
3001
3016 If one revision is given, it is used as the base revision.
3002 If one revision is given, it is used as the base revision.
3017 If two revisions are given, the differences between them are
3003 If two revisions are given, the differences between them are
3018 shown. The --change option can also be used as a shortcut to list
3004 shown. The --change option can also be used as a shortcut to list
3019 the changed files of a revision from its first parent.
3005 the changed files of a revision from its first parent.
3020
3006
3021 The codes used to show the status of files are::
3007 The codes used to show the status of files are::
3022
3008
3023 M = modified
3009 M = modified
3024 A = added
3010 A = added
3025 R = removed
3011 R = removed
3026 C = clean
3012 C = clean
3027 ! = missing (deleted by non-hg command, but still tracked)
3013 ! = missing (deleted by non-hg command, but still tracked)
3028 ? = not tracked
3014 ? = not tracked
3029 I = ignored
3015 I = ignored
3030 = origin of the previous file listed as A (added)
3016 = origin of the previous file listed as A (added)
3031 """
3017 """
3032
3018
3033 revs = opts.get('rev')
3019 revs = opts.get('rev')
3034 change = opts.get('change')
3020 change = opts.get('change')
3035
3021
3036 if revs and change:
3022 if revs and change:
3037 msg = _('cannot specify --rev and --change at the same time')
3023 msg = _('cannot specify --rev and --change at the same time')
3038 raise util.Abort(msg)
3024 raise util.Abort(msg)
3039 elif change:
3025 elif change:
3040 node2 = repo.lookup(change)
3026 node2 = repo.lookup(change)
3041 node1 = repo[node2].parents()[0].node()
3027 node1 = repo[node2].parents()[0].node()
3042 else:
3028 else:
3043 node1, node2 = cmdutil.revpair(repo, revs)
3029 node1, node2 = cmdutil.revpair(repo, revs)
3044
3030
3045 cwd = (pats and repo.getcwd()) or ''
3031 cwd = (pats and repo.getcwd()) or ''
3046 end = opts.get('print0') and '\0' or '\n'
3032 end = opts.get('print0') and '\0' or '\n'
3047 copy = {}
3033 copy = {}
3048 states = 'modified added removed deleted unknown ignored clean'.split()
3034 states = 'modified added removed deleted unknown ignored clean'.split()
3049 show = [k for k in states if opts.get(k)]
3035 show = [k for k in states if opts.get(k)]
3050 if opts.get('all'):
3036 if opts.get('all'):
3051 show += ui.quiet and (states[:4] + ['clean']) or states
3037 show += ui.quiet and (states[:4] + ['clean']) or states
3052 if not show:
3038 if not show:
3053 show = ui.quiet and states[:4] or states[:5]
3039 show = ui.quiet and states[:4] or states[:5]
3054
3040
3055 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3041 stat = repo.status(node1, node2, cmdutil.match(repo, pats, opts),
3056 'ignored' in show, 'clean' in show, 'unknown' in show)
3042 'ignored' in show, 'clean' in show, 'unknown' in show)
3057 changestates = zip(states, 'MAR!?IC', stat)
3043 changestates = zip(states, 'MAR!?IC', stat)
3058
3044
3059 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3045 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
3060 ctxn = repo[nullid]
3046 ctxn = repo[nullid]
3061 ctx1 = repo[node1]
3047 ctx1 = repo[node1]
3062 ctx2 = repo[node2]
3048 ctx2 = repo[node2]
3063 added = stat[1]
3049 added = stat[1]
3064 if node2 is None:
3050 if node2 is None:
3065 added = stat[0] + stat[1] # merged?
3051 added = stat[0] + stat[1] # merged?
3066
3052
3067 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3053 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
3068 if k in added:
3054 if k in added:
3069 copy[k] = v
3055 copy[k] = v
3070 elif v in added:
3056 elif v in added:
3071 copy[v] = k
3057 copy[v] = k
3072
3058
3073 for state, char, files in changestates:
3059 for state, char, files in changestates:
3074 if state in show:
3060 if state in show:
3075 format = "%s %%s%s" % (char, end)
3061 format = "%s %%s%s" % (char, end)
3076 if opts.get('no_status'):
3062 if opts.get('no_status'):
3077 format = "%%s%s" % end
3063 format = "%%s%s" % end
3078
3064
3079 for f in files:
3065 for f in files:
3080 ui.write(format % repo.pathto(f, cwd),
3066 ui.write(format % repo.pathto(f, cwd),
3081 label='status.' + state)
3067 label='status.' + state)
3082 if f in copy:
3068 if f in copy:
3083 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3069 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
3084 label='status.copied')
3070 label='status.copied')
3085
3071
3086 def summary(ui, repo, **opts):
3072 def summary(ui, repo, **opts):
3087 """summarize working directory state
3073 """summarize working directory state
3088
3074
3089 This generates a brief summary of the working directory state,
3075 This generates a brief summary of the working directory state,
3090 including parents, branch, commit status, and available updates.
3076 including parents, branch, commit status, and available updates.
3091
3077
3092 With the --remote option, this will check the default paths for
3078 With the --remote option, this will check the default paths for
3093 incoming and outgoing changes. This can be time-consuming.
3079 incoming and outgoing changes. This can be time-consuming.
3094 """
3080 """
3095
3081
3096 ctx = repo[None]
3082 ctx = repo[None]
3097 parents = ctx.parents()
3083 parents = ctx.parents()
3098 pnode = parents[0].node()
3084 pnode = parents[0].node()
3099
3085
3100 for p in parents:
3086 for p in parents:
3101 # label with log.changeset (instead of log.parent) since this
3087 # label with log.changeset (instead of log.parent) since this
3102 # shows a working directory parent *changeset*:
3088 # shows a working directory parent *changeset*:
3103 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3089 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
3104 label='log.changeset')
3090 label='log.changeset')
3105 ui.write(' '.join(p.tags()), label='log.tag')
3091 ui.write(' '.join(p.tags()), label='log.tag')
3106 if p.rev() == -1:
3092 if p.rev() == -1:
3107 if not len(repo):
3093 if not len(repo):
3108 ui.write(_(' (empty repository)'))
3094 ui.write(_(' (empty repository)'))
3109 else:
3095 else:
3110 ui.write(_(' (no revision checked out)'))
3096 ui.write(_(' (no revision checked out)'))
3111 ui.write('\n')
3097 ui.write('\n')
3112 if p.description():
3098 if p.description():
3113 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3099 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
3114 label='log.summary')
3100 label='log.summary')
3115
3101
3116 branch = ctx.branch()
3102 branch = ctx.branch()
3117 bheads = repo.branchheads(branch)
3103 bheads = repo.branchheads(branch)
3118 m = _('branch: %s\n') % branch
3104 m = _('branch: %s\n') % branch
3119 if branch != 'default':
3105 if branch != 'default':
3120 ui.write(m, label='log.branch')
3106 ui.write(m, label='log.branch')
3121 else:
3107 else:
3122 ui.status(m, label='log.branch')
3108 ui.status(m, label='log.branch')
3123
3109
3124 st = list(repo.status(unknown=True))[:6]
3110 st = list(repo.status(unknown=True))[:6]
3125 ms = mergemod.mergestate(repo)
3111 ms = mergemod.mergestate(repo)
3126 st.append([f for f in ms if ms[f] == 'u'])
3112 st.append([f for f in ms if ms[f] == 'u'])
3127 labels = [ui.label(_('%d modified'), 'status.modified'),
3113 labels = [ui.label(_('%d modified'), 'status.modified'),
3128 ui.label(_('%d added'), 'status.added'),
3114 ui.label(_('%d added'), 'status.added'),
3129 ui.label(_('%d removed'), 'status.removed'),
3115 ui.label(_('%d removed'), 'status.removed'),
3130 ui.label(_('%d deleted'), 'status.deleted'),
3116 ui.label(_('%d deleted'), 'status.deleted'),
3131 ui.label(_('%d unknown'), 'status.unknown'),
3117 ui.label(_('%d unknown'), 'status.unknown'),
3132 ui.label(_('%d ignored'), 'status.ignored'),
3118 ui.label(_('%d ignored'), 'status.ignored'),
3133 ui.label(_('%d unresolved'), 'resolve.unresolved')]
3119 ui.label(_('%d unresolved'), 'resolve.unresolved')]
3134 t = []
3120 t = []
3135 for s, l in zip(st, labels):
3121 for s, l in zip(st, labels):
3136 if s:
3122 if s:
3137 t.append(l % len(s))
3123 t.append(l % len(s))
3138
3124
3139 t = ', '.join(t)
3125 t = ', '.join(t)
3140 cleanworkdir = False
3126 cleanworkdir = False
3141
3127
3142 if len(parents) > 1:
3128 if len(parents) > 1:
3143 t += _(' (merge)')
3129 t += _(' (merge)')
3144 elif branch != parents[0].branch():
3130 elif branch != parents[0].branch():
3145 t += _(' (new branch)')
3131 t += _(' (new branch)')
3146 elif (not st[0] and not st[1] and not st[2]):
3132 elif (not st[0] and not st[1] and not st[2]):
3147 t += _(' (clean)')
3133 t += _(' (clean)')
3148 cleanworkdir = True
3134 cleanworkdir = True
3149 elif pnode not in bheads:
3135 elif pnode not in bheads:
3150 t += _(' (new branch head)')
3136 t += _(' (new branch head)')
3151
3137
3152 if cleanworkdir:
3138 if cleanworkdir:
3153 ui.status(_('commit: %s\n') % t.strip())
3139 ui.status(_('commit: %s\n') % t.strip())
3154 else:
3140 else:
3155 ui.write(_('commit: %s\n') % t.strip())
3141 ui.write(_('commit: %s\n') % t.strip())
3156
3142
3157 # all ancestors of branch heads - all ancestors of parent = new csets
3143 # all ancestors of branch heads - all ancestors of parent = new csets
3158 new = [0] * len(repo)
3144 new = [0] * len(repo)
3159 cl = repo.changelog
3145 cl = repo.changelog
3160 for a in [cl.rev(n) for n in bheads]:
3146 for a in [cl.rev(n) for n in bheads]:
3161 new[a] = 1
3147 new[a] = 1
3162 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3148 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
3163 new[a] = 1
3149 new[a] = 1
3164 for a in [p.rev() for p in parents]:
3150 for a in [p.rev() for p in parents]:
3165 if a >= 0:
3151 if a >= 0:
3166 new[a] = 0
3152 new[a] = 0
3167 for a in cl.ancestors(*[p.rev() for p in parents]):
3153 for a in cl.ancestors(*[p.rev() for p in parents]):
3168 new[a] = 0
3154 new[a] = 0
3169 new = sum(new)
3155 new = sum(new)
3170
3156
3171 if new == 0:
3157 if new == 0:
3172 ui.status(_('update: (current)\n'))
3158 ui.status(_('update: (current)\n'))
3173 elif pnode not in bheads:
3159 elif pnode not in bheads:
3174 ui.write(_('update: %d new changesets (update)\n') % new)
3160 ui.write(_('update: %d new changesets (update)\n') % new)
3175 else:
3161 else:
3176 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3162 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
3177 (new, len(bheads)))
3163 (new, len(bheads)))
3178
3164
3179 if opts.get('remote'):
3165 if opts.get('remote'):
3180 t = []
3166 t = []
3181 source, branches = hg.parseurl(ui.expandpath('default'))
3167 source, branches = hg.parseurl(ui.expandpath('default'))
3182 other = hg.repository(cmdutil.remoteui(repo, {}), source)
3168 other = hg.repository(cmdutil.remoteui(repo, {}), source)
3183 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3169 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3184 ui.debug('comparing with %s\n' % url.hidepassword(source))
3170 ui.debug('comparing with %s\n' % url.hidepassword(source))
3185 repo.ui.pushbuffer()
3171 repo.ui.pushbuffer()
3186 common, incoming, rheads = repo.findcommonincoming(other)
3172 common, incoming, rheads = repo.findcommonincoming(other)
3187 repo.ui.popbuffer()
3173 repo.ui.popbuffer()
3188 if incoming:
3174 if incoming:
3189 t.append(_('1 or more incoming'))
3175 t.append(_('1 or more incoming'))
3190
3176
3191 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3177 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
3192 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3178 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
3193 other = hg.repository(cmdutil.remoteui(repo, {}), dest)
3179 other = hg.repository(cmdutil.remoteui(repo, {}), dest)
3194 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3180 ui.debug('comparing with %s\n' % url.hidepassword(dest))
3195 repo.ui.pushbuffer()
3181 repo.ui.pushbuffer()
3196 o = repo.findoutgoing(other)
3182 o = repo.findoutgoing(other)
3197 repo.ui.popbuffer()
3183 repo.ui.popbuffer()
3198 o = repo.changelog.nodesbetween(o, None)[0]
3184 o = repo.changelog.nodesbetween(o, None)[0]
3199 if o:
3185 if o:
3200 t.append(_('%d outgoing') % len(o))
3186 t.append(_('%d outgoing') % len(o))
3201
3187
3202 if t:
3188 if t:
3203 ui.write(_('remote: %s\n') % (', '.join(t)))
3189 ui.write(_('remote: %s\n') % (', '.join(t)))
3204 else:
3190 else:
3205 ui.status(_('remote: (synced)\n'))
3191 ui.status(_('remote: (synced)\n'))
3206
3192
3207 def tag(ui, repo, name1, *names, **opts):
3193 def tag(ui, repo, name1, *names, **opts):
3208 """add one or more tags for the current or given revision
3194 """add one or more tags for the current or given revision
3209
3195
3210 Name a particular revision using <name>.
3196 Name a particular revision using <name>.
3211
3197
3212 Tags are used to name particular revisions of the repository and are
3198 Tags are used to name particular revisions of the repository and are
3213 very useful to compare different revisions, to go back to significant
3199 very useful to compare different revisions, to go back to significant
3214 earlier versions or to mark branch points as releases, etc.
3200 earlier versions or to mark branch points as releases, etc.
3215
3201
3216 If no revision is given, the parent of the working directory is
3202 If no revision is given, the parent of the working directory is
3217 used, or tip if no revision is checked out.
3203 used, or tip if no revision is checked out.
3218
3204
3219 To facilitate version control, distribution, and merging of tags,
3205 To facilitate version control, distribution, and merging of tags,
3220 they are stored as a file named ".hgtags" which is managed
3206 they are stored as a file named ".hgtags" which is managed
3221 similarly to other project files and can be hand-edited if
3207 similarly to other project files and can be hand-edited if
3222 necessary. The file '.hg/localtags' is used for local tags (not
3208 necessary. The file '.hg/localtags' is used for local tags (not
3223 shared among repositories).
3209 shared among repositories).
3224
3210
3225 See :hg:`help dates` for a list of formats valid for -d/--date.
3211 See :hg:`help dates` for a list of formats valid for -d/--date.
3226 """
3212 """
3227
3213
3228 rev_ = "."
3214 rev_ = "."
3229 names = (name1,) + names
3215 names = (name1,) + names
3230 if len(names) != len(set(names)):
3216 if len(names) != len(set(names)):
3231 raise util.Abort(_('tag names must be unique'))
3217 raise util.Abort(_('tag names must be unique'))
3232 for n in names:
3218 for n in names:
3233 if n in ['tip', '.', 'null']:
3219 if n in ['tip', '.', 'null']:
3234 raise util.Abort(_('the name \'%s\' is reserved') % n)
3220 raise util.Abort(_('the name \'%s\' is reserved') % n)
3235 if opts.get('rev') and opts.get('remove'):
3221 if opts.get('rev') and opts.get('remove'):
3236 raise util.Abort(_("--rev and --remove are incompatible"))
3222 raise util.Abort(_("--rev and --remove are incompatible"))
3237 if opts.get('rev'):
3223 if opts.get('rev'):
3238 rev_ = opts['rev']
3224 rev_ = opts['rev']
3239 message = opts.get('message')
3225 message = opts.get('message')
3240 if opts.get('remove'):
3226 if opts.get('remove'):
3241 expectedtype = opts.get('local') and 'local' or 'global'
3227 expectedtype = opts.get('local') and 'local' or 'global'
3242 for n in names:
3228 for n in names:
3243 if not repo.tagtype(n):
3229 if not repo.tagtype(n):
3244 raise util.Abort(_('tag \'%s\' does not exist') % n)
3230 raise util.Abort(_('tag \'%s\' does not exist') % n)
3245 if repo.tagtype(n) != expectedtype:
3231 if repo.tagtype(n) != expectedtype:
3246 if expectedtype == 'global':
3232 if expectedtype == 'global':
3247 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3233 raise util.Abort(_('tag \'%s\' is not a global tag') % n)
3248 else:
3234 else:
3249 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3235 raise util.Abort(_('tag \'%s\' is not a local tag') % n)
3250 rev_ = nullid
3236 rev_ = nullid
3251 if not message:
3237 if not message:
3252 # we don't translate commit messages
3238 # we don't translate commit messages
3253 message = 'Removed tag %s' % ', '.join(names)
3239 message = 'Removed tag %s' % ', '.join(names)
3254 elif not opts.get('force'):
3240 elif not opts.get('force'):
3255 for n in names:
3241 for n in names:
3256 if n in repo.tags():
3242 if n in repo.tags():
3257 raise util.Abort(_('tag \'%s\' already exists '
3243 raise util.Abort(_('tag \'%s\' already exists '
3258 '(use -f to force)') % n)
3244 '(use -f to force)') % n)
3259 if not rev_ and repo.dirstate.parents()[1] != nullid:
3245 if not rev_ and repo.dirstate.parents()[1] != nullid:
3260 raise util.Abort(_('uncommitted merge - please provide a '
3246 raise util.Abort(_('uncommitted merge - please provide a '
3261 'specific revision'))
3247 'specific revision'))
3262 r = repo[rev_].node()
3248 r = repo[rev_].node()
3263
3249
3264 if not message:
3250 if not message:
3265 # we don't translate commit messages
3251 # we don't translate commit messages
3266 message = ('Added tag %s for changeset %s' %
3252 message = ('Added tag %s for changeset %s' %
3267 (', '.join(names), short(r)))
3253 (', '.join(names), short(r)))
3268
3254
3269 date = opts.get('date')
3255 date = opts.get('date')
3270 if date:
3256 if date:
3271 date = util.parsedate(date)
3257 date = util.parsedate(date)
3272
3258
3273 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3259 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
3274
3260
3275 def tags(ui, repo):
3261 def tags(ui, repo):
3276 """list repository tags
3262 """list repository tags
3277
3263
3278 This lists both regular and local tags. When the -v/--verbose
3264 This lists both regular and local tags. When the -v/--verbose
3279 switch is used, a third column "local" is printed for local tags.
3265 switch is used, a third column "local" is printed for local tags.
3280 """
3266 """
3281
3267
3282 hexfunc = ui.debugflag and hex or short
3268 hexfunc = ui.debugflag and hex or short
3283 tagtype = ""
3269 tagtype = ""
3284
3270
3285 for t, n in reversed(repo.tagslist()):
3271 for t, n in reversed(repo.tagslist()):
3286 if ui.quiet:
3272 if ui.quiet:
3287 ui.write("%s\n" % t)
3273 ui.write("%s\n" % t)
3288 continue
3274 continue
3289
3275
3290 try:
3276 try:
3291 hn = hexfunc(n)
3277 hn = hexfunc(n)
3292 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3278 r = "%5d:%s" % (repo.changelog.rev(n), hn)
3293 except error.LookupError:
3279 except error.LookupError:
3294 r = " ?:%s" % hn
3280 r = " ?:%s" % hn
3295 else:
3281 else:
3296 spaces = " " * (30 - encoding.colwidth(t))
3282 spaces = " " * (30 - encoding.colwidth(t))
3297 if ui.verbose:
3283 if ui.verbose:
3298 if repo.tagtype(t) == 'local':
3284 if repo.tagtype(t) == 'local':
3299 tagtype = " local"
3285 tagtype = " local"
3300 else:
3286 else:
3301 tagtype = ""
3287 tagtype = ""
3302 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3288 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
3303
3289
3304 def tip(ui, repo, **opts):
3290 def tip(ui, repo, **opts):
3305 """show the tip revision
3291 """show the tip revision
3306
3292
3307 The tip revision (usually just called the tip) is the changeset
3293 The tip revision (usually just called the tip) is the changeset
3308 most recently added to the repository (and therefore the most
3294 most recently added to the repository (and therefore the most
3309 recently changed head).
3295 recently changed head).
3310
3296
3311 If you have just made a commit, that commit will be the tip. If
3297 If you have just made a commit, that commit will be the tip. If
3312 you have just pulled changes from another repository, the tip of
3298 you have just pulled changes from another repository, the tip of
3313 that repository becomes the current tip. The "tip" tag is special
3299 that repository becomes the current tip. The "tip" tag is special
3314 and cannot be renamed or assigned to a different changeset.
3300 and cannot be renamed or assigned to a different changeset.
3315 """
3301 """
3316 displayer = cmdutil.show_changeset(ui, repo, opts)
3302 displayer = cmdutil.show_changeset(ui, repo, opts)
3317 displayer.show(repo[len(repo) - 1])
3303 displayer.show(repo[len(repo) - 1])
3318 displayer.close()
3304 displayer.close()
3319
3305
3320 def unbundle(ui, repo, fname1, *fnames, **opts):
3306 def unbundle(ui, repo, fname1, *fnames, **opts):
3321 """apply one or more changegroup files
3307 """apply one or more changegroup files
3322
3308
3323 Apply one or more compressed changegroup files generated by the
3309 Apply one or more compressed changegroup files generated by the
3324 bundle command.
3310 bundle command.
3325 """
3311 """
3326 fnames = (fname1,) + fnames
3312 fnames = (fname1,) + fnames
3327
3313
3328 lock = repo.lock()
3314 lock = repo.lock()
3329 try:
3315 try:
3330 for fname in fnames:
3316 for fname in fnames:
3331 f = url.open(ui, fname)
3317 f = url.open(ui, fname)
3332 gen = changegroup.readbundle(f, fname)
3318 gen = changegroup.readbundle(f, fname)
3333 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
3319 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname)
3334 finally:
3320 finally:
3335 lock.release()
3321 lock.release()
3336
3322
3337 return postincoming(ui, repo, modheads, opts.get('update'), None)
3323 return postincoming(ui, repo, modheads, opts.get('update'), None)
3338
3324
3339 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3325 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
3340 """update working directory (or switch revisions)
3326 """update working directory (or switch revisions)
3341
3327
3342 Update the repository's working directory to the specified
3328 Update the repository's working directory to the specified
3343 changeset.
3329 changeset.
3344
3330
3345 If no changeset is specified, attempt to update to the head of the
3331 If no changeset is specified, attempt to update to the head of the
3346 current branch. If this head is a descendant of the working
3332 current branch. If this head is a descendant of the working
3347 directory's parent, update to it, otherwise abort.
3333 directory's parent, update to it, otherwise abort.
3348
3334
3349 The following rules apply when the working directory contains
3335 The following rules apply when the working directory contains
3350 uncommitted changes:
3336 uncommitted changes:
3351
3337
3352 1. If neither -c/--check nor -C/--clean is specified, and if
3338 1. If neither -c/--check nor -C/--clean is specified, and if
3353 the requested changeset is an ancestor or descendant of
3339 the requested changeset is an ancestor or descendant of
3354 the working directory's parent, the uncommitted changes
3340 the working directory's parent, the uncommitted changes
3355 are merged into the requested changeset and the merged
3341 are merged into the requested changeset and the merged
3356 result is left uncommitted. If the requested changeset is
3342 result is left uncommitted. If the requested changeset is
3357 not an ancestor or descendant (that is, it is on another
3343 not an ancestor or descendant (that is, it is on another
3358 branch), the update is aborted and the uncommitted changes
3344 branch), the update is aborted and the uncommitted changes
3359 are preserved.
3345 are preserved.
3360
3346
3361 2. With the -c/--check option, the update is aborted and the
3347 2. With the -c/--check option, the update is aborted and the
3362 uncommitted changes are preserved.
3348 uncommitted changes are preserved.
3363
3349
3364 3. With the -C/--clean option, uncommitted changes are discarded and
3350 3. With the -C/--clean option, uncommitted changes are discarded and
3365 the working directory is updated to the requested changeset.
3351 the working directory is updated to the requested changeset.
3366
3352
3367 Use null as the changeset to remove the working directory (like
3353 Use null as the changeset to remove the working directory (like
3368 :hg:`clone -U`).
3354 :hg:`clone -U`).
3369
3355
3370 If you want to update just one file to an older changeset, use :hg:`revert`.
3356 If you want to update just one file to an older changeset, use :hg:`revert`.
3371
3357
3372 See :hg:`help dates` for a list of formats valid for -d/--date.
3358 See :hg:`help dates` for a list of formats valid for -d/--date.
3373 """
3359 """
3374 if rev and node:
3360 if rev and node:
3375 raise util.Abort(_("please specify just one revision"))
3361 raise util.Abort(_("please specify just one revision"))
3376
3362
3377 if not rev:
3363 if not rev:
3378 rev = node
3364 rev = node
3379
3365
3380 if check and clean:
3366 if check and clean:
3381 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3367 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
3382
3368
3383 if check:
3369 if check:
3384 # we could use dirty() but we can ignore merge and branch trivia
3370 # we could use dirty() but we can ignore merge and branch trivia
3385 c = repo[None]
3371 c = repo[None]
3386 if c.modified() or c.added() or c.removed():
3372 if c.modified() or c.added() or c.removed():
3387 raise util.Abort(_("uncommitted local changes"))
3373 raise util.Abort(_("uncommitted local changes"))
3388
3374
3389 if date:
3375 if date:
3390 if rev:
3376 if rev:
3391 raise util.Abort(_("you can't specify a revision and a date"))
3377 raise util.Abort(_("you can't specify a revision and a date"))
3392 rev = cmdutil.finddate(ui, repo, date)
3378 rev = cmdutil.finddate(ui, repo, date)
3393
3379
3394 if clean or check:
3380 if clean or check:
3395 return hg.clean(repo, rev)
3381 return hg.clean(repo, rev)
3396 else:
3382 else:
3397 return hg.update(repo, rev)
3383 return hg.update(repo, rev)
3398
3384
3399 def verify(ui, repo):
3385 def verify(ui, repo):
3400 """verify the integrity of the repository
3386 """verify the integrity of the repository
3401
3387
3402 Verify the integrity of the current repository.
3388 Verify the integrity of the current repository.
3403
3389
3404 This will perform an extensive check of the repository's
3390 This will perform an extensive check of the repository's
3405 integrity, validating the hashes and checksums of each entry in
3391 integrity, validating the hashes and checksums of each entry in
3406 the changelog, manifest, and tracked files, as well as the
3392 the changelog, manifest, and tracked files, as well as the
3407 integrity of their crosslinks and indices.
3393 integrity of their crosslinks and indices.
3408 """
3394 """
3409 return hg.verify(repo)
3395 return hg.verify(repo)
3410
3396
3411 def version_(ui):
3397 def version_(ui):
3412 """output version and copyright information"""
3398 """output version and copyright information"""
3413 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3399 ui.write(_("Mercurial Distributed SCM (version %s)\n")
3414 % util.version())
3400 % util.version())
3415 ui.status(_(
3401 ui.status(_(
3416 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3402 "\nCopyright (C) 2005-2010 Matt Mackall <mpm@selenic.com> and others\n"
3417 "This is free software; see the source for copying conditions. "
3403 "This is free software; see the source for copying conditions. "
3418 "There is NO\nwarranty; "
3404 "There is NO\nwarranty; "
3419 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3405 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
3420 ))
3406 ))
3421
3407
3422 # Command options and aliases are listed here, alphabetically
3408 # Command options and aliases are listed here, alphabetically
3423
3409
3424 globalopts = [
3410 globalopts = [
3425 ('R', 'repository', '',
3411 ('R', 'repository', '',
3426 _('repository root directory or name of overlay bundle file')),
3412 _('repository root directory or name of overlay bundle file')),
3427 ('', 'cwd', '', _('change working directory')),
3413 ('', 'cwd', '', _('change working directory')),
3428 ('y', 'noninteractive', None,
3414 ('y', 'noninteractive', None,
3429 _('do not prompt, assume \'yes\' for any required answers')),
3415 _('do not prompt, assume \'yes\' for any required answers')),
3430 ('q', 'quiet', None, _('suppress output')),
3416 ('q', 'quiet', None, _('suppress output')),
3431 ('v', 'verbose', None, _('enable additional output')),
3417 ('v', 'verbose', None, _('enable additional output')),
3432 ('', 'config', [],
3418 ('', 'config', [],
3433 _('set/override config option (use \'section.name=value\')')),
3419 _('set/override config option (use \'section.name=value\')')),
3434 ('', 'debug', None, _('enable debugging output')),
3420 ('', 'debug', None, _('enable debugging output')),
3435 ('', 'debugger', None, _('start debugger')),
3421 ('', 'debugger', None, _('start debugger')),
3436 ('', 'encoding', encoding.encoding, _('set the charset encoding')),
3422 ('', 'encoding', encoding.encoding, _('set the charset encoding')),
3437 ('', 'encodingmode', encoding.encodingmode,
3423 ('', 'encodingmode', encoding.encodingmode,
3438 _('set the charset encoding mode')),
3424 _('set the charset encoding mode')),
3439 ('', 'traceback', None, _('always print a traceback on exception')),
3425 ('', 'traceback', None, _('always print a traceback on exception')),
3440 ('', 'time', None, _('time how long the command takes')),
3426 ('', 'time', None, _('time how long the command takes')),
3441 ('', 'profile', None, _('print command execution profile')),
3427 ('', 'profile', None, _('print command execution profile')),
3442 ('', 'version', None, _('output version information and exit')),
3428 ('', 'version', None, _('output version information and exit')),
3443 ('h', 'help', None, _('display help and exit')),
3429 ('h', 'help', None, _('display help and exit')),
3444 ]
3430 ]
3445
3431
3446 dryrunopts = [('n', 'dry-run', None,
3432 dryrunopts = [('n', 'dry-run', None,
3447 _('do not perform actions, just print output'))]
3433 _('do not perform actions, just print output'))]
3448
3434
3449 remoteopts = [
3435 remoteopts = [
3450 ('e', 'ssh', '', _('specify ssh command to use')),
3436 ('e', 'ssh', '', _('specify ssh command to use')),
3451 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
3437 ('', 'remotecmd', '', _('specify hg command to run on the remote side')),
3452 ]
3438 ]
3453
3439
3454 walkopts = [
3440 walkopts = [
3455 ('I', 'include', [], _('include names matching the given patterns')),
3441 ('I', 'include', [], _('include names matching the given patterns')),
3456 ('X', 'exclude', [], _('exclude names matching the given patterns')),
3442 ('X', 'exclude', [], _('exclude names matching the given patterns')),
3457 ]
3443 ]
3458
3444
3459 commitopts = [
3445 commitopts = [
3460 ('m', 'message', '', _('use <text> as commit message')),
3446 ('m', 'message', '', _('use <text> as commit message')),
3461 ('l', 'logfile', '', _('read commit message from <file>')),
3447 ('l', 'logfile', '', _('read commit message from <file>')),
3462 ]
3448 ]
3463
3449
3464 commitopts2 = [
3450 commitopts2 = [
3465 ('d', 'date', '', _('record datecode as commit date')),
3451 ('d', 'date', '', _('record datecode as commit date')),
3466 ('u', 'user', '', _('record the specified user as committer')),
3452 ('u', 'user', '', _('record the specified user as committer')),
3467 ]
3453 ]
3468
3454
3469 templateopts = [
3455 templateopts = [
3470 ('', 'style', '', _('display using template map file')),
3456 ('', 'style', '', _('display using template map file')),
3471 ('', 'template', '', _('display with template')),
3457 ('', 'template', '', _('display with template')),
3472 ]
3458 ]
3473
3459
3474 logopts = [
3460 logopts = [
3475 ('p', 'patch', None, _('show patch')),
3461 ('p', 'patch', None, _('show patch')),
3476 ('g', 'git', None, _('use git extended diff format')),
3462 ('g', 'git', None, _('use git extended diff format')),
3477 ('l', 'limit', '', _('limit number of changes displayed')),
3463 ('l', 'limit', '', _('limit number of changes displayed')),
3478 ('M', 'no-merges', None, _('do not show merges')),
3464 ('M', 'no-merges', None, _('do not show merges')),
3479 ] + templateopts
3465 ] + templateopts
3480
3466
3481 diffopts = [
3467 diffopts = [
3482 ('a', 'text', None, _('treat all files as text')),
3468 ('a', 'text', None, _('treat all files as text')),
3483 ('g', 'git', None, _('use git extended diff format')),
3469 ('g', 'git', None, _('use git extended diff format')),
3484 ('', 'nodates', None, _('omit dates from diff headers'))
3470 ('', 'nodates', None, _('omit dates from diff headers'))
3485 ]
3471 ]
3486
3472
3487 diffopts2 = [
3473 diffopts2 = [
3488 ('p', 'show-function', None, _('show which function each change is in')),
3474 ('p', 'show-function', None, _('show which function each change is in')),
3489 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3475 ('', 'reverse', None, _('produce a diff that undoes the changes')),
3490 ('w', 'ignore-all-space', None,
3476 ('w', 'ignore-all-space', None,
3491 _('ignore white space when comparing lines')),
3477 _('ignore white space when comparing lines')),
3492 ('b', 'ignore-space-change', None,
3478 ('b', 'ignore-space-change', None,
3493 _('ignore changes in the amount of white space')),
3479 _('ignore changes in the amount of white space')),
3494 ('B', 'ignore-blank-lines', None,
3480 ('B', 'ignore-blank-lines', None,
3495 _('ignore changes whose lines are all blank')),
3481 _('ignore changes whose lines are all blank')),
3496 ('U', 'unified', '', _('number of lines of context to show')),
3482 ('U', 'unified', '', _('number of lines of context to show')),
3497 ('', 'stat', None, _('output diffstat-style summary of changes')),
3483 ('', 'stat', None, _('output diffstat-style summary of changes')),
3498 ]
3484 ]
3499
3485
3500 similarityopts = [
3486 similarityopts = [
3501 ('s', 'similarity', '',
3487 ('s', 'similarity', '',
3502 _('guess renamed files by similarity (0<=s<=100)'))
3488 _('guess renamed files by similarity (0<=s<=100)'))
3503 ]
3489 ]
3504
3490
3505 table = {
3491 table = {
3506 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3492 "^add": (add, walkopts + dryrunopts, _('[OPTION]... [FILE]...')),
3507 "addremove":
3493 "addremove":
3508 (addremove, similarityopts + walkopts + dryrunopts,
3494 (addremove, similarityopts + walkopts + dryrunopts,
3509 _('[OPTION]... [FILE]...')),
3495 _('[OPTION]... [FILE]...')),
3510 "^annotate|blame":
3496 "^annotate|blame":
3511 (annotate,
3497 (annotate,
3512 [('r', 'rev', '', _('annotate the specified revision')),
3498 [('r', 'rev', '', _('annotate the specified revision')),
3513 ('', 'follow', None,
3499 ('', 'follow', None,
3514 _('follow copies/renames and list the filename (DEPRECATED)')),
3500 _('follow copies/renames and list the filename (DEPRECATED)')),
3515 ('', 'no-follow', None, _("don't follow copies and renames")),
3501 ('', 'no-follow', None, _("don't follow copies and renames")),
3516 ('a', 'text', None, _('treat all files as text')),
3502 ('a', 'text', None, _('treat all files as text')),
3517 ('u', 'user', None, _('list the author (long with -v)')),
3503 ('u', 'user', None, _('list the author (long with -v)')),
3518 ('f', 'file', None, _('list the filename')),
3504 ('f', 'file', None, _('list the filename')),
3519 ('d', 'date', None, _('list the date (short with -q)')),
3505 ('d', 'date', None, _('list the date (short with -q)')),
3520 ('n', 'number', None, _('list the revision number (default)')),
3506 ('n', 'number', None, _('list the revision number (default)')),
3521 ('c', 'changeset', None, _('list the changeset')),
3507 ('c', 'changeset', None, _('list the changeset')),
3522 ('l', 'line-number', None,
3508 ('l', 'line-number', None,
3523 _('show line number at the first appearance'))
3509 _('show line number at the first appearance'))
3524 ] + walkopts,
3510 ] + walkopts,
3525 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3511 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...')),
3526 "archive":
3512 "archive":
3527 (archive,
3513 (archive,
3528 [('', 'no-decode', None, _('do not pass files through decoders')),
3514 [('', 'no-decode', None, _('do not pass files through decoders')),
3529 ('p', 'prefix', '', _('directory prefix for files in archive')),
3515 ('p', 'prefix', '', _('directory prefix for files in archive')),
3530 ('r', 'rev', '', _('revision to distribute')),
3516 ('r', 'rev', '', _('revision to distribute')),
3531 ('t', 'type', '', _('type of distribution to create')),
3517 ('t', 'type', '', _('type of distribution to create')),
3532 ] + walkopts,
3518 ] + walkopts,
3533 _('[OPTION]... DEST')),
3519 _('[OPTION]... DEST')),
3534 "backout":
3520 "backout":
3535 (backout,
3521 (backout,
3536 [('', 'merge', None,
3522 [('', 'merge', None,
3537 _('merge with old dirstate parent after backout')),
3523 _('merge with old dirstate parent after backout')),
3538 ('', 'parent', '', _('parent to choose when backing out merge')),
3524 ('', 'parent', '', _('parent to choose when backing out merge')),
3539 ('r', 'rev', '', _('revision to backout')),
3525 ('r', 'rev', '', _('revision to backout')),
3540 ] + walkopts + commitopts + commitopts2,
3526 ] + walkopts + commitopts + commitopts2,
3541 _('[OPTION]... [-r] REV')),
3527 _('[OPTION]... [-r] REV')),
3542 "bisect":
3528 "bisect":
3543 (bisect,
3529 (bisect,
3544 [('r', 'reset', False, _('reset bisect state')),
3530 [('r', 'reset', False, _('reset bisect state')),
3545 ('g', 'good', False, _('mark changeset good')),
3531 ('g', 'good', False, _('mark changeset good')),
3546 ('b', 'bad', False, _('mark changeset bad')),
3532 ('b', 'bad', False, _('mark changeset bad')),
3547 ('s', 'skip', False, _('skip testing changeset')),
3533 ('s', 'skip', False, _('skip testing changeset')),
3548 ('c', 'command', '', _('use command to check changeset state')),
3534 ('c', 'command', '', _('use command to check changeset state')),
3549 ('U', 'noupdate', False, _('do not update to target'))],
3535 ('U', 'noupdate', False, _('do not update to target'))],
3550 _("[-gbsr] [-U] [-c CMD] [REV]")),
3536 _("[-gbsr] [-U] [-c CMD] [REV]")),
3551 "branch":
3537 "branch":
3552 (branch,
3538 (branch,
3553 [('f', 'force', None,
3539 [('f', 'force', None,
3554 _('set branch name even if it shadows an existing branch')),
3540 _('set branch name even if it shadows an existing branch')),
3555 ('C', 'clean', None, _('reset branch name to parent branch name'))],
3541 ('C', 'clean', None, _('reset branch name to parent branch name'))],
3556 _('[-fC] [NAME]')),
3542 _('[-fC] [NAME]')),
3557 "branches":
3543 "branches":
3558 (branches,
3544 (branches,
3559 [('a', 'active', False,
3545 [('a', 'active', False,
3560 _('show only branches that have unmerged heads')),
3546 _('show only branches that have unmerged heads')),
3561 ('c', 'closed', False,
3547 ('c', 'closed', False,
3562 _('show normal and closed branches'))],
3548 _('show normal and closed branches'))],
3563 _('[-ac]')),
3549 _('[-ac]')),
3564 "bundle":
3550 "bundle":
3565 (bundle,
3551 (bundle,
3566 [('f', 'force', None,
3552 [('f', 'force', None,
3567 _('run even when the destination is unrelated')),
3553 _('run even when the destination is unrelated')),
3568 ('r', 'rev', [],
3554 ('r', 'rev', [],
3569 _('a changeset intended to be added to the destination')),
3555 _('a changeset intended to be added to the destination')),
3570 ('b', 'branch', [],
3556 ('b', 'branch', [],
3571 _('a specific branch you would like to bundle')),
3557 _('a specific branch you would like to bundle')),
3572 ('', 'base', [],
3558 ('', 'base', [],
3573 _('a base changeset assumed to be available at the destination')),
3559 _('a base changeset assumed to be available at the destination')),
3574 ('a', 'all', None, _('bundle all changesets in the repository')),
3560 ('a', 'all', None, _('bundle all changesets in the repository')),
3575 ('t', 'type', 'bzip2', _('bundle compression type to use')),
3561 ('t', 'type', 'bzip2', _('bundle compression type to use')),
3576 ] + remoteopts,
3562 ] + remoteopts,
3577 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
3563 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]')),
3578 "cat":
3564 "cat":
3579 (cat,
3565 (cat,
3580 [('o', 'output', '', _('print output to file with formatted name')),
3566 [('o', 'output', '', _('print output to file with formatted name')),
3581 ('r', 'rev', '', _('print the given revision')),
3567 ('r', 'rev', '', _('print the given revision')),
3582 ('', 'decode', None, _('apply any matching decode filter')),
3568 ('', 'decode', None, _('apply any matching decode filter')),
3583 ] + walkopts,
3569 ] + walkopts,
3584 _('[OPTION]... FILE...')),
3570 _('[OPTION]... FILE...')),
3585 "^clone":
3571 "^clone":
3586 (clone,
3572 (clone,
3587 [('U', 'noupdate', None,
3573 [('U', 'noupdate', None,
3588 _('the clone will include an empty working copy (only a repository)')),
3574 _('the clone will include an empty working copy (only a repository)')),
3589 ('u', 'updaterev', '',
3575 ('u', 'updaterev', '',
3590 _('revision, tag or branch to check out')),
3576 _('revision, tag or branch to check out')),
3591 ('r', 'rev', [],
3577 ('r', 'rev', [],
3592 _('include the specified changeset')),
3578 _('include the specified changeset')),
3593 ('b', 'branch', [],
3579 ('b', 'branch', [],
3594 _('clone only the specified branch')),
3580 _('clone only the specified branch')),
3595 ('', 'pull', None, _('use pull protocol to copy metadata')),
3581 ('', 'pull', None, _('use pull protocol to copy metadata')),
3596 ('', 'uncompressed', None,
3582 ('', 'uncompressed', None,
3597 _('use uncompressed transfer (fast over LAN)')),
3583 _('use uncompressed transfer (fast over LAN)')),
3598 ] + remoteopts,
3584 ] + remoteopts,
3599 _('[OPTION]... SOURCE [DEST]')),
3585 _('[OPTION]... SOURCE [DEST]')),
3600 "^commit|ci":
3586 "^commit|ci":
3601 (commit,
3587 (commit,
3602 [('A', 'addremove', None,
3588 [('A', 'addremove', None,
3603 _('mark new/missing files as added/removed before committing')),
3589 _('mark new/missing files as added/removed before committing')),
3604 ('', 'close-branch', None,
3590 ('', 'close-branch', None,
3605 _('mark a branch as closed, hiding it from the branch list')),
3591 _('mark a branch as closed, hiding it from the branch list')),
3606 ] + walkopts + commitopts + commitopts2,
3592 ] + walkopts + commitopts + commitopts2,
3607 _('[OPTION]... [FILE]...')),
3593 _('[OPTION]... [FILE]...')),
3608 "copy|cp":
3594 "copy|cp":
3609 (copy,
3595 (copy,
3610 [('A', 'after', None, _('record a copy that has already occurred')),
3596 [('A', 'after', None, _('record a copy that has already occurred')),
3611 ('f', 'force', None,
3597 ('f', 'force', None,
3612 _('forcibly copy over an existing managed file')),
3598 _('forcibly copy over an existing managed file')),
3613 ] + walkopts + dryrunopts,
3599 ] + walkopts + dryrunopts,
3614 _('[OPTION]... [SOURCE]... DEST')),
3600 _('[OPTION]... [SOURCE]... DEST')),
3615 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
3601 "debugancestor": (debugancestor, [], _('[INDEX] REV1 REV2')),
3616 "debugcheckstate": (debugcheckstate, [], ''),
3602 "debugcheckstate": (debugcheckstate, [], ''),
3617 "debugcommands": (debugcommands, [], _('[COMMAND]')),
3603 "debugcommands": (debugcommands, [], _('[COMMAND]')),
3618 "debugcomplete":
3604 "debugcomplete":
3619 (debugcomplete,
3605 (debugcomplete,
3620 [('o', 'options', None, _('show the command options'))],
3606 [('o', 'options', None, _('show the command options'))],
3621 _('[-o] CMD')),
3607 _('[-o] CMD')),
3622 "debugdate":
3608 "debugdate":
3623 (debugdate,
3609 (debugdate,
3624 [('e', 'extended', None, _('try extended date formats'))],
3610 [('e', 'extended', None, _('try extended date formats'))],
3625 _('[-e] DATE [RANGE]')),
3611 _('[-e] DATE [RANGE]')),
3626 "debugdata": (debugdata, [], _('FILE REV')),
3612 "debugdata": (debugdata, [], _('FILE REV')),
3627 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
3613 "debugfsinfo": (debugfsinfo, [], _('[PATH]')),
3628 "debugindex": (debugindex, [], _('FILE')),
3614 "debugindex": (debugindex, [], _('FILE')),
3629 "debugindexdot": (debugindexdot, [], _('FILE')),
3615 "debugindexdot": (debugindexdot, [], _('FILE')),
3630 "debuginstall": (debuginstall, [], ''),
3616 "debuginstall": (debuginstall, [], ''),
3631 "debugrebuildstate":
3617 "debugrebuildstate":
3632 (debugrebuildstate,
3618 (debugrebuildstate,
3633 [('r', 'rev', '', _('revision to rebuild to'))],
3619 [('r', 'rev', '', _('revision to rebuild to'))],
3634 _('[-r REV] [REV]')),
3620 _('[-r REV] [REV]')),
3635 "debugrename":
3621 "debugrename":
3636 (debugrename,
3622 (debugrename,
3637 [('r', 'rev', '', _('revision to debug'))],
3623 [('r', 'rev', '', _('revision to debug'))],
3638 _('[-r REV] FILE')),
3624 _('[-r REV] FILE')),
3639 "debugsetparents":
3625 "debugsetparents":
3640 (debugsetparents, [], _('REV1 [REV2]')),
3626 (debugsetparents, [], _('REV1 [REV2]')),
3641 "debugstate":
3627 "debugstate":
3642 (debugstate,
3628 (debugstate,
3643 [('', 'nodates', None, _('do not display the saved mtime'))],
3629 [('', 'nodates', None, _('do not display the saved mtime'))],
3644 _('[OPTION]...')),
3630 _('[OPTION]...')),
3645 "debugsub":
3631 "debugsub":
3646 (debugsub,
3632 (debugsub,
3647 [('r', 'rev', '', _('revision to check'))],
3633 [('r', 'rev', '', _('revision to check'))],
3648 _('[-r REV] [REV]')),
3634 _('[-r REV] [REV]')),
3649 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
3635 "debugwalk": (debugwalk, walkopts, _('[OPTION]... [FILE]...')),
3650 "^diff":
3636 "^diff":
3651 (diff,
3637 (diff,
3652 [('r', 'rev', [], _('revision')),
3638 [('r', 'rev', [], _('revision')),
3653 ('c', 'change', '', _('change made by revision'))
3639 ('c', 'change', '', _('change made by revision'))
3654 ] + diffopts + diffopts2 + walkopts,
3640 ] + diffopts + diffopts2 + walkopts,
3655 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
3641 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...')),
3656 "^export":
3642 "^export":
3657 (export,
3643 (export,
3658 [('o', 'output', '', _('print output to file with formatted name')),
3644 [('o', 'output', '', _('print output to file with formatted name')),
3659 ('', 'switch-parent', None, _('diff against the second parent')),
3645 ('', 'switch-parent', None, _('diff against the second parent')),
3660 ('r', 'rev', [], _('revisions to export')),
3646 ('r', 'rev', [], _('revisions to export')),
3661 ] + diffopts,
3647 ] + diffopts,
3662 _('[OPTION]... [-o OUTFILESPEC] REV...')),
3648 _('[OPTION]... [-o OUTFILESPEC] REV...')),
3663 "^forget":
3649 "^forget":
3664 (forget,
3650 (forget,
3665 [] + walkopts,
3651 [] + walkopts,
3666 _('[OPTION]... FILE...')),
3652 _('[OPTION]... FILE...')),
3667 "grep":
3653 "grep":
3668 (grep,
3654 (grep,
3669 [('0', 'print0', None, _('end fields with NUL')),
3655 [('0', 'print0', None, _('end fields with NUL')),
3670 ('', 'all', None, _('print all revisions that match')),
3656 ('', 'all', None, _('print all revisions that match')),
3671 ('f', 'follow', None,
3657 ('f', 'follow', None,
3672 _('follow changeset history,'
3658 _('follow changeset history,'
3673 ' or file history across copies and renames')),
3659 ' or file history across copies and renames')),
3674 ('i', 'ignore-case', None, _('ignore case when matching')),
3660 ('i', 'ignore-case', None, _('ignore case when matching')),
3675 ('l', 'files-with-matches', None,
3661 ('l', 'files-with-matches', None,
3676 _('print only filenames and revisions that match')),
3662 _('print only filenames and revisions that match')),
3677 ('n', 'line-number', None, _('print matching line numbers')),
3663 ('n', 'line-number', None, _('print matching line numbers')),
3678 ('r', 'rev', [], _('search in given revision range')),
3664 ('r', 'rev', [], _('search in given revision range')),
3679 ('u', 'user', None, _('list the author (long with -v)')),
3665 ('u', 'user', None, _('list the author (long with -v)')),
3680 ('d', 'date', None, _('list the date (short with -q)')),
3666 ('d', 'date', None, _('list the date (short with -q)')),
3681 ] + walkopts,
3667 ] + walkopts,
3682 _('[OPTION]... PATTERN [FILE]...')),
3668 _('[OPTION]... PATTERN [FILE]...')),
3683 "heads":
3669 "heads":
3684 (heads,
3670 (heads,
3685 [('r', 'rev', '', _('show only heads which are descendants of REV')),
3671 [('r', 'rev', '', _('show only heads which are descendants of REV')),
3686 ('t', 'topo', False, _('show topological heads only')),
3672 ('t', 'topo', False, _('show topological heads only')),
3687 ('a', 'active', False,
3673 ('a', 'active', False,
3688 _('show active branchheads only [DEPRECATED]')),
3674 _('show active branchheads only [DEPRECATED]')),
3689 ('c', 'closed', False,
3675 ('c', 'closed', False,
3690 _('show normal and closed branch heads')),
3676 _('show normal and closed branch heads')),
3691 ] + templateopts,
3677 ] + templateopts,
3692 _('[-ac] [-r STARTREV] [REV]...')),
3678 _('[-ac] [-r STARTREV] [REV]...')),
3693 "help": (help_, [], _('[TOPIC]')),
3679 "help": (help_, [], _('[TOPIC]')),
3694 "identify|id":
3680 "identify|id":
3695 (identify,
3681 (identify,
3696 [('r', 'rev', '', _('identify the specified revision')),
3682 [('r', 'rev', '', _('identify the specified revision')),
3697 ('n', 'num', None, _('show local revision number')),
3683 ('n', 'num', None, _('show local revision number')),
3698 ('i', 'id', None, _('show global revision id')),
3684 ('i', 'id', None, _('show global revision id')),
3699 ('b', 'branch', None, _('show branch')),
3685 ('b', 'branch', None, _('show branch')),
3700 ('t', 'tags', None, _('show tags'))],
3686 ('t', 'tags', None, _('show tags'))],
3701 _('[-nibt] [-r REV] [SOURCE]')),
3687 _('[-nibt] [-r REV] [SOURCE]')),
3702 "import|patch":
3688 "import|patch":
3703 (import_,
3689 (import_,
3704 [('p', 'strip', 1,
3690 [('p', 'strip', 1,
3705 _('directory strip option for patch. This has the same '
3691 _('directory strip option for patch. This has the same '
3706 'meaning as the corresponding patch option')),
3692 'meaning as the corresponding patch option')),
3707 ('b', 'base', '', _('base path')),
3693 ('b', 'base', '', _('base path')),
3708 ('f', 'force', None,
3694 ('f', 'force', None,
3709 _('skip check for outstanding uncommitted changes')),
3695 _('skip check for outstanding uncommitted changes')),
3710 ('', 'no-commit', None,
3696 ('', 'no-commit', None,
3711 _("don't commit, just update the working directory")),
3697 _("don't commit, just update the working directory")),
3712 ('', 'exact', None,
3698 ('', 'exact', None,
3713 _('apply patch to the nodes from which it was generated')),
3699 _('apply patch to the nodes from which it was generated')),
3714 ('', 'import-branch', None,
3700 ('', 'import-branch', None,
3715 _('use any branch information in patch (implied by --exact)'))] +
3701 _('use any branch information in patch (implied by --exact)'))] +
3716 commitopts + commitopts2 + similarityopts,
3702 commitopts + commitopts2 + similarityopts,
3717 _('[OPTION]... PATCH...')),
3703 _('[OPTION]... PATCH...')),
3718 "incoming|in":
3704 "incoming|in":
3719 (incoming,
3705 (incoming,
3720 [('f', 'force', None,
3706 [('f', 'force', None,
3721 _('run even if remote repository is unrelated')),
3707 _('run even if remote repository is unrelated')),
3722 ('n', 'newest-first', None, _('show newest record first')),
3708 ('n', 'newest-first', None, _('show newest record first')),
3723 ('', 'bundle', '', _('file to store the bundles into')),
3709 ('', 'bundle', '', _('file to store the bundles into')),
3724 ('r', 'rev', [],
3710 ('r', 'rev', [],
3725 _('a remote changeset intended to be added')),
3711 _('a remote changeset intended to be added')),
3726 ('b', 'branch', [],
3712 ('b', 'branch', [],
3727 _('a specific branch you would like to pull')),
3713 _('a specific branch you would like to pull')),
3728 ] + logopts + remoteopts,
3714 ] + logopts + remoteopts,
3729 _('[-p] [-n] [-M] [-f] [-r REV]...'
3715 _('[-p] [-n] [-M] [-f] [-r REV]...'
3730 ' [--bundle FILENAME] [SOURCE]')),
3716 ' [--bundle FILENAME] [SOURCE]')),
3731 "^init":
3717 "^init":
3732 (init,
3718 (init,
3733 remoteopts,
3719 remoteopts,
3734 _('[-e CMD] [--remotecmd CMD] [DEST]')),
3720 _('[-e CMD] [--remotecmd CMD] [DEST]')),
3735 "locate":
3721 "locate":
3736 (locate,
3722 (locate,
3737 [('r', 'rev', '', _('search the repository as it is in REV')),
3723 [('r', 'rev', '', _('search the repository as it is in REV')),
3738 ('0', 'print0', None,
3724 ('0', 'print0', None,
3739 _('end filenames with NUL, for use with xargs')),
3725 _('end filenames with NUL, for use with xargs')),
3740 ('f', 'fullpath', None,
3726 ('f', 'fullpath', None,
3741 _('print complete paths from the filesystem root')),
3727 _('print complete paths from the filesystem root')),
3742 ] + walkopts,
3728 ] + walkopts,
3743 _('[OPTION]... [PATTERN]...')),
3729 _('[OPTION]... [PATTERN]...')),
3744 "^log|history":
3730 "^log|history":
3745 (log,
3731 (log,
3746 [('f', 'follow', None,
3732 [('f', 'follow', None,
3747 _('follow changeset history,'
3733 _('follow changeset history,'
3748 ' or file history across copies and renames')),
3734 ' or file history across copies and renames')),
3749 ('', 'follow-first', None,
3735 ('', 'follow-first', None,
3750 _('only follow the first parent of merge changesets')),
3736 _('only follow the first parent of merge changesets')),
3751 ('d', 'date', '', _('show revisions matching date spec')),
3737 ('d', 'date', '', _('show revisions matching date spec')),
3752 ('C', 'copies', None, _('show copied files')),
3738 ('C', 'copies', None, _('show copied files')),
3753 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3739 ('k', 'keyword', [], _('do case-insensitive search for a keyword')),
3754 ('r', 'rev', [], _('show the specified revision or range')),
3740 ('r', 'rev', [], _('show the specified revision or range')),
3755 ('', 'removed', None, _('include revisions where files were removed')),
3741 ('', 'removed', None, _('include revisions where files were removed')),
3756 ('m', 'only-merges', None, _('show only merges')),
3742 ('m', 'only-merges', None, _('show only merges')),
3757 ('u', 'user', [], _('revisions committed by user')),
3743 ('u', 'user', [], _('revisions committed by user')),
3758 ('', 'only-branch', [],
3744 ('', 'only-branch', [],
3759 _('show only changesets within the given named branch (DEPRECATED)')),
3745 _('show only changesets within the given named branch (DEPRECATED)')),
3760 ('b', 'branch', [],
3746 ('b', 'branch', [],
3761 _('show changesets within the given named branch')),
3747 _('show changesets within the given named branch')),
3762 ('P', 'prune', [],
3748 ('P', 'prune', [],
3763 _('do not display revision or any of its ancestors')),
3749 _('do not display revision or any of its ancestors')),
3764 ] + logopts + walkopts,
3750 ] + logopts + walkopts,
3765 _('[OPTION]... [FILE]')),
3751 _('[OPTION]... [FILE]')),
3766 "manifest":
3752 "manifest":
3767 (manifest,
3753 (manifest,
3768 [('r', 'rev', '', _('revision to display'))],
3754 [('r', 'rev', '', _('revision to display'))],
3769 _('[-r REV]')),
3755 _('[-r REV]')),
3770 "^merge":
3756 "^merge":
3771 (merge,
3757 (merge,
3772 [('f', 'force', None, _('force a merge with outstanding changes')),
3758 [('f', 'force', None, _('force a merge with outstanding changes')),
3773 ('r', 'rev', '', _('revision to merge')),
3759 ('r', 'rev', '', _('revision to merge')),
3774 ('P', 'preview', None,
3760 ('P', 'preview', None,
3775 _('review revisions to merge (no merge is performed)'))],
3761 _('review revisions to merge (no merge is performed)'))],
3776 _('[-P] [-f] [[-r] REV]')),
3762 _('[-P] [-f] [[-r] REV]')),
3777 "outgoing|out":
3763 "outgoing|out":
3778 (outgoing,
3764 (outgoing,
3779 [('f', 'force', None,
3765 [('f', 'force', None,
3780 _('run even when the destination is unrelated')),
3766 _('run even when the destination is unrelated')),
3781 ('r', 'rev', [],
3767 ('r', 'rev', [],
3782 _('a changeset intended to be included in the destination')),
3768 _('a changeset intended to be included in the destination')),
3783 ('n', 'newest-first', None, _('show newest record first')),
3769 ('n', 'newest-first', None, _('show newest record first')),
3784 ('b', 'branch', [],
3770 ('b', 'branch', [],
3785 _('a specific branch you would like to push')),
3771 _('a specific branch you would like to push')),
3786 ] + logopts + remoteopts,
3772 ] + logopts + remoteopts,
3787 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3773 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]')),
3788 "parents":
3774 "parents":
3789 (parents,
3775 (parents,
3790 [('r', 'rev', '', _('show parents of the specified revision')),
3776 [('r', 'rev', '', _('show parents of the specified revision')),
3791 ] + templateopts,
3777 ] + templateopts,
3792 _('[-r REV] [FILE]')),
3778 _('[-r REV] [FILE]')),
3793 "paths": (paths, [], _('[NAME]')),
3779 "paths": (paths, [], _('[NAME]')),
3794 "^pull":
3780 "^pull":
3795 (pull,
3781 (pull,
3796 [('u', 'update', None,
3782 [('u', 'update', None,
3797 _('update to new branch head if changesets were pulled')),
3783 _('update to new branch head if changesets were pulled')),
3798 ('f', 'force', None,
3784 ('f', 'force', None,
3799 _('run even when remote repository is unrelated')),
3785 _('run even when remote repository is unrelated')),
3800 ('r', 'rev', [],
3786 ('r', 'rev', [],
3801 _('a remote changeset intended to be added')),
3787 _('a remote changeset intended to be added')),
3802 ('b', 'branch', [],
3788 ('b', 'branch', [],
3803 _('a specific branch you would like to pull')),
3789 _('a specific branch you would like to pull')),
3804 ] + remoteopts,
3790 ] + remoteopts,
3805 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3791 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]')),
3806 "^push":
3792 "^push":
3807 (push,
3793 (push,
3808 [('f', 'force', None, _('force push')),
3794 [('f', 'force', None, _('force push')),
3809 ('r', 'rev', [],
3795 ('r', 'rev', [],
3810 _('a changeset intended to be included in the destination')),
3796 _('a changeset intended to be included in the destination')),
3811 ('b', 'branch', [],
3797 ('b', 'branch', [],
3812 _('a specific branch you would like to push')),
3798 _('a specific branch you would like to push')),
3813 ] + remoteopts,
3799 ] + remoteopts,
3814 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3800 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]')),
3815 "recover": (recover, []),
3801 "recover": (recover, []),
3816 "^remove|rm":
3802 "^remove|rm":
3817 (remove,
3803 (remove,
3818 [('A', 'after', None, _('record delete for missing files')),
3804 [('A', 'after', None, _('record delete for missing files')),
3819 ('f', 'force', None,
3805 ('f', 'force', None,
3820 _('remove (and delete) file even if added or modified')),
3806 _('remove (and delete) file even if added or modified')),
3821 ] + walkopts,
3807 ] + walkopts,
3822 _('[OPTION]... FILE...')),
3808 _('[OPTION]... FILE...')),
3823 "rename|mv":
3809 "rename|mv":
3824 (rename,
3810 (rename,
3825 [('A', 'after', None, _('record a rename that has already occurred')),
3811 [('A', 'after', None, _('record a rename that has already occurred')),
3826 ('f', 'force', None,
3812 ('f', 'force', None,
3827 _('forcibly copy over an existing managed file')),
3813 _('forcibly copy over an existing managed file')),
3828 ] + walkopts + dryrunopts,
3814 ] + walkopts + dryrunopts,
3829 _('[OPTION]... SOURCE... DEST')),
3815 _('[OPTION]... SOURCE... DEST')),
3830 "resolve":
3816 "resolve":
3831 (resolve,
3817 (resolve,
3832 [('a', 'all', None, _('select all unresolved files')),
3818 [('a', 'all', None, _('select all unresolved files')),
3833 ('l', 'list', None, _('list state of files needing merge')),
3819 ('l', 'list', None, _('list state of files needing merge')),
3834 ('m', 'mark', None, _('mark files as resolved')),
3820 ('m', 'mark', None, _('mark files as resolved')),
3835 ('u', 'unmark', None, _('unmark files as resolved')),
3821 ('u', 'unmark', None, _('unmark files as resolved')),
3836 ('n', 'no-status', None, _('hide status prefix'))]
3822 ('n', 'no-status', None, _('hide status prefix'))]
3837 + walkopts,
3823 + walkopts,
3838 _('[OPTION]... [FILE]...')),
3824 _('[OPTION]... [FILE]...')),
3839 "revert":
3825 "revert":
3840 (revert,
3826 (revert,
3841 [('a', 'all', None, _('revert all changes when no arguments given')),
3827 [('a', 'all', None, _('revert all changes when no arguments given')),
3842 ('d', 'date', '', _('tipmost revision matching date')),
3828 ('d', 'date', '', _('tipmost revision matching date')),
3843 ('r', 'rev', '', _('revert to the specified revision')),
3829 ('r', 'rev', '', _('revert to the specified revision')),
3844 ('', 'no-backup', None, _('do not save backup copies of files')),
3830 ('', 'no-backup', None, _('do not save backup copies of files')),
3845 ] + walkopts + dryrunopts,
3831 ] + walkopts + dryrunopts,
3846 _('[OPTION]... [-r REV] [NAME]...')),
3832 _('[OPTION]... [-r REV] [NAME]...')),
3847 "rollback": (rollback, dryrunopts),
3833 "rollback": (rollback, dryrunopts),
3848 "root": (root, []),
3834 "root": (root, []),
3849 "^serve":
3835 "^serve":
3850 (serve,
3836 (serve,
3851 [('A', 'accesslog', '', _('name of access log file to write to')),
3837 [('A', 'accesslog', '', _('name of access log file to write to')),
3852 ('d', 'daemon', None, _('run server in background')),
3838 ('d', 'daemon', None, _('run server in background')),
3853 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3839 ('', 'daemon-pipefds', '', _('used internally by daemon mode')),
3854 ('E', 'errorlog', '', _('name of error log file to write to')),
3840 ('E', 'errorlog', '', _('name of error log file to write to')),
3855 # use string type, then we can check if something was passed
3841 # use string type, then we can check if something was passed
3856 ('p', 'port', '', _('port to listen on (default: 8000)')),
3842 ('p', 'port', '', _('port to listen on (default: 8000)')),
3857 ('a', 'address', '',
3843 ('a', 'address', '',
3858 _('address to listen on (default: all interfaces)')),
3844 _('address to listen on (default: all interfaces)')),
3859 ('', 'prefix', '',
3845 ('', 'prefix', '',
3860 _('prefix path to serve from (default: server root)')),
3846 _('prefix path to serve from (default: server root)')),
3861 ('n', 'name', '',
3847 ('n', 'name', '',
3862 _('name to show in web pages (default: working directory)')),
3848 _('name to show in web pages (default: working directory)')),
3863 ('', 'web-conf', '', _('name of the hgweb config file'
3849 ('', 'web-conf', '', _('name of the hgweb config file'
3864 ' (serve more than one repository)')),
3850 ' (serve more than one repository)')),
3865 ('', 'webdir-conf', '', _('name of the hgweb config file'
3851 ('', 'webdir-conf', '', _('name of the hgweb config file'
3866 ' (DEPRECATED)')),
3852 ' (DEPRECATED)')),
3867 ('', 'pid-file', '', _('name of file to write process ID to')),
3853 ('', 'pid-file', '', _('name of file to write process ID to')),
3868 ('', 'stdio', None, _('for remote clients')),
3854 ('', 'stdio', None, _('for remote clients')),
3869 ('t', 'templates', '', _('web templates to use')),
3855 ('t', 'templates', '', _('web templates to use')),
3870 ('', 'style', '', _('template style to use')),
3856 ('', 'style', '', _('template style to use')),
3871 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3857 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
3872 ('', 'certificate', '', _('SSL certificate file'))],
3858 ('', 'certificate', '', _('SSL certificate file'))],
3873 _('[OPTION]...')),
3859 _('[OPTION]...')),
3874 "showconfig|debugconfig":
3860 "showconfig|debugconfig":
3875 (showconfig,
3861 (showconfig,
3876 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3862 [('u', 'untrusted', None, _('show untrusted configuration options'))],
3877 _('[-u] [NAME]...')),
3863 _('[-u] [NAME]...')),
3878 "^summary|sum":
3864 "^summary|sum":
3879 (summary,
3865 (summary,
3880 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
3866 [('', 'remote', None, _('check for push and pull'))], '[--remote]'),
3881 "^status|st":
3867 "^status|st":
3882 (status,
3868 (status,
3883 [('A', 'all', None, _('show status of all files')),
3869 [('A', 'all', None, _('show status of all files')),
3884 ('m', 'modified', None, _('show only modified files')),
3870 ('m', 'modified', None, _('show only modified files')),
3885 ('a', 'added', None, _('show only added files')),
3871 ('a', 'added', None, _('show only added files')),
3886 ('r', 'removed', None, _('show only removed files')),
3872 ('r', 'removed', None, _('show only removed files')),
3887 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3873 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
3888 ('c', 'clean', None, _('show only files without changes')),
3874 ('c', 'clean', None, _('show only files without changes')),
3889 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3875 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
3890 ('i', 'ignored', None, _('show only ignored files')),
3876 ('i', 'ignored', None, _('show only ignored files')),
3891 ('n', 'no-status', None, _('hide status prefix')),
3877 ('n', 'no-status', None, _('hide status prefix')),
3892 ('C', 'copies', None, _('show source of copied files')),
3878 ('C', 'copies', None, _('show source of copied files')),
3893 ('0', 'print0', None,
3879 ('0', 'print0', None,
3894 _('end filenames with NUL, for use with xargs')),
3880 _('end filenames with NUL, for use with xargs')),
3895 ('', 'rev', [], _('show difference from revision')),
3881 ('', 'rev', [], _('show difference from revision')),
3896 ('', 'change', '', _('list the changed files of a revision')),
3882 ('', 'change', '', _('list the changed files of a revision')),
3897 ] + walkopts,
3883 ] + walkopts,
3898 _('[OPTION]... [FILE]...')),
3884 _('[OPTION]... [FILE]...')),
3899 "tag":
3885 "tag":
3900 (tag,
3886 (tag,
3901 [('f', 'force', None, _('replace existing tag')),
3887 [('f', 'force', None, _('replace existing tag')),
3902 ('l', 'local', None, _('make the tag local')),
3888 ('l', 'local', None, _('make the tag local')),
3903 ('r', 'rev', '', _('revision to tag')),
3889 ('r', 'rev', '', _('revision to tag')),
3904 ('', 'remove', None, _('remove a tag')),
3890 ('', 'remove', None, _('remove a tag')),
3905 # -l/--local is already there, commitopts cannot be used
3891 # -l/--local is already there, commitopts cannot be used
3906 ('m', 'message', '', _('use <text> as commit message')),
3892 ('m', 'message', '', _('use <text> as commit message')),
3907 ] + commitopts2,
3893 ] + commitopts2,
3908 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
3894 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...')),
3909 "tags": (tags, [], ''),
3895 "tags": (tags, [], ''),
3910 "tip":
3896 "tip":
3911 (tip,
3897 (tip,
3912 [('p', 'patch', None, _('show patch')),
3898 [('p', 'patch', None, _('show patch')),
3913 ('g', 'git', None, _('use git extended diff format')),
3899 ('g', 'git', None, _('use git extended diff format')),
3914 ] + templateopts,
3900 ] + templateopts,
3915 _('[-p] [-g]')),
3901 _('[-p] [-g]')),
3916 "unbundle":
3902 "unbundle":
3917 (unbundle,
3903 (unbundle,
3918 [('u', 'update', None,
3904 [('u', 'update', None,
3919 _('update to new branch head if changesets were unbundled'))],
3905 _('update to new branch head if changesets were unbundled'))],
3920 _('[-u] FILE...')),
3906 _('[-u] FILE...')),
3921 "^update|up|checkout|co":
3907 "^update|up|checkout|co":
3922 (update,
3908 (update,
3923 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
3909 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
3924 ('c', 'check', None, _('check for uncommitted changes')),
3910 ('c', 'check', None, _('check for uncommitted changes')),
3925 ('d', 'date', '', _('tipmost revision matching date')),
3911 ('d', 'date', '', _('tipmost revision matching date')),
3926 ('r', 'rev', '', _('revision'))],
3912 ('r', 'rev', '', _('revision'))],
3927 _('[-c] [-C] [-d DATE] [[-r] REV]')),
3913 _('[-c] [-C] [-d DATE] [[-r] REV]')),
3928 "verify": (verify, []),
3914 "verify": (verify, []),
3929 "version": (version_, []),
3915 "version": (version_, []),
3930 }
3916 }
3931
3917
3932 norepo = ("clone init version help debugcommands debugcomplete debugdata"
3918 norepo = ("clone init version help debugcommands debugcomplete debugdata"
3933 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3919 " debugindex debugindexdot debugdate debuginstall debugfsinfo")
3934 optionalrepo = ("identify paths serve showconfig debugancestor")
3920 optionalrepo = ("identify paths serve showconfig debugancestor")
General Comments 0
You need to be logged in to leave comments. Login now