##// END OF EJS Templates
cmdutil, logmessage: use ui.fin when reading from '-'
Idan Kamara -
r14635:217b7d83 default
parent child Browse files
Show More
@@ -1,151 +1,151
1 1 # fetch.py - pull and merge remote changes
2 2 #
3 3 # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''pull, update and merge in one command'''
9 9
10 10 from mercurial.i18n import _
11 11 from mercurial.node import nullid, short
12 12 from mercurial import commands, cmdutil, hg, util, error
13 13 from mercurial.lock import release
14 14
15 15 def fetch(ui, repo, source='default', **opts):
16 16 '''pull changes from a remote repository, merge new changes if needed.
17 17
18 18 This finds all changes from the repository at the specified path
19 19 or URL and adds them to the local repository.
20 20
21 21 If the pulled changes add a new branch head, the head is
22 22 automatically merged, and the result of the merge is committed.
23 23 Otherwise, the working directory is updated to include the new
24 24 changes.
25 25
26 26 When a merge occurs, the newly pulled changes are assumed to be
27 27 "authoritative". The head of the new changes is used as the first
28 28 parent, with local changes as the second. To switch the merge
29 29 order, use --switch-parent.
30 30
31 31 See :hg:`help dates` for a list of formats valid for -d/--date.
32 32
33 33 Returns 0 on success.
34 34 '''
35 35
36 36 date = opts.get('date')
37 37 if date:
38 38 opts['date'] = util.parsedate(date)
39 39
40 40 parent, p2 = repo.dirstate.parents()
41 41 branch = repo.dirstate.branch()
42 42 branchnode = repo.branchtags().get(branch)
43 43 if parent != branchnode:
44 44 raise util.Abort(_('working dir not at branch tip '
45 45 '(use "hg update" to check out branch tip)'))
46 46
47 47 if p2 != nullid:
48 48 raise util.Abort(_('outstanding uncommitted merge'))
49 49
50 50 wlock = lock = None
51 51 try:
52 52 wlock = repo.wlock()
53 53 lock = repo.lock()
54 54 mod, add, rem, del_ = repo.status()[:4]
55 55
56 56 if mod or add or rem:
57 57 raise util.Abort(_('outstanding uncommitted changes'))
58 58 if del_:
59 59 raise util.Abort(_('working directory is missing some files'))
60 60 bheads = repo.branchheads(branch)
61 61 bheads = [head for head in bheads if len(repo[head].children()) == 0]
62 62 if len(bheads) > 1:
63 63 raise util.Abort(_('multiple heads in this branch '
64 64 '(use "hg heads ." and "hg merge" to merge)'))
65 65
66 66 other = hg.peer(repo, opts, ui.expandpath(source))
67 67 ui.status(_('pulling from %s\n') %
68 68 util.hidepassword(ui.expandpath(source)))
69 69 revs = None
70 70 if opts['rev']:
71 71 try:
72 72 revs = [other.lookup(rev) for rev in opts['rev']]
73 73 except error.CapabilityError:
74 74 err = _("Other repository doesn't support revision lookup, "
75 75 "so a rev cannot be specified.")
76 76 raise util.Abort(err)
77 77
78 78 # Are there any changes at all?
79 79 modheads = repo.pull(other, heads=revs)
80 80 if modheads == 0:
81 81 return 0
82 82
83 83 # Is this a simple fast-forward along the current branch?
84 84 newheads = repo.branchheads(branch)
85 85 newchildren = repo.changelog.nodesbetween([parent], newheads)[2]
86 86 if len(newheads) == 1:
87 87 if newchildren[0] != parent:
88 88 return hg.clean(repo, newchildren[0])
89 89 else:
90 90 return 0
91 91
92 92 # Are there more than one additional branch heads?
93 93 newchildren = [n for n in newchildren if n != parent]
94 94 newparent = parent
95 95 if newchildren:
96 96 newparent = newchildren[0]
97 97 hg.clean(repo, newparent)
98 98 newheads = [n for n in newheads if n != newparent]
99 99 if len(newheads) > 1:
100 100 ui.status(_('not merging with %d other new branch heads '
101 101 '(use "hg heads ." and "hg merge" to merge them)\n') %
102 102 (len(newheads) - 1))
103 103 return 1
104 104
105 105 # Otherwise, let's merge.
106 106 err = False
107 107 if newheads:
108 108 # By default, we consider the repository we're pulling
109 109 # *from* as authoritative, so we merge our changes into
110 110 # theirs.
111 111 if opts['switch_parent']:
112 112 firstparent, secondparent = newparent, newheads[0]
113 113 else:
114 114 firstparent, secondparent = newheads[0], newparent
115 115 ui.status(_('updating to %d:%s\n') %
116 116 (repo.changelog.rev(firstparent),
117 117 short(firstparent)))
118 118 hg.clean(repo, firstparent)
119 119 ui.status(_('merging with %d:%s\n') %
120 120 (repo.changelog.rev(secondparent), short(secondparent)))
121 121 err = hg.merge(repo, secondparent, remind=False)
122 122
123 123 if not err:
124 124 # we don't translate commit messages
125 message = (cmdutil.logmessage(opts) or
125 message = (cmdutil.logmessage(ui, opts) or
126 126 ('Automated merge with %s' %
127 127 util.removeauth(other.url())))
128 128 editor = cmdutil.commiteditor
129 129 if opts.get('force_editor') or opts.get('edit'):
130 130 editor = cmdutil.commitforceeditor
131 131 n = repo.commit(message, opts['user'], opts['date'], editor=editor)
132 132 ui.status(_('new changeset %d:%s merges remote changes '
133 133 'with local\n') % (repo.changelog.rev(n),
134 134 short(n)))
135 135
136 136 return err
137 137
138 138 finally:
139 139 release(lock, wlock)
140 140
141 141 cmdtable = {
142 142 'fetch':
143 143 (fetch,
144 144 [('r', 'rev', [],
145 145 _('a specific revision you would like to pull'), _('REV')),
146 146 ('e', 'edit', None, _('edit commit message')),
147 147 ('', 'force-editor', None, _('edit commit message (DEPRECATED)')),
148 148 ('', 'switch-parent', None, _('switch parents when merging')),
149 149 ] + commands.commitopts + commands.commitopts2 + commands.remoteopts,
150 150 _('hg fetch [SOURCE]')),
151 151 }
@@ -1,3301 +1,3301
1 1 # mq.py - patch queues for mercurial
2 2 #
3 3 # Copyright 2005, 2006 Chris Mason <mason@suse.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''manage a stack of patches
9 9
10 10 This extension lets you work with a stack of patches in a Mercurial
11 11 repository. It manages two stacks of patches - all known patches, and
12 12 applied patches (subset of known patches).
13 13
14 14 Known patches are represented as patch files in the .hg/patches
15 15 directory. Applied patches are both patch files and changesets.
16 16
17 17 Common tasks (use :hg:`help command` for more details)::
18 18
19 19 create new patch qnew
20 20 import existing patch qimport
21 21
22 22 print patch series qseries
23 23 print applied patches qapplied
24 24
25 25 add known patch to applied stack qpush
26 26 remove patch from applied stack qpop
27 27 refresh contents of top applied patch qrefresh
28 28
29 29 By default, mq will automatically use git patches when required to
30 30 avoid losing file mode changes, copy records, binary files or empty
31 31 files creations or deletions. This behaviour can be configured with::
32 32
33 33 [mq]
34 34 git = auto/keep/yes/no
35 35
36 36 If set to 'keep', mq will obey the [diff] section configuration while
37 37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 38 'no', mq will override the [diff] section and always generate git or
39 39 regular patches, possibly losing data in the second case.
40 40
41 41 You will by default be managing a patch queue named "patches". You can
42 42 create other, independent patch queues with the :hg:`qqueue` command.
43 43 '''
44 44
45 45 from mercurial.i18n import _
46 46 from mercurial.node import bin, hex, short, nullid, nullrev
47 47 from mercurial.lock import release
48 48 from mercurial import commands, cmdutil, hg, scmutil, util, revset
49 49 from mercurial import repair, extensions, url, error
50 50 from mercurial import patch as patchmod
51 51 import os, sys, re, errno, shutil
52 52
53 53 commands.norepo += " qclone"
54 54
55 55 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
56 56
57 57 cmdtable = {}
58 58 command = cmdutil.command(cmdtable)
59 59
60 60 # Patch names looks like unix-file names.
61 61 # They must be joinable with queue directory and result in the patch path.
62 62 normname = util.normpath
63 63
64 64 class statusentry(object):
65 65 def __init__(self, node, name):
66 66 self.node, self.name = node, name
67 67 def __repr__(self):
68 68 return hex(self.node) + ':' + self.name
69 69
70 70 class patchheader(object):
71 71 def __init__(self, pf, plainmode=False):
72 72 def eatdiff(lines):
73 73 while lines:
74 74 l = lines[-1]
75 75 if (l.startswith("diff -") or
76 76 l.startswith("Index:") or
77 77 l.startswith("===========")):
78 78 del lines[-1]
79 79 else:
80 80 break
81 81 def eatempty(lines):
82 82 while lines:
83 83 if not lines[-1].strip():
84 84 del lines[-1]
85 85 else:
86 86 break
87 87
88 88 message = []
89 89 comments = []
90 90 user = None
91 91 date = None
92 92 parent = None
93 93 format = None
94 94 subject = None
95 95 branch = None
96 96 nodeid = None
97 97 diffstart = 0
98 98
99 99 for line in file(pf):
100 100 line = line.rstrip()
101 101 if (line.startswith('diff --git')
102 102 or (diffstart and line.startswith('+++ '))):
103 103 diffstart = 2
104 104 break
105 105 diffstart = 0 # reset
106 106 if line.startswith("--- "):
107 107 diffstart = 1
108 108 continue
109 109 elif format == "hgpatch":
110 110 # parse values when importing the result of an hg export
111 111 if line.startswith("# User "):
112 112 user = line[7:]
113 113 elif line.startswith("# Date "):
114 114 date = line[7:]
115 115 elif line.startswith("# Parent "):
116 116 parent = line[9:].lstrip()
117 117 elif line.startswith("# Branch "):
118 118 branch = line[9:]
119 119 elif line.startswith("# Node ID "):
120 120 nodeid = line[10:]
121 121 elif not line.startswith("# ") and line:
122 122 message.append(line)
123 123 format = None
124 124 elif line == '# HG changeset patch':
125 125 message = []
126 126 format = "hgpatch"
127 127 elif (format != "tagdone" and (line.startswith("Subject: ") or
128 128 line.startswith("subject: "))):
129 129 subject = line[9:]
130 130 format = "tag"
131 131 elif (format != "tagdone" and (line.startswith("From: ") or
132 132 line.startswith("from: "))):
133 133 user = line[6:]
134 134 format = "tag"
135 135 elif (format != "tagdone" and (line.startswith("Date: ") or
136 136 line.startswith("date: "))):
137 137 date = line[6:]
138 138 format = "tag"
139 139 elif format == "tag" and line == "":
140 140 # when looking for tags (subject: from: etc) they
141 141 # end once you find a blank line in the source
142 142 format = "tagdone"
143 143 elif message or line:
144 144 message.append(line)
145 145 comments.append(line)
146 146
147 147 eatdiff(message)
148 148 eatdiff(comments)
149 149 # Remember the exact starting line of the patch diffs before consuming
150 150 # empty lines, for external use by TortoiseHg and others
151 151 self.diffstartline = len(comments)
152 152 eatempty(message)
153 153 eatempty(comments)
154 154
155 155 # make sure message isn't empty
156 156 if format and format.startswith("tag") and subject:
157 157 message.insert(0, "")
158 158 message.insert(0, subject)
159 159
160 160 self.message = message
161 161 self.comments = comments
162 162 self.user = user
163 163 self.date = date
164 164 self.parent = parent
165 165 # nodeid and branch are for external use by TortoiseHg and others
166 166 self.nodeid = nodeid
167 167 self.branch = branch
168 168 self.haspatch = diffstart > 1
169 169 self.plainmode = plainmode
170 170
171 171 def setuser(self, user):
172 172 if not self.updateheader(['From: ', '# User '], user):
173 173 try:
174 174 patchheaderat = self.comments.index('# HG changeset patch')
175 175 self.comments.insert(patchheaderat + 1, '# User ' + user)
176 176 except ValueError:
177 177 if self.plainmode or self._hasheader(['Date: ']):
178 178 self.comments = ['From: ' + user] + self.comments
179 179 else:
180 180 tmp = ['# HG changeset patch', '# User ' + user, '']
181 181 self.comments = tmp + self.comments
182 182 self.user = user
183 183
184 184 def setdate(self, date):
185 185 if not self.updateheader(['Date: ', '# Date '], date):
186 186 try:
187 187 patchheaderat = self.comments.index('# HG changeset patch')
188 188 self.comments.insert(patchheaderat + 1, '# Date ' + date)
189 189 except ValueError:
190 190 if self.plainmode or self._hasheader(['From: ']):
191 191 self.comments = ['Date: ' + date] + self.comments
192 192 else:
193 193 tmp = ['# HG changeset patch', '# Date ' + date, '']
194 194 self.comments = tmp + self.comments
195 195 self.date = date
196 196
197 197 def setparent(self, parent):
198 198 if not self.updateheader(['# Parent '], parent):
199 199 try:
200 200 patchheaderat = self.comments.index('# HG changeset patch')
201 201 self.comments.insert(patchheaderat + 1, '# Parent ' + parent)
202 202 except ValueError:
203 203 pass
204 204 self.parent = parent
205 205
206 206 def setmessage(self, message):
207 207 if self.comments:
208 208 self._delmsg()
209 209 self.message = [message]
210 210 self.comments += self.message
211 211
212 212 def updateheader(self, prefixes, new):
213 213 '''Update all references to a field in the patch header.
214 214 Return whether the field is present.'''
215 215 res = False
216 216 for prefix in prefixes:
217 217 for i in xrange(len(self.comments)):
218 218 if self.comments[i].startswith(prefix):
219 219 self.comments[i] = prefix + new
220 220 res = True
221 221 break
222 222 return res
223 223
224 224 def _hasheader(self, prefixes):
225 225 '''Check if a header starts with any of the given prefixes.'''
226 226 for prefix in prefixes:
227 227 for comment in self.comments:
228 228 if comment.startswith(prefix):
229 229 return True
230 230 return False
231 231
232 232 def __str__(self):
233 233 if not self.comments:
234 234 return ''
235 235 return '\n'.join(self.comments) + '\n\n'
236 236
237 237 def _delmsg(self):
238 238 '''Remove existing message, keeping the rest of the comments fields.
239 239 If comments contains 'subject: ', message will prepend
240 240 the field and a blank line.'''
241 241 if self.message:
242 242 subj = 'subject: ' + self.message[0].lower()
243 243 for i in xrange(len(self.comments)):
244 244 if subj == self.comments[i].lower():
245 245 del self.comments[i]
246 246 self.message = self.message[2:]
247 247 break
248 248 ci = 0
249 249 for mi in self.message:
250 250 while mi != self.comments[ci]:
251 251 ci += 1
252 252 del self.comments[ci]
253 253
254 254 class queue(object):
255 255 def __init__(self, ui, path, patchdir=None):
256 256 self.basepath = path
257 257 try:
258 258 fh = open(os.path.join(path, 'patches.queue'))
259 259 cur = fh.read().rstrip()
260 260 fh.close()
261 261 if not cur:
262 262 curpath = os.path.join(path, 'patches')
263 263 else:
264 264 curpath = os.path.join(path, 'patches-' + cur)
265 265 except IOError:
266 266 curpath = os.path.join(path, 'patches')
267 267 self.path = patchdir or curpath
268 268 self.opener = scmutil.opener(self.path)
269 269 self.ui = ui
270 270 self.applieddirty = 0
271 271 self.seriesdirty = 0
272 272 self.added = []
273 273 self.seriespath = "series"
274 274 self.statuspath = "status"
275 275 self.guardspath = "guards"
276 276 self.activeguards = None
277 277 self.guardsdirty = False
278 278 # Handle mq.git as a bool with extended values
279 279 try:
280 280 gitmode = ui.configbool('mq', 'git', None)
281 281 if gitmode is None:
282 282 raise error.ConfigError()
283 283 self.gitmode = gitmode and 'yes' or 'no'
284 284 except error.ConfigError:
285 285 self.gitmode = ui.config('mq', 'git', 'auto').lower()
286 286 self.plainmode = ui.configbool('mq', 'plain', False)
287 287
288 288 @util.propertycache
289 289 def applied(self):
290 290 if os.path.exists(self.join(self.statuspath)):
291 291 def parselines(lines):
292 292 for l in lines:
293 293 entry = l.split(':', 1)
294 294 if len(entry) > 1:
295 295 n, name = entry
296 296 yield statusentry(bin(n), name)
297 297 elif l.strip():
298 298 self.ui.warn(_('malformated mq status line: %s\n') % entry)
299 299 # else we ignore empty lines
300 300 lines = self.opener.read(self.statuspath).splitlines()
301 301 return list(parselines(lines))
302 302 return []
303 303
304 304 @util.propertycache
305 305 def fullseries(self):
306 306 if os.path.exists(self.join(self.seriespath)):
307 307 return self.opener.read(self.seriespath).splitlines()
308 308 return []
309 309
310 310 @util.propertycache
311 311 def series(self):
312 312 self.parseseries()
313 313 return self.series
314 314
315 315 @util.propertycache
316 316 def seriesguards(self):
317 317 self.parseseries()
318 318 return self.seriesguards
319 319
320 320 def invalidate(self):
321 321 for a in 'applied fullseries series seriesguards'.split():
322 322 if a in self.__dict__:
323 323 delattr(self, a)
324 324 self.applieddirty = 0
325 325 self.seriesdirty = 0
326 326 self.guardsdirty = False
327 327 self.activeguards = None
328 328
329 329 def diffopts(self, opts={}, patchfn=None):
330 330 diffopts = patchmod.diffopts(self.ui, opts)
331 331 if self.gitmode == 'auto':
332 332 diffopts.upgrade = True
333 333 elif self.gitmode == 'keep':
334 334 pass
335 335 elif self.gitmode in ('yes', 'no'):
336 336 diffopts.git = self.gitmode == 'yes'
337 337 else:
338 338 raise util.Abort(_('mq.git option can be auto/keep/yes/no'
339 339 ' got %s') % self.gitmode)
340 340 if patchfn:
341 341 diffopts = self.patchopts(diffopts, patchfn)
342 342 return diffopts
343 343
344 344 def patchopts(self, diffopts, *patches):
345 345 """Return a copy of input diff options with git set to true if
346 346 referenced patch is a git patch and should be preserved as such.
347 347 """
348 348 diffopts = diffopts.copy()
349 349 if not diffopts.git and self.gitmode == 'keep':
350 350 for patchfn in patches:
351 351 patchf = self.opener(patchfn, 'r')
352 352 # if the patch was a git patch, refresh it as a git patch
353 353 for line in patchf:
354 354 if line.startswith('diff --git'):
355 355 diffopts.git = True
356 356 break
357 357 patchf.close()
358 358 return diffopts
359 359
360 360 def join(self, *p):
361 361 return os.path.join(self.path, *p)
362 362
363 363 def findseries(self, patch):
364 364 def matchpatch(l):
365 365 l = l.split('#', 1)[0]
366 366 return l.strip() == patch
367 367 for index, l in enumerate(self.fullseries):
368 368 if matchpatch(l):
369 369 return index
370 370 return None
371 371
372 372 guard_re = re.compile(r'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
373 373
374 374 def parseseries(self):
375 375 self.series = []
376 376 self.seriesguards = []
377 377 for l in self.fullseries:
378 378 h = l.find('#')
379 379 if h == -1:
380 380 patch = l
381 381 comment = ''
382 382 elif h == 0:
383 383 continue
384 384 else:
385 385 patch = l[:h]
386 386 comment = l[h:]
387 387 patch = patch.strip()
388 388 if patch:
389 389 if patch in self.series:
390 390 raise util.Abort(_('%s appears more than once in %s') %
391 391 (patch, self.join(self.seriespath)))
392 392 self.series.append(patch)
393 393 self.seriesguards.append(self.guard_re.findall(comment))
394 394
395 395 def checkguard(self, guard):
396 396 if not guard:
397 397 return _('guard cannot be an empty string')
398 398 bad_chars = '# \t\r\n\f'
399 399 first = guard[0]
400 400 if first in '-+':
401 401 return (_('guard %r starts with invalid character: %r') %
402 402 (guard, first))
403 403 for c in bad_chars:
404 404 if c in guard:
405 405 return _('invalid character in guard %r: %r') % (guard, c)
406 406
407 407 def setactive(self, guards):
408 408 for guard in guards:
409 409 bad = self.checkguard(guard)
410 410 if bad:
411 411 raise util.Abort(bad)
412 412 guards = sorted(set(guards))
413 413 self.ui.debug('active guards: %s\n' % ' '.join(guards))
414 414 self.activeguards = guards
415 415 self.guardsdirty = True
416 416
417 417 def active(self):
418 418 if self.activeguards is None:
419 419 self.activeguards = []
420 420 try:
421 421 guards = self.opener.read(self.guardspath).split()
422 422 except IOError, err:
423 423 if err.errno != errno.ENOENT:
424 424 raise
425 425 guards = []
426 426 for i, guard in enumerate(guards):
427 427 bad = self.checkguard(guard)
428 428 if bad:
429 429 self.ui.warn('%s:%d: %s\n' %
430 430 (self.join(self.guardspath), i + 1, bad))
431 431 else:
432 432 self.activeguards.append(guard)
433 433 return self.activeguards
434 434
435 435 def setguards(self, idx, guards):
436 436 for g in guards:
437 437 if len(g) < 2:
438 438 raise util.Abort(_('guard %r too short') % g)
439 439 if g[0] not in '-+':
440 440 raise util.Abort(_('guard %r starts with invalid char') % g)
441 441 bad = self.checkguard(g[1:])
442 442 if bad:
443 443 raise util.Abort(bad)
444 444 drop = self.guard_re.sub('', self.fullseries[idx])
445 445 self.fullseries[idx] = drop + ''.join([' #' + g for g in guards])
446 446 self.parseseries()
447 447 self.seriesdirty = True
448 448
449 449 def pushable(self, idx):
450 450 if isinstance(idx, str):
451 451 idx = self.series.index(idx)
452 452 patchguards = self.seriesguards[idx]
453 453 if not patchguards:
454 454 return True, None
455 455 guards = self.active()
456 456 exactneg = [g for g in patchguards if g[0] == '-' and g[1:] in guards]
457 457 if exactneg:
458 458 return False, repr(exactneg[0])
459 459 pos = [g for g in patchguards if g[0] == '+']
460 460 exactpos = [g for g in pos if g[1:] in guards]
461 461 if pos:
462 462 if exactpos:
463 463 return True, repr(exactpos[0])
464 464 return False, ' '.join(map(repr, pos))
465 465 return True, ''
466 466
467 467 def explainpushable(self, idx, all_patches=False):
468 468 write = all_patches and self.ui.write or self.ui.warn
469 469 if all_patches or self.ui.verbose:
470 470 if isinstance(idx, str):
471 471 idx = self.series.index(idx)
472 472 pushable, why = self.pushable(idx)
473 473 if all_patches and pushable:
474 474 if why is None:
475 475 write(_('allowing %s - no guards in effect\n') %
476 476 self.series[idx])
477 477 else:
478 478 if not why:
479 479 write(_('allowing %s - no matching negative guards\n') %
480 480 self.series[idx])
481 481 else:
482 482 write(_('allowing %s - guarded by %s\n') %
483 483 (self.series[idx], why))
484 484 if not pushable:
485 485 if why:
486 486 write(_('skipping %s - guarded by %s\n') %
487 487 (self.series[idx], why))
488 488 else:
489 489 write(_('skipping %s - no matching guards\n') %
490 490 self.series[idx])
491 491
492 492 def savedirty(self):
493 493 def writelist(items, path):
494 494 fp = self.opener(path, 'w')
495 495 for i in items:
496 496 fp.write("%s\n" % i)
497 497 fp.close()
498 498 if self.applieddirty:
499 499 writelist(map(str, self.applied), self.statuspath)
500 500 if self.seriesdirty:
501 501 writelist(self.fullseries, self.seriespath)
502 502 if self.guardsdirty:
503 503 writelist(self.activeguards, self.guardspath)
504 504 if self.added:
505 505 qrepo = self.qrepo()
506 506 if qrepo:
507 507 qrepo[None].add(f for f in self.added if f not in qrepo[None])
508 508 self.added = []
509 509
510 510 def removeundo(self, repo):
511 511 undo = repo.sjoin('undo')
512 512 if not os.path.exists(undo):
513 513 return
514 514 try:
515 515 os.unlink(undo)
516 516 except OSError, inst:
517 517 self.ui.warn(_('error removing undo: %s\n') % str(inst))
518 518
519 519 def printdiff(self, repo, diffopts, node1, node2=None, files=None,
520 520 fp=None, changes=None, opts={}):
521 521 stat = opts.get('stat')
522 522 m = scmutil.match(repo, files, opts)
523 523 cmdutil.diffordiffstat(self.ui, repo, diffopts, node1, node2, m,
524 524 changes, stat, fp)
525 525
526 526 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
527 527 # first try just applying the patch
528 528 (err, n) = self.apply(repo, [patch], update_status=False,
529 529 strict=True, merge=rev)
530 530
531 531 if err == 0:
532 532 return (err, n)
533 533
534 534 if n is None:
535 535 raise util.Abort(_("apply failed for patch %s") % patch)
536 536
537 537 self.ui.warn(_("patch didn't work out, merging %s\n") % patch)
538 538
539 539 # apply failed, strip away that rev and merge.
540 540 hg.clean(repo, head)
541 541 self.strip(repo, [n], update=False, backup='strip')
542 542
543 543 ctx = repo[rev]
544 544 ret = hg.merge(repo, rev)
545 545 if ret:
546 546 raise util.Abort(_("update returned %d") % ret)
547 547 n = repo.commit(ctx.description(), ctx.user(), force=True)
548 548 if n is None:
549 549 raise util.Abort(_("repo commit failed"))
550 550 try:
551 551 ph = patchheader(mergeq.join(patch), self.plainmode)
552 552 except:
553 553 raise util.Abort(_("unable to read %s") % patch)
554 554
555 555 diffopts = self.patchopts(diffopts, patch)
556 556 patchf = self.opener(patch, "w")
557 557 comments = str(ph)
558 558 if comments:
559 559 patchf.write(comments)
560 560 self.printdiff(repo, diffopts, head, n, fp=patchf)
561 561 patchf.close()
562 562 self.removeundo(repo)
563 563 return (0, n)
564 564
565 565 def qparents(self, repo, rev=None):
566 566 if rev is None:
567 567 (p1, p2) = repo.dirstate.parents()
568 568 if p2 == nullid:
569 569 return p1
570 570 if not self.applied:
571 571 return None
572 572 return self.applied[-1].node
573 573 p1, p2 = repo.changelog.parents(rev)
574 574 if p2 != nullid and p2 in [x.node for x in self.applied]:
575 575 return p2
576 576 return p1
577 577
578 578 def mergepatch(self, repo, mergeq, series, diffopts):
579 579 if not self.applied:
580 580 # each of the patches merged in will have two parents. This
581 581 # can confuse the qrefresh, qdiff, and strip code because it
582 582 # needs to know which parent is actually in the patch queue.
583 583 # so, we insert a merge marker with only one parent. This way
584 584 # the first patch in the queue is never a merge patch
585 585 #
586 586 pname = ".hg.patches.merge.marker"
587 587 n = repo.commit('[mq]: merge marker', force=True)
588 588 self.removeundo(repo)
589 589 self.applied.append(statusentry(n, pname))
590 590 self.applieddirty = 1
591 591
592 592 head = self.qparents(repo)
593 593
594 594 for patch in series:
595 595 patch = mergeq.lookup(patch, strict=True)
596 596 if not patch:
597 597 self.ui.warn(_("patch %s does not exist\n") % patch)
598 598 return (1, None)
599 599 pushable, reason = self.pushable(patch)
600 600 if not pushable:
601 601 self.explainpushable(patch, all_patches=True)
602 602 continue
603 603 info = mergeq.isapplied(patch)
604 604 if not info:
605 605 self.ui.warn(_("patch %s is not applied\n") % patch)
606 606 return (1, None)
607 607 rev = info[1]
608 608 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
609 609 if head:
610 610 self.applied.append(statusentry(head, patch))
611 611 self.applieddirty = 1
612 612 if err:
613 613 return (err, head)
614 614 self.savedirty()
615 615 return (0, head)
616 616
617 617 def patch(self, repo, patchfile):
618 618 '''Apply patchfile to the working directory.
619 619 patchfile: name of patch file'''
620 620 files = set()
621 621 try:
622 622 fuzz = patchmod.patch(self.ui, repo, patchfile, strip=1,
623 623 files=files, eolmode=None)
624 624 return (True, list(files), fuzz)
625 625 except Exception, inst:
626 626 self.ui.note(str(inst) + '\n')
627 627 if not self.ui.verbose:
628 628 self.ui.warn(_("patch failed, unable to continue (try -v)\n"))
629 629 return (False, list(files), False)
630 630
631 631 def apply(self, repo, series, list=False, update_status=True,
632 632 strict=False, patchdir=None, merge=None, all_files=None):
633 633 wlock = lock = tr = None
634 634 try:
635 635 wlock = repo.wlock()
636 636 lock = repo.lock()
637 637 tr = repo.transaction("qpush")
638 638 try:
639 639 ret = self._apply(repo, series, list, update_status,
640 640 strict, patchdir, merge, all_files=all_files)
641 641 tr.close()
642 642 self.savedirty()
643 643 return ret
644 644 except:
645 645 try:
646 646 tr.abort()
647 647 finally:
648 648 repo.invalidate()
649 649 repo.dirstate.invalidate()
650 650 raise
651 651 finally:
652 652 release(tr, lock, wlock)
653 653 self.removeundo(repo)
654 654
655 655 def _apply(self, repo, series, list=False, update_status=True,
656 656 strict=False, patchdir=None, merge=None, all_files=None):
657 657 '''returns (error, hash)
658 658 error = 1 for unable to read, 2 for patch failed, 3 for patch fuzz'''
659 659 # TODO unify with commands.py
660 660 if not patchdir:
661 661 patchdir = self.path
662 662 err = 0
663 663 n = None
664 664 for patchname in series:
665 665 pushable, reason = self.pushable(patchname)
666 666 if not pushable:
667 667 self.explainpushable(patchname, all_patches=True)
668 668 continue
669 669 self.ui.status(_("applying %s\n") % patchname)
670 670 pf = os.path.join(patchdir, patchname)
671 671
672 672 try:
673 673 ph = patchheader(self.join(patchname), self.plainmode)
674 674 except IOError:
675 675 self.ui.warn(_("unable to read %s\n") % patchname)
676 676 err = 1
677 677 break
678 678
679 679 message = ph.message
680 680 if not message:
681 681 # The commit message should not be translated
682 682 message = "imported patch %s\n" % patchname
683 683 else:
684 684 if list:
685 685 # The commit message should not be translated
686 686 message.append("\nimported patch %s" % patchname)
687 687 message = '\n'.join(message)
688 688
689 689 if ph.haspatch:
690 690 (patcherr, files, fuzz) = self.patch(repo, pf)
691 691 if all_files is not None:
692 692 all_files.update(files)
693 693 patcherr = not patcherr
694 694 else:
695 695 self.ui.warn(_("patch %s is empty\n") % patchname)
696 696 patcherr, files, fuzz = 0, [], 0
697 697
698 698 if merge and files:
699 699 # Mark as removed/merged and update dirstate parent info
700 700 removed = []
701 701 merged = []
702 702 for f in files:
703 703 if os.path.lexists(repo.wjoin(f)):
704 704 merged.append(f)
705 705 else:
706 706 removed.append(f)
707 707 for f in removed:
708 708 repo.dirstate.remove(f)
709 709 for f in merged:
710 710 repo.dirstate.merge(f)
711 711 p1, p2 = repo.dirstate.parents()
712 712 repo.dirstate.setparents(p1, merge)
713 713
714 714 match = scmutil.matchfiles(repo, files or [])
715 715 n = repo.commit(message, ph.user, ph.date, match=match, force=True)
716 716
717 717 if n is None:
718 718 raise util.Abort(_("repository commit failed"))
719 719
720 720 if update_status:
721 721 self.applied.append(statusentry(n, patchname))
722 722
723 723 if patcherr:
724 724 self.ui.warn(_("patch failed, rejects left in working dir\n"))
725 725 err = 2
726 726 break
727 727
728 728 if fuzz and strict:
729 729 self.ui.warn(_("fuzz found when applying patch, stopping\n"))
730 730 err = 3
731 731 break
732 732 return (err, n)
733 733
734 734 def _cleanup(self, patches, numrevs, keep=False):
735 735 if not keep:
736 736 r = self.qrepo()
737 737 if r:
738 738 r[None].forget(patches)
739 739 for p in patches:
740 740 os.unlink(self.join(p))
741 741
742 742 if numrevs:
743 743 qfinished = self.applied[:numrevs]
744 744 del self.applied[:numrevs]
745 745 self.applieddirty = 1
746 746
747 747 unknown = []
748 748
749 749 for (i, p) in sorted([(self.findseries(p), p) for p in patches],
750 750 reverse=True):
751 751 if i is not None:
752 752 del self.fullseries[i]
753 753 else:
754 754 unknown.append(p)
755 755
756 756 if unknown:
757 757 if numrevs:
758 758 rev = dict((entry.name, entry.node) for entry in qfinished)
759 759 for p in unknown:
760 760 msg = _('revision %s refers to unknown patches: %s\n')
761 761 self.ui.warn(msg % (short(rev[p]), p))
762 762 else:
763 763 msg = _('unknown patches: %s\n')
764 764 raise util.Abort(''.join(msg % p for p in unknown))
765 765
766 766 self.parseseries()
767 767 self.seriesdirty = 1
768 768
769 769 def _revpatches(self, repo, revs):
770 770 firstrev = repo[self.applied[0].node].rev()
771 771 patches = []
772 772 for i, rev in enumerate(revs):
773 773
774 774 if rev < firstrev:
775 775 raise util.Abort(_('revision %d is not managed') % rev)
776 776
777 777 ctx = repo[rev]
778 778 base = self.applied[i].node
779 779 if ctx.node() != base:
780 780 msg = _('cannot delete revision %d above applied patches')
781 781 raise util.Abort(msg % rev)
782 782
783 783 patch = self.applied[i].name
784 784 for fmt in ('[mq]: %s', 'imported patch %s'):
785 785 if ctx.description() == fmt % patch:
786 786 msg = _('patch %s finalized without changeset message\n')
787 787 repo.ui.status(msg % patch)
788 788 break
789 789
790 790 patches.append(patch)
791 791 return patches
792 792
793 793 def finish(self, repo, revs):
794 794 patches = self._revpatches(repo, sorted(revs))
795 795 self._cleanup(patches, len(patches))
796 796
797 797 def delete(self, repo, patches, opts):
798 798 if not patches and not opts.get('rev'):
799 799 raise util.Abort(_('qdelete requires at least one revision or '
800 800 'patch name'))
801 801
802 802 realpatches = []
803 803 for patch in patches:
804 804 patch = self.lookup(patch, strict=True)
805 805 info = self.isapplied(patch)
806 806 if info:
807 807 raise util.Abort(_("cannot delete applied patch %s") % patch)
808 808 if patch not in self.series:
809 809 raise util.Abort(_("patch %s not in series file") % patch)
810 810 if patch not in realpatches:
811 811 realpatches.append(patch)
812 812
813 813 numrevs = 0
814 814 if opts.get('rev'):
815 815 if not self.applied:
816 816 raise util.Abort(_('no patches applied'))
817 817 revs = scmutil.revrange(repo, opts.get('rev'))
818 818 if len(revs) > 1 and revs[0] > revs[1]:
819 819 revs.reverse()
820 820 revpatches = self._revpatches(repo, revs)
821 821 realpatches += revpatches
822 822 numrevs = len(revpatches)
823 823
824 824 self._cleanup(realpatches, numrevs, opts.get('keep'))
825 825
826 826 def checktoppatch(self, repo):
827 827 if self.applied:
828 828 top = self.applied[-1].node
829 829 patch = self.applied[-1].name
830 830 pp = repo.dirstate.parents()
831 831 if top not in pp:
832 832 raise util.Abort(_("working directory revision is not qtip"))
833 833 return top, patch
834 834 return None, None
835 835
836 836 def checksubstate(self, repo):
837 837 '''return list of subrepos at a different revision than substate.
838 838 Abort if any subrepos have uncommitted changes.'''
839 839 inclsubs = []
840 840 wctx = repo[None]
841 841 for s in wctx.substate:
842 842 if wctx.sub(s).dirty(True):
843 843 raise util.Abort(
844 844 _("uncommitted changes in subrepository %s") % s)
845 845 elif wctx.sub(s).dirty():
846 846 inclsubs.append(s)
847 847 return inclsubs
848 848
849 849 def localchangesfound(self, refresh=True):
850 850 if refresh:
851 851 raise util.Abort(_("local changes found, refresh first"))
852 852 else:
853 853 raise util.Abort(_("local changes found"))
854 854
855 855 def checklocalchanges(self, repo, force=False, refresh=True):
856 856 m, a, r, d = repo.status()[:4]
857 857 if (m or a or r or d) and not force:
858 858 self.localchangesfound(refresh)
859 859 return m, a, r, d
860 860
861 861 _reserved = ('series', 'status', 'guards', '.', '..')
862 862 def checkreservedname(self, name):
863 863 if name in self._reserved:
864 864 raise util.Abort(_('"%s" cannot be used as the name of a patch')
865 865 % name)
866 866 for prefix in ('.hg', '.mq'):
867 867 if name.startswith(prefix):
868 868 raise util.Abort(_('patch name cannot begin with "%s"')
869 869 % prefix)
870 870 for c in ('#', ':'):
871 871 if c in name:
872 872 raise util.Abort(_('"%s" cannot be used in the name of a patch')
873 873 % c)
874 874
875 875 def checkpatchname(self, name, force=False):
876 876 self.checkreservedname(name)
877 877 if not force and os.path.exists(self.join(name)):
878 878 if os.path.isdir(self.join(name)):
879 879 raise util.Abort(_('"%s" already exists as a directory')
880 880 % name)
881 881 else:
882 882 raise util.Abort(_('patch "%s" already exists') % name)
883 883
884 884 def new(self, repo, patchfn, *pats, **opts):
885 885 """options:
886 886 msg: a string or a no-argument function returning a string
887 887 """
888 888 msg = opts.get('msg')
889 889 user = opts.get('user')
890 890 date = opts.get('date')
891 891 if date:
892 892 date = util.parsedate(date)
893 893 diffopts = self.diffopts({'git': opts.get('git')})
894 894 if opts.get('checkname', True):
895 895 self.checkpatchname(patchfn)
896 896 inclsubs = self.checksubstate(repo)
897 897 if inclsubs:
898 898 inclsubs.append('.hgsubstate')
899 899 if opts.get('include') or opts.get('exclude') or pats:
900 900 if inclsubs:
901 901 pats = list(pats or []) + inclsubs
902 902 match = scmutil.match(repo, pats, opts)
903 903 # detect missing files in pats
904 904 def badfn(f, msg):
905 905 if f != '.hgsubstate': # .hgsubstate is auto-created
906 906 raise util.Abort('%s: %s' % (f, msg))
907 907 match.bad = badfn
908 908 m, a, r, d = repo.status(match=match)[:4]
909 909 else:
910 910 m, a, r, d = self.checklocalchanges(repo, force=True)
911 911 match = scmutil.matchfiles(repo, m + a + r + inclsubs)
912 912 if len(repo[None].parents()) > 1:
913 913 raise util.Abort(_('cannot manage merge changesets'))
914 914 commitfiles = m + a + r
915 915 self.checktoppatch(repo)
916 916 insert = self.fullseriesend()
917 917 wlock = repo.wlock()
918 918 try:
919 919 try:
920 920 # if patch file write fails, abort early
921 921 p = self.opener(patchfn, "w")
922 922 except IOError, e:
923 923 raise util.Abort(_('cannot write patch "%s": %s')
924 924 % (patchfn, e.strerror))
925 925 try:
926 926 if self.plainmode:
927 927 if user:
928 928 p.write("From: " + user + "\n")
929 929 if not date:
930 930 p.write("\n")
931 931 if date:
932 932 p.write("Date: %d %d\n\n" % date)
933 933 else:
934 934 p.write("# HG changeset patch\n")
935 935 p.write("# Parent "
936 936 + hex(repo[None].p1().node()) + "\n")
937 937 if user:
938 938 p.write("# User " + user + "\n")
939 939 if date:
940 940 p.write("# Date %s %s\n\n" % date)
941 941 if hasattr(msg, '__call__'):
942 942 msg = msg()
943 943 commitmsg = msg and msg or ("[mq]: %s" % patchfn)
944 944 n = repo.commit(commitmsg, user, date, match=match, force=True)
945 945 if n is None:
946 946 raise util.Abort(_("repo commit failed"))
947 947 try:
948 948 self.fullseries[insert:insert] = [patchfn]
949 949 self.applied.append(statusentry(n, patchfn))
950 950 self.parseseries()
951 951 self.seriesdirty = 1
952 952 self.applieddirty = 1
953 953 if msg:
954 954 msg = msg + "\n\n"
955 955 p.write(msg)
956 956 if commitfiles:
957 957 parent = self.qparents(repo, n)
958 958 chunks = patchmod.diff(repo, node1=parent, node2=n,
959 959 match=match, opts=diffopts)
960 960 for chunk in chunks:
961 961 p.write(chunk)
962 962 p.close()
963 963 wlock.release()
964 964 wlock = None
965 965 r = self.qrepo()
966 966 if r:
967 967 r[None].add([patchfn])
968 968 except:
969 969 repo.rollback()
970 970 raise
971 971 except Exception:
972 972 patchpath = self.join(patchfn)
973 973 try:
974 974 os.unlink(patchpath)
975 975 except:
976 976 self.ui.warn(_('error unlinking %s\n') % patchpath)
977 977 raise
978 978 self.removeundo(repo)
979 979 finally:
980 980 release(wlock)
981 981
982 982 def strip(self, repo, revs, update=True, backup="all", force=None):
983 983 wlock = lock = None
984 984 try:
985 985 wlock = repo.wlock()
986 986 lock = repo.lock()
987 987
988 988 if update:
989 989 self.checklocalchanges(repo, force=force, refresh=False)
990 990 urev = self.qparents(repo, revs[0])
991 991 hg.clean(repo, urev)
992 992 repo.dirstate.write()
993 993
994 994 self.removeundo(repo)
995 995 for rev in revs:
996 996 repair.strip(self.ui, repo, rev, backup)
997 997 # strip may have unbundled a set of backed up revisions after
998 998 # the actual strip
999 999 self.removeundo(repo)
1000 1000 finally:
1001 1001 release(lock, wlock)
1002 1002
1003 1003 def isapplied(self, patch):
1004 1004 """returns (index, rev, patch)"""
1005 1005 for i, a in enumerate(self.applied):
1006 1006 if a.name == patch:
1007 1007 return (i, a.node, a.name)
1008 1008 return None
1009 1009
1010 1010 # if the exact patch name does not exist, we try a few
1011 1011 # variations. If strict is passed, we try only #1
1012 1012 #
1013 1013 # 1) a number to indicate an offset in the series file
1014 1014 # 2) a unique substring of the patch name was given
1015 1015 # 3) patchname[-+]num to indicate an offset in the series file
1016 1016 def lookup(self, patch, strict=False):
1017 1017 patch = patch and str(patch)
1018 1018
1019 1019 def partialname(s):
1020 1020 if s in self.series:
1021 1021 return s
1022 1022 matches = [x for x in self.series if s in x]
1023 1023 if len(matches) > 1:
1024 1024 self.ui.warn(_('patch name "%s" is ambiguous:\n') % s)
1025 1025 for m in matches:
1026 1026 self.ui.warn(' %s\n' % m)
1027 1027 return None
1028 1028 if matches:
1029 1029 return matches[0]
1030 1030 if self.series and self.applied:
1031 1031 if s == 'qtip':
1032 1032 return self.series[self.seriesend(True)-1]
1033 1033 if s == 'qbase':
1034 1034 return self.series[0]
1035 1035 return None
1036 1036
1037 1037 if patch is None:
1038 1038 return None
1039 1039 if patch in self.series:
1040 1040 return patch
1041 1041
1042 1042 if not os.path.isfile(self.join(patch)):
1043 1043 try:
1044 1044 sno = int(patch)
1045 1045 except (ValueError, OverflowError):
1046 1046 pass
1047 1047 else:
1048 1048 if -len(self.series) <= sno < len(self.series):
1049 1049 return self.series[sno]
1050 1050
1051 1051 if not strict:
1052 1052 res = partialname(patch)
1053 1053 if res:
1054 1054 return res
1055 1055 minus = patch.rfind('-')
1056 1056 if minus >= 0:
1057 1057 res = partialname(patch[:minus])
1058 1058 if res:
1059 1059 i = self.series.index(res)
1060 1060 try:
1061 1061 off = int(patch[minus + 1:] or 1)
1062 1062 except (ValueError, OverflowError):
1063 1063 pass
1064 1064 else:
1065 1065 if i - off >= 0:
1066 1066 return self.series[i - off]
1067 1067 plus = patch.rfind('+')
1068 1068 if plus >= 0:
1069 1069 res = partialname(patch[:plus])
1070 1070 if res:
1071 1071 i = self.series.index(res)
1072 1072 try:
1073 1073 off = int(patch[plus + 1:] or 1)
1074 1074 except (ValueError, OverflowError):
1075 1075 pass
1076 1076 else:
1077 1077 if i + off < len(self.series):
1078 1078 return self.series[i + off]
1079 1079 raise util.Abort(_("patch %s not in series") % patch)
1080 1080
1081 1081 def push(self, repo, patch=None, force=False, list=False,
1082 1082 mergeq=None, all=False, move=False, exact=False):
1083 1083 diffopts = self.diffopts()
1084 1084 wlock = repo.wlock()
1085 1085 try:
1086 1086 heads = []
1087 1087 for b, ls in repo.branchmap().iteritems():
1088 1088 heads += ls
1089 1089 if not heads:
1090 1090 heads = [nullid]
1091 1091 if repo.dirstate.p1() not in heads and not exact:
1092 1092 self.ui.status(_("(working directory not at a head)\n"))
1093 1093
1094 1094 if not self.series:
1095 1095 self.ui.warn(_('no patches in series\n'))
1096 1096 return 0
1097 1097
1098 1098 patch = self.lookup(patch)
1099 1099 # Suppose our series file is: A B C and the current 'top'
1100 1100 # patch is B. qpush C should be performed (moving forward)
1101 1101 # qpush B is a NOP (no change) qpush A is an error (can't
1102 1102 # go backwards with qpush)
1103 1103 if patch:
1104 1104 info = self.isapplied(patch)
1105 1105 if info and info[0] >= len(self.applied) - 1:
1106 1106 self.ui.warn(
1107 1107 _('qpush: %s is already at the top\n') % patch)
1108 1108 return 0
1109 1109
1110 1110 pushable, reason = self.pushable(patch)
1111 1111 if pushable:
1112 1112 if self.series.index(patch) < self.seriesend():
1113 1113 raise util.Abort(
1114 1114 _("cannot push to a previous patch: %s") % patch)
1115 1115 else:
1116 1116 if reason:
1117 1117 reason = _('guarded by %s') % reason
1118 1118 else:
1119 1119 reason = _('no matching guards')
1120 1120 self.ui.warn(_("cannot push '%s' - %s\n") % (patch, reason))
1121 1121 return 1
1122 1122 elif all:
1123 1123 patch = self.series[-1]
1124 1124 if self.isapplied(patch):
1125 1125 self.ui.warn(_('all patches are currently applied\n'))
1126 1126 return 0
1127 1127
1128 1128 # Following the above example, starting at 'top' of B:
1129 1129 # qpush should be performed (pushes C), but a subsequent
1130 1130 # qpush without an argument is an error (nothing to
1131 1131 # apply). This allows a loop of "...while hg qpush..." to
1132 1132 # work as it detects an error when done
1133 1133 start = self.seriesend()
1134 1134 if start == len(self.series):
1135 1135 self.ui.warn(_('patch series already fully applied\n'))
1136 1136 return 1
1137 1137
1138 1138 if exact:
1139 1139 if move:
1140 1140 raise util.Abort(_("cannot use --exact and --move together"))
1141 1141 if self.applied:
1142 1142 raise util.Abort(_("cannot push --exact with applied patches"))
1143 1143 root = self.series[start]
1144 1144 target = patchheader(self.join(root), self.plainmode).parent
1145 1145 if not target:
1146 1146 raise util.Abort(_("%s does not have a parent recorded" % root))
1147 1147 if not repo[target] == repo['.']:
1148 1148 hg.update(repo, target)
1149 1149
1150 1150 if move:
1151 1151 if not patch:
1152 1152 raise util.Abort(_("please specify the patch to move"))
1153 1153 for i, rpn in enumerate(self.fullseries[start:]):
1154 1154 # strip markers for patch guards
1155 1155 if self.guard_re.split(rpn, 1)[0] == patch:
1156 1156 break
1157 1157 index = start + i
1158 1158 assert index < len(self.fullseries)
1159 1159 fullpatch = self.fullseries[index]
1160 1160 del self.fullseries[index]
1161 1161 self.fullseries.insert(start, fullpatch)
1162 1162 self.parseseries()
1163 1163 self.seriesdirty = 1
1164 1164
1165 1165 self.applieddirty = 1
1166 1166 if start > 0:
1167 1167 self.checktoppatch(repo)
1168 1168 if not patch:
1169 1169 patch = self.series[start]
1170 1170 end = start + 1
1171 1171 else:
1172 1172 end = self.series.index(patch, start) + 1
1173 1173
1174 1174 s = self.series[start:end]
1175 1175
1176 1176 if not force:
1177 1177 mm, aa, rr, dd = repo.status()[:4]
1178 1178 wcfiles = set(mm + aa + rr + dd)
1179 1179 if wcfiles:
1180 1180 for patchname in s:
1181 1181 pf = os.path.join(self.path, patchname)
1182 1182 patchfiles = patchmod.changedfiles(self.ui, repo, pf)
1183 1183 if wcfiles.intersection(patchfiles):
1184 1184 self.localchangesfound(self.applied)
1185 1185 elif mergeq:
1186 1186 self.checklocalchanges(refresh=self.applied)
1187 1187
1188 1188 all_files = set()
1189 1189 try:
1190 1190 if mergeq:
1191 1191 ret = self.mergepatch(repo, mergeq, s, diffopts)
1192 1192 else:
1193 1193 ret = self.apply(repo, s, list, all_files=all_files)
1194 1194 except:
1195 1195 self.ui.warn(_('cleaning up working directory...'))
1196 1196 node = repo.dirstate.p1()
1197 1197 hg.revert(repo, node, None)
1198 1198 # only remove unknown files that we know we touched or
1199 1199 # created while patching
1200 1200 for f in all_files:
1201 1201 if f not in repo.dirstate:
1202 1202 try:
1203 1203 util.unlinkpath(repo.wjoin(f))
1204 1204 except OSError, inst:
1205 1205 if inst.errno != errno.ENOENT:
1206 1206 raise
1207 1207 self.ui.warn(_('done\n'))
1208 1208 raise
1209 1209
1210 1210 if not self.applied:
1211 1211 return ret[0]
1212 1212 top = self.applied[-1].name
1213 1213 if ret[0] and ret[0] > 1:
1214 1214 msg = _("errors during apply, please fix and refresh %s\n")
1215 1215 self.ui.write(msg % top)
1216 1216 else:
1217 1217 self.ui.write(_("now at: %s\n") % top)
1218 1218 return ret[0]
1219 1219
1220 1220 finally:
1221 1221 wlock.release()
1222 1222
1223 1223 def pop(self, repo, patch=None, force=False, update=True, all=False):
1224 1224 wlock = repo.wlock()
1225 1225 try:
1226 1226 if patch:
1227 1227 # index, rev, patch
1228 1228 info = self.isapplied(patch)
1229 1229 if not info:
1230 1230 patch = self.lookup(patch)
1231 1231 info = self.isapplied(patch)
1232 1232 if not info:
1233 1233 raise util.Abort(_("patch %s is not applied") % patch)
1234 1234
1235 1235 if not self.applied:
1236 1236 # Allow qpop -a to work repeatedly,
1237 1237 # but not qpop without an argument
1238 1238 self.ui.warn(_("no patches applied\n"))
1239 1239 return not all
1240 1240
1241 1241 if all:
1242 1242 start = 0
1243 1243 elif patch:
1244 1244 start = info[0] + 1
1245 1245 else:
1246 1246 start = len(self.applied) - 1
1247 1247
1248 1248 if start >= len(self.applied):
1249 1249 self.ui.warn(_("qpop: %s is already at the top\n") % patch)
1250 1250 return
1251 1251
1252 1252 if not update:
1253 1253 parents = repo.dirstate.parents()
1254 1254 rr = [x.node for x in self.applied]
1255 1255 for p in parents:
1256 1256 if p in rr:
1257 1257 self.ui.warn(_("qpop: forcing dirstate update\n"))
1258 1258 update = True
1259 1259 else:
1260 1260 parents = [p.node() for p in repo[None].parents()]
1261 1261 needupdate = False
1262 1262 for entry in self.applied[start:]:
1263 1263 if entry.node in parents:
1264 1264 needupdate = True
1265 1265 break
1266 1266 update = needupdate
1267 1267
1268 1268 self.applieddirty = 1
1269 1269 end = len(self.applied)
1270 1270 rev = self.applied[start].node
1271 1271 if update:
1272 1272 top = self.checktoppatch(repo)[0]
1273 1273
1274 1274 try:
1275 1275 heads = repo.changelog.heads(rev)
1276 1276 except error.LookupError:
1277 1277 node = short(rev)
1278 1278 raise util.Abort(_('trying to pop unknown node %s') % node)
1279 1279
1280 1280 if heads != [self.applied[-1].node]:
1281 1281 raise util.Abort(_("popping would remove a revision not "
1282 1282 "managed by this patch queue"))
1283 1283
1284 1284 # we know there are no local changes, so we can make a simplified
1285 1285 # form of hg.update.
1286 1286 if update:
1287 1287 qp = self.qparents(repo, rev)
1288 1288 ctx = repo[qp]
1289 1289 m, a, r, d = repo.status(qp, top)[:4]
1290 1290 parentfiles = set(m + a + r + d)
1291 1291 if not force and parentfiles:
1292 1292 mm, aa, rr, dd = repo.status()[:4]
1293 1293 wcfiles = set(mm + aa + rr + dd)
1294 1294 if wcfiles.intersection(parentfiles):
1295 1295 self.localchangesfound()
1296 1296 if d:
1297 1297 raise util.Abort(_("deletions found between repo revs"))
1298 1298 for f in a:
1299 1299 try:
1300 1300 util.unlinkpath(repo.wjoin(f))
1301 1301 except OSError, e:
1302 1302 if e.errno != errno.ENOENT:
1303 1303 raise
1304 1304 repo.dirstate.drop(f)
1305 1305 for f in m + r:
1306 1306 fctx = ctx[f]
1307 1307 repo.wwrite(f, fctx.data(), fctx.flags())
1308 1308 repo.dirstate.normal(f)
1309 1309 repo.dirstate.setparents(qp, nullid)
1310 1310 for patch in reversed(self.applied[start:end]):
1311 1311 self.ui.status(_("popping %s\n") % patch.name)
1312 1312 del self.applied[start:end]
1313 1313 self.strip(repo, [rev], update=False, backup='strip')
1314 1314 if self.applied:
1315 1315 self.ui.write(_("now at: %s\n") % self.applied[-1].name)
1316 1316 else:
1317 1317 self.ui.write(_("patch queue now empty\n"))
1318 1318 finally:
1319 1319 wlock.release()
1320 1320
1321 1321 def diff(self, repo, pats, opts):
1322 1322 top, patch = self.checktoppatch(repo)
1323 1323 if not top:
1324 1324 self.ui.write(_("no patches applied\n"))
1325 1325 return
1326 1326 qp = self.qparents(repo, top)
1327 1327 if opts.get('reverse'):
1328 1328 node1, node2 = None, qp
1329 1329 else:
1330 1330 node1, node2 = qp, None
1331 1331 diffopts = self.diffopts(opts, patch)
1332 1332 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1333 1333
1334 1334 def refresh(self, repo, pats=None, **opts):
1335 1335 if not self.applied:
1336 1336 self.ui.write(_("no patches applied\n"))
1337 1337 return 1
1338 1338 msg = opts.get('msg', '').rstrip()
1339 1339 newuser = opts.get('user')
1340 1340 newdate = opts.get('date')
1341 1341 if newdate:
1342 1342 newdate = '%d %d' % util.parsedate(newdate)
1343 1343 wlock = repo.wlock()
1344 1344
1345 1345 try:
1346 1346 self.checktoppatch(repo)
1347 1347 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1348 1348 if repo.changelog.heads(top) != [top]:
1349 1349 raise util.Abort(_("cannot refresh a revision with children"))
1350 1350
1351 1351 inclsubs = self.checksubstate(repo)
1352 1352
1353 1353 cparents = repo.changelog.parents(top)
1354 1354 patchparent = self.qparents(repo, top)
1355 1355 ph = patchheader(self.join(patchfn), self.plainmode)
1356 1356 diffopts = self.diffopts({'git': opts.get('git')}, patchfn)
1357 1357 if msg:
1358 1358 ph.setmessage(msg)
1359 1359 if newuser:
1360 1360 ph.setuser(newuser)
1361 1361 if newdate:
1362 1362 ph.setdate(newdate)
1363 1363 ph.setparent(hex(patchparent))
1364 1364
1365 1365 # only commit new patch when write is complete
1366 1366 patchf = self.opener(patchfn, 'w', atomictemp=True)
1367 1367
1368 1368 comments = str(ph)
1369 1369 if comments:
1370 1370 patchf.write(comments)
1371 1371
1372 1372 # update the dirstate in place, strip off the qtip commit
1373 1373 # and then commit.
1374 1374 #
1375 1375 # this should really read:
1376 1376 # mm, dd, aa = repo.status(top, patchparent)[:3]
1377 1377 # but we do it backwards to take advantage of manifest/chlog
1378 1378 # caching against the next repo.status call
1379 1379 mm, aa, dd = repo.status(patchparent, top)[:3]
1380 1380 changes = repo.changelog.read(top)
1381 1381 man = repo.manifest.read(changes[0])
1382 1382 aaa = aa[:]
1383 1383 matchfn = scmutil.match(repo, pats, opts)
1384 1384 # in short mode, we only diff the files included in the
1385 1385 # patch already plus specified files
1386 1386 if opts.get('short'):
1387 1387 # if amending a patch, we start with existing
1388 1388 # files plus specified files - unfiltered
1389 1389 match = scmutil.matchfiles(repo, mm + aa + dd + matchfn.files())
1390 1390 # filter with inc/exl options
1391 1391 matchfn = scmutil.match(repo, opts=opts)
1392 1392 else:
1393 1393 match = scmutil.matchall(repo)
1394 1394 m, a, r, d = repo.status(match=match)[:4]
1395 1395 mm = set(mm)
1396 1396 aa = set(aa)
1397 1397 dd = set(dd)
1398 1398
1399 1399 # we might end up with files that were added between
1400 1400 # qtip and the dirstate parent, but then changed in the
1401 1401 # local dirstate. in this case, we want them to only
1402 1402 # show up in the added section
1403 1403 for x in m:
1404 1404 if x not in aa:
1405 1405 mm.add(x)
1406 1406 # we might end up with files added by the local dirstate that
1407 1407 # were deleted by the patch. In this case, they should only
1408 1408 # show up in the changed section.
1409 1409 for x in a:
1410 1410 if x in dd:
1411 1411 dd.remove(x)
1412 1412 mm.add(x)
1413 1413 else:
1414 1414 aa.add(x)
1415 1415 # make sure any files deleted in the local dirstate
1416 1416 # are not in the add or change column of the patch
1417 1417 forget = []
1418 1418 for x in d + r:
1419 1419 if x in aa:
1420 1420 aa.remove(x)
1421 1421 forget.append(x)
1422 1422 continue
1423 1423 else:
1424 1424 mm.discard(x)
1425 1425 dd.add(x)
1426 1426
1427 1427 m = list(mm)
1428 1428 r = list(dd)
1429 1429 a = list(aa)
1430 1430 c = [filter(matchfn, l) for l in (m, a, r)]
1431 1431 match = scmutil.matchfiles(repo, set(c[0] + c[1] + c[2] + inclsubs))
1432 1432 chunks = patchmod.diff(repo, patchparent, match=match,
1433 1433 changes=c, opts=diffopts)
1434 1434 for chunk in chunks:
1435 1435 patchf.write(chunk)
1436 1436
1437 1437 try:
1438 1438 if diffopts.git or diffopts.upgrade:
1439 1439 copies = {}
1440 1440 for dst in a:
1441 1441 src = repo.dirstate.copied(dst)
1442 1442 # during qfold, the source file for copies may
1443 1443 # be removed. Treat this as a simple add.
1444 1444 if src is not None and src in repo.dirstate:
1445 1445 copies.setdefault(src, []).append(dst)
1446 1446 repo.dirstate.add(dst)
1447 1447 # remember the copies between patchparent and qtip
1448 1448 for dst in aaa:
1449 1449 f = repo.file(dst)
1450 1450 src = f.renamed(man[dst])
1451 1451 if src:
1452 1452 copies.setdefault(src[0], []).extend(
1453 1453 copies.get(dst, []))
1454 1454 if dst in a:
1455 1455 copies[src[0]].append(dst)
1456 1456 # we can't copy a file created by the patch itself
1457 1457 if dst in copies:
1458 1458 del copies[dst]
1459 1459 for src, dsts in copies.iteritems():
1460 1460 for dst in dsts:
1461 1461 repo.dirstate.copy(src, dst)
1462 1462 else:
1463 1463 for dst in a:
1464 1464 repo.dirstate.add(dst)
1465 1465 # Drop useless copy information
1466 1466 for f in list(repo.dirstate.copies()):
1467 1467 repo.dirstate.copy(None, f)
1468 1468 for f in r:
1469 1469 repo.dirstate.remove(f)
1470 1470 # if the patch excludes a modified file, mark that
1471 1471 # file with mtime=0 so status can see it.
1472 1472 mm = []
1473 1473 for i in xrange(len(m)-1, -1, -1):
1474 1474 if not matchfn(m[i]):
1475 1475 mm.append(m[i])
1476 1476 del m[i]
1477 1477 for f in m:
1478 1478 repo.dirstate.normal(f)
1479 1479 for f in mm:
1480 1480 repo.dirstate.normallookup(f)
1481 1481 for f in forget:
1482 1482 repo.dirstate.drop(f)
1483 1483
1484 1484 if not msg:
1485 1485 if not ph.message:
1486 1486 message = "[mq]: %s\n" % patchfn
1487 1487 else:
1488 1488 message = "\n".join(ph.message)
1489 1489 else:
1490 1490 message = msg
1491 1491
1492 1492 user = ph.user or changes[1]
1493 1493
1494 1494 # assumes strip can roll itself back if interrupted
1495 1495 repo.dirstate.setparents(*cparents)
1496 1496 self.applied.pop()
1497 1497 self.applieddirty = 1
1498 1498 self.strip(repo, [top], update=False,
1499 1499 backup='strip')
1500 1500 except:
1501 1501 repo.dirstate.invalidate()
1502 1502 raise
1503 1503
1504 1504 try:
1505 1505 # might be nice to attempt to roll back strip after this
1506 1506 n = repo.commit(message, user, ph.date, match=match,
1507 1507 force=True)
1508 1508 # only write patch after a successful commit
1509 1509 patchf.rename()
1510 1510 self.applied.append(statusentry(n, patchfn))
1511 1511 except:
1512 1512 ctx = repo[cparents[0]]
1513 1513 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1514 1514 self.savedirty()
1515 1515 self.ui.warn(_('refresh interrupted while patch was popped! '
1516 1516 '(revert --all, qpush to recover)\n'))
1517 1517 raise
1518 1518 finally:
1519 1519 wlock.release()
1520 1520 self.removeundo(repo)
1521 1521
1522 1522 def init(self, repo, create=False):
1523 1523 if not create and os.path.isdir(self.path):
1524 1524 raise util.Abort(_("patch queue directory already exists"))
1525 1525 try:
1526 1526 os.mkdir(self.path)
1527 1527 except OSError, inst:
1528 1528 if inst.errno != errno.EEXIST or not create:
1529 1529 raise
1530 1530 if create:
1531 1531 return self.qrepo(create=True)
1532 1532
1533 1533 def unapplied(self, repo, patch=None):
1534 1534 if patch and patch not in self.series:
1535 1535 raise util.Abort(_("patch %s is not in series file") % patch)
1536 1536 if not patch:
1537 1537 start = self.seriesend()
1538 1538 else:
1539 1539 start = self.series.index(patch) + 1
1540 1540 unapplied = []
1541 1541 for i in xrange(start, len(self.series)):
1542 1542 pushable, reason = self.pushable(i)
1543 1543 if pushable:
1544 1544 unapplied.append((i, self.series[i]))
1545 1545 self.explainpushable(i)
1546 1546 return unapplied
1547 1547
1548 1548 def qseries(self, repo, missing=None, start=0, length=None, status=None,
1549 1549 summary=False):
1550 1550 def displayname(pfx, patchname, state):
1551 1551 if pfx:
1552 1552 self.ui.write(pfx)
1553 1553 if summary:
1554 1554 ph = patchheader(self.join(patchname), self.plainmode)
1555 1555 msg = ph.message and ph.message[0] or ''
1556 1556 if self.ui.formatted():
1557 1557 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
1558 1558 if width > 0:
1559 1559 msg = util.ellipsis(msg, width)
1560 1560 else:
1561 1561 msg = ''
1562 1562 self.ui.write(patchname, label='qseries.' + state)
1563 1563 self.ui.write(': ')
1564 1564 self.ui.write(msg, label='qseries.message.' + state)
1565 1565 else:
1566 1566 self.ui.write(patchname, label='qseries.' + state)
1567 1567 self.ui.write('\n')
1568 1568
1569 1569 applied = set([p.name for p in self.applied])
1570 1570 if length is None:
1571 1571 length = len(self.series) - start
1572 1572 if not missing:
1573 1573 if self.ui.verbose:
1574 1574 idxwidth = len(str(start + length - 1))
1575 1575 for i in xrange(start, start + length):
1576 1576 patch = self.series[i]
1577 1577 if patch in applied:
1578 1578 char, state = 'A', 'applied'
1579 1579 elif self.pushable(i)[0]:
1580 1580 char, state = 'U', 'unapplied'
1581 1581 else:
1582 1582 char, state = 'G', 'guarded'
1583 1583 pfx = ''
1584 1584 if self.ui.verbose:
1585 1585 pfx = '%*d %s ' % (idxwidth, i, char)
1586 1586 elif status and status != char:
1587 1587 continue
1588 1588 displayname(pfx, patch, state)
1589 1589 else:
1590 1590 msng_list = []
1591 1591 for root, dirs, files in os.walk(self.path):
1592 1592 d = root[len(self.path) + 1:]
1593 1593 for f in files:
1594 1594 fl = os.path.join(d, f)
1595 1595 if (fl not in self.series and
1596 1596 fl not in (self.statuspath, self.seriespath,
1597 1597 self.guardspath)
1598 1598 and not fl.startswith('.')):
1599 1599 msng_list.append(fl)
1600 1600 for x in sorted(msng_list):
1601 1601 pfx = self.ui.verbose and ('D ') or ''
1602 1602 displayname(pfx, x, 'missing')
1603 1603
1604 1604 def issaveline(self, l):
1605 1605 if l.name == '.hg.patches.save.line':
1606 1606 return True
1607 1607
1608 1608 def qrepo(self, create=False):
1609 1609 ui = self.ui.copy()
1610 1610 ui.setconfig('paths', 'default', '', overlay=False)
1611 1611 ui.setconfig('paths', 'default-push', '', overlay=False)
1612 1612 if create or os.path.isdir(self.join(".hg")):
1613 1613 return hg.repository(ui, path=self.path, create=create)
1614 1614
1615 1615 def restore(self, repo, rev, delete=None, qupdate=None):
1616 1616 desc = repo[rev].description().strip()
1617 1617 lines = desc.splitlines()
1618 1618 i = 0
1619 1619 datastart = None
1620 1620 series = []
1621 1621 applied = []
1622 1622 qpp = None
1623 1623 for i, line in enumerate(lines):
1624 1624 if line == 'Patch Data:':
1625 1625 datastart = i + 1
1626 1626 elif line.startswith('Dirstate:'):
1627 1627 l = line.rstrip()
1628 1628 l = l[10:].split(' ')
1629 1629 qpp = [bin(x) for x in l]
1630 1630 elif datastart is not None:
1631 1631 l = line.rstrip()
1632 1632 n, name = l.split(':', 1)
1633 1633 if n:
1634 1634 applied.append(statusentry(bin(n), name))
1635 1635 else:
1636 1636 series.append(l)
1637 1637 if datastart is None:
1638 1638 self.ui.warn(_("No saved patch data found\n"))
1639 1639 return 1
1640 1640 self.ui.warn(_("restoring status: %s\n") % lines[0])
1641 1641 self.fullseries = series
1642 1642 self.applied = applied
1643 1643 self.parseseries()
1644 1644 self.seriesdirty = 1
1645 1645 self.applieddirty = 1
1646 1646 heads = repo.changelog.heads()
1647 1647 if delete:
1648 1648 if rev not in heads:
1649 1649 self.ui.warn(_("save entry has children, leaving it alone\n"))
1650 1650 else:
1651 1651 self.ui.warn(_("removing save entry %s\n") % short(rev))
1652 1652 pp = repo.dirstate.parents()
1653 1653 if rev in pp:
1654 1654 update = True
1655 1655 else:
1656 1656 update = False
1657 1657 self.strip(repo, [rev], update=update, backup='strip')
1658 1658 if qpp:
1659 1659 self.ui.warn(_("saved queue repository parents: %s %s\n") %
1660 1660 (short(qpp[0]), short(qpp[1])))
1661 1661 if qupdate:
1662 1662 self.ui.status(_("updating queue directory\n"))
1663 1663 r = self.qrepo()
1664 1664 if not r:
1665 1665 self.ui.warn(_("Unable to load queue repository\n"))
1666 1666 return 1
1667 1667 hg.clean(r, qpp[0])
1668 1668
1669 1669 def save(self, repo, msg=None):
1670 1670 if not self.applied:
1671 1671 self.ui.warn(_("save: no patches applied, exiting\n"))
1672 1672 return 1
1673 1673 if self.issaveline(self.applied[-1]):
1674 1674 self.ui.warn(_("status is already saved\n"))
1675 1675 return 1
1676 1676
1677 1677 if not msg:
1678 1678 msg = _("hg patches saved state")
1679 1679 else:
1680 1680 msg = "hg patches: " + msg.rstrip('\r\n')
1681 1681 r = self.qrepo()
1682 1682 if r:
1683 1683 pp = r.dirstate.parents()
1684 1684 msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
1685 1685 msg += "\n\nPatch Data:\n"
1686 1686 msg += ''.join('%s\n' % x for x in self.applied)
1687 1687 msg += ''.join(':%s\n' % x for x in self.fullseries)
1688 1688 n = repo.commit(msg, force=True)
1689 1689 if not n:
1690 1690 self.ui.warn(_("repo commit failed\n"))
1691 1691 return 1
1692 1692 self.applied.append(statusentry(n, '.hg.patches.save.line'))
1693 1693 self.applieddirty = 1
1694 1694 self.removeundo(repo)
1695 1695
1696 1696 def fullseriesend(self):
1697 1697 if self.applied:
1698 1698 p = self.applied[-1].name
1699 1699 end = self.findseries(p)
1700 1700 if end is None:
1701 1701 return len(self.fullseries)
1702 1702 return end + 1
1703 1703 return 0
1704 1704
1705 1705 def seriesend(self, all_patches=False):
1706 1706 """If all_patches is False, return the index of the next pushable patch
1707 1707 in the series, or the series length. If all_patches is True, return the
1708 1708 index of the first patch past the last applied one.
1709 1709 """
1710 1710 end = 0
1711 1711 def next(start):
1712 1712 if all_patches or start >= len(self.series):
1713 1713 return start
1714 1714 for i in xrange(start, len(self.series)):
1715 1715 p, reason = self.pushable(i)
1716 1716 if p:
1717 1717 break
1718 1718 self.explainpushable(i)
1719 1719 return i
1720 1720 if self.applied:
1721 1721 p = self.applied[-1].name
1722 1722 try:
1723 1723 end = self.series.index(p)
1724 1724 except ValueError:
1725 1725 return 0
1726 1726 return next(end + 1)
1727 1727 return next(end)
1728 1728
1729 1729 def appliedname(self, index):
1730 1730 pname = self.applied[index].name
1731 1731 if not self.ui.verbose:
1732 1732 p = pname
1733 1733 else:
1734 1734 p = str(self.series.index(pname)) + " " + pname
1735 1735 return p
1736 1736
1737 1737 def qimport(self, repo, files, patchname=None, rev=None, existing=None,
1738 1738 force=None, git=False):
1739 1739 def checkseries(patchname):
1740 1740 if patchname in self.series:
1741 1741 raise util.Abort(_('patch %s is already in the series file')
1742 1742 % patchname)
1743 1743
1744 1744 if rev:
1745 1745 if files:
1746 1746 raise util.Abort(_('option "-r" not valid when importing '
1747 1747 'files'))
1748 1748 rev = scmutil.revrange(repo, rev)
1749 1749 rev.sort(reverse=True)
1750 1750 if (len(files) > 1 or len(rev) > 1) and patchname:
1751 1751 raise util.Abort(_('option "-n" not valid when importing multiple '
1752 1752 'patches'))
1753 1753 if rev:
1754 1754 # If mq patches are applied, we can only import revisions
1755 1755 # that form a linear path to qbase.
1756 1756 # Otherwise, they should form a linear path to a head.
1757 1757 heads = repo.changelog.heads(repo.changelog.node(rev[-1]))
1758 1758 if len(heads) > 1:
1759 1759 raise util.Abort(_('revision %d is the root of more than one '
1760 1760 'branch') % rev[-1])
1761 1761 if self.applied:
1762 1762 base = repo.changelog.node(rev[0])
1763 1763 if base in [n.node for n in self.applied]:
1764 1764 raise util.Abort(_('revision %d is already managed')
1765 1765 % rev[0])
1766 1766 if heads != [self.applied[-1].node]:
1767 1767 raise util.Abort(_('revision %d is not the parent of '
1768 1768 'the queue') % rev[0])
1769 1769 base = repo.changelog.rev(self.applied[0].node)
1770 1770 lastparent = repo.changelog.parentrevs(base)[0]
1771 1771 else:
1772 1772 if heads != [repo.changelog.node(rev[0])]:
1773 1773 raise util.Abort(_('revision %d has unmanaged children')
1774 1774 % rev[0])
1775 1775 lastparent = None
1776 1776
1777 1777 diffopts = self.diffopts({'git': git})
1778 1778 for r in rev:
1779 1779 p1, p2 = repo.changelog.parentrevs(r)
1780 1780 n = repo.changelog.node(r)
1781 1781 if p2 != nullrev:
1782 1782 raise util.Abort(_('cannot import merge revision %d') % r)
1783 1783 if lastparent and lastparent != r:
1784 1784 raise util.Abort(_('revision %d is not the parent of %d')
1785 1785 % (r, lastparent))
1786 1786 lastparent = p1
1787 1787
1788 1788 if not patchname:
1789 1789 patchname = normname('%d.diff' % r)
1790 1790 checkseries(patchname)
1791 1791 self.checkpatchname(patchname, force)
1792 1792 self.fullseries.insert(0, patchname)
1793 1793
1794 1794 patchf = self.opener(patchname, "w")
1795 1795 cmdutil.export(repo, [n], fp=patchf, opts=diffopts)
1796 1796 patchf.close()
1797 1797
1798 1798 se = statusentry(n, patchname)
1799 1799 self.applied.insert(0, se)
1800 1800
1801 1801 self.added.append(patchname)
1802 1802 patchname = None
1803 1803 self.parseseries()
1804 1804 self.applieddirty = 1
1805 1805 self.seriesdirty = True
1806 1806
1807 1807 for i, filename in enumerate(files):
1808 1808 if existing:
1809 1809 if filename == '-':
1810 1810 raise util.Abort(_('-e is incompatible with import from -'))
1811 1811 filename = normname(filename)
1812 1812 self.checkreservedname(filename)
1813 1813 originpath = self.join(filename)
1814 1814 if not os.path.isfile(originpath):
1815 1815 raise util.Abort(_("patch %s does not exist") % filename)
1816 1816
1817 1817 if patchname:
1818 1818 self.checkpatchname(patchname, force)
1819 1819
1820 1820 self.ui.write(_('renaming %s to %s\n')
1821 1821 % (filename, patchname))
1822 1822 util.rename(originpath, self.join(patchname))
1823 1823 else:
1824 1824 patchname = filename
1825 1825
1826 1826 else:
1827 1827 if filename == '-' and not patchname:
1828 1828 raise util.Abort(_('need --name to import a patch from -'))
1829 1829 elif not patchname:
1830 1830 patchname = normname(os.path.basename(filename.rstrip('/')))
1831 1831 self.checkpatchname(patchname, force)
1832 1832 try:
1833 1833 if filename == '-':
1834 1834 text = sys.stdin.read()
1835 1835 else:
1836 1836 fp = url.open(self.ui, filename)
1837 1837 text = fp.read()
1838 1838 fp.close()
1839 1839 except (OSError, IOError):
1840 1840 raise util.Abort(_("unable to read file %s") % filename)
1841 1841 patchf = self.opener(patchname, "w")
1842 1842 patchf.write(text)
1843 1843 patchf.close()
1844 1844 if not force:
1845 1845 checkseries(patchname)
1846 1846 if patchname not in self.series:
1847 1847 index = self.fullseriesend() + i
1848 1848 self.fullseries[index:index] = [patchname]
1849 1849 self.parseseries()
1850 1850 self.seriesdirty = True
1851 1851 self.ui.warn(_("adding %s to series file\n") % patchname)
1852 1852 self.added.append(patchname)
1853 1853 patchname = None
1854 1854
1855 1855 self.removeundo(repo)
1856 1856
1857 1857 @command("qdelete|qremove|qrm",
1858 1858 [('k', 'keep', None, _('keep patch file')),
1859 1859 ('r', 'rev', [],
1860 1860 _('stop managing a revision (DEPRECATED)'), _('REV'))],
1861 1861 _('hg qdelete [-k] [PATCH]...'))
1862 1862 def delete(ui, repo, *patches, **opts):
1863 1863 """remove patches from queue
1864 1864
1865 1865 The patches must not be applied, and at least one patch is required. With
1866 1866 -k/--keep, the patch files are preserved in the patch directory.
1867 1867
1868 1868 To stop managing a patch and move it into permanent history,
1869 1869 use the :hg:`qfinish` command."""
1870 1870 q = repo.mq
1871 1871 q.delete(repo, patches, opts)
1872 1872 q.savedirty()
1873 1873 return 0
1874 1874
1875 1875 @command("qapplied",
1876 1876 [('1', 'last', None, _('show only the last patch'))
1877 1877 ] + seriesopts,
1878 1878 _('hg qapplied [-1] [-s] [PATCH]'))
1879 1879 def applied(ui, repo, patch=None, **opts):
1880 1880 """print the patches already applied
1881 1881
1882 1882 Returns 0 on success."""
1883 1883
1884 1884 q = repo.mq
1885 1885
1886 1886 if patch:
1887 1887 if patch not in q.series:
1888 1888 raise util.Abort(_("patch %s is not in series file") % patch)
1889 1889 end = q.series.index(patch) + 1
1890 1890 else:
1891 1891 end = q.seriesend(True)
1892 1892
1893 1893 if opts.get('last') and not end:
1894 1894 ui.write(_("no patches applied\n"))
1895 1895 return 1
1896 1896 elif opts.get('last') and end == 1:
1897 1897 ui.write(_("only one patch applied\n"))
1898 1898 return 1
1899 1899 elif opts.get('last'):
1900 1900 start = end - 2
1901 1901 end = 1
1902 1902 else:
1903 1903 start = 0
1904 1904
1905 1905 q.qseries(repo, length=end, start=start, status='A',
1906 1906 summary=opts.get('summary'))
1907 1907
1908 1908
1909 1909 @command("qunapplied",
1910 1910 [('1', 'first', None, _('show only the first patch'))] + seriesopts,
1911 1911 _('hg qunapplied [-1] [-s] [PATCH]'))
1912 1912 def unapplied(ui, repo, patch=None, **opts):
1913 1913 """print the patches not yet applied
1914 1914
1915 1915 Returns 0 on success."""
1916 1916
1917 1917 q = repo.mq
1918 1918 if patch:
1919 1919 if patch not in q.series:
1920 1920 raise util.Abort(_("patch %s is not in series file") % patch)
1921 1921 start = q.series.index(patch) + 1
1922 1922 else:
1923 1923 start = q.seriesend(True)
1924 1924
1925 1925 if start == len(q.series) and opts.get('first'):
1926 1926 ui.write(_("all patches applied\n"))
1927 1927 return 1
1928 1928
1929 1929 length = opts.get('first') and 1 or None
1930 1930 q.qseries(repo, start=start, length=length, status='U',
1931 1931 summary=opts.get('summary'))
1932 1932
1933 1933 @command("qimport",
1934 1934 [('e', 'existing', None, _('import file in patch directory')),
1935 1935 ('n', 'name', '',
1936 1936 _('name of patch file'), _('NAME')),
1937 1937 ('f', 'force', None, _('overwrite existing files')),
1938 1938 ('r', 'rev', [],
1939 1939 _('place existing revisions under mq control'), _('REV')),
1940 1940 ('g', 'git', None, _('use git extended diff format')),
1941 1941 ('P', 'push', None, _('qpush after importing'))],
1942 1942 _('hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... FILE...'))
1943 1943 def qimport(ui, repo, *filename, **opts):
1944 1944 """import a patch
1945 1945
1946 1946 The patch is inserted into the series after the last applied
1947 1947 patch. If no patches have been applied, qimport prepends the patch
1948 1948 to the series.
1949 1949
1950 1950 The patch will have the same name as its source file unless you
1951 1951 give it a new one with -n/--name.
1952 1952
1953 1953 You can register an existing patch inside the patch directory with
1954 1954 the -e/--existing flag.
1955 1955
1956 1956 With -f/--force, an existing patch of the same name will be
1957 1957 overwritten.
1958 1958
1959 1959 An existing changeset may be placed under mq control with -r/--rev
1960 1960 (e.g. qimport --rev tip -n patch will place tip under mq control).
1961 1961 With -g/--git, patches imported with --rev will use the git diff
1962 1962 format. See the diffs help topic for information on why this is
1963 1963 important for preserving rename/copy information and permission
1964 1964 changes. Use :hg:`qfinish` to remove changesets from mq control.
1965 1965
1966 1966 To import a patch from standard input, pass - as the patch file.
1967 1967 When importing from standard input, a patch name must be specified
1968 1968 using the --name flag.
1969 1969
1970 1970 To import an existing patch while renaming it::
1971 1971
1972 1972 hg qimport -e existing-patch -n new-name
1973 1973
1974 1974 Returns 0 if import succeeded.
1975 1975 """
1976 1976 q = repo.mq
1977 1977 try:
1978 1978 q.qimport(repo, filename, patchname=opts.get('name'),
1979 1979 existing=opts.get('existing'), force=opts.get('force'),
1980 1980 rev=opts.get('rev'), git=opts.get('git'))
1981 1981 finally:
1982 1982 q.savedirty()
1983 1983
1984 1984 if opts.get('push') and not opts.get('rev'):
1985 1985 return q.push(repo, None)
1986 1986 return 0
1987 1987
1988 1988 def qinit(ui, repo, create):
1989 1989 """initialize a new queue repository
1990 1990
1991 1991 This command also creates a series file for ordering patches, and
1992 1992 an mq-specific .hgignore file in the queue repository, to exclude
1993 1993 the status and guards files (these contain mostly transient state).
1994 1994
1995 1995 Returns 0 if initialization succeeded."""
1996 1996 q = repo.mq
1997 1997 r = q.init(repo, create)
1998 1998 q.savedirty()
1999 1999 if r:
2000 2000 if not os.path.exists(r.wjoin('.hgignore')):
2001 2001 fp = r.wopener('.hgignore', 'w')
2002 2002 fp.write('^\\.hg\n')
2003 2003 fp.write('^\\.mq\n')
2004 2004 fp.write('syntax: glob\n')
2005 2005 fp.write('status\n')
2006 2006 fp.write('guards\n')
2007 2007 fp.close()
2008 2008 if not os.path.exists(r.wjoin('series')):
2009 2009 r.wopener('series', 'w').close()
2010 2010 r[None].add(['.hgignore', 'series'])
2011 2011 commands.add(ui, r)
2012 2012 return 0
2013 2013
2014 2014 @command("^qinit",
2015 2015 [('c', 'create-repo', None, _('create queue repository'))],
2016 2016 _('hg qinit [-c]'))
2017 2017 def init(ui, repo, **opts):
2018 2018 """init a new queue repository (DEPRECATED)
2019 2019
2020 2020 The queue repository is unversioned by default. If
2021 2021 -c/--create-repo is specified, qinit will create a separate nested
2022 2022 repository for patches (qinit -c may also be run later to convert
2023 2023 an unversioned patch repository into a versioned one). You can use
2024 2024 qcommit to commit changes to this queue repository.
2025 2025
2026 2026 This command is deprecated. Without -c, it's implied by other relevant
2027 2027 commands. With -c, use :hg:`init --mq` instead."""
2028 2028 return qinit(ui, repo, create=opts.get('create_repo'))
2029 2029
2030 2030 @command("qclone",
2031 2031 [('', 'pull', None, _('use pull protocol to copy metadata')),
2032 2032 ('U', 'noupdate', None, _('do not update the new working directories')),
2033 2033 ('', 'uncompressed', None,
2034 2034 _('use uncompressed transfer (fast over LAN)')),
2035 2035 ('p', 'patches', '',
2036 2036 _('location of source patch repository'), _('REPO')),
2037 2037 ] + commands.remoteopts,
2038 2038 _('hg qclone [OPTION]... SOURCE [DEST]'))
2039 2039 def clone(ui, source, dest=None, **opts):
2040 2040 '''clone main and patch repository at same time
2041 2041
2042 2042 If source is local, destination will have no patches applied. If
2043 2043 source is remote, this command can not check if patches are
2044 2044 applied in source, so cannot guarantee that patches are not
2045 2045 applied in destination. If you clone remote repository, be sure
2046 2046 before that it has no patches applied.
2047 2047
2048 2048 Source patch repository is looked for in <src>/.hg/patches by
2049 2049 default. Use -p <url> to change.
2050 2050
2051 2051 The patch directory must be a nested Mercurial repository, as
2052 2052 would be created by :hg:`init --mq`.
2053 2053
2054 2054 Return 0 on success.
2055 2055 '''
2056 2056 def patchdir(repo):
2057 2057 url = repo.url()
2058 2058 if url.endswith('/'):
2059 2059 url = url[:-1]
2060 2060 return url + '/.hg/patches'
2061 2061 if dest is None:
2062 2062 dest = hg.defaultdest(source)
2063 2063 sr = hg.repository(hg.remoteui(ui, opts), ui.expandpath(source))
2064 2064 if opts.get('patches'):
2065 2065 patchespath = ui.expandpath(opts.get('patches'))
2066 2066 else:
2067 2067 patchespath = patchdir(sr)
2068 2068 try:
2069 2069 hg.repository(ui, patchespath)
2070 2070 except error.RepoError:
2071 2071 raise util.Abort(_('versioned patch repository not found'
2072 2072 ' (see init --mq)'))
2073 2073 qbase, destrev = None, None
2074 2074 if sr.local():
2075 2075 if sr.mq.applied:
2076 2076 qbase = sr.mq.applied[0].node
2077 2077 if not hg.islocal(dest):
2078 2078 heads = set(sr.heads())
2079 2079 destrev = list(heads.difference(sr.heads(qbase)))
2080 2080 destrev.append(sr.changelog.parents(qbase)[0])
2081 2081 elif sr.capable('lookup'):
2082 2082 try:
2083 2083 qbase = sr.lookup('qbase')
2084 2084 except error.RepoError:
2085 2085 pass
2086 2086 ui.note(_('cloning main repository\n'))
2087 2087 sr, dr = hg.clone(ui, opts, sr.url(), dest,
2088 2088 pull=opts.get('pull'),
2089 2089 rev=destrev,
2090 2090 update=False,
2091 2091 stream=opts.get('uncompressed'))
2092 2092 ui.note(_('cloning patch repository\n'))
2093 2093 hg.clone(ui, opts, opts.get('patches') or patchdir(sr), patchdir(dr),
2094 2094 pull=opts.get('pull'), update=not opts.get('noupdate'),
2095 2095 stream=opts.get('uncompressed'))
2096 2096 if dr.local():
2097 2097 if qbase:
2098 2098 ui.note(_('stripping applied patches from destination '
2099 2099 'repository\n'))
2100 2100 dr.mq.strip(dr, [qbase], update=False, backup=None)
2101 2101 if not opts.get('noupdate'):
2102 2102 ui.note(_('updating destination repository\n'))
2103 2103 hg.update(dr, dr.changelog.tip())
2104 2104
2105 2105 @command("qcommit|qci",
2106 2106 commands.table["^commit|ci"][1],
2107 2107 _('hg qcommit [OPTION]... [FILE]...'))
2108 2108 def commit(ui, repo, *pats, **opts):
2109 2109 """commit changes in the queue repository (DEPRECATED)
2110 2110
2111 2111 This command is deprecated; use :hg:`commit --mq` instead."""
2112 2112 q = repo.mq
2113 2113 r = q.qrepo()
2114 2114 if not r:
2115 2115 raise util.Abort('no queue repository')
2116 2116 commands.commit(r.ui, r, *pats, **opts)
2117 2117
2118 2118 @command("qseries",
2119 2119 [('m', 'missing', None, _('print patches not in series')),
2120 2120 ] + seriesopts,
2121 2121 _('hg qseries [-ms]'))
2122 2122 def series(ui, repo, **opts):
2123 2123 """print the entire series file
2124 2124
2125 2125 Returns 0 on success."""
2126 2126 repo.mq.qseries(repo, missing=opts.get('missing'), summary=opts.get('summary'))
2127 2127 return 0
2128 2128
2129 2129 @command("qtop", seriesopts, _('hg qtop [-s]'))
2130 2130 def top(ui, repo, **opts):
2131 2131 """print the name of the current patch
2132 2132
2133 2133 Returns 0 on success."""
2134 2134 q = repo.mq
2135 2135 t = q.applied and q.seriesend(True) or 0
2136 2136 if t:
2137 2137 q.qseries(repo, start=t - 1, length=1, status='A',
2138 2138 summary=opts.get('summary'))
2139 2139 else:
2140 2140 ui.write(_("no patches applied\n"))
2141 2141 return 1
2142 2142
2143 2143 @command("qnext", seriesopts, _('hg qnext [-s]'))
2144 2144 def next(ui, repo, **opts):
2145 2145 """print the name of the next patch
2146 2146
2147 2147 Returns 0 on success."""
2148 2148 q = repo.mq
2149 2149 end = q.seriesend()
2150 2150 if end == len(q.series):
2151 2151 ui.write(_("all patches applied\n"))
2152 2152 return 1
2153 2153 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
2154 2154
2155 2155 @command("qprev", seriesopts, _('hg qprev [-s]'))
2156 2156 def prev(ui, repo, **opts):
2157 2157 """print the name of the previous patch
2158 2158
2159 2159 Returns 0 on success."""
2160 2160 q = repo.mq
2161 2161 l = len(q.applied)
2162 2162 if l == 1:
2163 2163 ui.write(_("only one patch applied\n"))
2164 2164 return 1
2165 2165 if not l:
2166 2166 ui.write(_("no patches applied\n"))
2167 2167 return 1
2168 2168 q.qseries(repo, start=l - 2, length=1, status='A',
2169 2169 summary=opts.get('summary'))
2170 2170
2171 2171 def setupheaderopts(ui, opts):
2172 2172 if not opts.get('user') and opts.get('currentuser'):
2173 2173 opts['user'] = ui.username()
2174 2174 if not opts.get('date') and opts.get('currentdate'):
2175 2175 opts['date'] = "%d %d" % util.makedate()
2176 2176
2177 2177 @command("^qnew",
2178 2178 [('e', 'edit', None, _('edit commit message')),
2179 2179 ('f', 'force', None, _('import uncommitted changes (DEPRECATED)')),
2180 2180 ('g', 'git', None, _('use git extended diff format')),
2181 2181 ('U', 'currentuser', None, _('add "From: <current user>" to patch')),
2182 2182 ('u', 'user', '',
2183 2183 _('add "From: <USER>" to patch'), _('USER')),
2184 2184 ('D', 'currentdate', None, _('add "Date: <current date>" to patch')),
2185 2185 ('d', 'date', '',
2186 2186 _('add "Date: <DATE>" to patch'), _('DATE'))
2187 2187 ] + commands.walkopts + commands.commitopts,
2188 2188 _('hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'))
2189 2189 def new(ui, repo, patch, *args, **opts):
2190 2190 """create a new patch
2191 2191
2192 2192 qnew creates a new patch on top of the currently-applied patch (if
2193 2193 any). The patch will be initialized with any outstanding changes
2194 2194 in the working directory. You may also use -I/--include,
2195 2195 -X/--exclude, and/or a list of files after the patch name to add
2196 2196 only changes to matching files to the new patch, leaving the rest
2197 2197 as uncommitted modifications.
2198 2198
2199 2199 -u/--user and -d/--date can be used to set the (given) user and
2200 2200 date, respectively. -U/--currentuser and -D/--currentdate set user
2201 2201 to current user and date to current date.
2202 2202
2203 2203 -e/--edit, -m/--message or -l/--logfile set the patch header as
2204 2204 well as the commit message. If none is specified, the header is
2205 2205 empty and the commit message is '[mq]: PATCH'.
2206 2206
2207 2207 Use the -g/--git option to keep the patch in the git extended diff
2208 2208 format. Read the diffs help topic for more information on why this
2209 2209 is important for preserving permission changes and copy/rename
2210 2210 information.
2211 2211
2212 2212 Returns 0 on successful creation of a new patch.
2213 2213 """
2214 msg = cmdutil.logmessage(opts)
2214 msg = cmdutil.logmessage(ui, opts)
2215 2215 def getmsg():
2216 2216 return ui.edit(msg, opts.get('user') or ui.username())
2217 2217 q = repo.mq
2218 2218 opts['msg'] = msg
2219 2219 if opts.get('edit'):
2220 2220 opts['msg'] = getmsg
2221 2221 else:
2222 2222 opts['msg'] = msg
2223 2223 setupheaderopts(ui, opts)
2224 2224 q.new(repo, patch, *args, **opts)
2225 2225 q.savedirty()
2226 2226 return 0
2227 2227
2228 2228 @command("^qrefresh",
2229 2229 [('e', 'edit', None, _('edit commit message')),
2230 2230 ('g', 'git', None, _('use git extended diff format')),
2231 2231 ('s', 'short', None,
2232 2232 _('refresh only files already in the patch and specified files')),
2233 2233 ('U', 'currentuser', None,
2234 2234 _('add/update author field in patch with current user')),
2235 2235 ('u', 'user', '',
2236 2236 _('add/update author field in patch with given user'), _('USER')),
2237 2237 ('D', 'currentdate', None,
2238 2238 _('add/update date field in patch with current date')),
2239 2239 ('d', 'date', '',
2240 2240 _('add/update date field in patch with given date'), _('DATE'))
2241 2241 ] + commands.walkopts + commands.commitopts,
2242 2242 _('hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'))
2243 2243 def refresh(ui, repo, *pats, **opts):
2244 2244 """update the current patch
2245 2245
2246 2246 If any file patterns are provided, the refreshed patch will
2247 2247 contain only the modifications that match those patterns; the
2248 2248 remaining modifications will remain in the working directory.
2249 2249
2250 2250 If -s/--short is specified, files currently included in the patch
2251 2251 will be refreshed just like matched files and remain in the patch.
2252 2252
2253 2253 If -e/--edit is specified, Mercurial will start your configured editor for
2254 2254 you to enter a message. In case qrefresh fails, you will find a backup of
2255 2255 your message in ``.hg/last-message.txt``.
2256 2256
2257 2257 hg add/remove/copy/rename work as usual, though you might want to
2258 2258 use git-style patches (-g/--git or [diff] git=1) to track copies
2259 2259 and renames. See the diffs help topic for more information on the
2260 2260 git diff format.
2261 2261
2262 2262 Returns 0 on success.
2263 2263 """
2264 2264 q = repo.mq
2265 message = cmdutil.logmessage(opts)
2265 message = cmdutil.logmessage(ui, opts)
2266 2266 if opts.get('edit'):
2267 2267 if not q.applied:
2268 2268 ui.write(_("no patches applied\n"))
2269 2269 return 1
2270 2270 if message:
2271 2271 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2272 2272 patch = q.applied[-1].name
2273 2273 ph = patchheader(q.join(patch), q.plainmode)
2274 2274 message = ui.edit('\n'.join(ph.message), ph.user or ui.username())
2275 2275 # We don't want to lose the patch message if qrefresh fails (issue2062)
2276 2276 repo.savecommitmessage(message)
2277 2277 setupheaderopts(ui, opts)
2278 2278 wlock = repo.wlock()
2279 2279 try:
2280 2280 ret = q.refresh(repo, pats, msg=message, **opts)
2281 2281 q.savedirty()
2282 2282 return ret
2283 2283 finally:
2284 2284 wlock.release()
2285 2285
2286 2286 @command("^qdiff",
2287 2287 commands.diffopts + commands.diffopts2 + commands.walkopts,
2288 2288 _('hg qdiff [OPTION]... [FILE]...'))
2289 2289 def diff(ui, repo, *pats, **opts):
2290 2290 """diff of the current patch and subsequent modifications
2291 2291
2292 2292 Shows a diff which includes the current patch as well as any
2293 2293 changes which have been made in the working directory since the
2294 2294 last refresh (thus showing what the current patch would become
2295 2295 after a qrefresh).
2296 2296
2297 2297 Use :hg:`diff` if you only want to see the changes made since the
2298 2298 last qrefresh, or :hg:`export qtip` if you want to see changes
2299 2299 made by the current patch without including changes made since the
2300 2300 qrefresh.
2301 2301
2302 2302 Returns 0 on success.
2303 2303 """
2304 2304 repo.mq.diff(repo, pats, opts)
2305 2305 return 0
2306 2306
2307 2307 @command('qfold',
2308 2308 [('e', 'edit', None, _('edit patch header')),
2309 2309 ('k', 'keep', None, _('keep folded patch files')),
2310 2310 ] + commands.commitopts,
2311 2311 _('hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'))
2312 2312 def fold(ui, repo, *files, **opts):
2313 2313 """fold the named patches into the current patch
2314 2314
2315 2315 Patches must not yet be applied. Each patch will be successively
2316 2316 applied to the current patch in the order given. If all the
2317 2317 patches apply successfully, the current patch will be refreshed
2318 2318 with the new cumulative patch, and the folded patches will be
2319 2319 deleted. With -k/--keep, the folded patch files will not be
2320 2320 removed afterwards.
2321 2321
2322 2322 The header for each folded patch will be concatenated with the
2323 2323 current patch header, separated by a line of ``* * *``.
2324 2324
2325 2325 Returns 0 on success."""
2326 2326
2327 2327 q = repo.mq
2328 2328
2329 2329 if not files:
2330 2330 raise util.Abort(_('qfold requires at least one patch name'))
2331 2331 if not q.checktoppatch(repo)[0]:
2332 2332 raise util.Abort(_('no patches applied'))
2333 2333 q.checklocalchanges(repo)
2334 2334
2335 message = cmdutil.logmessage(opts)
2335 message = cmdutil.logmessage(ui, opts)
2336 2336 if opts.get('edit'):
2337 2337 if message:
2338 2338 raise util.Abort(_('option "-e" incompatible with "-m" or "-l"'))
2339 2339
2340 2340 parent = q.lookup('qtip')
2341 2341 patches = []
2342 2342 messages = []
2343 2343 for f in files:
2344 2344 p = q.lookup(f)
2345 2345 if p in patches or p == parent:
2346 2346 ui.warn(_('Skipping already folded patch %s\n') % p)
2347 2347 if q.isapplied(p):
2348 2348 raise util.Abort(_('qfold cannot fold already applied patch %s') % p)
2349 2349 patches.append(p)
2350 2350
2351 2351 for p in patches:
2352 2352 if not message:
2353 2353 ph = patchheader(q.join(p), q.plainmode)
2354 2354 if ph.message:
2355 2355 messages.append(ph.message)
2356 2356 pf = q.join(p)
2357 2357 (patchsuccess, files, fuzz) = q.patch(repo, pf)
2358 2358 if not patchsuccess:
2359 2359 raise util.Abort(_('error folding patch %s') % p)
2360 2360
2361 2361 if not message:
2362 2362 ph = patchheader(q.join(parent), q.plainmode)
2363 2363 message, user = ph.message, ph.user
2364 2364 for msg in messages:
2365 2365 message.append('* * *')
2366 2366 message.extend(msg)
2367 2367 message = '\n'.join(message)
2368 2368
2369 2369 if opts.get('edit'):
2370 2370 message = ui.edit(message, user or ui.username())
2371 2371
2372 2372 diffopts = q.patchopts(q.diffopts(), *patches)
2373 2373 wlock = repo.wlock()
2374 2374 try:
2375 2375 q.refresh(repo, msg=message, git=diffopts.git)
2376 2376 q.delete(repo, patches, opts)
2377 2377 q.savedirty()
2378 2378 finally:
2379 2379 wlock.release()
2380 2380
2381 2381 @command("qgoto",
2382 2382 [('f', 'force', None, _('overwrite any local changes'))],
2383 2383 _('hg qgoto [OPTION]... PATCH'))
2384 2384 def goto(ui, repo, patch, **opts):
2385 2385 '''push or pop patches until named patch is at top of stack
2386 2386
2387 2387 Returns 0 on success.'''
2388 2388 q = repo.mq
2389 2389 patch = q.lookup(patch)
2390 2390 if q.isapplied(patch):
2391 2391 ret = q.pop(repo, patch, force=opts.get('force'))
2392 2392 else:
2393 2393 ret = q.push(repo, patch, force=opts.get('force'))
2394 2394 q.savedirty()
2395 2395 return ret
2396 2396
2397 2397 @command("qguard",
2398 2398 [('l', 'list', None, _('list all patches and guards')),
2399 2399 ('n', 'none', None, _('drop all guards'))],
2400 2400 _('hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'))
2401 2401 def guard(ui, repo, *args, **opts):
2402 2402 '''set or print guards for a patch
2403 2403
2404 2404 Guards control whether a patch can be pushed. A patch with no
2405 2405 guards is always pushed. A patch with a positive guard ("+foo") is
2406 2406 pushed only if the :hg:`qselect` command has activated it. A patch with
2407 2407 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
2408 2408 has activated it.
2409 2409
2410 2410 With no arguments, print the currently active guards.
2411 2411 With arguments, set guards for the named patch.
2412 2412
2413 2413 .. note::
2414 2414 Specifying negative guards now requires '--'.
2415 2415
2416 2416 To set guards on another patch::
2417 2417
2418 2418 hg qguard other.patch -- +2.6.17 -stable
2419 2419
2420 2420 Returns 0 on success.
2421 2421 '''
2422 2422 def status(idx):
2423 2423 guards = q.seriesguards[idx] or ['unguarded']
2424 2424 if q.series[idx] in applied:
2425 2425 state = 'applied'
2426 2426 elif q.pushable(idx)[0]:
2427 2427 state = 'unapplied'
2428 2428 else:
2429 2429 state = 'guarded'
2430 2430 label = 'qguard.patch qguard.%s qseries.%s' % (state, state)
2431 2431 ui.write('%s: ' % ui.label(q.series[idx], label))
2432 2432
2433 2433 for i, guard in enumerate(guards):
2434 2434 if guard.startswith('+'):
2435 2435 ui.write(guard, label='qguard.positive')
2436 2436 elif guard.startswith('-'):
2437 2437 ui.write(guard, label='qguard.negative')
2438 2438 else:
2439 2439 ui.write(guard, label='qguard.unguarded')
2440 2440 if i != len(guards) - 1:
2441 2441 ui.write(' ')
2442 2442 ui.write('\n')
2443 2443 q = repo.mq
2444 2444 applied = set(p.name for p in q.applied)
2445 2445 patch = None
2446 2446 args = list(args)
2447 2447 if opts.get('list'):
2448 2448 if args or opts.get('none'):
2449 2449 raise util.Abort(_('cannot mix -l/--list with options or arguments'))
2450 2450 for i in xrange(len(q.series)):
2451 2451 status(i)
2452 2452 return
2453 2453 if not args or args[0][0:1] in '-+':
2454 2454 if not q.applied:
2455 2455 raise util.Abort(_('no patches applied'))
2456 2456 patch = q.applied[-1].name
2457 2457 if patch is None and args[0][0:1] not in '-+':
2458 2458 patch = args.pop(0)
2459 2459 if patch is None:
2460 2460 raise util.Abort(_('no patch to work with'))
2461 2461 if args or opts.get('none'):
2462 2462 idx = q.findseries(patch)
2463 2463 if idx is None:
2464 2464 raise util.Abort(_('no patch named %s') % patch)
2465 2465 q.setguards(idx, args)
2466 2466 q.savedirty()
2467 2467 else:
2468 2468 status(q.series.index(q.lookup(patch)))
2469 2469
2470 2470 @command("qheader", [], _('hg qheader [PATCH]'))
2471 2471 def header(ui, repo, patch=None):
2472 2472 """print the header of the topmost or specified patch
2473 2473
2474 2474 Returns 0 on success."""
2475 2475 q = repo.mq
2476 2476
2477 2477 if patch:
2478 2478 patch = q.lookup(patch)
2479 2479 else:
2480 2480 if not q.applied:
2481 2481 ui.write(_('no patches applied\n'))
2482 2482 return 1
2483 2483 patch = q.lookup('qtip')
2484 2484 ph = patchheader(q.join(patch), q.plainmode)
2485 2485
2486 2486 ui.write('\n'.join(ph.message) + '\n')
2487 2487
2488 2488 def lastsavename(path):
2489 2489 (directory, base) = os.path.split(path)
2490 2490 names = os.listdir(directory)
2491 2491 namere = re.compile("%s.([0-9]+)" % base)
2492 2492 maxindex = None
2493 2493 maxname = None
2494 2494 for f in names:
2495 2495 m = namere.match(f)
2496 2496 if m:
2497 2497 index = int(m.group(1))
2498 2498 if maxindex is None or index > maxindex:
2499 2499 maxindex = index
2500 2500 maxname = f
2501 2501 if maxname:
2502 2502 return (os.path.join(directory, maxname), maxindex)
2503 2503 return (None, None)
2504 2504
2505 2505 def savename(path):
2506 2506 (last, index) = lastsavename(path)
2507 2507 if last is None:
2508 2508 index = 0
2509 2509 newpath = path + ".%d" % (index + 1)
2510 2510 return newpath
2511 2511
2512 2512 @command("^qpush",
2513 2513 [('f', 'force', None, _('apply on top of local changes')),
2514 2514 ('e', 'exact', None, _('apply the target patch to its recorded parent')),
2515 2515 ('l', 'list', None, _('list patch name in commit text')),
2516 2516 ('a', 'all', None, _('apply all patches')),
2517 2517 ('m', 'merge', None, _('merge from another queue (DEPRECATED)')),
2518 2518 ('n', 'name', '',
2519 2519 _('merge queue name (DEPRECATED)'), _('NAME')),
2520 2520 ('', 'move', None, _('reorder patch series and apply only the patch'))],
2521 2521 _('hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'))
2522 2522 def push(ui, repo, patch=None, **opts):
2523 2523 """push the next patch onto the stack
2524 2524
2525 2525 When -f/--force is applied, all local changes in patched files
2526 2526 will be lost.
2527 2527
2528 2528 Return 0 on success.
2529 2529 """
2530 2530 q = repo.mq
2531 2531 mergeq = None
2532 2532
2533 2533 if opts.get('merge'):
2534 2534 if opts.get('name'):
2535 2535 newpath = repo.join(opts.get('name'))
2536 2536 else:
2537 2537 newpath, i = lastsavename(q.path)
2538 2538 if not newpath:
2539 2539 ui.warn(_("no saved queues found, please use -n\n"))
2540 2540 return 1
2541 2541 mergeq = queue(ui, repo.join(""), newpath)
2542 2542 ui.warn(_("merging with queue at: %s\n") % mergeq.path)
2543 2543 ret = q.push(repo, patch, force=opts.get('force'), list=opts.get('list'),
2544 2544 mergeq=mergeq, all=opts.get('all'), move=opts.get('move'),
2545 2545 exact=opts.get('exact'))
2546 2546 return ret
2547 2547
2548 2548 @command("^qpop",
2549 2549 [('a', 'all', None, _('pop all patches')),
2550 2550 ('n', 'name', '',
2551 2551 _('queue name to pop (DEPRECATED)'), _('NAME')),
2552 2552 ('f', 'force', None, _('forget any local changes to patched files'))],
2553 2553 _('hg qpop [-a] [-f] [PATCH | INDEX]'))
2554 2554 def pop(ui, repo, patch=None, **opts):
2555 2555 """pop the current patch off the stack
2556 2556
2557 2557 By default, pops off the top of the patch stack. If given a patch
2558 2558 name, keeps popping off patches until the named patch is at the
2559 2559 top of the stack.
2560 2560
2561 2561 Return 0 on success.
2562 2562 """
2563 2563 localupdate = True
2564 2564 if opts.get('name'):
2565 2565 q = queue(ui, repo.join(""), repo.join(opts.get('name')))
2566 2566 ui.warn(_('using patch queue: %s\n') % q.path)
2567 2567 localupdate = False
2568 2568 else:
2569 2569 q = repo.mq
2570 2570 ret = q.pop(repo, patch, force=opts.get('force'), update=localupdate,
2571 2571 all=opts.get('all'))
2572 2572 q.savedirty()
2573 2573 return ret
2574 2574
2575 2575 @command("qrename|qmv", [], _('hg qrename PATCH1 [PATCH2]'))
2576 2576 def rename(ui, repo, patch, name=None, **opts):
2577 2577 """rename a patch
2578 2578
2579 2579 With one argument, renames the current patch to PATCH1.
2580 2580 With two arguments, renames PATCH1 to PATCH2.
2581 2581
2582 2582 Returns 0 on success."""
2583 2583
2584 2584 q = repo.mq
2585 2585
2586 2586 if not name:
2587 2587 name = patch
2588 2588 patch = None
2589 2589
2590 2590 if patch:
2591 2591 patch = q.lookup(patch)
2592 2592 else:
2593 2593 if not q.applied:
2594 2594 ui.write(_('no patches applied\n'))
2595 2595 return
2596 2596 patch = q.lookup('qtip')
2597 2597 absdest = q.join(name)
2598 2598 if os.path.isdir(absdest):
2599 2599 name = normname(os.path.join(name, os.path.basename(patch)))
2600 2600 absdest = q.join(name)
2601 2601 q.checkpatchname(name)
2602 2602
2603 2603 ui.note(_('renaming %s to %s\n') % (patch, name))
2604 2604 i = q.findseries(patch)
2605 2605 guards = q.guard_re.findall(q.fullseries[i])
2606 2606 q.fullseries[i] = name + ''.join([' #' + g for g in guards])
2607 2607 q.parseseries()
2608 2608 q.seriesdirty = 1
2609 2609
2610 2610 info = q.isapplied(patch)
2611 2611 if info:
2612 2612 q.applied[info[0]] = statusentry(info[1], name)
2613 2613 q.applieddirty = 1
2614 2614
2615 2615 destdir = os.path.dirname(absdest)
2616 2616 if not os.path.isdir(destdir):
2617 2617 os.makedirs(destdir)
2618 2618 util.rename(q.join(patch), absdest)
2619 2619 r = q.qrepo()
2620 2620 if r and patch in r.dirstate:
2621 2621 wctx = r[None]
2622 2622 wlock = r.wlock()
2623 2623 try:
2624 2624 if r.dirstate[patch] == 'a':
2625 2625 r.dirstate.drop(patch)
2626 2626 r.dirstate.add(name)
2627 2627 else:
2628 2628 if r.dirstate[name] == 'r':
2629 2629 wctx.undelete([name])
2630 2630 wctx.copy(patch, name)
2631 2631 wctx.forget([patch])
2632 2632 finally:
2633 2633 wlock.release()
2634 2634
2635 2635 q.savedirty()
2636 2636
2637 2637 @command("qrestore",
2638 2638 [('d', 'delete', None, _('delete save entry')),
2639 2639 ('u', 'update', None, _('update queue working directory'))],
2640 2640 _('hg qrestore [-d] [-u] REV'))
2641 2641 def restore(ui, repo, rev, **opts):
2642 2642 """restore the queue state saved by a revision (DEPRECATED)
2643 2643
2644 2644 This command is deprecated, use :hg:`rebase` instead."""
2645 2645 rev = repo.lookup(rev)
2646 2646 q = repo.mq
2647 2647 q.restore(repo, rev, delete=opts.get('delete'),
2648 2648 qupdate=opts.get('update'))
2649 2649 q.savedirty()
2650 2650 return 0
2651 2651
2652 2652 @command("qsave",
2653 2653 [('c', 'copy', None, _('copy patch directory')),
2654 2654 ('n', 'name', '',
2655 2655 _('copy directory name'), _('NAME')),
2656 2656 ('e', 'empty', None, _('clear queue status file')),
2657 2657 ('f', 'force', None, _('force copy'))] + commands.commitopts,
2658 2658 _('hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'))
2659 2659 def save(ui, repo, **opts):
2660 2660 """save current queue state (DEPRECATED)
2661 2661
2662 2662 This command is deprecated, use :hg:`rebase` instead."""
2663 2663 q = repo.mq
2664 message = cmdutil.logmessage(opts)
2664 message = cmdutil.logmessage(ui, opts)
2665 2665 ret = q.save(repo, msg=message)
2666 2666 if ret:
2667 2667 return ret
2668 2668 q.savedirty()
2669 2669 if opts.get('copy'):
2670 2670 path = q.path
2671 2671 if opts.get('name'):
2672 2672 newpath = os.path.join(q.basepath, opts.get('name'))
2673 2673 if os.path.exists(newpath):
2674 2674 if not os.path.isdir(newpath):
2675 2675 raise util.Abort(_('destination %s exists and is not '
2676 2676 'a directory') % newpath)
2677 2677 if not opts.get('force'):
2678 2678 raise util.Abort(_('destination %s exists, '
2679 2679 'use -f to force') % newpath)
2680 2680 else:
2681 2681 newpath = savename(path)
2682 2682 ui.warn(_("copy %s to %s\n") % (path, newpath))
2683 2683 util.copyfiles(path, newpath)
2684 2684 if opts.get('empty'):
2685 2685 try:
2686 2686 os.unlink(q.join(q.statuspath))
2687 2687 except:
2688 2688 pass
2689 2689 return 0
2690 2690
2691 2691 @command("strip",
2692 2692 [('f', 'force', None, _('force removal of changesets, discard '
2693 2693 'uncommitted changes (no backup)')),
2694 2694 ('b', 'backup', None, _('bundle only changesets with local revision'
2695 2695 ' number greater than REV which are not'
2696 2696 ' descendants of REV (DEPRECATED)')),
2697 2697 ('n', 'no-backup', None, _('no backups')),
2698 2698 ('', 'nobackup', None, _('no backups (DEPRECATED)')),
2699 2699 ('k', 'keep', None, _("do not modify working copy during strip"))],
2700 2700 _('hg strip [-k] [-f] [-n] REV...'))
2701 2701 def strip(ui, repo, *revs, **opts):
2702 2702 """strip changesets and all their descendants from the repository
2703 2703
2704 2704 The strip command removes the specified changesets and all their
2705 2705 descendants. If the working directory has uncommitted changes, the
2706 2706 operation is aborted unless the --force flag is supplied, in which
2707 2707 case changes will be discarded.
2708 2708
2709 2709 If a parent of the working directory is stripped, then the working
2710 2710 directory will automatically be updated to the most recent
2711 2711 available ancestor of the stripped parent after the operation
2712 2712 completes.
2713 2713
2714 2714 Any stripped changesets are stored in ``.hg/strip-backup`` as a
2715 2715 bundle (see :hg:`help bundle` and :hg:`help unbundle`). They can
2716 2716 be restored by running :hg:`unbundle .hg/strip-backup/BUNDLE`,
2717 2717 where BUNDLE is the bundle file created by the strip. Note that
2718 2718 the local revision numbers will in general be different after the
2719 2719 restore.
2720 2720
2721 2721 Use the --no-backup option to discard the backup bundle once the
2722 2722 operation completes.
2723 2723
2724 2724 Return 0 on success.
2725 2725 """
2726 2726 backup = 'all'
2727 2727 if opts.get('backup'):
2728 2728 backup = 'strip'
2729 2729 elif opts.get('no_backup') or opts.get('nobackup'):
2730 2730 backup = 'none'
2731 2731
2732 2732 cl = repo.changelog
2733 2733 revs = set(scmutil.revrange(repo, revs))
2734 2734 if not revs:
2735 2735 raise util.Abort(_('empty revision set'))
2736 2736
2737 2737 descendants = set(cl.descendants(*revs))
2738 2738 strippedrevs = revs.union(descendants)
2739 2739 roots = revs.difference(descendants)
2740 2740
2741 2741 update = False
2742 2742 # if one of the wdir parent is stripped we'll need
2743 2743 # to update away to an earlier revision
2744 2744 for p in repo.dirstate.parents():
2745 2745 if p != nullid and cl.rev(p) in strippedrevs:
2746 2746 update = True
2747 2747 break
2748 2748
2749 2749 rootnodes = set(cl.node(r) for r in roots)
2750 2750
2751 2751 q = repo.mq
2752 2752 if q.applied:
2753 2753 # refresh queue state if we're about to strip
2754 2754 # applied patches
2755 2755 if cl.rev(repo.lookup('qtip')) in strippedrevs:
2756 2756 q.applieddirty = True
2757 2757 start = 0
2758 2758 end = len(q.applied)
2759 2759 for i, statusentry in enumerate(q.applied):
2760 2760 if statusentry.node in rootnodes:
2761 2761 # if one of the stripped roots is an applied
2762 2762 # patch, only part of the queue is stripped
2763 2763 start = i
2764 2764 break
2765 2765 del q.applied[start:end]
2766 2766 q.savedirty()
2767 2767
2768 2768 revs = list(rootnodes)
2769 2769 if update and opts.get('keep'):
2770 2770 wlock = repo.wlock()
2771 2771 try:
2772 2772 urev = repo.mq.qparents(repo, revs[0])
2773 2773 repo.dirstate.rebuild(urev, repo[urev].manifest())
2774 2774 repo.dirstate.write()
2775 2775 update = False
2776 2776 finally:
2777 2777 wlock.release()
2778 2778
2779 2779 repo.mq.strip(repo, revs, backup=backup, update=update,
2780 2780 force=opts.get('force'))
2781 2781 return 0
2782 2782
2783 2783 @command("qselect",
2784 2784 [('n', 'none', None, _('disable all guards')),
2785 2785 ('s', 'series', None, _('list all guards in series file')),
2786 2786 ('', 'pop', None, _('pop to before first guarded applied patch')),
2787 2787 ('', 'reapply', None, _('pop, then reapply patches'))],
2788 2788 _('hg qselect [OPTION]... [GUARD]...'))
2789 2789 def select(ui, repo, *args, **opts):
2790 2790 '''set or print guarded patches to push
2791 2791
2792 2792 Use the :hg:`qguard` command to set or print guards on patch, then use
2793 2793 qselect to tell mq which guards to use. A patch will be pushed if
2794 2794 it has no guards or any positive guards match the currently
2795 2795 selected guard, but will not be pushed if any negative guards
2796 2796 match the current guard. For example::
2797 2797
2798 2798 qguard foo.patch -- -stable (negative guard)
2799 2799 qguard bar.patch +stable (positive guard)
2800 2800 qselect stable
2801 2801
2802 2802 This activates the "stable" guard. mq will skip foo.patch (because
2803 2803 it has a negative match) but push bar.patch (because it has a
2804 2804 positive match).
2805 2805
2806 2806 With no arguments, prints the currently active guards.
2807 2807 With one argument, sets the active guard.
2808 2808
2809 2809 Use -n/--none to deactivate guards (no other arguments needed).
2810 2810 When no guards are active, patches with positive guards are
2811 2811 skipped and patches with negative guards are pushed.
2812 2812
2813 2813 qselect can change the guards on applied patches. It does not pop
2814 2814 guarded patches by default. Use --pop to pop back to the last
2815 2815 applied patch that is not guarded. Use --reapply (which implies
2816 2816 --pop) to push back to the current patch afterwards, but skip
2817 2817 guarded patches.
2818 2818
2819 2819 Use -s/--series to print a list of all guards in the series file
2820 2820 (no other arguments needed). Use -v for more information.
2821 2821
2822 2822 Returns 0 on success.'''
2823 2823
2824 2824 q = repo.mq
2825 2825 guards = q.active()
2826 2826 if args or opts.get('none'):
2827 2827 old_unapplied = q.unapplied(repo)
2828 2828 old_guarded = [i for i in xrange(len(q.applied)) if
2829 2829 not q.pushable(i)[0]]
2830 2830 q.setactive(args)
2831 2831 q.savedirty()
2832 2832 if not args:
2833 2833 ui.status(_('guards deactivated\n'))
2834 2834 if not opts.get('pop') and not opts.get('reapply'):
2835 2835 unapplied = q.unapplied(repo)
2836 2836 guarded = [i for i in xrange(len(q.applied))
2837 2837 if not q.pushable(i)[0]]
2838 2838 if len(unapplied) != len(old_unapplied):
2839 2839 ui.status(_('number of unguarded, unapplied patches has '
2840 2840 'changed from %d to %d\n') %
2841 2841 (len(old_unapplied), len(unapplied)))
2842 2842 if len(guarded) != len(old_guarded):
2843 2843 ui.status(_('number of guarded, applied patches has changed '
2844 2844 'from %d to %d\n') %
2845 2845 (len(old_guarded), len(guarded)))
2846 2846 elif opts.get('series'):
2847 2847 guards = {}
2848 2848 noguards = 0
2849 2849 for gs in q.seriesguards:
2850 2850 if not gs:
2851 2851 noguards += 1
2852 2852 for g in gs:
2853 2853 guards.setdefault(g, 0)
2854 2854 guards[g] += 1
2855 2855 if ui.verbose:
2856 2856 guards['NONE'] = noguards
2857 2857 guards = guards.items()
2858 2858 guards.sort(key=lambda x: x[0][1:])
2859 2859 if guards:
2860 2860 ui.note(_('guards in series file:\n'))
2861 2861 for guard, count in guards:
2862 2862 ui.note('%2d ' % count)
2863 2863 ui.write(guard, '\n')
2864 2864 else:
2865 2865 ui.note(_('no guards in series file\n'))
2866 2866 else:
2867 2867 if guards:
2868 2868 ui.note(_('active guards:\n'))
2869 2869 for g in guards:
2870 2870 ui.write(g, '\n')
2871 2871 else:
2872 2872 ui.write(_('no active guards\n'))
2873 2873 reapply = opts.get('reapply') and q.applied and q.appliedname(-1)
2874 2874 popped = False
2875 2875 if opts.get('pop') or opts.get('reapply'):
2876 2876 for i in xrange(len(q.applied)):
2877 2877 pushable, reason = q.pushable(i)
2878 2878 if not pushable:
2879 2879 ui.status(_('popping guarded patches\n'))
2880 2880 popped = True
2881 2881 if i == 0:
2882 2882 q.pop(repo, all=True)
2883 2883 else:
2884 2884 q.pop(repo, i - 1)
2885 2885 break
2886 2886 if popped:
2887 2887 try:
2888 2888 if reapply:
2889 2889 ui.status(_('reapplying unguarded patches\n'))
2890 2890 q.push(repo, reapply)
2891 2891 finally:
2892 2892 q.savedirty()
2893 2893
2894 2894 @command("qfinish",
2895 2895 [('a', 'applied', None, _('finish all applied changesets'))],
2896 2896 _('hg qfinish [-a] [REV]...'))
2897 2897 def finish(ui, repo, *revrange, **opts):
2898 2898 """move applied patches into repository history
2899 2899
2900 2900 Finishes the specified revisions (corresponding to applied
2901 2901 patches) by moving them out of mq control into regular repository
2902 2902 history.
2903 2903
2904 2904 Accepts a revision range or the -a/--applied option. If --applied
2905 2905 is specified, all applied mq revisions are removed from mq
2906 2906 control. Otherwise, the given revisions must be at the base of the
2907 2907 stack of applied patches.
2908 2908
2909 2909 This can be especially useful if your changes have been applied to
2910 2910 an upstream repository, or if you are about to push your changes
2911 2911 to upstream.
2912 2912
2913 2913 Returns 0 on success.
2914 2914 """
2915 2915 if not opts.get('applied') and not revrange:
2916 2916 raise util.Abort(_('no revisions specified'))
2917 2917 elif opts.get('applied'):
2918 2918 revrange = ('qbase::qtip',) + revrange
2919 2919
2920 2920 q = repo.mq
2921 2921 if not q.applied:
2922 2922 ui.status(_('no patches applied\n'))
2923 2923 return 0
2924 2924
2925 2925 revs = scmutil.revrange(repo, revrange)
2926 2926 q.finish(repo, revs)
2927 2927 q.savedirty()
2928 2928 return 0
2929 2929
2930 2930 @command("qqueue",
2931 2931 [('l', 'list', False, _('list all available queues')),
2932 2932 ('c', 'create', False, _('create new queue')),
2933 2933 ('', 'rename', False, _('rename active queue')),
2934 2934 ('', 'delete', False, _('delete reference to queue')),
2935 2935 ('', 'purge', False, _('delete queue, and remove patch dir')),
2936 2936 ],
2937 2937 _('[OPTION] [QUEUE]'))
2938 2938 def qqueue(ui, repo, name=None, **opts):
2939 2939 '''manage multiple patch queues
2940 2940
2941 2941 Supports switching between different patch queues, as well as creating
2942 2942 new patch queues and deleting existing ones.
2943 2943
2944 2944 Omitting a queue name or specifying -l/--list will show you the registered
2945 2945 queues - by default the "normal" patches queue is registered. The currently
2946 2946 active queue will be marked with "(active)".
2947 2947
2948 2948 To create a new queue, use -c/--create. The queue is automatically made
2949 2949 active, except in the case where there are applied patches from the
2950 2950 currently active queue in the repository. Then the queue will only be
2951 2951 created and switching will fail.
2952 2952
2953 2953 To delete an existing queue, use --delete. You cannot delete the currently
2954 2954 active queue.
2955 2955
2956 2956 Returns 0 on success.
2957 2957 '''
2958 2958
2959 2959 q = repo.mq
2960 2960
2961 2961 _defaultqueue = 'patches'
2962 2962 _allqueues = 'patches.queues'
2963 2963 _activequeue = 'patches.queue'
2964 2964
2965 2965 def _getcurrent():
2966 2966 cur = os.path.basename(q.path)
2967 2967 if cur.startswith('patches-'):
2968 2968 cur = cur[8:]
2969 2969 return cur
2970 2970
2971 2971 def _noqueues():
2972 2972 try:
2973 2973 fh = repo.opener(_allqueues, 'r')
2974 2974 fh.close()
2975 2975 except IOError:
2976 2976 return True
2977 2977
2978 2978 return False
2979 2979
2980 2980 def _getqueues():
2981 2981 current = _getcurrent()
2982 2982
2983 2983 try:
2984 2984 fh = repo.opener(_allqueues, 'r')
2985 2985 queues = [queue.strip() for queue in fh if queue.strip()]
2986 2986 fh.close()
2987 2987 if current not in queues:
2988 2988 queues.append(current)
2989 2989 except IOError:
2990 2990 queues = [_defaultqueue]
2991 2991
2992 2992 return sorted(queues)
2993 2993
2994 2994 def _setactive(name):
2995 2995 if q.applied:
2996 2996 raise util.Abort(_('patches applied - cannot set new queue active'))
2997 2997 _setactivenocheck(name)
2998 2998
2999 2999 def _setactivenocheck(name):
3000 3000 fh = repo.opener(_activequeue, 'w')
3001 3001 if name != 'patches':
3002 3002 fh.write(name)
3003 3003 fh.close()
3004 3004
3005 3005 def _addqueue(name):
3006 3006 fh = repo.opener(_allqueues, 'a')
3007 3007 fh.write('%s\n' % (name,))
3008 3008 fh.close()
3009 3009
3010 3010 def _queuedir(name):
3011 3011 if name == 'patches':
3012 3012 return repo.join('patches')
3013 3013 else:
3014 3014 return repo.join('patches-' + name)
3015 3015
3016 3016 def _validname(name):
3017 3017 for n in name:
3018 3018 if n in ':\\/.':
3019 3019 return False
3020 3020 return True
3021 3021
3022 3022 def _delete(name):
3023 3023 if name not in existing:
3024 3024 raise util.Abort(_('cannot delete queue that does not exist'))
3025 3025
3026 3026 current = _getcurrent()
3027 3027
3028 3028 if name == current:
3029 3029 raise util.Abort(_('cannot delete currently active queue'))
3030 3030
3031 3031 fh = repo.opener('patches.queues.new', 'w')
3032 3032 for queue in existing:
3033 3033 if queue == name:
3034 3034 continue
3035 3035 fh.write('%s\n' % (queue,))
3036 3036 fh.close()
3037 3037 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3038 3038
3039 3039 if not name or opts.get('list'):
3040 3040 current = _getcurrent()
3041 3041 for queue in _getqueues():
3042 3042 ui.write('%s' % (queue,))
3043 3043 if queue == current and not ui.quiet:
3044 3044 ui.write(_(' (active)\n'))
3045 3045 else:
3046 3046 ui.write('\n')
3047 3047 return
3048 3048
3049 3049 if not _validname(name):
3050 3050 raise util.Abort(
3051 3051 _('invalid queue name, may not contain the characters ":\\/."'))
3052 3052
3053 3053 existing = _getqueues()
3054 3054
3055 3055 if opts.get('create'):
3056 3056 if name in existing:
3057 3057 raise util.Abort(_('queue "%s" already exists') % name)
3058 3058 if _noqueues():
3059 3059 _addqueue(_defaultqueue)
3060 3060 _addqueue(name)
3061 3061 _setactive(name)
3062 3062 elif opts.get('rename'):
3063 3063 current = _getcurrent()
3064 3064 if name == current:
3065 3065 raise util.Abort(_('can\'t rename "%s" to its current name') % name)
3066 3066 if name in existing:
3067 3067 raise util.Abort(_('queue "%s" already exists') % name)
3068 3068
3069 3069 olddir = _queuedir(current)
3070 3070 newdir = _queuedir(name)
3071 3071
3072 3072 if os.path.exists(newdir):
3073 3073 raise util.Abort(_('non-queue directory "%s" already exists') %
3074 3074 newdir)
3075 3075
3076 3076 fh = repo.opener('patches.queues.new', 'w')
3077 3077 for queue in existing:
3078 3078 if queue == current:
3079 3079 fh.write('%s\n' % (name,))
3080 3080 if os.path.exists(olddir):
3081 3081 util.rename(olddir, newdir)
3082 3082 else:
3083 3083 fh.write('%s\n' % (queue,))
3084 3084 fh.close()
3085 3085 util.rename(repo.join('patches.queues.new'), repo.join(_allqueues))
3086 3086 _setactivenocheck(name)
3087 3087 elif opts.get('delete'):
3088 3088 _delete(name)
3089 3089 elif opts.get('purge'):
3090 3090 if name in existing:
3091 3091 _delete(name)
3092 3092 qdir = _queuedir(name)
3093 3093 if os.path.exists(qdir):
3094 3094 shutil.rmtree(qdir)
3095 3095 else:
3096 3096 if name not in existing:
3097 3097 raise util.Abort(_('use --create to create a new queue'))
3098 3098 _setactive(name)
3099 3099
3100 3100 def reposetup(ui, repo):
3101 3101 class mqrepo(repo.__class__):
3102 3102 @util.propertycache
3103 3103 def mq(self):
3104 3104 return queue(self.ui, self.join(""))
3105 3105
3106 3106 def abortifwdirpatched(self, errmsg, force=False):
3107 3107 if self.mq.applied and not force:
3108 3108 parents = self.dirstate.parents()
3109 3109 patches = [s.node for s in self.mq.applied]
3110 3110 if parents[0] in patches or parents[1] in patches:
3111 3111 raise util.Abort(errmsg)
3112 3112
3113 3113 def commit(self, text="", user=None, date=None, match=None,
3114 3114 force=False, editor=False, extra={}):
3115 3115 self.abortifwdirpatched(
3116 3116 _('cannot commit over an applied mq patch'),
3117 3117 force)
3118 3118
3119 3119 return super(mqrepo, self).commit(text, user, date, match, force,
3120 3120 editor, extra)
3121 3121
3122 3122 def checkpush(self, force, revs):
3123 3123 if self.mq.applied and not force:
3124 3124 haspatches = True
3125 3125 if revs:
3126 3126 # Assume applied patches have no non-patch descendants
3127 3127 # and are not on remote already. If they appear in the
3128 3128 # set of resolved 'revs', bail out.
3129 3129 applied = set(e.node for e in self.mq.applied)
3130 3130 haspatches = bool([n for n in revs if n in applied])
3131 3131 if haspatches:
3132 3132 raise util.Abort(_('source has mq patches applied'))
3133 3133 super(mqrepo, self).checkpush(force, revs)
3134 3134
3135 3135 def _findtags(self):
3136 3136 '''augment tags from base class with patch tags'''
3137 3137 result = super(mqrepo, self)._findtags()
3138 3138
3139 3139 q = self.mq
3140 3140 if not q.applied:
3141 3141 return result
3142 3142
3143 3143 mqtags = [(patch.node, patch.name) for patch in q.applied]
3144 3144
3145 3145 try:
3146 3146 self.changelog.rev(mqtags[-1][0])
3147 3147 except error.LookupError:
3148 3148 self.ui.warn(_('mq status file refers to unknown node %s\n')
3149 3149 % short(mqtags[-1][0]))
3150 3150 return result
3151 3151
3152 3152 mqtags.append((mqtags[-1][0], 'qtip'))
3153 3153 mqtags.append((mqtags[0][0], 'qbase'))
3154 3154 mqtags.append((self.changelog.parents(mqtags[0][0])[0], 'qparent'))
3155 3155 tags = result[0]
3156 3156 for patch in mqtags:
3157 3157 if patch[1] in tags:
3158 3158 self.ui.warn(_('Tag %s overrides mq patch of the same name\n')
3159 3159 % patch[1])
3160 3160 else:
3161 3161 tags[patch[1]] = patch[0]
3162 3162
3163 3163 return result
3164 3164
3165 3165 def _branchtags(self, partial, lrev):
3166 3166 q = self.mq
3167 3167 if not q.applied:
3168 3168 return super(mqrepo, self)._branchtags(partial, lrev)
3169 3169
3170 3170 cl = self.changelog
3171 3171 qbasenode = q.applied[0].node
3172 3172 try:
3173 3173 qbase = cl.rev(qbasenode)
3174 3174 except error.LookupError:
3175 3175 self.ui.warn(_('mq status file refers to unknown node %s\n')
3176 3176 % short(qbasenode))
3177 3177 return super(mqrepo, self)._branchtags(partial, lrev)
3178 3178
3179 3179 start = lrev + 1
3180 3180 if start < qbase:
3181 3181 # update the cache (excluding the patches) and save it
3182 3182 ctxgen = (self[r] for r in xrange(lrev + 1, qbase))
3183 3183 self._updatebranchcache(partial, ctxgen)
3184 3184 self._writebranchcache(partial, cl.node(qbase - 1), qbase - 1)
3185 3185 start = qbase
3186 3186 # if start = qbase, the cache is as updated as it should be.
3187 3187 # if start > qbase, the cache includes (part of) the patches.
3188 3188 # we might as well use it, but we won't save it.
3189 3189
3190 3190 # update the cache up to the tip
3191 3191 ctxgen = (self[r] for r in xrange(start, len(cl)))
3192 3192 self._updatebranchcache(partial, ctxgen)
3193 3193
3194 3194 return partial
3195 3195
3196 3196 if repo.local():
3197 3197 repo.__class__ = mqrepo
3198 3198
3199 3199 def mqimport(orig, ui, repo, *args, **kwargs):
3200 3200 if (hasattr(repo, 'abortifwdirpatched')
3201 3201 and not kwargs.get('no_commit', False)):
3202 3202 repo.abortifwdirpatched(_('cannot import over an applied patch'),
3203 3203 kwargs.get('force'))
3204 3204 return orig(ui, repo, *args, **kwargs)
3205 3205
3206 3206 def mqinit(orig, ui, *args, **kwargs):
3207 3207 mq = kwargs.pop('mq', None)
3208 3208
3209 3209 if not mq:
3210 3210 return orig(ui, *args, **kwargs)
3211 3211
3212 3212 if args:
3213 3213 repopath = args[0]
3214 3214 if not hg.islocal(repopath):
3215 3215 raise util.Abort(_('only a local queue repository '
3216 3216 'may be initialized'))
3217 3217 else:
3218 3218 repopath = cmdutil.findrepo(os.getcwd())
3219 3219 if not repopath:
3220 3220 raise util.Abort(_('there is no Mercurial repository here '
3221 3221 '(.hg not found)'))
3222 3222 repo = hg.repository(ui, repopath)
3223 3223 return qinit(ui, repo, True)
3224 3224
3225 3225 def mqcommand(orig, ui, repo, *args, **kwargs):
3226 3226 """Add --mq option to operate on patch repository instead of main"""
3227 3227
3228 3228 # some commands do not like getting unknown options
3229 3229 mq = kwargs.pop('mq', None)
3230 3230
3231 3231 if not mq:
3232 3232 return orig(ui, repo, *args, **kwargs)
3233 3233
3234 3234 q = repo.mq
3235 3235 r = q.qrepo()
3236 3236 if not r:
3237 3237 raise util.Abort(_('no queue repository'))
3238 3238 return orig(r.ui, r, *args, **kwargs)
3239 3239
3240 3240 def summary(orig, ui, repo, *args, **kwargs):
3241 3241 r = orig(ui, repo, *args, **kwargs)
3242 3242 q = repo.mq
3243 3243 m = []
3244 3244 a, u = len(q.applied), len(q.unapplied(repo))
3245 3245 if a:
3246 3246 m.append(ui.label(_("%d applied"), 'qseries.applied') % a)
3247 3247 if u:
3248 3248 m.append(ui.label(_("%d unapplied"), 'qseries.unapplied') % u)
3249 3249 if m:
3250 3250 ui.write("mq: %s\n" % ', '.join(m))
3251 3251 else:
3252 3252 ui.note(_("mq: (empty queue)\n"))
3253 3253 return r
3254 3254
3255 3255 def revsetmq(repo, subset, x):
3256 3256 """``mq()``
3257 3257 Changesets managed by MQ.
3258 3258 """
3259 3259 revset.getargs(x, 0, 0, _("mq takes no arguments"))
3260 3260 applied = set([repo[r.node].rev() for r in repo.mq.applied])
3261 3261 return [r for r in subset if r in applied]
3262 3262
3263 3263 def extsetup(ui):
3264 3264 revset.symbols['mq'] = revsetmq
3265 3265
3266 3266 # tell hggettext to extract docstrings from these functions:
3267 3267 i18nfunctions = [revsetmq]
3268 3268
3269 3269 def uisetup(ui):
3270 3270 mqopt = [('', 'mq', None, _("operate on patch repository"))]
3271 3271
3272 3272 extensions.wrapcommand(commands.table, 'import', mqimport)
3273 3273 extensions.wrapcommand(commands.table, 'summary', summary)
3274 3274
3275 3275 entry = extensions.wrapcommand(commands.table, 'init', mqinit)
3276 3276 entry[1].extend(mqopt)
3277 3277
3278 3278 nowrap = set(commands.norepo.split(" "))
3279 3279
3280 3280 def dotable(cmdtable):
3281 3281 for cmd in cmdtable.keys():
3282 3282 cmd = cmdutil.parsealiases(cmd)[0]
3283 3283 if cmd in nowrap:
3284 3284 continue
3285 3285 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
3286 3286 entry[1].extend(mqopt)
3287 3287
3288 3288 dotable(commands.table)
3289 3289
3290 3290 for extname, extmodule in extensions.extensions():
3291 3291 if extmodule.__file__ != __file__:
3292 3292 dotable(getattr(extmodule, 'cmdtable', {}))
3293 3293
3294 3294
3295 3295 colortable = {'qguard.negative': 'red',
3296 3296 'qguard.positive': 'yellow',
3297 3297 'qguard.unguarded': 'green',
3298 3298 'qseries.applied': 'blue bold underline',
3299 3299 'qseries.guarded': 'black bold',
3300 3300 'qseries.missing': 'red bold',
3301 3301 'qseries.unapplied': 'black bold'}
@@ -1,585 +1,585
1 1 # rebase.py - rebasing feature for mercurial
2 2 #
3 3 # Copyright 2008 Stefano Tortarolo <stefano.tortarolo at gmail dot com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 '''command to move sets of revisions to a different ancestor
9 9
10 10 This extension lets you rebase changesets in an existing Mercurial
11 11 repository.
12 12
13 13 For more information:
14 14 http://mercurial.selenic.com/wiki/RebaseExtension
15 15 '''
16 16
17 17 from mercurial import hg, util, repair, merge, cmdutil, commands
18 18 from mercurial import extensions, copies, patch
19 19 from mercurial.commands import templateopts
20 20 from mercurial.node import nullrev
21 21 from mercurial.lock import release
22 22 from mercurial.i18n import _
23 23 import os, errno
24 24
25 25 nullmerge = -2
26 26
27 27 cmdtable = {}
28 28 command = cmdutil.command(cmdtable)
29 29
30 30 @command('rebase',
31 31 [('s', 'source', '',
32 32 _('rebase from the specified changeset'), _('REV')),
33 33 ('b', 'base', '',
34 34 _('rebase from the base of the specified changeset '
35 35 '(up to greatest common ancestor of base and dest)'),
36 36 _('REV')),
37 37 ('d', 'dest', '',
38 38 _('rebase onto the specified changeset'), _('REV')),
39 39 ('', 'collapse', False, _('collapse the rebased changesets')),
40 40 ('m', 'message', '',
41 41 _('use text as collapse commit message'), _('TEXT')),
42 42 ('l', 'logfile', '',
43 43 _('read collapse commit message from file'), _('FILE')),
44 44 ('', 'keep', False, _('keep original changesets')),
45 45 ('', 'keepbranches', False, _('keep original branch names')),
46 46 ('', 'detach', False, _('force detaching of source from its original '
47 47 'branch')),
48 48 ('t', 'tool', '', _('specify merge tool')),
49 49 ('c', 'continue', False, _('continue an interrupted rebase')),
50 50 ('a', 'abort', False, _('abort an interrupted rebase'))] +
51 51 templateopts,
52 52 _('hg rebase [-s REV | -b REV] [-d REV] [options]\n'
53 53 'hg rebase {-a|-c}'))
54 54 def rebase(ui, repo, **opts):
55 55 """move changeset (and descendants) to a different branch
56 56
57 57 Rebase uses repeated merging to graft changesets from one part of
58 58 history (the source) onto another (the destination). This can be
59 59 useful for linearizing *local* changes relative to a master
60 60 development tree.
61 61
62 62 You should not rebase changesets that have already been shared
63 63 with others. Doing so will force everybody else to perform the
64 64 same rebase or they will end up with duplicated changesets after
65 65 pulling in your rebased changesets.
66 66
67 67 If you don't specify a destination changeset (``-d/--dest``),
68 68 rebase uses the tipmost head of the current named branch as the
69 69 destination. (The destination changeset is not modified by
70 70 rebasing, but new changesets are added as its descendants.)
71 71
72 72 You can specify which changesets to rebase in two ways: as a
73 73 "source" changeset or as a "base" changeset. Both are shorthand
74 74 for a topologically related set of changesets (the "source
75 75 branch"). If you specify source (``-s/--source``), rebase will
76 76 rebase that changeset and all of its descendants onto dest. If you
77 77 specify base (``-b/--base``), rebase will select ancestors of base
78 78 back to but not including the common ancestor with dest. Thus,
79 79 ``-b`` is less precise but more convenient than ``-s``: you can
80 80 specify any changeset in the source branch, and rebase will select
81 81 the whole branch. If you specify neither ``-s`` nor ``-b``, rebase
82 82 uses the parent of the working directory as the base.
83 83
84 84 By default, rebase recreates the changesets in the source branch
85 85 as descendants of dest and then destroys the originals. Use
86 86 ``--keep`` to preserve the original source changesets. Some
87 87 changesets in the source branch (e.g. merges from the destination
88 88 branch) may be dropped if they no longer contribute any change.
89 89
90 90 One result of the rules for selecting the destination changeset
91 91 and source branch is that, unlike ``merge``, rebase will do
92 92 nothing if you are at the latest (tipmost) head of a named branch
93 93 with two heads. You need to explicitly specify source and/or
94 94 destination (or ``update`` to the other head, if it's the head of
95 95 the intended source branch).
96 96
97 97 If a rebase is interrupted to manually resolve a merge, it can be
98 98 continued with --continue/-c or aborted with --abort/-a.
99 99
100 100 Returns 0 on success, 1 if nothing to rebase.
101 101 """
102 102 originalwd = target = None
103 103 external = nullrev
104 104 state = {}
105 105 skipped = set()
106 106 targetancestors = set()
107 107
108 108 lock = wlock = None
109 109 try:
110 110 lock = repo.lock()
111 111 wlock = repo.wlock()
112 112
113 113 # Validate input and define rebasing points
114 114 destf = opts.get('dest', None)
115 115 srcf = opts.get('source', None)
116 116 basef = opts.get('base', None)
117 117 contf = opts.get('continue')
118 118 abortf = opts.get('abort')
119 119 collapsef = opts.get('collapse', False)
120 collapsemsg = cmdutil.logmessage(opts)
120 collapsemsg = cmdutil.logmessage(ui, opts)
121 121 extrafn = opts.get('extrafn') # internal, used by e.g. hgsubversion
122 122 keepf = opts.get('keep', False)
123 123 keepbranchesf = opts.get('keepbranches', False)
124 124 detachf = opts.get('detach', False)
125 125 # keepopen is not meant for use on the command line, but by
126 126 # other extensions
127 127 keepopen = opts.get('keepopen', False)
128 128
129 129 if collapsemsg and not collapsef:
130 130 raise util.Abort(
131 131 _('message can only be specified with collapse'))
132 132
133 133 if contf or abortf:
134 134 if contf and abortf:
135 135 raise util.Abort(_('cannot use both abort and continue'))
136 136 if collapsef:
137 137 raise util.Abort(
138 138 _('cannot use collapse with continue or abort'))
139 139 if detachf:
140 140 raise util.Abort(_('cannot use detach with continue or abort'))
141 141 if srcf or basef or destf:
142 142 raise util.Abort(
143 143 _('abort and continue do not allow specifying revisions'))
144 144 if opts.get('tool', False):
145 145 ui.warn(_('tool option will be ignored\n'))
146 146
147 147 (originalwd, target, state, skipped, collapsef, keepf,
148 148 keepbranchesf, external) = restorestatus(repo)
149 149 if abortf:
150 150 return abort(repo, originalwd, target, state)
151 151 else:
152 152 if srcf and basef:
153 153 raise util.Abort(_('cannot specify both a '
154 154 'revision and a base'))
155 155 if detachf:
156 156 if not srcf:
157 157 raise util.Abort(
158 158 _('detach requires a revision to be specified'))
159 159 if basef:
160 160 raise util.Abort(_('cannot specify a base with detach'))
161 161
162 162 cmdutil.bailifchanged(repo)
163 163 result = buildstate(repo, destf, srcf, basef, detachf)
164 164 if not result:
165 165 # Empty state built, nothing to rebase
166 166 ui.status(_('nothing to rebase\n'))
167 167 return 1
168 168 else:
169 169 originalwd, target, state = result
170 170 if collapsef:
171 171 targetancestors = set(repo.changelog.ancestors(target))
172 172 external = checkexternal(repo, state, targetancestors)
173 173
174 174 if keepbranchesf:
175 175 assert not extrafn, 'cannot use both keepbranches and extrafn'
176 176 def extrafn(ctx, extra):
177 177 extra['branch'] = ctx.branch()
178 178
179 179 # Rebase
180 180 if not targetancestors:
181 181 targetancestors = set(repo.changelog.ancestors(target))
182 182 targetancestors.add(target)
183 183
184 184 sortedstate = sorted(state)
185 185 total = len(sortedstate)
186 186 pos = 0
187 187 for rev in sortedstate:
188 188 pos += 1
189 189 if state[rev] == -1:
190 190 ui.progress(_("rebasing"), pos, ("%d:%s" % (rev, repo[rev])),
191 191 _('changesets'), total)
192 192 storestatus(repo, originalwd, target, state, collapsef, keepf,
193 193 keepbranchesf, external)
194 194 p1, p2 = defineparents(repo, rev, target, state,
195 195 targetancestors)
196 196 if len(repo.parents()) == 2:
197 197 repo.ui.debug('resuming interrupted rebase\n')
198 198 else:
199 199 try:
200 200 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
201 201 stats = rebasenode(repo, rev, p1, state)
202 202 if stats and stats[3] > 0:
203 203 raise util.Abort(_('unresolved conflicts (see hg '
204 204 'resolve, then hg rebase --continue)'))
205 205 finally:
206 206 ui.setconfig('ui', 'forcemerge', '')
207 207 updatedirstate(repo, rev, target, p2)
208 208 if not collapsef:
209 209 newrev = concludenode(repo, rev, p1, p2, extrafn=extrafn)
210 210 else:
211 211 # Skip commit if we are collapsing
212 212 repo.dirstate.setparents(repo[p1].node())
213 213 newrev = None
214 214 # Update the state
215 215 if newrev is not None:
216 216 state[rev] = repo[newrev].rev()
217 217 else:
218 218 if not collapsef:
219 219 ui.note(_('no changes, revision %d skipped\n') % rev)
220 220 ui.debug('next revision set to %s\n' % p1)
221 221 skipped.add(rev)
222 222 state[rev] = p1
223 223
224 224 ui.progress(_('rebasing'), None)
225 225 ui.note(_('rebase merging completed\n'))
226 226
227 227 if collapsef and not keepopen:
228 228 p1, p2 = defineparents(repo, min(state), target,
229 229 state, targetancestors)
230 230 if collapsemsg:
231 231 commitmsg = collapsemsg
232 232 else:
233 233 commitmsg = 'Collapsed revision'
234 234 for rebased in state:
235 235 if rebased not in skipped and state[rebased] != nullmerge:
236 236 commitmsg += '\n* %s' % repo[rebased].description()
237 237 commitmsg = ui.edit(commitmsg, repo.ui.username())
238 238 newrev = concludenode(repo, rev, p1, external, commitmsg=commitmsg,
239 239 extrafn=extrafn)
240 240
241 241 if 'qtip' in repo.tags():
242 242 updatemq(repo, state, skipped, **opts)
243 243
244 244 if not keepf:
245 245 # Remove no more useful revisions
246 246 rebased = [rev for rev in state if state[rev] != nullmerge]
247 247 if rebased:
248 248 if set(repo.changelog.descendants(min(rebased))) - set(state):
249 249 ui.warn(_("warning: new changesets detected "
250 250 "on source branch, not stripping\n"))
251 251 else:
252 252 # backup the old csets by default
253 253 repair.strip(ui, repo, repo[min(rebased)].node(), "all")
254 254
255 255 clearstatus(repo)
256 256 ui.note(_("rebase completed\n"))
257 257 if os.path.exists(repo.sjoin('undo')):
258 258 util.unlinkpath(repo.sjoin('undo'))
259 259 if skipped:
260 260 ui.note(_("%d revisions have been skipped\n") % len(skipped))
261 261 finally:
262 262 release(lock, wlock)
263 263
264 264 def checkexternal(repo, state, targetancestors):
265 265 """Check whether one or more external revisions need to be taken in
266 266 consideration. In the latter case, abort.
267 267 """
268 268 external = nullrev
269 269 source = min(state)
270 270 for rev in state:
271 271 if rev == source:
272 272 continue
273 273 # Check externals and fail if there are more than one
274 274 for p in repo[rev].parents():
275 275 if (p.rev() not in state
276 276 and p.rev() not in targetancestors):
277 277 if external != nullrev:
278 278 raise util.Abort(_('unable to collapse, there is more '
279 279 'than one external parent'))
280 280 external = p.rev()
281 281 return external
282 282
283 283 def updatedirstate(repo, rev, p1, p2):
284 284 """Keep track of renamed files in the revision that is going to be rebased
285 285 """
286 286 # Here we simulate the copies and renames in the source changeset
287 287 cop, diver = copies.copies(repo, repo[rev], repo[p1], repo[p2], True)
288 288 m1 = repo[rev].manifest()
289 289 m2 = repo[p1].manifest()
290 290 for k, v in cop.iteritems():
291 291 if k in m1:
292 292 if v in m1 or v in m2:
293 293 repo.dirstate.copy(v, k)
294 294 if v in m2 and v not in m1 and k in m2:
295 295 repo.dirstate.remove(v)
296 296
297 297 def concludenode(repo, rev, p1, p2, commitmsg=None, extrafn=None):
298 298 'Commit the changes and store useful information in extra'
299 299 try:
300 300 repo.dirstate.setparents(repo[p1].node(), repo[p2].node())
301 301 ctx = repo[rev]
302 302 if commitmsg is None:
303 303 commitmsg = ctx.description()
304 304 extra = {'rebase_source': ctx.hex()}
305 305 if extrafn:
306 306 extrafn(ctx, extra)
307 307 # Commit might fail if unresolved files exist
308 308 newrev = repo.commit(text=commitmsg, user=ctx.user(),
309 309 date=ctx.date(), extra=extra)
310 310 repo.dirstate.setbranch(repo[newrev].branch())
311 311 return newrev
312 312 except util.Abort:
313 313 # Invalidate the previous setparents
314 314 repo.dirstate.invalidate()
315 315 raise
316 316
317 317 def rebasenode(repo, rev, p1, state):
318 318 'Rebase a single revision'
319 319 # Merge phase
320 320 # Update to target and merge it with local
321 321 if repo['.'].rev() != repo[p1].rev():
322 322 repo.ui.debug(" update to %d:%s\n" % (repo[p1].rev(), repo[p1]))
323 323 merge.update(repo, p1, False, True, False)
324 324 else:
325 325 repo.ui.debug(" already in target\n")
326 326 repo.dirstate.write()
327 327 repo.ui.debug(" merge against %d:%s\n" % (repo[rev].rev(), repo[rev]))
328 328 base = None
329 329 if repo[rev].rev() != repo[min(state)].rev():
330 330 base = repo[rev].p1().node()
331 331 return merge.update(repo, rev, True, True, False, base)
332 332
333 333 def defineparents(repo, rev, target, state, targetancestors):
334 334 'Return the new parent relationship of the revision that will be rebased'
335 335 parents = repo[rev].parents()
336 336 p1 = p2 = nullrev
337 337
338 338 P1n = parents[0].rev()
339 339 if P1n in targetancestors:
340 340 p1 = target
341 341 elif P1n in state:
342 342 if state[P1n] == nullmerge:
343 343 p1 = target
344 344 else:
345 345 p1 = state[P1n]
346 346 else: # P1n external
347 347 p1 = target
348 348 p2 = P1n
349 349
350 350 if len(parents) == 2 and parents[1].rev() not in targetancestors:
351 351 P2n = parents[1].rev()
352 352 # interesting second parent
353 353 if P2n in state:
354 354 if p1 == target: # P1n in targetancestors or external
355 355 p1 = state[P2n]
356 356 else:
357 357 p2 = state[P2n]
358 358 else: # P2n external
359 359 if p2 != nullrev: # P1n external too => rev is a merged revision
360 360 raise util.Abort(_('cannot use revision %d as base, result '
361 361 'would have 3 parents') % rev)
362 362 p2 = P2n
363 363 repo.ui.debug(" future parents are %d and %d\n" %
364 364 (repo[p1].rev(), repo[p2].rev()))
365 365 return p1, p2
366 366
367 367 def isagitpatch(repo, patchname):
368 368 'Return true if the given patch is in git format'
369 369 mqpatch = os.path.join(repo.mq.path, patchname)
370 370 for line in patch.linereader(file(mqpatch, 'rb')):
371 371 if line.startswith('diff --git'):
372 372 return True
373 373 return False
374 374
375 375 def updatemq(repo, state, skipped, **opts):
376 376 'Update rebased mq patches - finalize and then import them'
377 377 mqrebase = {}
378 378 mq = repo.mq
379 379 original_series = mq.fullseries[:]
380 380
381 381 for p in mq.applied:
382 382 rev = repo[p.node].rev()
383 383 if rev in state:
384 384 repo.ui.debug('revision %d is an mq patch (%s), finalize it.\n' %
385 385 (rev, p.name))
386 386 mqrebase[rev] = (p.name, isagitpatch(repo, p.name))
387 387
388 388 if mqrebase:
389 389 mq.finish(repo, mqrebase.keys())
390 390
391 391 # We must start import from the newest revision
392 392 for rev in sorted(mqrebase, reverse=True):
393 393 if rev not in skipped:
394 394 name, isgit = mqrebase[rev]
395 395 repo.ui.debug('import mq patch %d (%s)\n' % (state[rev], name))
396 396 mq.qimport(repo, (), patchname=name, git=isgit,
397 397 rev=[str(state[rev])])
398 398
399 399 # restore old series to preserve guards
400 400 mq.fullseries = original_series
401 401 mq.series_dirty = True
402 402 mq.savedirty()
403 403
404 404 def storestatus(repo, originalwd, target, state, collapse, keep, keepbranches,
405 405 external):
406 406 'Store the current status to allow recovery'
407 407 f = repo.opener("rebasestate", "w")
408 408 f.write(repo[originalwd].hex() + '\n')
409 409 f.write(repo[target].hex() + '\n')
410 410 f.write(repo[external].hex() + '\n')
411 411 f.write('%d\n' % int(collapse))
412 412 f.write('%d\n' % int(keep))
413 413 f.write('%d\n' % int(keepbranches))
414 414 for d, v in state.iteritems():
415 415 oldrev = repo[d].hex()
416 416 newrev = repo[v].hex()
417 417 f.write("%s:%s\n" % (oldrev, newrev))
418 418 f.close()
419 419 repo.ui.debug('rebase status stored\n')
420 420
421 421 def clearstatus(repo):
422 422 'Remove the status files'
423 423 if os.path.exists(repo.join("rebasestate")):
424 424 util.unlinkpath(repo.join("rebasestate"))
425 425
426 426 def restorestatus(repo):
427 427 'Restore a previously stored status'
428 428 try:
429 429 target = None
430 430 collapse = False
431 431 external = nullrev
432 432 state = {}
433 433 f = repo.opener("rebasestate")
434 434 for i, l in enumerate(f.read().splitlines()):
435 435 if i == 0:
436 436 originalwd = repo[l].rev()
437 437 elif i == 1:
438 438 target = repo[l].rev()
439 439 elif i == 2:
440 440 external = repo[l].rev()
441 441 elif i == 3:
442 442 collapse = bool(int(l))
443 443 elif i == 4:
444 444 keep = bool(int(l))
445 445 elif i == 5:
446 446 keepbranches = bool(int(l))
447 447 else:
448 448 oldrev, newrev = l.split(':')
449 449 state[repo[oldrev].rev()] = repo[newrev].rev()
450 450 skipped = set()
451 451 # recompute the set of skipped revs
452 452 if not collapse:
453 453 seen = set([target])
454 454 for old, new in sorted(state.items()):
455 455 if new != nullrev and new in seen:
456 456 skipped.add(old)
457 457 seen.add(new)
458 458 repo.ui.debug('computed skipped revs: %s\n' % skipped)
459 459 repo.ui.debug('rebase status resumed\n')
460 460 return (originalwd, target, state, skipped,
461 461 collapse, keep, keepbranches, external)
462 462 except IOError, err:
463 463 if err.errno != errno.ENOENT:
464 464 raise
465 465 raise util.Abort(_('no rebase in progress'))
466 466
467 467 def abort(repo, originalwd, target, state):
468 468 'Restore the repository to its original state'
469 469 if set(repo.changelog.descendants(target)) - set(state.values()):
470 470 repo.ui.warn(_("warning: new changesets detected on target branch, "
471 471 "can't abort\n"))
472 472 return -1
473 473 else:
474 474 # Strip from the first rebased revision
475 475 merge.update(repo, repo[originalwd].rev(), False, True, False)
476 476 rebased = filter(lambda x: x > -1 and x != target, state.values())
477 477 if rebased:
478 478 strippoint = min(rebased)
479 479 # no backup of rebased cset versions needed
480 480 repair.strip(repo.ui, repo, repo[strippoint].node())
481 481 clearstatus(repo)
482 482 repo.ui.warn(_('rebase aborted\n'))
483 483 return 0
484 484
485 485 def buildstate(repo, dest, src, base, detach):
486 486 'Define which revisions are going to be rebased and where'
487 487 targetancestors = set()
488 488 detachset = set()
489 489
490 490 if not dest:
491 491 # Destination defaults to the latest revision in the current branch
492 492 branch = repo[None].branch()
493 493 dest = repo[branch].rev()
494 494 else:
495 495 dest = repo[dest].rev()
496 496
497 497 # This check isn't strictly necessary, since mq detects commits over an
498 498 # applied patch. But it prevents messing up the working directory when
499 499 # a partially completed rebase is blocked by mq.
500 500 if 'qtip' in repo.tags() and (repo[dest].node() in
501 501 [s.node for s in repo.mq.applied]):
502 502 raise util.Abort(_('cannot rebase onto an applied mq patch'))
503 503
504 504 if src:
505 505 commonbase = repo[src].ancestor(repo[dest])
506 506 samebranch = repo[src].branch() == repo[dest].branch()
507 507 if commonbase == repo[src]:
508 508 raise util.Abort(_('source is ancestor of destination'))
509 509 if samebranch and commonbase == repo[dest]:
510 510 raise util.Abort(_('source is descendant of destination'))
511 511 source = repo[src].rev()
512 512 if detach:
513 513 # We need to keep track of source's ancestors up to the common base
514 514 srcancestors = set(repo.changelog.ancestors(source))
515 515 baseancestors = set(repo.changelog.ancestors(commonbase.rev()))
516 516 detachset = srcancestors - baseancestors
517 517 detachset.discard(commonbase.rev())
518 518 else:
519 519 if base:
520 520 cwd = repo[base].rev()
521 521 else:
522 522 cwd = repo['.'].rev()
523 523
524 524 if cwd == dest:
525 525 repo.ui.debug('source and destination are the same\n')
526 526 return None
527 527
528 528 targetancestors = set(repo.changelog.ancestors(dest))
529 529 if cwd in targetancestors:
530 530 repo.ui.debug('source is ancestor of destination\n')
531 531 return None
532 532
533 533 cwdancestors = set(repo.changelog.ancestors(cwd))
534 534 if dest in cwdancestors:
535 535 repo.ui.debug('source is descendant of destination\n')
536 536 return None
537 537
538 538 cwdancestors.add(cwd)
539 539 rebasingbranch = cwdancestors - targetancestors
540 540 source = min(rebasingbranch)
541 541
542 542 repo.ui.debug('rebase onto %d starting from %d\n' % (dest, source))
543 543 state = dict.fromkeys(repo.changelog.descendants(source), nullrev)
544 544 state.update(dict.fromkeys(detachset, nullmerge))
545 545 state[source] = nullrev
546 546 return repo['.'].rev(), repo[dest].rev(), state
547 547
548 548 def pullrebase(orig, ui, repo, *args, **opts):
549 549 'Call rebase after pull if the latter has been invoked with --rebase'
550 550 if opts.get('rebase'):
551 551 if opts.get('update'):
552 552 del opts['update']
553 553 ui.debug('--update and --rebase are not compatible, ignoring '
554 554 'the update flag\n')
555 555
556 556 cmdutil.bailifchanged(repo)
557 557 revsprepull = len(repo)
558 558 origpostincoming = commands.postincoming
559 559 def _dummy(*args, **kwargs):
560 560 pass
561 561 commands.postincoming = _dummy
562 562 try:
563 563 orig(ui, repo, *args, **opts)
564 564 finally:
565 565 commands.postincoming = origpostincoming
566 566 revspostpull = len(repo)
567 567 if revspostpull > revsprepull:
568 568 rebase(ui, repo, **opts)
569 569 branch = repo[None].branch()
570 570 dest = repo[branch].rev()
571 571 if dest != repo['.'].rev():
572 572 # there was nothing to rebase we force an update
573 573 hg.update(repo, dest)
574 574 else:
575 575 if opts.get('tool'):
576 576 raise util.Abort(_('--tool can only be used with --rebase'))
577 577 orig(ui, repo, *args, **opts)
578 578
579 579 def uisetup(ui):
580 580 'Replace pull with a decorator to provide --rebase option'
581 581 entry = extensions.wrapcommand(commands.table, 'pull', pullrebase)
582 582 entry[1].append(('', 'rebase', None,
583 583 _("rebase working directory to branch head")))
584 584 entry[1].append(('t', 'tool', '',
585 585 _("specify merge tool for rebase")))
@@ -1,1228 +1,1228
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, nullid, nullrev, short
9 9 from i18n import _
10 10 import os, sys, errno, re, tempfile
11 11 import util, scmutil, templater, patch, error, templatekw, revlog
12 12 import match as matchmod
13 13 import subrepo
14 14
15 15 def parsealiases(cmd):
16 16 return cmd.lstrip("^").split("|")
17 17
18 18 def findpossible(cmd, table, strict=False):
19 19 """
20 20 Return cmd -> (aliases, command table entry)
21 21 for each matching command.
22 22 Return debug commands (or their aliases) only if no normal command matches.
23 23 """
24 24 choice = {}
25 25 debugchoice = {}
26 26 for e in table.keys():
27 27 aliases = parsealiases(e)
28 28 found = None
29 29 if cmd in aliases:
30 30 found = cmd
31 31 elif not strict:
32 32 for a in aliases:
33 33 if a.startswith(cmd):
34 34 found = a
35 35 break
36 36 if found is not None:
37 37 if aliases[0].startswith("debug") or found.startswith("debug"):
38 38 debugchoice[found] = (aliases, table[e])
39 39 else:
40 40 choice[found] = (aliases, table[e])
41 41
42 42 if not choice and debugchoice:
43 43 choice = debugchoice
44 44
45 45 return choice
46 46
47 47 def findcmd(cmd, table, strict=True):
48 48 """Return (aliases, command table entry) for command string."""
49 49 choice = findpossible(cmd, table, strict)
50 50
51 51 if cmd in choice:
52 52 return choice[cmd]
53 53
54 54 if len(choice) > 1:
55 55 clist = choice.keys()
56 56 clist.sort()
57 57 raise error.AmbiguousCommand(cmd, clist)
58 58
59 59 if choice:
60 60 return choice.values()[0]
61 61
62 62 raise error.UnknownCommand(cmd)
63 63
64 64 def findrepo(p):
65 65 while not os.path.isdir(os.path.join(p, ".hg")):
66 66 oldp, p = p, os.path.dirname(p)
67 67 if p == oldp:
68 68 return None
69 69
70 70 return p
71 71
72 72 def bailifchanged(repo):
73 73 if repo.dirstate.p2() != nullid:
74 74 raise util.Abort(_('outstanding uncommitted merge'))
75 75 modified, added, removed, deleted = repo.status()[:4]
76 76 if modified or added or removed or deleted:
77 77 raise util.Abort(_("outstanding uncommitted changes"))
78 78
79 def logmessage(opts):
79 def logmessage(ui, opts):
80 80 """ get the log message according to -m and -l option """
81 81 message = opts.get('message')
82 82 logfile = opts.get('logfile')
83 83
84 84 if message and logfile:
85 85 raise util.Abort(_('options --message and --logfile are mutually '
86 86 'exclusive'))
87 87 if not message and logfile:
88 88 try:
89 89 if logfile == '-':
90 message = sys.stdin.read()
90 message = ui.fin.read()
91 91 else:
92 92 message = '\n'.join(util.readfile(logfile).splitlines())
93 93 except IOError, inst:
94 94 raise util.Abort(_("can't read commit message '%s': %s") %
95 95 (logfile, inst.strerror))
96 96 return message
97 97
98 98 def loglimit(opts):
99 99 """get the log limit according to option -l/--limit"""
100 100 limit = opts.get('limit')
101 101 if limit:
102 102 try:
103 103 limit = int(limit)
104 104 except ValueError:
105 105 raise util.Abort(_('limit must be a positive integer'))
106 106 if limit <= 0:
107 107 raise util.Abort(_('limit must be positive'))
108 108 else:
109 109 limit = None
110 110 return limit
111 111
112 112 def makefilename(repo, pat, node,
113 113 total=None, seqno=None, revwidth=None, pathname=None):
114 114 node_expander = {
115 115 'H': lambda: hex(node),
116 116 'R': lambda: str(repo.changelog.rev(node)),
117 117 'h': lambda: short(node),
118 118 }
119 119 expander = {
120 120 '%': lambda: '%',
121 121 'b': lambda: os.path.basename(repo.root),
122 122 }
123 123
124 124 try:
125 125 if node:
126 126 expander.update(node_expander)
127 127 if node:
128 128 expander['r'] = (lambda:
129 129 str(repo.changelog.rev(node)).zfill(revwidth or 0))
130 130 if total is not None:
131 131 expander['N'] = lambda: str(total)
132 132 if seqno is not None:
133 133 expander['n'] = lambda: str(seqno)
134 134 if total is not None and seqno is not None:
135 135 expander['n'] = lambda: str(seqno).zfill(len(str(total)))
136 136 if pathname is not None:
137 137 expander['s'] = lambda: os.path.basename(pathname)
138 138 expander['d'] = lambda: os.path.dirname(pathname) or '.'
139 139 expander['p'] = lambda: pathname
140 140
141 141 newname = []
142 142 patlen = len(pat)
143 143 i = 0
144 144 while i < patlen:
145 145 c = pat[i]
146 146 if c == '%':
147 147 i += 1
148 148 c = pat[i]
149 149 c = expander[c]()
150 150 newname.append(c)
151 151 i += 1
152 152 return ''.join(newname)
153 153 except KeyError, inst:
154 154 raise util.Abort(_("invalid format spec '%%%s' in output filename") %
155 155 inst.args[0])
156 156
157 157 def makefileobj(repo, pat, node=None, total=None,
158 158 seqno=None, revwidth=None, mode='wb', pathname=None):
159 159
160 160 writable = mode not in ('r', 'rb')
161 161
162 162 if not pat or pat == '-':
163 163 fp = writable and sys.stdout or sys.stdin
164 164 return os.fdopen(os.dup(fp.fileno()), mode)
165 165 if hasattr(pat, 'write') and writable:
166 166 return pat
167 167 if hasattr(pat, 'read') and 'r' in mode:
168 168 return pat
169 169 return open(makefilename(repo, pat, node, total, seqno, revwidth,
170 170 pathname),
171 171 mode)
172 172
173 173 def openrevlog(repo, cmd, file_, opts):
174 174 """opens the changelog, manifest, a filelog or a given revlog"""
175 175 cl = opts['changelog']
176 176 mf = opts['manifest']
177 177 msg = None
178 178 if cl and mf:
179 179 msg = _('cannot specify --changelog and --manifest at the same time')
180 180 elif cl or mf:
181 181 if file_:
182 182 msg = _('cannot specify filename with --changelog or --manifest')
183 183 elif not repo:
184 184 msg = _('cannot specify --changelog or --manifest '
185 185 'without a repository')
186 186 if msg:
187 187 raise util.Abort(msg)
188 188
189 189 r = None
190 190 if repo:
191 191 if cl:
192 192 r = repo.changelog
193 193 elif mf:
194 194 r = repo.manifest
195 195 elif file_:
196 196 filelog = repo.file(file_)
197 197 if len(filelog):
198 198 r = filelog
199 199 if not r:
200 200 if not file_:
201 201 raise error.CommandError(cmd, _('invalid arguments'))
202 202 if not os.path.isfile(file_):
203 203 raise util.Abort(_("revlog '%s' not found") % file_)
204 204 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False),
205 205 file_[:-2] + ".i")
206 206 return r
207 207
208 208 def copy(ui, repo, pats, opts, rename=False):
209 209 # called with the repo lock held
210 210 #
211 211 # hgsep => pathname that uses "/" to separate directories
212 212 # ossep => pathname that uses os.sep to separate directories
213 213 cwd = repo.getcwd()
214 214 targets = {}
215 215 after = opts.get("after")
216 216 dryrun = opts.get("dry_run")
217 217 wctx = repo[None]
218 218
219 219 def walkpat(pat):
220 220 srcs = []
221 221 badstates = after and '?' or '?r'
222 222 m = scmutil.match(repo, [pat], opts, globbed=True)
223 223 for abs in repo.walk(m):
224 224 state = repo.dirstate[abs]
225 225 rel = m.rel(abs)
226 226 exact = m.exact(abs)
227 227 if state in badstates:
228 228 if exact and state == '?':
229 229 ui.warn(_('%s: not copying - file is not managed\n') % rel)
230 230 if exact and state == 'r':
231 231 ui.warn(_('%s: not copying - file has been marked for'
232 232 ' remove\n') % rel)
233 233 continue
234 234 # abs: hgsep
235 235 # rel: ossep
236 236 srcs.append((abs, rel, exact))
237 237 return srcs
238 238
239 239 # abssrc: hgsep
240 240 # relsrc: ossep
241 241 # otarget: ossep
242 242 def copyfile(abssrc, relsrc, otarget, exact):
243 243 abstarget = scmutil.canonpath(repo.root, cwd, otarget)
244 244 reltarget = repo.pathto(abstarget, cwd)
245 245 target = repo.wjoin(abstarget)
246 246 src = repo.wjoin(abssrc)
247 247 state = repo.dirstate[abstarget]
248 248
249 249 scmutil.checkportable(ui, abstarget)
250 250
251 251 # check for collisions
252 252 prevsrc = targets.get(abstarget)
253 253 if prevsrc is not None:
254 254 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
255 255 (reltarget, repo.pathto(abssrc, cwd),
256 256 repo.pathto(prevsrc, cwd)))
257 257 return
258 258
259 259 # check for overwrites
260 260 exists = os.path.lexists(target)
261 261 if not after and exists or after and state in 'mn':
262 262 if not opts['force']:
263 263 ui.warn(_('%s: not overwriting - file exists\n') %
264 264 reltarget)
265 265 return
266 266
267 267 if after:
268 268 if not exists:
269 269 if rename:
270 270 ui.warn(_('%s: not recording move - %s does not exist\n') %
271 271 (relsrc, reltarget))
272 272 else:
273 273 ui.warn(_('%s: not recording copy - %s does not exist\n') %
274 274 (relsrc, reltarget))
275 275 return
276 276 elif not dryrun:
277 277 try:
278 278 if exists:
279 279 os.unlink(target)
280 280 targetdir = os.path.dirname(target) or '.'
281 281 if not os.path.isdir(targetdir):
282 282 os.makedirs(targetdir)
283 283 util.copyfile(src, target)
284 284 srcexists = True
285 285 except IOError, inst:
286 286 if inst.errno == errno.ENOENT:
287 287 ui.warn(_('%s: deleted in working copy\n') % relsrc)
288 288 srcexists = False
289 289 else:
290 290 ui.warn(_('%s: cannot copy - %s\n') %
291 291 (relsrc, inst.strerror))
292 292 return True # report a failure
293 293
294 294 if ui.verbose or not exact:
295 295 if rename:
296 296 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
297 297 else:
298 298 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
299 299
300 300 targets[abstarget] = abssrc
301 301
302 302 # fix up dirstate
303 303 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
304 304 dryrun=dryrun, cwd=cwd)
305 305 if rename and not dryrun:
306 306 if not after and srcexists:
307 307 util.unlinkpath(repo.wjoin(abssrc))
308 308 wctx.forget([abssrc])
309 309
310 310 # pat: ossep
311 311 # dest ossep
312 312 # srcs: list of (hgsep, hgsep, ossep, bool)
313 313 # return: function that takes hgsep and returns ossep
314 314 def targetpathfn(pat, dest, srcs):
315 315 if os.path.isdir(pat):
316 316 abspfx = scmutil.canonpath(repo.root, cwd, pat)
317 317 abspfx = util.localpath(abspfx)
318 318 if destdirexists:
319 319 striplen = len(os.path.split(abspfx)[0])
320 320 else:
321 321 striplen = len(abspfx)
322 322 if striplen:
323 323 striplen += len(os.sep)
324 324 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
325 325 elif destdirexists:
326 326 res = lambda p: os.path.join(dest,
327 327 os.path.basename(util.localpath(p)))
328 328 else:
329 329 res = lambda p: dest
330 330 return res
331 331
332 332 # pat: ossep
333 333 # dest ossep
334 334 # srcs: list of (hgsep, hgsep, ossep, bool)
335 335 # return: function that takes hgsep and returns ossep
336 336 def targetpathafterfn(pat, dest, srcs):
337 337 if matchmod.patkind(pat):
338 338 # a mercurial pattern
339 339 res = lambda p: os.path.join(dest,
340 340 os.path.basename(util.localpath(p)))
341 341 else:
342 342 abspfx = scmutil.canonpath(repo.root, cwd, pat)
343 343 if len(abspfx) < len(srcs[0][0]):
344 344 # A directory. Either the target path contains the last
345 345 # component of the source path or it does not.
346 346 def evalpath(striplen):
347 347 score = 0
348 348 for s in srcs:
349 349 t = os.path.join(dest, util.localpath(s[0])[striplen:])
350 350 if os.path.lexists(t):
351 351 score += 1
352 352 return score
353 353
354 354 abspfx = util.localpath(abspfx)
355 355 striplen = len(abspfx)
356 356 if striplen:
357 357 striplen += len(os.sep)
358 358 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
359 359 score = evalpath(striplen)
360 360 striplen1 = len(os.path.split(abspfx)[0])
361 361 if striplen1:
362 362 striplen1 += len(os.sep)
363 363 if evalpath(striplen1) > score:
364 364 striplen = striplen1
365 365 res = lambda p: os.path.join(dest,
366 366 util.localpath(p)[striplen:])
367 367 else:
368 368 # a file
369 369 if destdirexists:
370 370 res = lambda p: os.path.join(dest,
371 371 os.path.basename(util.localpath(p)))
372 372 else:
373 373 res = lambda p: dest
374 374 return res
375 375
376 376
377 377 pats = scmutil.expandpats(pats)
378 378 if not pats:
379 379 raise util.Abort(_('no source or destination specified'))
380 380 if len(pats) == 1:
381 381 raise util.Abort(_('no destination specified'))
382 382 dest = pats.pop()
383 383 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
384 384 if not destdirexists:
385 385 if len(pats) > 1 or matchmod.patkind(pats[0]):
386 386 raise util.Abort(_('with multiple sources, destination must be an '
387 387 'existing directory'))
388 388 if util.endswithsep(dest):
389 389 raise util.Abort(_('destination %s is not a directory') % dest)
390 390
391 391 tfn = targetpathfn
392 392 if after:
393 393 tfn = targetpathafterfn
394 394 copylist = []
395 395 for pat in pats:
396 396 srcs = walkpat(pat)
397 397 if not srcs:
398 398 continue
399 399 copylist.append((tfn(pat, dest, srcs), srcs))
400 400 if not copylist:
401 401 raise util.Abort(_('no files to copy'))
402 402
403 403 errors = 0
404 404 for targetpath, srcs in copylist:
405 405 for abssrc, relsrc, exact in srcs:
406 406 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
407 407 errors += 1
408 408
409 409 if errors:
410 410 ui.warn(_('(consider using --after)\n'))
411 411
412 412 return errors != 0
413 413
414 414 def service(opts, parentfn=None, initfn=None, runfn=None, logfile=None,
415 415 runargs=None, appendpid=False):
416 416 '''Run a command as a service.'''
417 417
418 418 if opts['daemon'] and not opts['daemon_pipefds']:
419 419 # Signal child process startup with file removal
420 420 lockfd, lockpath = tempfile.mkstemp(prefix='hg-service-')
421 421 os.close(lockfd)
422 422 try:
423 423 if not runargs:
424 424 runargs = util.hgcmd() + sys.argv[1:]
425 425 runargs.append('--daemon-pipefds=%s' % lockpath)
426 426 # Don't pass --cwd to the child process, because we've already
427 427 # changed directory.
428 428 for i in xrange(1, len(runargs)):
429 429 if runargs[i].startswith('--cwd='):
430 430 del runargs[i]
431 431 break
432 432 elif runargs[i].startswith('--cwd'):
433 433 del runargs[i:i + 2]
434 434 break
435 435 def condfn():
436 436 return not os.path.exists(lockpath)
437 437 pid = util.rundetached(runargs, condfn)
438 438 if pid < 0:
439 439 raise util.Abort(_('child process failed to start'))
440 440 finally:
441 441 try:
442 442 os.unlink(lockpath)
443 443 except OSError, e:
444 444 if e.errno != errno.ENOENT:
445 445 raise
446 446 if parentfn:
447 447 return parentfn(pid)
448 448 else:
449 449 return
450 450
451 451 if initfn:
452 452 initfn()
453 453
454 454 if opts['pid_file']:
455 455 mode = appendpid and 'a' or 'w'
456 456 fp = open(opts['pid_file'], mode)
457 457 fp.write(str(os.getpid()) + '\n')
458 458 fp.close()
459 459
460 460 if opts['daemon_pipefds']:
461 461 lockpath = opts['daemon_pipefds']
462 462 try:
463 463 os.setsid()
464 464 except AttributeError:
465 465 pass
466 466 os.unlink(lockpath)
467 467 util.hidewindow()
468 468 sys.stdout.flush()
469 469 sys.stderr.flush()
470 470
471 471 nullfd = os.open(util.nulldev, os.O_RDWR)
472 472 logfilefd = nullfd
473 473 if logfile:
474 474 logfilefd = os.open(logfile, os.O_RDWR | os.O_CREAT | os.O_APPEND)
475 475 os.dup2(nullfd, 0)
476 476 os.dup2(logfilefd, 1)
477 477 os.dup2(logfilefd, 2)
478 478 if nullfd not in (0, 1, 2):
479 479 os.close(nullfd)
480 480 if logfile and logfilefd not in (0, 1, 2):
481 481 os.close(logfilefd)
482 482
483 483 if runfn:
484 484 return runfn()
485 485
486 486 def export(repo, revs, template='hg-%h.patch', fp=None, switch_parent=False,
487 487 opts=None):
488 488 '''export changesets as hg patches.'''
489 489
490 490 total = len(revs)
491 491 revwidth = max([len(str(rev)) for rev in revs])
492 492
493 493 def single(rev, seqno, fp):
494 494 ctx = repo[rev]
495 495 node = ctx.node()
496 496 parents = [p.node() for p in ctx.parents() if p]
497 497 branch = ctx.branch()
498 498 if switch_parent:
499 499 parents.reverse()
500 500 prev = (parents and parents[0]) or nullid
501 501
502 502 shouldclose = False
503 503 if not fp:
504 504 fp = makefileobj(repo, template, node, total=total, seqno=seqno,
505 505 revwidth=revwidth, mode='ab')
506 506 if fp != template:
507 507 shouldclose = True
508 508 if fp != sys.stdout and hasattr(fp, 'name'):
509 509 repo.ui.note("%s\n" % fp.name)
510 510
511 511 fp.write("# HG changeset patch\n")
512 512 fp.write("# User %s\n" % ctx.user())
513 513 fp.write("# Date %d %d\n" % ctx.date())
514 514 if branch and branch != 'default':
515 515 fp.write("# Branch %s\n" % branch)
516 516 fp.write("# Node ID %s\n" % hex(node))
517 517 fp.write("# Parent %s\n" % hex(prev))
518 518 if len(parents) > 1:
519 519 fp.write("# Parent %s\n" % hex(parents[1]))
520 520 fp.write(ctx.description().rstrip())
521 521 fp.write("\n\n")
522 522
523 523 for chunk in patch.diff(repo, prev, node, opts=opts):
524 524 fp.write(chunk)
525 525
526 526 if shouldclose:
527 527 fp.close()
528 528
529 529 for seqno, rev in enumerate(revs):
530 530 single(rev, seqno + 1, fp)
531 531
532 532 def diffordiffstat(ui, repo, diffopts, node1, node2, match,
533 533 changes=None, stat=False, fp=None, prefix='',
534 534 listsubrepos=False):
535 535 '''show diff or diffstat.'''
536 536 if fp is None:
537 537 write = ui.write
538 538 else:
539 539 def write(s, **kw):
540 540 fp.write(s)
541 541
542 542 if stat:
543 543 diffopts = diffopts.copy(context=0)
544 544 width = 80
545 545 if not ui.plain():
546 546 width = ui.termwidth()
547 547 chunks = patch.diff(repo, node1, node2, match, changes, diffopts,
548 548 prefix=prefix)
549 549 for chunk, label in patch.diffstatui(util.iterlines(chunks),
550 550 width=width,
551 551 git=diffopts.git):
552 552 write(chunk, label=label)
553 553 else:
554 554 for chunk, label in patch.diffui(repo, node1, node2, match,
555 555 changes, diffopts, prefix=prefix):
556 556 write(chunk, label=label)
557 557
558 558 if listsubrepos:
559 559 ctx1 = repo[node1]
560 560 ctx2 = repo[node2]
561 561 for subpath, sub in subrepo.itersubrepos(ctx1, ctx2):
562 562 if node2 is not None:
563 563 node2 = ctx2.substate[subpath][1]
564 564 submatch = matchmod.narrowmatcher(subpath, match)
565 565 sub.diff(diffopts, node2, submatch, changes=changes,
566 566 stat=stat, fp=fp, prefix=prefix)
567 567
568 568 class changeset_printer(object):
569 569 '''show changeset information when templating not requested.'''
570 570
571 571 def __init__(self, ui, repo, patch, diffopts, buffered):
572 572 self.ui = ui
573 573 self.repo = repo
574 574 self.buffered = buffered
575 575 self.patch = patch
576 576 self.diffopts = diffopts
577 577 self.header = {}
578 578 self.hunk = {}
579 579 self.lastheader = None
580 580 self.footer = None
581 581
582 582 def flush(self, rev):
583 583 if rev in self.header:
584 584 h = self.header[rev]
585 585 if h != self.lastheader:
586 586 self.lastheader = h
587 587 self.ui.write(h)
588 588 del self.header[rev]
589 589 if rev in self.hunk:
590 590 self.ui.write(self.hunk[rev])
591 591 del self.hunk[rev]
592 592 return 1
593 593 return 0
594 594
595 595 def close(self):
596 596 if self.footer:
597 597 self.ui.write(self.footer)
598 598
599 599 def show(self, ctx, copies=None, matchfn=None, **props):
600 600 if self.buffered:
601 601 self.ui.pushbuffer()
602 602 self._show(ctx, copies, matchfn, props)
603 603 self.hunk[ctx.rev()] = self.ui.popbuffer(labeled=True)
604 604 else:
605 605 self._show(ctx, copies, matchfn, props)
606 606
607 607 def _show(self, ctx, copies, matchfn, props):
608 608 '''show a single changeset or file revision'''
609 609 changenode = ctx.node()
610 610 rev = ctx.rev()
611 611
612 612 if self.ui.quiet:
613 613 self.ui.write("%d:%s\n" % (rev, short(changenode)),
614 614 label='log.node')
615 615 return
616 616
617 617 log = self.repo.changelog
618 618 date = util.datestr(ctx.date())
619 619
620 620 hexfunc = self.ui.debugflag and hex or short
621 621
622 622 parents = [(p, hexfunc(log.node(p)))
623 623 for p in self._meaningful_parentrevs(log, rev)]
624 624
625 625 self.ui.write(_("changeset: %d:%s\n") % (rev, hexfunc(changenode)),
626 626 label='log.changeset')
627 627
628 628 branch = ctx.branch()
629 629 # don't show the default branch name
630 630 if branch != 'default':
631 631 self.ui.write(_("branch: %s\n") % branch,
632 632 label='log.branch')
633 633 for bookmark in self.repo.nodebookmarks(changenode):
634 634 self.ui.write(_("bookmark: %s\n") % bookmark,
635 635 label='log.bookmark')
636 636 for tag in self.repo.nodetags(changenode):
637 637 self.ui.write(_("tag: %s\n") % tag,
638 638 label='log.tag')
639 639 for parent in parents:
640 640 self.ui.write(_("parent: %d:%s\n") % parent,
641 641 label='log.parent')
642 642
643 643 if self.ui.debugflag:
644 644 mnode = ctx.manifestnode()
645 645 self.ui.write(_("manifest: %d:%s\n") %
646 646 (self.repo.manifest.rev(mnode), hex(mnode)),
647 647 label='ui.debug log.manifest')
648 648 self.ui.write(_("user: %s\n") % ctx.user(),
649 649 label='log.user')
650 650 self.ui.write(_("date: %s\n") % date,
651 651 label='log.date')
652 652
653 653 if self.ui.debugflag:
654 654 files = self.repo.status(log.parents(changenode)[0], changenode)[:3]
655 655 for key, value in zip([_("files:"), _("files+:"), _("files-:")],
656 656 files):
657 657 if value:
658 658 self.ui.write("%-12s %s\n" % (key, " ".join(value)),
659 659 label='ui.debug log.files')
660 660 elif ctx.files() and self.ui.verbose:
661 661 self.ui.write(_("files: %s\n") % " ".join(ctx.files()),
662 662 label='ui.note log.files')
663 663 if copies and self.ui.verbose:
664 664 copies = ['%s (%s)' % c for c in copies]
665 665 self.ui.write(_("copies: %s\n") % ' '.join(copies),
666 666 label='ui.note log.copies')
667 667
668 668 extra = ctx.extra()
669 669 if extra and self.ui.debugflag:
670 670 for key, value in sorted(extra.items()):
671 671 self.ui.write(_("extra: %s=%s\n")
672 672 % (key, value.encode('string_escape')),
673 673 label='ui.debug log.extra')
674 674
675 675 description = ctx.description().strip()
676 676 if description:
677 677 if self.ui.verbose:
678 678 self.ui.write(_("description:\n"),
679 679 label='ui.note log.description')
680 680 self.ui.write(description,
681 681 label='ui.note log.description')
682 682 self.ui.write("\n\n")
683 683 else:
684 684 self.ui.write(_("summary: %s\n") %
685 685 description.splitlines()[0],
686 686 label='log.summary')
687 687 self.ui.write("\n")
688 688
689 689 self.showpatch(changenode, matchfn)
690 690
691 691 def showpatch(self, node, matchfn):
692 692 if not matchfn:
693 693 matchfn = self.patch
694 694 if matchfn:
695 695 stat = self.diffopts.get('stat')
696 696 diff = self.diffopts.get('patch')
697 697 diffopts = patch.diffopts(self.ui, self.diffopts)
698 698 prev = self.repo.changelog.parents(node)[0]
699 699 if stat:
700 700 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
701 701 match=matchfn, stat=True)
702 702 if diff:
703 703 if stat:
704 704 self.ui.write("\n")
705 705 diffordiffstat(self.ui, self.repo, diffopts, prev, node,
706 706 match=matchfn, stat=False)
707 707 self.ui.write("\n")
708 708
709 709 def _meaningful_parentrevs(self, log, rev):
710 710 """Return list of meaningful (or all if debug) parentrevs for rev.
711 711
712 712 For merges (two non-nullrev revisions) both parents are meaningful.
713 713 Otherwise the first parent revision is considered meaningful if it
714 714 is not the preceding revision.
715 715 """
716 716 parents = log.parentrevs(rev)
717 717 if not self.ui.debugflag and parents[1] == nullrev:
718 718 if parents[0] >= rev - 1:
719 719 parents = []
720 720 else:
721 721 parents = [parents[0]]
722 722 return parents
723 723
724 724
725 725 class changeset_templater(changeset_printer):
726 726 '''format changeset information.'''
727 727
728 728 def __init__(self, ui, repo, patch, diffopts, mapfile, buffered):
729 729 changeset_printer.__init__(self, ui, repo, patch, diffopts, buffered)
730 730 formatnode = ui.debugflag and (lambda x: x) or (lambda x: x[:12])
731 731 defaulttempl = {
732 732 'parent': '{rev}:{node|formatnode} ',
733 733 'manifest': '{rev}:{node|formatnode}',
734 734 'file_copy': '{name} ({source})',
735 735 'extra': '{key}={value|stringescape}'
736 736 }
737 737 # filecopy is preserved for compatibility reasons
738 738 defaulttempl['filecopy'] = defaulttempl['file_copy']
739 739 self.t = templater.templater(mapfile, {'formatnode': formatnode},
740 740 cache=defaulttempl)
741 741 self.cache = {}
742 742
743 743 def use_template(self, t):
744 744 '''set template string to use'''
745 745 self.t.cache['changeset'] = t
746 746
747 747 def _meaningful_parentrevs(self, ctx):
748 748 """Return list of meaningful (or all if debug) parentrevs for rev.
749 749 """
750 750 parents = ctx.parents()
751 751 if len(parents) > 1:
752 752 return parents
753 753 if self.ui.debugflag:
754 754 return [parents[0], self.repo['null']]
755 755 if parents[0].rev() >= ctx.rev() - 1:
756 756 return []
757 757 return parents
758 758
759 759 def _show(self, ctx, copies, matchfn, props):
760 760 '''show a single changeset or file revision'''
761 761
762 762 showlist = templatekw.showlist
763 763
764 764 # showparents() behaviour depends on ui trace level which
765 765 # causes unexpected behaviours at templating level and makes
766 766 # it harder to extract it in a standalone function. Its
767 767 # behaviour cannot be changed so leave it here for now.
768 768 def showparents(**args):
769 769 ctx = args['ctx']
770 770 parents = [[('rev', p.rev()), ('node', p.hex())]
771 771 for p in self._meaningful_parentrevs(ctx)]
772 772 return showlist('parent', parents, **args)
773 773
774 774 props = props.copy()
775 775 props.update(templatekw.keywords)
776 776 props['parents'] = showparents
777 777 props['templ'] = self.t
778 778 props['ctx'] = ctx
779 779 props['repo'] = self.repo
780 780 props['revcache'] = {'copies': copies}
781 781 props['cache'] = self.cache
782 782
783 783 # find correct templates for current mode
784 784
785 785 tmplmodes = [
786 786 (True, None),
787 787 (self.ui.verbose, 'verbose'),
788 788 (self.ui.quiet, 'quiet'),
789 789 (self.ui.debugflag, 'debug'),
790 790 ]
791 791
792 792 types = {'header': '', 'footer':'', 'changeset': 'changeset'}
793 793 for mode, postfix in tmplmodes:
794 794 for type in types:
795 795 cur = postfix and ('%s_%s' % (type, postfix)) or type
796 796 if mode and cur in self.t:
797 797 types[type] = cur
798 798
799 799 try:
800 800
801 801 # write header
802 802 if types['header']:
803 803 h = templater.stringify(self.t(types['header'], **props))
804 804 if self.buffered:
805 805 self.header[ctx.rev()] = h
806 806 else:
807 807 if self.lastheader != h:
808 808 self.lastheader = h
809 809 self.ui.write(h)
810 810
811 811 # write changeset metadata, then patch if requested
812 812 key = types['changeset']
813 813 self.ui.write(templater.stringify(self.t(key, **props)))
814 814 self.showpatch(ctx.node(), matchfn)
815 815
816 816 if types['footer']:
817 817 if not self.footer:
818 818 self.footer = templater.stringify(self.t(types['footer'],
819 819 **props))
820 820
821 821 except KeyError, inst:
822 822 msg = _("%s: no key named '%s'")
823 823 raise util.Abort(msg % (self.t.mapfile, inst.args[0]))
824 824 except SyntaxError, inst:
825 825 raise util.Abort('%s: %s' % (self.t.mapfile, inst.args[0]))
826 826
827 827 def show_changeset(ui, repo, opts, buffered=False):
828 828 """show one changeset using template or regular display.
829 829
830 830 Display format will be the first non-empty hit of:
831 831 1. option 'template'
832 832 2. option 'style'
833 833 3. [ui] setting 'logtemplate'
834 834 4. [ui] setting 'style'
835 835 If all of these values are either the unset or the empty string,
836 836 regular display via changeset_printer() is done.
837 837 """
838 838 # options
839 839 patch = False
840 840 if opts.get('patch') or opts.get('stat'):
841 841 patch = scmutil.matchall(repo)
842 842
843 843 tmpl = opts.get('template')
844 844 style = None
845 845 if tmpl:
846 846 tmpl = templater.parsestring(tmpl, quoted=False)
847 847 else:
848 848 style = opts.get('style')
849 849
850 850 # ui settings
851 851 if not (tmpl or style):
852 852 tmpl = ui.config('ui', 'logtemplate')
853 853 if tmpl:
854 854 tmpl = templater.parsestring(tmpl)
855 855 else:
856 856 style = util.expandpath(ui.config('ui', 'style', ''))
857 857
858 858 if not (tmpl or style):
859 859 return changeset_printer(ui, repo, patch, opts, buffered)
860 860
861 861 mapfile = None
862 862 if style and not tmpl:
863 863 mapfile = style
864 864 if not os.path.split(mapfile)[0]:
865 865 mapname = (templater.templatepath('map-cmdline.' + mapfile)
866 866 or templater.templatepath(mapfile))
867 867 if mapname:
868 868 mapfile = mapname
869 869
870 870 try:
871 871 t = changeset_templater(ui, repo, patch, opts, mapfile, buffered)
872 872 except SyntaxError, inst:
873 873 raise util.Abort(inst.args[0])
874 874 if tmpl:
875 875 t.use_template(tmpl)
876 876 return t
877 877
878 878 def finddate(ui, repo, date):
879 879 """Find the tipmost changeset that matches the given date spec"""
880 880
881 881 df = util.matchdate(date)
882 882 m = scmutil.matchall(repo)
883 883 results = {}
884 884
885 885 def prep(ctx, fns):
886 886 d = ctx.date()
887 887 if df(d[0]):
888 888 results[ctx.rev()] = d
889 889
890 890 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
891 891 rev = ctx.rev()
892 892 if rev in results:
893 893 ui.status(_("Found revision %s from %s\n") %
894 894 (rev, util.datestr(results[rev])))
895 895 return str(rev)
896 896
897 897 raise util.Abort(_("revision matching date not found"))
898 898
899 899 def walkchangerevs(repo, match, opts, prepare):
900 900 '''Iterate over files and the revs in which they changed.
901 901
902 902 Callers most commonly need to iterate backwards over the history
903 903 in which they are interested. Doing so has awful (quadratic-looking)
904 904 performance, so we use iterators in a "windowed" way.
905 905
906 906 We walk a window of revisions in the desired order. Within the
907 907 window, we first walk forwards to gather data, then in the desired
908 908 order (usually backwards) to display it.
909 909
910 910 This function returns an iterator yielding contexts. Before
911 911 yielding each context, the iterator will first call the prepare
912 912 function on each context in the window in forward order.'''
913 913
914 914 def increasing_windows(start, end, windowsize=8, sizelimit=512):
915 915 if start < end:
916 916 while start < end:
917 917 yield start, min(windowsize, end - start)
918 918 start += windowsize
919 919 if windowsize < sizelimit:
920 920 windowsize *= 2
921 921 else:
922 922 while start > end:
923 923 yield start, min(windowsize, start - end - 1)
924 924 start -= windowsize
925 925 if windowsize < sizelimit:
926 926 windowsize *= 2
927 927
928 928 follow = opts.get('follow') or opts.get('follow_first')
929 929
930 930 if not len(repo):
931 931 return []
932 932
933 933 if follow:
934 934 defrange = '%s:0' % repo['.'].rev()
935 935 else:
936 936 defrange = '-1:0'
937 937 revs = scmutil.revrange(repo, opts['rev'] or [defrange])
938 938 if not revs:
939 939 return []
940 940 wanted = set()
941 941 slowpath = match.anypats() or (match.files() and opts.get('removed'))
942 942 fncache = {}
943 943 change = util.cachefunc(repo.changectx)
944 944
945 945 # First step is to fill wanted, the set of revisions that we want to yield.
946 946 # When it does not induce extra cost, we also fill fncache for revisions in
947 947 # wanted: a cache of filenames that were changed (ctx.files()) and that
948 948 # match the file filtering conditions.
949 949
950 950 if not slowpath and not match.files():
951 951 # No files, no patterns. Display all revs.
952 952 wanted = set(revs)
953 953 copies = []
954 954
955 955 if not slowpath:
956 956 # We only have to read through the filelog to find wanted revisions
957 957
958 958 minrev, maxrev = min(revs), max(revs)
959 959 def filerevgen(filelog, last):
960 960 """
961 961 Only files, no patterns. Check the history of each file.
962 962
963 963 Examines filelog entries within minrev, maxrev linkrev range
964 964 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
965 965 tuples in backwards order
966 966 """
967 967 cl_count = len(repo)
968 968 revs = []
969 969 for j in xrange(0, last + 1):
970 970 linkrev = filelog.linkrev(j)
971 971 if linkrev < minrev:
972 972 continue
973 973 # only yield rev for which we have the changelog, it can
974 974 # happen while doing "hg log" during a pull or commit
975 975 if linkrev >= cl_count:
976 976 break
977 977
978 978 parentlinkrevs = []
979 979 for p in filelog.parentrevs(j):
980 980 if p != nullrev:
981 981 parentlinkrevs.append(filelog.linkrev(p))
982 982 n = filelog.node(j)
983 983 revs.append((linkrev, parentlinkrevs,
984 984 follow and filelog.renamed(n)))
985 985
986 986 return reversed(revs)
987 987 def iterfiles():
988 988 for filename in match.files():
989 989 yield filename, None
990 990 for filename_node in copies:
991 991 yield filename_node
992 992 for file_, node in iterfiles():
993 993 filelog = repo.file(file_)
994 994 if not len(filelog):
995 995 if node is None:
996 996 # A zero count may be a directory or deleted file, so
997 997 # try to find matching entries on the slow path.
998 998 if follow:
999 999 raise util.Abort(
1000 1000 _('cannot follow nonexistent file: "%s"') % file_)
1001 1001 slowpath = True
1002 1002 break
1003 1003 else:
1004 1004 continue
1005 1005
1006 1006 if node is None:
1007 1007 last = len(filelog) - 1
1008 1008 else:
1009 1009 last = filelog.rev(node)
1010 1010
1011 1011
1012 1012 # keep track of all ancestors of the file
1013 1013 ancestors = set([filelog.linkrev(last)])
1014 1014
1015 1015 # iterate from latest to oldest revision
1016 1016 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1017 1017 if not follow:
1018 1018 if rev > maxrev:
1019 1019 continue
1020 1020 else:
1021 1021 # Note that last might not be the first interesting
1022 1022 # rev to us:
1023 1023 # if the file has been changed after maxrev, we'll
1024 1024 # have linkrev(last) > maxrev, and we still need
1025 1025 # to explore the file graph
1026 1026 if rev not in ancestors:
1027 1027 continue
1028 1028 # XXX insert 1327 fix here
1029 1029 if flparentlinkrevs:
1030 1030 ancestors.update(flparentlinkrevs)
1031 1031
1032 1032 fncache.setdefault(rev, []).append(file_)
1033 1033 wanted.add(rev)
1034 1034 if copied:
1035 1035 copies.append(copied)
1036 1036 if slowpath:
1037 1037 # We have to read the changelog to match filenames against
1038 1038 # changed files
1039 1039
1040 1040 if follow:
1041 1041 raise util.Abort(_('can only follow copies/renames for explicit '
1042 1042 'filenames'))
1043 1043
1044 1044 # The slow path checks files modified in every changeset.
1045 1045 for i in sorted(revs):
1046 1046 ctx = change(i)
1047 1047 matches = filter(match, ctx.files())
1048 1048 if matches:
1049 1049 fncache[i] = matches
1050 1050 wanted.add(i)
1051 1051
1052 1052 class followfilter(object):
1053 1053 def __init__(self, onlyfirst=False):
1054 1054 self.startrev = nullrev
1055 1055 self.roots = set()
1056 1056 self.onlyfirst = onlyfirst
1057 1057
1058 1058 def match(self, rev):
1059 1059 def realparents(rev):
1060 1060 if self.onlyfirst:
1061 1061 return repo.changelog.parentrevs(rev)[0:1]
1062 1062 else:
1063 1063 return filter(lambda x: x != nullrev,
1064 1064 repo.changelog.parentrevs(rev))
1065 1065
1066 1066 if self.startrev == nullrev:
1067 1067 self.startrev = rev
1068 1068 return True
1069 1069
1070 1070 if rev > self.startrev:
1071 1071 # forward: all descendants
1072 1072 if not self.roots:
1073 1073 self.roots.add(self.startrev)
1074 1074 for parent in realparents(rev):
1075 1075 if parent in self.roots:
1076 1076 self.roots.add(rev)
1077 1077 return True
1078 1078 else:
1079 1079 # backwards: all parents
1080 1080 if not self.roots:
1081 1081 self.roots.update(realparents(self.startrev))
1082 1082 if rev in self.roots:
1083 1083 self.roots.remove(rev)
1084 1084 self.roots.update(realparents(rev))
1085 1085 return True
1086 1086
1087 1087 return False
1088 1088
1089 1089 # it might be worthwhile to do this in the iterator if the rev range
1090 1090 # is descending and the prune args are all within that range
1091 1091 for rev in opts.get('prune', ()):
1092 1092 rev = repo.changelog.rev(repo.lookup(rev))
1093 1093 ff = followfilter()
1094 1094 stop = min(revs[0], revs[-1])
1095 1095 for x in xrange(rev, stop - 1, -1):
1096 1096 if ff.match(x):
1097 1097 wanted.discard(x)
1098 1098
1099 1099 # Now that wanted is correctly initialized, we can iterate over the
1100 1100 # revision range, yielding only revisions in wanted.
1101 1101 def iterate():
1102 1102 if follow and not match.files():
1103 1103 ff = followfilter(onlyfirst=opts.get('follow_first'))
1104 1104 def want(rev):
1105 1105 return ff.match(rev) and rev in wanted
1106 1106 else:
1107 1107 def want(rev):
1108 1108 return rev in wanted
1109 1109
1110 1110 for i, window in increasing_windows(0, len(revs)):
1111 1111 nrevs = [rev for rev in revs[i:i + window] if want(rev)]
1112 1112 for rev in sorted(nrevs):
1113 1113 fns = fncache.get(rev)
1114 1114 ctx = change(rev)
1115 1115 if not fns:
1116 1116 def fns_generator():
1117 1117 for f in ctx.files():
1118 1118 if match(f):
1119 1119 yield f
1120 1120 fns = fns_generator()
1121 1121 prepare(ctx, fns)
1122 1122 for rev in nrevs:
1123 1123 yield change(rev)
1124 1124 return iterate()
1125 1125
1126 1126 def add(ui, repo, match, dryrun, listsubrepos, prefix):
1127 1127 join = lambda f: os.path.join(prefix, f)
1128 1128 bad = []
1129 1129 oldbad = match.bad
1130 1130 match.bad = lambda x, y: bad.append(x) or oldbad(x, y)
1131 1131 names = []
1132 1132 wctx = repo[None]
1133 1133 cca = None
1134 1134 abort, warn = scmutil.checkportabilityalert(ui)
1135 1135 if abort or warn:
1136 1136 cca = scmutil.casecollisionauditor(ui, abort, wctx)
1137 1137 for f in repo.walk(match):
1138 1138 exact = match.exact(f)
1139 1139 if exact or f not in repo.dirstate:
1140 1140 if cca:
1141 1141 cca(f)
1142 1142 names.append(f)
1143 1143 if ui.verbose or not exact:
1144 1144 ui.status(_('adding %s\n') % match.rel(join(f)))
1145 1145
1146 1146 if listsubrepos:
1147 1147 for subpath in wctx.substate:
1148 1148 sub = wctx.sub(subpath)
1149 1149 try:
1150 1150 submatch = matchmod.narrowmatcher(subpath, match)
1151 1151 bad.extend(sub.add(ui, submatch, dryrun, prefix))
1152 1152 except error.LookupError:
1153 1153 ui.status(_("skipping missing subrepository: %s\n")
1154 1154 % join(subpath))
1155 1155
1156 1156 if not dryrun:
1157 1157 rejected = wctx.add(names, prefix)
1158 1158 bad.extend(f for f in rejected if f in match.files())
1159 1159 return bad
1160 1160
1161 1161 def commit(ui, repo, commitfunc, pats, opts):
1162 1162 '''commit the specified files or all outstanding changes'''
1163 1163 date = opts.get('date')
1164 1164 if date:
1165 1165 opts['date'] = util.parsedate(date)
1166 message = logmessage(opts)
1166 message = logmessage(ui, opts)
1167 1167
1168 1168 # extract addremove carefully -- this function can be called from a command
1169 1169 # that doesn't support addremove
1170 1170 if opts.get('addremove'):
1171 1171 scmutil.addremove(repo, pats, opts)
1172 1172
1173 1173 return commitfunc(ui, repo, message, scmutil.match(repo, pats, opts), opts)
1174 1174
1175 1175 def commiteditor(repo, ctx, subs):
1176 1176 if ctx.description():
1177 1177 return ctx.description()
1178 1178 return commitforceeditor(repo, ctx, subs)
1179 1179
1180 1180 def commitforceeditor(repo, ctx, subs):
1181 1181 edittext = []
1182 1182 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
1183 1183 if ctx.description():
1184 1184 edittext.append(ctx.description())
1185 1185 edittext.append("")
1186 1186 edittext.append("") # Empty line between message and comments.
1187 1187 edittext.append(_("HG: Enter commit message."
1188 1188 " Lines beginning with 'HG:' are removed."))
1189 1189 edittext.append(_("HG: Leave message empty to abort commit."))
1190 1190 edittext.append("HG: --")
1191 1191 edittext.append(_("HG: user: %s") % ctx.user())
1192 1192 if ctx.p2():
1193 1193 edittext.append(_("HG: branch merge"))
1194 1194 if ctx.branch():
1195 1195 edittext.append(_("HG: branch '%s'") % ctx.branch())
1196 1196 edittext.extend([_("HG: subrepo %s") % s for s in subs])
1197 1197 edittext.extend([_("HG: added %s") % f for f in added])
1198 1198 edittext.extend([_("HG: changed %s") % f for f in modified])
1199 1199 edittext.extend([_("HG: removed %s") % f for f in removed])
1200 1200 if not added and not modified and not removed:
1201 1201 edittext.append(_("HG: no files changed"))
1202 1202 edittext.append("")
1203 1203 # run editor in the repository root
1204 1204 olddir = os.getcwd()
1205 1205 os.chdir(repo.root)
1206 1206 text = repo.ui.edit("\n".join(edittext), ctx.user())
1207 1207 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
1208 1208 os.chdir(olddir)
1209 1209
1210 1210 if not text.strip():
1211 1211 raise util.Abort(_("empty commit message"))
1212 1212
1213 1213 return text
1214 1214
1215 1215 def command(table):
1216 1216 '''returns a function object bound to table which can be used as
1217 1217 a decorator for populating table as a command table'''
1218 1218
1219 1219 def cmd(name, options, synopsis=None):
1220 1220 def decorator(func):
1221 1221 if synopsis:
1222 1222 table[name] = func, options[:], synopsis
1223 1223 else:
1224 1224 table[name] = func, options[:]
1225 1225 return func
1226 1226 return decorator
1227 1227
1228 1228 return cmd
@@ -1,5129 +1,5129
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from node import hex, bin, nullid, nullrev, short
9 9 from lock import release
10 10 from i18n import _, gettext
11 11 import os, re, sys, difflib, time, tempfile, errno
12 12 import hg, scmutil, util, revlog, extensions, copies, error, bookmarks
13 13 import patch, help, url, encoding, templatekw, discovery
14 14 import archival, changegroup, cmdutil, sshserver, hbisect, hgweb, hgweb.server
15 15 import merge as mergemod
16 16 import minirst, revset, fileset
17 17 import dagparser, context, simplemerge
18 18 import random, setdiscovery, treediscovery, dagutil
19 19
20 20 table = {}
21 21
22 22 command = cmdutil.command(table)
23 23
24 24 # common command options
25 25
26 26 globalopts = [
27 27 ('R', 'repository', '',
28 28 _('repository root directory or name of overlay bundle file'),
29 29 _('REPO')),
30 30 ('', 'cwd', '',
31 31 _('change working directory'), _('DIR')),
32 32 ('y', 'noninteractive', None,
33 33 _('do not prompt, assume \'yes\' for any required answers')),
34 34 ('q', 'quiet', None, _('suppress output')),
35 35 ('v', 'verbose', None, _('enable additional output')),
36 36 ('', 'config', [],
37 37 _('set/override config option (use \'section.name=value\')'),
38 38 _('CONFIG')),
39 39 ('', 'debug', None, _('enable debugging output')),
40 40 ('', 'debugger', None, _('start debugger')),
41 41 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
42 42 _('ENCODE')),
43 43 ('', 'encodingmode', encoding.encodingmode,
44 44 _('set the charset encoding mode'), _('MODE')),
45 45 ('', 'traceback', None, _('always print a traceback on exception')),
46 46 ('', 'time', None, _('time how long the command takes')),
47 47 ('', 'profile', None, _('print command execution profile')),
48 48 ('', 'version', None, _('output version information and exit')),
49 49 ('h', 'help', None, _('display help and exit')),
50 50 ]
51 51
52 52 dryrunopts = [('n', 'dry-run', None,
53 53 _('do not perform actions, just print output'))]
54 54
55 55 remoteopts = [
56 56 ('e', 'ssh', '',
57 57 _('specify ssh command to use'), _('CMD')),
58 58 ('', 'remotecmd', '',
59 59 _('specify hg command to run on the remote side'), _('CMD')),
60 60 ('', 'insecure', None,
61 61 _('do not verify server certificate (ignoring web.cacerts config)')),
62 62 ]
63 63
64 64 walkopts = [
65 65 ('I', 'include', [],
66 66 _('include names matching the given patterns'), _('PATTERN')),
67 67 ('X', 'exclude', [],
68 68 _('exclude names matching the given patterns'), _('PATTERN')),
69 69 ]
70 70
71 71 commitopts = [
72 72 ('m', 'message', '',
73 73 _('use text as commit message'), _('TEXT')),
74 74 ('l', 'logfile', '',
75 75 _('read commit message from file'), _('FILE')),
76 76 ]
77 77
78 78 commitopts2 = [
79 79 ('d', 'date', '',
80 80 _('record the specified date as commit date'), _('DATE')),
81 81 ('u', 'user', '',
82 82 _('record the specified user as committer'), _('USER')),
83 83 ]
84 84
85 85 templateopts = [
86 86 ('', 'style', '',
87 87 _('display using template map file'), _('STYLE')),
88 88 ('', 'template', '',
89 89 _('display with template'), _('TEMPLATE')),
90 90 ]
91 91
92 92 logopts = [
93 93 ('p', 'patch', None, _('show patch')),
94 94 ('g', 'git', None, _('use git extended diff format')),
95 95 ('l', 'limit', '',
96 96 _('limit number of changes displayed'), _('NUM')),
97 97 ('M', 'no-merges', None, _('do not show merges')),
98 98 ('', 'stat', None, _('output diffstat-style summary of changes')),
99 99 ] + templateopts
100 100
101 101 diffopts = [
102 102 ('a', 'text', None, _('treat all files as text')),
103 103 ('g', 'git', None, _('use git extended diff format')),
104 104 ('', 'nodates', None, _('omit dates from diff headers'))
105 105 ]
106 106
107 107 diffopts2 = [
108 108 ('p', 'show-function', None, _('show which function each change is in')),
109 109 ('', 'reverse', None, _('produce a diff that undoes the changes')),
110 110 ('w', 'ignore-all-space', None,
111 111 _('ignore white space when comparing lines')),
112 112 ('b', 'ignore-space-change', None,
113 113 _('ignore changes in the amount of white space')),
114 114 ('B', 'ignore-blank-lines', None,
115 115 _('ignore changes whose lines are all blank')),
116 116 ('U', 'unified', '',
117 117 _('number of lines of context to show'), _('NUM')),
118 118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 119 ]
120 120
121 121 similarityopts = [
122 122 ('s', 'similarity', '',
123 123 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
124 124 ]
125 125
126 126 subrepoopts = [
127 127 ('S', 'subrepos', None,
128 128 _('recurse into subrepositories'))
129 129 ]
130 130
131 131 # Commands start here, listed alphabetically
132 132
133 133 @command('^add',
134 134 walkopts + subrepoopts + dryrunopts,
135 135 _('[OPTION]... [FILE]...'))
136 136 def add(ui, repo, *pats, **opts):
137 137 """add the specified files on the next commit
138 138
139 139 Schedule files to be version controlled and added to the
140 140 repository.
141 141
142 142 The files will be added to the repository at the next commit. To
143 143 undo an add before that, see :hg:`forget`.
144 144
145 145 If no names are given, add all files to the repository.
146 146
147 147 .. container:: verbose
148 148
149 149 An example showing how new (unknown) files are added
150 150 automatically by :hg:`add`::
151 151
152 152 $ ls
153 153 foo.c
154 154 $ hg status
155 155 ? foo.c
156 156 $ hg add
157 157 adding foo.c
158 158 $ hg status
159 159 A foo.c
160 160
161 161 Returns 0 if all files are successfully added.
162 162 """
163 163
164 164 m = scmutil.match(repo, pats, opts)
165 165 rejected = cmdutil.add(ui, repo, m, opts.get('dry_run'),
166 166 opts.get('subrepos'), prefix="")
167 167 return rejected and 1 or 0
168 168
169 169 @command('addremove',
170 170 similarityopts + walkopts + dryrunopts,
171 171 _('[OPTION]... [FILE]...'))
172 172 def addremove(ui, repo, *pats, **opts):
173 173 """add all new files, delete all missing files
174 174
175 175 Add all new files and remove all missing files from the
176 176 repository.
177 177
178 178 New files are ignored if they match any of the patterns in
179 179 ``.hgignore``. As with add, these changes take effect at the next
180 180 commit.
181 181
182 182 Use the -s/--similarity option to detect renamed files. With a
183 183 parameter greater than 0, this compares every removed file with
184 184 every added file and records those similar enough as renames. This
185 185 option takes a percentage between 0 (disabled) and 100 (files must
186 186 be identical) as its parameter. Detecting renamed files this way
187 187 can be expensive. After using this option, :hg:`status -C` can be
188 188 used to check which files were identified as moved or renamed.
189 189
190 190 Returns 0 if all files are successfully added.
191 191 """
192 192 try:
193 193 sim = float(opts.get('similarity') or 100)
194 194 except ValueError:
195 195 raise util.Abort(_('similarity must be a number'))
196 196 if sim < 0 or sim > 100:
197 197 raise util.Abort(_('similarity must be between 0 and 100'))
198 198 return scmutil.addremove(repo, pats, opts, similarity=sim / 100.0)
199 199
200 200 @command('^annotate|blame',
201 201 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
202 202 ('', 'follow', None,
203 203 _('follow copies/renames and list the filename (DEPRECATED)')),
204 204 ('', 'no-follow', None, _("don't follow copies and renames")),
205 205 ('a', 'text', None, _('treat all files as text')),
206 206 ('u', 'user', None, _('list the author (long with -v)')),
207 207 ('f', 'file', None, _('list the filename')),
208 208 ('d', 'date', None, _('list the date (short with -q)')),
209 209 ('n', 'number', None, _('list the revision number (default)')),
210 210 ('c', 'changeset', None, _('list the changeset')),
211 211 ('l', 'line-number', None, _('show line number at the first appearance'))
212 212 ] + walkopts,
213 213 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'))
214 214 def annotate(ui, repo, *pats, **opts):
215 215 """show changeset information by line for each file
216 216
217 217 List changes in files, showing the revision id responsible for
218 218 each line
219 219
220 220 This command is useful for discovering when a change was made and
221 221 by whom.
222 222
223 223 Without the -a/--text option, annotate will avoid processing files
224 224 it detects as binary. With -a, annotate will annotate the file
225 225 anyway, although the results will probably be neither useful
226 226 nor desirable.
227 227
228 228 Returns 0 on success.
229 229 """
230 230 if opts.get('follow'):
231 231 # --follow is deprecated and now just an alias for -f/--file
232 232 # to mimic the behavior of Mercurial before version 1.5
233 233 opts['file'] = True
234 234
235 235 datefunc = ui.quiet and util.shortdate or util.datestr
236 236 getdate = util.cachefunc(lambda x: datefunc(x[0].date()))
237 237
238 238 if not pats:
239 239 raise util.Abort(_('at least one filename or pattern is required'))
240 240
241 241 opmap = [('user', ' ', lambda x: ui.shortuser(x[0].user())),
242 242 ('number', ' ', lambda x: str(x[0].rev())),
243 243 ('changeset', ' ', lambda x: short(x[0].node())),
244 244 ('date', ' ', getdate),
245 245 ('file', ' ', lambda x: x[0].path()),
246 246 ('line_number', ':', lambda x: str(x[1])),
247 247 ]
248 248
249 249 if (not opts.get('user') and not opts.get('changeset')
250 250 and not opts.get('date') and not opts.get('file')):
251 251 opts['number'] = True
252 252
253 253 linenumber = opts.get('line_number') is not None
254 254 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
255 255 raise util.Abort(_('at least one of -n/-c is required for -l'))
256 256
257 257 funcmap = [(func, sep) for op, sep, func in opmap if opts.get(op)]
258 258 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
259 259
260 260 def bad(x, y):
261 261 raise util.Abort("%s: %s" % (x, y))
262 262
263 263 ctx = scmutil.revsingle(repo, opts.get('rev'))
264 264 m = scmutil.match(repo, pats, opts)
265 265 m.bad = bad
266 266 follow = not opts.get('no_follow')
267 267 for abs in ctx.walk(m):
268 268 fctx = ctx[abs]
269 269 if not opts.get('text') and util.binary(fctx.data()):
270 270 ui.write(_("%s: binary file\n") % ((pats and m.rel(abs)) or abs))
271 271 continue
272 272
273 273 lines = fctx.annotate(follow=follow, linenumber=linenumber)
274 274 pieces = []
275 275
276 276 for f, sep in funcmap:
277 277 l = [f(n) for n, dummy in lines]
278 278 if l:
279 279 sized = [(x, encoding.colwidth(x)) for x in l]
280 280 ml = max([w for x, w in sized])
281 281 pieces.append(["%s%s%s" % (sep, ' ' * (ml - w), x)
282 282 for x, w in sized])
283 283
284 284 if pieces:
285 285 for p, l in zip(zip(*pieces), lines):
286 286 ui.write("%s: %s" % ("".join(p), l[1]))
287 287
288 288 @command('archive',
289 289 [('', 'no-decode', None, _('do not pass files through decoders')),
290 290 ('p', 'prefix', '', _('directory prefix for files in archive'),
291 291 _('PREFIX')),
292 292 ('r', 'rev', '', _('revision to distribute'), _('REV')),
293 293 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
294 294 ] + subrepoopts + walkopts,
295 295 _('[OPTION]... DEST'))
296 296 def archive(ui, repo, dest, **opts):
297 297 '''create an unversioned archive of a repository revision
298 298
299 299 By default, the revision used is the parent of the working
300 300 directory; use -r/--rev to specify a different revision.
301 301
302 302 The archive type is automatically detected based on file
303 303 extension (or override using -t/--type).
304 304
305 305 Valid types are:
306 306
307 307 :``files``: a directory full of files (default)
308 308 :``tar``: tar archive, uncompressed
309 309 :``tbz2``: tar archive, compressed using bzip2
310 310 :``tgz``: tar archive, compressed using gzip
311 311 :``uzip``: zip archive, uncompressed
312 312 :``zip``: zip archive, compressed using deflate
313 313
314 314 The exact name of the destination archive or directory is given
315 315 using a format string; see :hg:`help export` for details.
316 316
317 317 Each member added to an archive file has a directory prefix
318 318 prepended. Use -p/--prefix to specify a format string for the
319 319 prefix. The default is the basename of the archive, with suffixes
320 320 removed.
321 321
322 322 Returns 0 on success.
323 323 '''
324 324
325 325 ctx = scmutil.revsingle(repo, opts.get('rev'))
326 326 if not ctx:
327 327 raise util.Abort(_('no working directory: please specify a revision'))
328 328 node = ctx.node()
329 329 dest = cmdutil.makefilename(repo, dest, node)
330 330 if os.path.realpath(dest) == repo.root:
331 331 raise util.Abort(_('repository root cannot be destination'))
332 332
333 333 kind = opts.get('type') or archival.guesskind(dest) or 'files'
334 334 prefix = opts.get('prefix')
335 335
336 336 if dest == '-':
337 337 if kind == 'files':
338 338 raise util.Abort(_('cannot archive plain files to stdout'))
339 339 dest = sys.stdout
340 340 if not prefix:
341 341 prefix = os.path.basename(repo.root) + '-%h'
342 342
343 343 prefix = cmdutil.makefilename(repo, prefix, node)
344 344 matchfn = scmutil.match(repo, [], opts)
345 345 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
346 346 matchfn, prefix, subrepos=opts.get('subrepos'))
347 347
348 348 @command('backout',
349 349 [('', 'merge', None, _('merge with old dirstate parent after backout')),
350 350 ('', 'parent', '', _('parent to choose when backing out merge'), _('REV')),
351 351 ('t', 'tool', '', _('specify merge tool')),
352 352 ('r', 'rev', '', _('revision to backout'), _('REV')),
353 353 ] + walkopts + commitopts + commitopts2,
354 354 _('[OPTION]... [-r] REV'))
355 355 def backout(ui, repo, node=None, rev=None, **opts):
356 356 '''reverse effect of earlier changeset
357 357
358 358 Prepare a new changeset with the effect of REV undone in the
359 359 current working directory.
360 360
361 361 If REV is the parent of the working directory, then this new changeset
362 362 is committed automatically. Otherwise, hg needs to merge the
363 363 changes and the merged result is left uncommitted.
364 364
365 365 By default, the pending changeset will have one parent,
366 366 maintaining a linear history. With --merge, the pending changeset
367 367 will instead have two parents: the old parent of the working
368 368 directory and a new child of REV that simply undoes REV.
369 369
370 370 Before version 1.7, the behavior without --merge was equivalent to
371 371 specifying --merge followed by :hg:`update --clean .` to cancel
372 372 the merge and leave the child of REV as a head to be merged
373 373 separately.
374 374
375 375 See :hg:`help dates` for a list of formats valid for -d/--date.
376 376
377 377 Returns 0 on success.
378 378 '''
379 379 if rev and node:
380 380 raise util.Abort(_("please specify just one revision"))
381 381
382 382 if not rev:
383 383 rev = node
384 384
385 385 if not rev:
386 386 raise util.Abort(_("please specify a revision to backout"))
387 387
388 388 date = opts.get('date')
389 389 if date:
390 390 opts['date'] = util.parsedate(date)
391 391
392 392 cmdutil.bailifchanged(repo)
393 393 node = scmutil.revsingle(repo, rev).node()
394 394
395 395 op1, op2 = repo.dirstate.parents()
396 396 a = repo.changelog.ancestor(op1, node)
397 397 if a != node:
398 398 raise util.Abort(_('cannot backout change on a different branch'))
399 399
400 400 p1, p2 = repo.changelog.parents(node)
401 401 if p1 == nullid:
402 402 raise util.Abort(_('cannot backout a change with no parents'))
403 403 if p2 != nullid:
404 404 if not opts.get('parent'):
405 405 raise util.Abort(_('cannot backout a merge changeset without '
406 406 '--parent'))
407 407 p = repo.lookup(opts['parent'])
408 408 if p not in (p1, p2):
409 409 raise util.Abort(_('%s is not a parent of %s') %
410 410 (short(p), short(node)))
411 411 parent = p
412 412 else:
413 413 if opts.get('parent'):
414 414 raise util.Abort(_('cannot use --parent on non-merge changeset'))
415 415 parent = p1
416 416
417 417 # the backout should appear on the same branch
418 418 branch = repo.dirstate.branch()
419 419 hg.clean(repo, node, show_stats=False)
420 420 repo.dirstate.setbranch(branch)
421 421 revert_opts = opts.copy()
422 422 revert_opts['date'] = None
423 423 revert_opts['all'] = True
424 424 revert_opts['rev'] = hex(parent)
425 425 revert_opts['no_backup'] = None
426 426 revert(ui, repo, **revert_opts)
427 427 if not opts.get('merge') and op1 != node:
428 428 try:
429 429 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
430 430 return hg.update(repo, op1)
431 431 finally:
432 432 ui.setconfig('ui', 'forcemerge', '')
433 433
434 434 commit_opts = opts.copy()
435 435 commit_opts['addremove'] = False
436 436 if not commit_opts['message'] and not commit_opts['logfile']:
437 437 # we don't translate commit messages
438 438 commit_opts['message'] = "Backed out changeset %s" % short(node)
439 439 commit_opts['force_editor'] = True
440 440 commit(ui, repo, **commit_opts)
441 441 def nice(node):
442 442 return '%d:%s' % (repo.changelog.rev(node), short(node))
443 443 ui.status(_('changeset %s backs out changeset %s\n') %
444 444 (nice(repo.changelog.tip()), nice(node)))
445 445 if opts.get('merge') and op1 != node:
446 446 hg.clean(repo, op1, show_stats=False)
447 447 ui.status(_('merging with changeset %s\n')
448 448 % nice(repo.changelog.tip()))
449 449 try:
450 450 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
451 451 return hg.merge(repo, hex(repo.changelog.tip()))
452 452 finally:
453 453 ui.setconfig('ui', 'forcemerge', '')
454 454 return 0
455 455
456 456 @command('bisect',
457 457 [('r', 'reset', False, _('reset bisect state')),
458 458 ('g', 'good', False, _('mark changeset good')),
459 459 ('b', 'bad', False, _('mark changeset bad')),
460 460 ('s', 'skip', False, _('skip testing changeset')),
461 461 ('e', 'extend', False, _('extend the bisect range')),
462 462 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
463 463 ('U', 'noupdate', False, _('do not update to target'))],
464 464 _("[-gbsr] [-U] [-c CMD] [REV]"))
465 465 def bisect(ui, repo, rev=None, extra=None, command=None,
466 466 reset=None, good=None, bad=None, skip=None, extend=None,
467 467 noupdate=None):
468 468 """subdivision search of changesets
469 469
470 470 This command helps to find changesets which introduce problems. To
471 471 use, mark the earliest changeset you know exhibits the problem as
472 472 bad, then mark the latest changeset which is free from the problem
473 473 as good. Bisect will update your working directory to a revision
474 474 for testing (unless the -U/--noupdate option is specified). Once
475 475 you have performed tests, mark the working directory as good or
476 476 bad, and bisect will either update to another candidate changeset
477 477 or announce that it has found the bad revision.
478 478
479 479 As a shortcut, you can also use the revision argument to mark a
480 480 revision as good or bad without checking it out first.
481 481
482 482 If you supply a command, it will be used for automatic bisection.
483 483 Its exit status will be used to mark revisions as good or bad:
484 484 status 0 means good, 125 means to skip the revision, 127
485 485 (command not found) will abort the bisection, and any other
486 486 non-zero exit status means the revision is bad.
487 487
488 488 Returns 0 on success.
489 489 """
490 490 def extendbisectrange(nodes, good):
491 491 # bisect is incomplete when it ends on a merge node and
492 492 # one of the parent was not checked.
493 493 parents = repo[nodes[0]].parents()
494 494 if len(parents) > 1:
495 495 side = good and state['bad'] or state['good']
496 496 num = len(set(i.node() for i in parents) & set(side))
497 497 if num == 1:
498 498 return parents[0].ancestor(parents[1])
499 499 return None
500 500
501 501 def print_result(nodes, good):
502 502 displayer = cmdutil.show_changeset(ui, repo, {})
503 503 if len(nodes) == 1:
504 504 # narrowed it down to a single revision
505 505 if good:
506 506 ui.write(_("The first good revision is:\n"))
507 507 else:
508 508 ui.write(_("The first bad revision is:\n"))
509 509 displayer.show(repo[nodes[0]])
510 510 extendnode = extendbisectrange(nodes, good)
511 511 if extendnode is not None:
512 512 ui.write(_('Not all ancestors of this changeset have been'
513 513 ' checked.\nUse bisect --extend to continue the '
514 514 'bisection from\nthe common ancestor, %s.\n')
515 515 % extendnode)
516 516 else:
517 517 # multiple possible revisions
518 518 if good:
519 519 ui.write(_("Due to skipped revisions, the first "
520 520 "good revision could be any of:\n"))
521 521 else:
522 522 ui.write(_("Due to skipped revisions, the first "
523 523 "bad revision could be any of:\n"))
524 524 for n in nodes:
525 525 displayer.show(repo[n])
526 526 displayer.close()
527 527
528 528 def check_state(state, interactive=True):
529 529 if not state['good'] or not state['bad']:
530 530 if (good or bad or skip or reset) and interactive:
531 531 return
532 532 if not state['good']:
533 533 raise util.Abort(_('cannot bisect (no known good revisions)'))
534 534 else:
535 535 raise util.Abort(_('cannot bisect (no known bad revisions)'))
536 536 return True
537 537
538 538 # backward compatibility
539 539 if rev in "good bad reset init".split():
540 540 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
541 541 cmd, rev, extra = rev, extra, None
542 542 if cmd == "good":
543 543 good = True
544 544 elif cmd == "bad":
545 545 bad = True
546 546 else:
547 547 reset = True
548 548 elif extra or good + bad + skip + reset + extend + bool(command) > 1:
549 549 raise util.Abort(_('incompatible arguments'))
550 550
551 551 if reset:
552 552 p = repo.join("bisect.state")
553 553 if os.path.exists(p):
554 554 os.unlink(p)
555 555 return
556 556
557 557 state = hbisect.load_state(repo)
558 558
559 559 if command:
560 560 changesets = 1
561 561 try:
562 562 while changesets:
563 563 # update state
564 564 status = util.system(command)
565 565 if status == 125:
566 566 transition = "skip"
567 567 elif status == 0:
568 568 transition = "good"
569 569 # status < 0 means process was killed
570 570 elif status == 127:
571 571 raise util.Abort(_("failed to execute %s") % command)
572 572 elif status < 0:
573 573 raise util.Abort(_("%s killed") % command)
574 574 else:
575 575 transition = "bad"
576 576 ctx = scmutil.revsingle(repo, rev)
577 577 rev = None # clear for future iterations
578 578 state[transition].append(ctx.node())
579 579 ui.status(_('Changeset %d:%s: %s\n') % (ctx, ctx, transition))
580 580 check_state(state, interactive=False)
581 581 # bisect
582 582 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
583 583 # update to next check
584 584 cmdutil.bailifchanged(repo)
585 585 hg.clean(repo, nodes[0], show_stats=False)
586 586 finally:
587 587 hbisect.save_state(repo, state)
588 588 print_result(nodes, good)
589 589 return
590 590
591 591 # update state
592 592
593 593 if rev:
594 594 nodes = [repo.lookup(i) for i in scmutil.revrange(repo, [rev])]
595 595 else:
596 596 nodes = [repo.lookup('.')]
597 597
598 598 if good or bad or skip:
599 599 if good:
600 600 state['good'] += nodes
601 601 elif bad:
602 602 state['bad'] += nodes
603 603 elif skip:
604 604 state['skip'] += nodes
605 605 hbisect.save_state(repo, state)
606 606
607 607 if not check_state(state):
608 608 return
609 609
610 610 # actually bisect
611 611 nodes, changesets, good = hbisect.bisect(repo.changelog, state)
612 612 if extend:
613 613 if not changesets:
614 614 extendnode = extendbisectrange(nodes, good)
615 615 if extendnode is not None:
616 616 ui.write(_("Extending search to changeset %d:%s\n"
617 617 % (extendnode.rev(), extendnode)))
618 618 if noupdate:
619 619 return
620 620 cmdutil.bailifchanged(repo)
621 621 return hg.clean(repo, extendnode.node())
622 622 raise util.Abort(_("nothing to extend"))
623 623
624 624 if changesets == 0:
625 625 print_result(nodes, good)
626 626 else:
627 627 assert len(nodes) == 1 # only a single node can be tested next
628 628 node = nodes[0]
629 629 # compute the approximate number of remaining tests
630 630 tests, size = 0, 2
631 631 while size <= changesets:
632 632 tests, size = tests + 1, size * 2
633 633 rev = repo.changelog.rev(node)
634 634 ui.write(_("Testing changeset %d:%s "
635 635 "(%d changesets remaining, ~%d tests)\n")
636 636 % (rev, short(node), changesets, tests))
637 637 if not noupdate:
638 638 cmdutil.bailifchanged(repo)
639 639 return hg.clean(repo, node)
640 640
641 641 @command('bookmarks',
642 642 [('f', 'force', False, _('force')),
643 643 ('r', 'rev', '', _('revision'), _('REV')),
644 644 ('d', 'delete', False, _('delete a given bookmark')),
645 645 ('m', 'rename', '', _('rename a given bookmark'), _('NAME')),
646 646 ('i', 'inactive', False, _('do not mark a new bookmark active'))],
647 647 _('hg bookmarks [-f] [-d] [-i] [-m NAME] [-r REV] [NAME]'))
648 648 def bookmark(ui, repo, mark=None, rev=None, force=False, delete=False,
649 649 rename=None, inactive=False):
650 650 '''track a line of development with movable markers
651 651
652 652 Bookmarks are pointers to certain commits that move when
653 653 committing. Bookmarks are local. They can be renamed, copied and
654 654 deleted. It is possible to use bookmark names in :hg:`merge` and
655 655 :hg:`update` to merge and update respectively to a given bookmark.
656 656
657 657 You can use :hg:`bookmark NAME` to set a bookmark on the working
658 658 directory's parent revision with the given name. If you specify
659 659 a revision using -r REV (where REV may be an existing bookmark),
660 660 the bookmark is assigned to that revision.
661 661
662 662 Bookmarks can be pushed and pulled between repositories (see :hg:`help
663 663 push` and :hg:`help pull`). This requires both the local and remote
664 664 repositories to support bookmarks. For versions prior to 1.8, this means
665 665 the bookmarks extension must be enabled.
666 666 '''
667 667 hexfn = ui.debugflag and hex or short
668 668 marks = repo._bookmarks
669 669 cur = repo.changectx('.').node()
670 670
671 671 if rename:
672 672 if rename not in marks:
673 673 raise util.Abort(_("bookmark '%s' does not exist") % rename)
674 674 if mark in marks and not force:
675 675 raise util.Abort(_("bookmark '%s' already exists "
676 676 "(use -f to force)") % mark)
677 677 if mark is None:
678 678 raise util.Abort(_("new bookmark name required"))
679 679 marks[mark] = marks[rename]
680 680 if repo._bookmarkcurrent == rename and not inactive:
681 681 bookmarks.setcurrent(repo, mark)
682 682 del marks[rename]
683 683 bookmarks.write(repo)
684 684 return
685 685
686 686 if delete:
687 687 if mark is None:
688 688 raise util.Abort(_("bookmark name required"))
689 689 if mark not in marks:
690 690 raise util.Abort(_("bookmark '%s' does not exist") % mark)
691 691 if mark == repo._bookmarkcurrent:
692 692 bookmarks.setcurrent(repo, None)
693 693 del marks[mark]
694 694 bookmarks.write(repo)
695 695 return
696 696
697 697 if mark is not None:
698 698 if "\n" in mark:
699 699 raise util.Abort(_("bookmark name cannot contain newlines"))
700 700 mark = mark.strip()
701 701 if not mark:
702 702 raise util.Abort(_("bookmark names cannot consist entirely of "
703 703 "whitespace"))
704 704 if inactive and mark == repo._bookmarkcurrent:
705 705 bookmarks.setcurrent(repo, None)
706 706 return
707 707 if mark in marks and not force:
708 708 raise util.Abort(_("bookmark '%s' already exists "
709 709 "(use -f to force)") % mark)
710 710 if ((mark in repo.branchtags() or mark == repo.dirstate.branch())
711 711 and not force):
712 712 raise util.Abort(
713 713 _("a bookmark cannot have the name of an existing branch"))
714 714 if rev:
715 715 marks[mark] = repo.lookup(rev)
716 716 else:
717 717 marks[mark] = repo.changectx('.').node()
718 718 if not inactive and repo.changectx('.').node() == marks[mark]:
719 719 bookmarks.setcurrent(repo, mark)
720 720 bookmarks.write(repo)
721 721 return
722 722
723 723 if mark is None:
724 724 if rev:
725 725 raise util.Abort(_("bookmark name required"))
726 726 if len(marks) == 0:
727 727 ui.status(_("no bookmarks set\n"))
728 728 else:
729 729 for bmark, n in sorted(marks.iteritems()):
730 730 current = repo._bookmarkcurrent
731 731 if bmark == current and n == cur:
732 732 prefix, label = '*', 'bookmarks.current'
733 733 else:
734 734 prefix, label = ' ', ''
735 735
736 736 if ui.quiet:
737 737 ui.write("%s\n" % bmark, label=label)
738 738 else:
739 739 ui.write(" %s %-25s %d:%s\n" % (
740 740 prefix, bmark, repo.changelog.rev(n), hexfn(n)),
741 741 label=label)
742 742 return
743 743
744 744 @command('branch',
745 745 [('f', 'force', None,
746 746 _('set branch name even if it shadows an existing branch')),
747 747 ('C', 'clean', None, _('reset branch name to parent branch name'))],
748 748 _('[-fC] [NAME]'))
749 749 def branch(ui, repo, label=None, **opts):
750 750 """set or show the current branch name
751 751
752 752 With no argument, show the current branch name. With one argument,
753 753 set the working directory branch name (the branch will not exist
754 754 in the repository until the next commit). Standard practice
755 755 recommends that primary development take place on the 'default'
756 756 branch.
757 757
758 758 Unless -f/--force is specified, branch will not let you set a
759 759 branch name that already exists, even if it's inactive.
760 760
761 761 Use -C/--clean to reset the working directory branch to that of
762 762 the parent of the working directory, negating a previous branch
763 763 change.
764 764
765 765 Use the command :hg:`update` to switch to an existing branch. Use
766 766 :hg:`commit --close-branch` to mark this branch as closed.
767 767
768 768 .. note::
769 769
770 770 Branch names are permanent. Use :hg:`bookmark` to create a
771 771 light-weight bookmark instead. See :hg:`help glossary` for more
772 772 information about named branches and bookmarks.
773 773
774 774 Returns 0 on success.
775 775 """
776 776
777 777 if opts.get('clean'):
778 778 label = repo[None].p1().branch()
779 779 repo.dirstate.setbranch(label)
780 780 ui.status(_('reset working directory to branch %s\n') % label)
781 781 elif label:
782 782 if not opts.get('force') and label in repo.branchtags():
783 783 if label not in [p.branch() for p in repo.parents()]:
784 784 raise util.Abort(_('a branch of the same name already exists'),
785 785 # i18n: "it" refers to an existing branch
786 786 hint=_("use 'hg update' to switch to it"))
787 787 repo.dirstate.setbranch(label)
788 788 ui.status(_('marked working directory as branch %s\n') % label)
789 789 else:
790 790 ui.write("%s\n" % repo.dirstate.branch())
791 791
792 792 @command('branches',
793 793 [('a', 'active', False, _('show only branches that have unmerged heads')),
794 794 ('c', 'closed', False, _('show normal and closed branches'))],
795 795 _('[-ac]'))
796 796 def branches(ui, repo, active=False, closed=False):
797 797 """list repository named branches
798 798
799 799 List the repository's named branches, indicating which ones are
800 800 inactive. If -c/--closed is specified, also list branches which have
801 801 been marked closed (see :hg:`commit --close-branch`).
802 802
803 803 If -a/--active is specified, only show active branches. A branch
804 804 is considered active if it contains repository heads.
805 805
806 806 Use the command :hg:`update` to switch to an existing branch.
807 807
808 808 Returns 0.
809 809 """
810 810
811 811 hexfunc = ui.debugflag and hex or short
812 812 activebranches = [repo[n].branch() for n in repo.heads()]
813 813 def testactive(tag, node):
814 814 realhead = tag in activebranches
815 815 open = node in repo.branchheads(tag, closed=False)
816 816 return realhead and open
817 817 branches = sorted([(testactive(tag, node), repo.changelog.rev(node), tag)
818 818 for tag, node in repo.branchtags().items()],
819 819 reverse=True)
820 820
821 821 for isactive, node, tag in branches:
822 822 if (not active) or isactive:
823 823 if ui.quiet:
824 824 ui.write("%s\n" % tag)
825 825 else:
826 826 hn = repo.lookup(node)
827 827 if isactive:
828 828 label = 'branches.active'
829 829 notice = ''
830 830 elif hn not in repo.branchheads(tag, closed=False):
831 831 if not closed:
832 832 continue
833 833 label = 'branches.closed'
834 834 notice = _(' (closed)')
835 835 else:
836 836 label = 'branches.inactive'
837 837 notice = _(' (inactive)')
838 838 if tag == repo.dirstate.branch():
839 839 label = 'branches.current'
840 840 rev = str(node).rjust(31 - encoding.colwidth(tag))
841 841 rev = ui.label('%s:%s' % (rev, hexfunc(hn)), 'log.changeset')
842 842 tag = ui.label(tag, label)
843 843 ui.write("%s %s%s\n" % (tag, rev, notice))
844 844
845 845 @command('bundle',
846 846 [('f', 'force', None, _('run even when the destination is unrelated')),
847 847 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
848 848 _('REV')),
849 849 ('b', 'branch', [], _('a specific branch you would like to bundle'),
850 850 _('BRANCH')),
851 851 ('', 'base', [],
852 852 _('a base changeset assumed to be available at the destination'),
853 853 _('REV')),
854 854 ('a', 'all', None, _('bundle all changesets in the repository')),
855 855 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
856 856 ] + remoteopts,
857 857 _('[-f] [-t TYPE] [-a] [-r REV]... [--base REV]... FILE [DEST]'))
858 858 def bundle(ui, repo, fname, dest=None, **opts):
859 859 """create a changegroup file
860 860
861 861 Generate a compressed changegroup file collecting changesets not
862 862 known to be in another repository.
863 863
864 864 If you omit the destination repository, then hg assumes the
865 865 destination will have all the nodes you specify with --base
866 866 parameters. To create a bundle containing all changesets, use
867 867 -a/--all (or --base null).
868 868
869 869 You can change compression method with the -t/--type option.
870 870 The available compression methods are: none, bzip2, and
871 871 gzip (by default, bundles are compressed using bzip2).
872 872
873 873 The bundle file can then be transferred using conventional means
874 874 and applied to another repository with the unbundle or pull
875 875 command. This is useful when direct push and pull are not
876 876 available or when exporting an entire repository is undesirable.
877 877
878 878 Applying bundles preserves all changeset contents including
879 879 permissions, copy/rename information, and revision history.
880 880
881 881 Returns 0 on success, 1 if no changes found.
882 882 """
883 883 revs = None
884 884 if 'rev' in opts:
885 885 revs = scmutil.revrange(repo, opts['rev'])
886 886
887 887 if opts.get('all'):
888 888 base = ['null']
889 889 else:
890 890 base = scmutil.revrange(repo, opts.get('base'))
891 891 if base:
892 892 if dest:
893 893 raise util.Abort(_("--base is incompatible with specifying "
894 894 "a destination"))
895 895 common = [repo.lookup(rev) for rev in base]
896 896 heads = revs and map(repo.lookup, revs) or revs
897 897 else:
898 898 dest = ui.expandpath(dest or 'default-push', dest or 'default')
899 899 dest, branches = hg.parseurl(dest, opts.get('branch'))
900 900 other = hg.peer(repo, opts, dest)
901 901 revs, checkout = hg.addbranchrevs(repo, other, branches, revs)
902 902 heads = revs and map(repo.lookup, revs) or revs
903 903 common, outheads = discovery.findcommonoutgoing(repo, other,
904 904 onlyheads=heads,
905 905 force=opts.get('force'))
906 906
907 907 cg = repo.getbundle('bundle', common=common, heads=heads)
908 908 if not cg:
909 909 ui.status(_("no changes found\n"))
910 910 return 1
911 911
912 912 bundletype = opts.get('type', 'bzip2').lower()
913 913 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
914 914 bundletype = btypes.get(bundletype)
915 915 if bundletype not in changegroup.bundletypes:
916 916 raise util.Abort(_('unknown bundle type specified with --type'))
917 917
918 918 changegroup.writebundle(cg, fname, bundletype)
919 919
920 920 @command('cat',
921 921 [('o', 'output', '',
922 922 _('print output to file with formatted name'), _('FORMAT')),
923 923 ('r', 'rev', '', _('print the given revision'), _('REV')),
924 924 ('', 'decode', None, _('apply any matching decode filter')),
925 925 ] + walkopts,
926 926 _('[OPTION]... FILE...'))
927 927 def cat(ui, repo, file1, *pats, **opts):
928 928 """output the current or given revision of files
929 929
930 930 Print the specified files as they were at the given revision. If
931 931 no revision is given, the parent of the working directory is used,
932 932 or tip if no revision is checked out.
933 933
934 934 Output may be to a file, in which case the name of the file is
935 935 given using a format string. The formatting rules are the same as
936 936 for the export command, with the following additions:
937 937
938 938 :``%s``: basename of file being printed
939 939 :``%d``: dirname of file being printed, or '.' if in repository root
940 940 :``%p``: root-relative path name of file being printed
941 941
942 942 Returns 0 on success.
943 943 """
944 944 ctx = scmutil.revsingle(repo, opts.get('rev'))
945 945 err = 1
946 946 m = scmutil.match(repo, (file1,) + pats, opts)
947 947 for abs in ctx.walk(m):
948 948 fp = cmdutil.makefileobj(repo, opts.get('output'), ctx.node(),
949 949 pathname=abs)
950 950 data = ctx[abs].data()
951 951 if opts.get('decode'):
952 952 data = repo.wwritedata(abs, data)
953 953 fp.write(data)
954 954 fp.close()
955 955 err = 0
956 956 return err
957 957
958 958 @command('^clone',
959 959 [('U', 'noupdate', None,
960 960 _('the clone will include an empty working copy (only a repository)')),
961 961 ('u', 'updaterev', '', _('revision, tag or branch to check out'), _('REV')),
962 962 ('r', 'rev', [], _('include the specified changeset'), _('REV')),
963 963 ('b', 'branch', [], _('clone only the specified branch'), _('BRANCH')),
964 964 ('', 'pull', None, _('use pull protocol to copy metadata')),
965 965 ('', 'uncompressed', None, _('use uncompressed transfer (fast over LAN)')),
966 966 ] + remoteopts,
967 967 _('[OPTION]... SOURCE [DEST]'))
968 968 def clone(ui, source, dest=None, **opts):
969 969 """make a copy of an existing repository
970 970
971 971 Create a copy of an existing repository in a new directory.
972 972
973 973 If no destination directory name is specified, it defaults to the
974 974 basename of the source.
975 975
976 976 The location of the source is added to the new repository's
977 977 ``.hg/hgrc`` file, as the default to be used for future pulls.
978 978
979 979 See :hg:`help urls` for valid source format details.
980 980
981 981 It is possible to specify an ``ssh://`` URL as the destination, but no
982 982 ``.hg/hgrc`` and working directory will be created on the remote side.
983 983 Please see :hg:`help urls` for important details about ``ssh://`` URLs.
984 984
985 985 A set of changesets (tags, or branch names) to pull may be specified
986 986 by listing each changeset (tag, or branch name) with -r/--rev.
987 987 If -r/--rev is used, the cloned repository will contain only a subset
988 988 of the changesets of the source repository. Only the set of changesets
989 989 defined by all -r/--rev options (including all their ancestors)
990 990 will be pulled into the destination repository.
991 991 No subsequent changesets (including subsequent tags) will be present
992 992 in the destination.
993 993
994 994 Using -r/--rev (or 'clone src#rev dest') implies --pull, even for
995 995 local source repositories.
996 996
997 997 For efficiency, hardlinks are used for cloning whenever the source
998 998 and destination are on the same filesystem (note this applies only
999 999 to the repository data, not to the working directory). Some
1000 1000 filesystems, such as AFS, implement hardlinking incorrectly, but
1001 1001 do not report errors. In these cases, use the --pull option to
1002 1002 avoid hardlinking.
1003 1003
1004 1004 In some cases, you can clone repositories and the working directory
1005 1005 using full hardlinks with ::
1006 1006
1007 1007 $ cp -al REPO REPOCLONE
1008 1008
1009 1009 This is the fastest way to clone, but it is not always safe. The
1010 1010 operation is not atomic (making sure REPO is not modified during
1011 1011 the operation is up to you) and you have to make sure your editor
1012 1012 breaks hardlinks (Emacs and most Linux Kernel tools do so). Also,
1013 1013 this is not compatible with certain extensions that place their
1014 1014 metadata under the .hg directory, such as mq.
1015 1015
1016 1016 Mercurial will update the working directory to the first applicable
1017 1017 revision from this list:
1018 1018
1019 1019 a) null if -U or the source repository has no changesets
1020 1020 b) if -u . and the source repository is local, the first parent of
1021 1021 the source repository's working directory
1022 1022 c) the changeset specified with -u (if a branch name, this means the
1023 1023 latest head of that branch)
1024 1024 d) the changeset specified with -r
1025 1025 e) the tipmost head specified with -b
1026 1026 f) the tipmost head specified with the url#branch source syntax
1027 1027 g) the tipmost head of the default branch
1028 1028 h) tip
1029 1029
1030 1030 Returns 0 on success.
1031 1031 """
1032 1032 if opts.get('noupdate') and opts.get('updaterev'):
1033 1033 raise util.Abort(_("cannot specify both --noupdate and --updaterev"))
1034 1034
1035 1035 r = hg.clone(ui, opts, source, dest,
1036 1036 pull=opts.get('pull'),
1037 1037 stream=opts.get('uncompressed'),
1038 1038 rev=opts.get('rev'),
1039 1039 update=opts.get('updaterev') or not opts.get('noupdate'),
1040 1040 branch=opts.get('branch'))
1041 1041
1042 1042 return r is None
1043 1043
1044 1044 @command('^commit|ci',
1045 1045 [('A', 'addremove', None,
1046 1046 _('mark new/missing files as added/removed before committing')),
1047 1047 ('', 'close-branch', None,
1048 1048 _('mark a branch as closed, hiding it from the branch list')),
1049 1049 ] + walkopts + commitopts + commitopts2,
1050 1050 _('[OPTION]... [FILE]...'))
1051 1051 def commit(ui, repo, *pats, **opts):
1052 1052 """commit the specified files or all outstanding changes
1053 1053
1054 1054 Commit changes to the given files into the repository. Unlike a
1055 1055 centralized SCM, this operation is a local operation. See
1056 1056 :hg:`push` for a way to actively distribute your changes.
1057 1057
1058 1058 If a list of files is omitted, all changes reported by :hg:`status`
1059 1059 will be committed.
1060 1060
1061 1061 If you are committing the result of a merge, do not provide any
1062 1062 filenames or -I/-X filters.
1063 1063
1064 1064 If no commit message is specified, Mercurial starts your
1065 1065 configured editor where you can enter a message. In case your
1066 1066 commit fails, you will find a backup of your message in
1067 1067 ``.hg/last-message.txt``.
1068 1068
1069 1069 See :hg:`help dates` for a list of formats valid for -d/--date.
1070 1070
1071 1071 Returns 0 on success, 1 if nothing changed.
1072 1072 """
1073 1073 extra = {}
1074 1074 if opts.get('close_branch'):
1075 1075 if repo['.'].node() not in repo.branchheads():
1076 1076 # The topo heads set is included in the branch heads set of the
1077 1077 # current branch, so it's sufficient to test branchheads
1078 1078 raise util.Abort(_('can only close branch heads'))
1079 1079 extra['close'] = 1
1080 1080 e = cmdutil.commiteditor
1081 1081 if opts.get('force_editor'):
1082 1082 e = cmdutil.commitforceeditor
1083 1083
1084 1084 def commitfunc(ui, repo, message, match, opts):
1085 1085 return repo.commit(message, opts.get('user'), opts.get('date'), match,
1086 1086 editor=e, extra=extra)
1087 1087
1088 1088 branch = repo[None].branch()
1089 1089 bheads = repo.branchheads(branch)
1090 1090
1091 1091 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1092 1092 if not node:
1093 1093 stat = repo.status(match=scmutil.match(repo, pats, opts))
1094 1094 if stat[3]:
1095 1095 ui.status(_("nothing changed (%d missing files, see 'hg status')\n")
1096 1096 % len(stat[3]))
1097 1097 else:
1098 1098 ui.status(_("nothing changed\n"))
1099 1099 return 1
1100 1100
1101 1101 ctx = repo[node]
1102 1102 parents = ctx.parents()
1103 1103
1104 1104 if bheads and not [x for x in parents
1105 1105 if x.node() in bheads and x.branch() == branch]:
1106 1106 ui.status(_('created new head\n'))
1107 1107 # The message is not printed for initial roots. For the other
1108 1108 # changesets, it is printed in the following situations:
1109 1109 #
1110 1110 # Par column: for the 2 parents with ...
1111 1111 # N: null or no parent
1112 1112 # B: parent is on another named branch
1113 1113 # C: parent is a regular non head changeset
1114 1114 # H: parent was a branch head of the current branch
1115 1115 # Msg column: whether we print "created new head" message
1116 1116 # In the following, it is assumed that there already exists some
1117 1117 # initial branch heads of the current branch, otherwise nothing is
1118 1118 # printed anyway.
1119 1119 #
1120 1120 # Par Msg Comment
1121 1121 # NN y additional topo root
1122 1122 #
1123 1123 # BN y additional branch root
1124 1124 # CN y additional topo head
1125 1125 # HN n usual case
1126 1126 #
1127 1127 # BB y weird additional branch root
1128 1128 # CB y branch merge
1129 1129 # HB n merge with named branch
1130 1130 #
1131 1131 # CC y additional head from merge
1132 1132 # CH n merge with a head
1133 1133 #
1134 1134 # HH n head merge: head count decreases
1135 1135
1136 1136 if not opts.get('close_branch'):
1137 1137 for r in parents:
1138 1138 if r.extra().get('close') and r.branch() == branch:
1139 1139 ui.status(_('reopening closed branch head %d\n') % r)
1140 1140
1141 1141 if ui.debugflag:
1142 1142 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx.hex()))
1143 1143 elif ui.verbose:
1144 1144 ui.write(_('committed changeset %d:%s\n') % (int(ctx), ctx))
1145 1145
1146 1146 @command('copy|cp',
1147 1147 [('A', 'after', None, _('record a copy that has already occurred')),
1148 1148 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1149 1149 ] + walkopts + dryrunopts,
1150 1150 _('[OPTION]... [SOURCE]... DEST'))
1151 1151 def copy(ui, repo, *pats, **opts):
1152 1152 """mark files as copied for the next commit
1153 1153
1154 1154 Mark dest as having copies of source files. If dest is a
1155 1155 directory, copies are put in that directory. If dest is a file,
1156 1156 the source must be a single file.
1157 1157
1158 1158 By default, this command copies the contents of files as they
1159 1159 exist in the working directory. If invoked with -A/--after, the
1160 1160 operation is recorded, but no copying is performed.
1161 1161
1162 1162 This command takes effect with the next commit. To undo a copy
1163 1163 before that, see :hg:`revert`.
1164 1164
1165 1165 Returns 0 on success, 1 if errors are encountered.
1166 1166 """
1167 1167 wlock = repo.wlock(False)
1168 1168 try:
1169 1169 return cmdutil.copy(ui, repo, pats, opts)
1170 1170 finally:
1171 1171 wlock.release()
1172 1172
1173 1173 @command('debugancestor', [], _('[INDEX] REV1 REV2'))
1174 1174 def debugancestor(ui, repo, *args):
1175 1175 """find the ancestor revision of two revisions in a given index"""
1176 1176 if len(args) == 3:
1177 1177 index, rev1, rev2 = args
1178 1178 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), index)
1179 1179 lookup = r.lookup
1180 1180 elif len(args) == 2:
1181 1181 if not repo:
1182 1182 raise util.Abort(_("there is no Mercurial repository here "
1183 1183 "(.hg not found)"))
1184 1184 rev1, rev2 = args
1185 1185 r = repo.changelog
1186 1186 lookup = repo.lookup
1187 1187 else:
1188 1188 raise util.Abort(_('either two or three arguments required'))
1189 1189 a = r.ancestor(lookup(rev1), lookup(rev2))
1190 1190 ui.write("%d:%s\n" % (r.rev(a), hex(a)))
1191 1191
1192 1192 @command('debugbuilddag',
1193 1193 [('m', 'mergeable-file', None, _('add single file mergeable changes')),
1194 1194 ('o', 'overwritten-file', None, _('add single file all revs overwrite')),
1195 1195 ('n', 'new-file', None, _('add new file at each rev'))],
1196 1196 _('[OPTION]... [TEXT]'))
1197 1197 def debugbuilddag(ui, repo, text=None,
1198 1198 mergeable_file=False,
1199 1199 overwritten_file=False,
1200 1200 new_file=False):
1201 1201 """builds a repo with a given DAG from scratch in the current empty repo
1202 1202
1203 1203 The description of the DAG is read from stdin if not given on the
1204 1204 command line.
1205 1205
1206 1206 Elements:
1207 1207
1208 1208 - "+n" is a linear run of n nodes based on the current default parent
1209 1209 - "." is a single node based on the current default parent
1210 1210 - "$" resets the default parent to null (implied at the start);
1211 1211 otherwise the default parent is always the last node created
1212 1212 - "<p" sets the default parent to the backref p
1213 1213 - "*p" is a fork at parent p, which is a backref
1214 1214 - "*p1/p2" is a merge of parents p1 and p2, which are backrefs
1215 1215 - "/p2" is a merge of the preceding node and p2
1216 1216 - ":tag" defines a local tag for the preceding node
1217 1217 - "@branch" sets the named branch for subsequent nodes
1218 1218 - "#...\\n" is a comment up to the end of the line
1219 1219
1220 1220 Whitespace between the above elements is ignored.
1221 1221
1222 1222 A backref is either
1223 1223
1224 1224 - a number n, which references the node curr-n, where curr is the current
1225 1225 node, or
1226 1226 - the name of a local tag you placed earlier using ":tag", or
1227 1227 - empty to denote the default parent.
1228 1228
1229 1229 All string valued-elements are either strictly alphanumeric, or must
1230 1230 be enclosed in double quotes ("..."), with "\\" as escape character.
1231 1231 """
1232 1232
1233 1233 if text is None:
1234 1234 ui.status(_("reading DAG from stdin\n"))
1235 1235 text = sys.stdin.read()
1236 1236
1237 1237 cl = repo.changelog
1238 1238 if len(cl) > 0:
1239 1239 raise util.Abort(_('repository is not empty'))
1240 1240
1241 1241 # determine number of revs in DAG
1242 1242 total = 0
1243 1243 for type, data in dagparser.parsedag(text):
1244 1244 if type == 'n':
1245 1245 total += 1
1246 1246
1247 1247 if mergeable_file:
1248 1248 linesperrev = 2
1249 1249 # make a file with k lines per rev
1250 1250 initialmergedlines = [str(i) for i in xrange(0, total * linesperrev)]
1251 1251 initialmergedlines.append("")
1252 1252
1253 1253 tags = []
1254 1254
1255 1255 tr = repo.transaction("builddag")
1256 1256 try:
1257 1257
1258 1258 at = -1
1259 1259 atbranch = 'default'
1260 1260 nodeids = []
1261 1261 ui.progress(_('building'), 0, unit=_('revisions'), total=total)
1262 1262 for type, data in dagparser.parsedag(text):
1263 1263 if type == 'n':
1264 1264 ui.note('node %s\n' % str(data))
1265 1265 id, ps = data
1266 1266
1267 1267 files = []
1268 1268 fctxs = {}
1269 1269
1270 1270 p2 = None
1271 1271 if mergeable_file:
1272 1272 fn = "mf"
1273 1273 p1 = repo[ps[0]]
1274 1274 if len(ps) > 1:
1275 1275 p2 = repo[ps[1]]
1276 1276 pa = p1.ancestor(p2)
1277 1277 base, local, other = [x[fn].data() for x in pa, p1, p2]
1278 1278 m3 = simplemerge.Merge3Text(base, local, other)
1279 1279 ml = [l.strip() for l in m3.merge_lines()]
1280 1280 ml.append("")
1281 1281 elif at > 0:
1282 1282 ml = p1[fn].data().split("\n")
1283 1283 else:
1284 1284 ml = initialmergedlines
1285 1285 ml[id * linesperrev] += " r%i" % id
1286 1286 mergedtext = "\n".join(ml)
1287 1287 files.append(fn)
1288 1288 fctxs[fn] = context.memfilectx(fn, mergedtext)
1289 1289
1290 1290 if overwritten_file:
1291 1291 fn = "of"
1292 1292 files.append(fn)
1293 1293 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1294 1294
1295 1295 if new_file:
1296 1296 fn = "nf%i" % id
1297 1297 files.append(fn)
1298 1298 fctxs[fn] = context.memfilectx(fn, "r%i\n" % id)
1299 1299 if len(ps) > 1:
1300 1300 if not p2:
1301 1301 p2 = repo[ps[1]]
1302 1302 for fn in p2:
1303 1303 if fn.startswith("nf"):
1304 1304 files.append(fn)
1305 1305 fctxs[fn] = p2[fn]
1306 1306
1307 1307 def fctxfn(repo, cx, path):
1308 1308 return fctxs.get(path)
1309 1309
1310 1310 if len(ps) == 0 or ps[0] < 0:
1311 1311 pars = [None, None]
1312 1312 elif len(ps) == 1:
1313 1313 pars = [nodeids[ps[0]], None]
1314 1314 else:
1315 1315 pars = [nodeids[p] for p in ps]
1316 1316 cx = context.memctx(repo, pars, "r%i" % id, files, fctxfn,
1317 1317 date=(id, 0),
1318 1318 user="debugbuilddag",
1319 1319 extra={'branch': atbranch})
1320 1320 nodeid = repo.commitctx(cx)
1321 1321 nodeids.append(nodeid)
1322 1322 at = id
1323 1323 elif type == 'l':
1324 1324 id, name = data
1325 1325 ui.note('tag %s\n' % name)
1326 1326 tags.append("%s %s\n" % (hex(repo.changelog.node(id)), name))
1327 1327 elif type == 'a':
1328 1328 ui.note('branch %s\n' % data)
1329 1329 atbranch = data
1330 1330 ui.progress(_('building'), id, unit=_('revisions'), total=total)
1331 1331 tr.close()
1332 1332 finally:
1333 1333 ui.progress(_('building'), None)
1334 1334 tr.release()
1335 1335
1336 1336 if tags:
1337 1337 repo.opener.write("localtags", "".join(tags))
1338 1338
1339 1339 @command('debugbundle', [('a', 'all', None, _('show all details'))], _('FILE'))
1340 1340 def debugbundle(ui, bundlepath, all=None, **opts):
1341 1341 """lists the contents of a bundle"""
1342 1342 f = url.open(ui, bundlepath)
1343 1343 try:
1344 1344 gen = changegroup.readbundle(f, bundlepath)
1345 1345 if all:
1346 1346 ui.write("format: id, p1, p2, cset, delta base, len(delta)\n")
1347 1347
1348 1348 def showchunks(named):
1349 1349 ui.write("\n%s\n" % named)
1350 1350 chain = None
1351 1351 while True:
1352 1352 chunkdata = gen.deltachunk(chain)
1353 1353 if not chunkdata:
1354 1354 break
1355 1355 node = chunkdata['node']
1356 1356 p1 = chunkdata['p1']
1357 1357 p2 = chunkdata['p2']
1358 1358 cs = chunkdata['cs']
1359 1359 deltabase = chunkdata['deltabase']
1360 1360 delta = chunkdata['delta']
1361 1361 ui.write("%s %s %s %s %s %s\n" %
1362 1362 (hex(node), hex(p1), hex(p2),
1363 1363 hex(cs), hex(deltabase), len(delta)))
1364 1364 chain = node
1365 1365
1366 1366 chunkdata = gen.changelogheader()
1367 1367 showchunks("changelog")
1368 1368 chunkdata = gen.manifestheader()
1369 1369 showchunks("manifest")
1370 1370 while True:
1371 1371 chunkdata = gen.filelogheader()
1372 1372 if not chunkdata:
1373 1373 break
1374 1374 fname = chunkdata['filename']
1375 1375 showchunks(fname)
1376 1376 else:
1377 1377 chunkdata = gen.changelogheader()
1378 1378 chain = None
1379 1379 while True:
1380 1380 chunkdata = gen.deltachunk(chain)
1381 1381 if not chunkdata:
1382 1382 break
1383 1383 node = chunkdata['node']
1384 1384 ui.write("%s\n" % hex(node))
1385 1385 chain = node
1386 1386 finally:
1387 1387 f.close()
1388 1388
1389 1389 @command('debugcheckstate', [], '')
1390 1390 def debugcheckstate(ui, repo):
1391 1391 """validate the correctness of the current dirstate"""
1392 1392 parent1, parent2 = repo.dirstate.parents()
1393 1393 m1 = repo[parent1].manifest()
1394 1394 m2 = repo[parent2].manifest()
1395 1395 errors = 0
1396 1396 for f in repo.dirstate:
1397 1397 state = repo.dirstate[f]
1398 1398 if state in "nr" and f not in m1:
1399 1399 ui.warn(_("%s in state %s, but not in manifest1\n") % (f, state))
1400 1400 errors += 1
1401 1401 if state in "a" and f in m1:
1402 1402 ui.warn(_("%s in state %s, but also in manifest1\n") % (f, state))
1403 1403 errors += 1
1404 1404 if state in "m" and f not in m1 and f not in m2:
1405 1405 ui.warn(_("%s in state %s, but not in either manifest\n") %
1406 1406 (f, state))
1407 1407 errors += 1
1408 1408 for f in m1:
1409 1409 state = repo.dirstate[f]
1410 1410 if state not in "nrm":
1411 1411 ui.warn(_("%s in manifest1, but listed as state %s") % (f, state))
1412 1412 errors += 1
1413 1413 if errors:
1414 1414 error = _(".hg/dirstate inconsistent with current parent's manifest")
1415 1415 raise util.Abort(error)
1416 1416
1417 1417 @command('debugcommands', [], _('[COMMAND]'))
1418 1418 def debugcommands(ui, cmd='', *args):
1419 1419 """list all available commands and options"""
1420 1420 for cmd, vals in sorted(table.iteritems()):
1421 1421 cmd = cmd.split('|')[0].strip('^')
1422 1422 opts = ', '.join([i[1] for i in vals[1]])
1423 1423 ui.write('%s: %s\n' % (cmd, opts))
1424 1424
1425 1425 @command('debugcomplete',
1426 1426 [('o', 'options', None, _('show the command options'))],
1427 1427 _('[-o] CMD'))
1428 1428 def debugcomplete(ui, cmd='', **opts):
1429 1429 """returns the completion list associated with the given command"""
1430 1430
1431 1431 if opts.get('options'):
1432 1432 options = []
1433 1433 otables = [globalopts]
1434 1434 if cmd:
1435 1435 aliases, entry = cmdutil.findcmd(cmd, table, False)
1436 1436 otables.append(entry[1])
1437 1437 for t in otables:
1438 1438 for o in t:
1439 1439 if "(DEPRECATED)" in o[3]:
1440 1440 continue
1441 1441 if o[0]:
1442 1442 options.append('-%s' % o[0])
1443 1443 options.append('--%s' % o[1])
1444 1444 ui.write("%s\n" % "\n".join(options))
1445 1445 return
1446 1446
1447 1447 cmdlist = cmdutil.findpossible(cmd, table)
1448 1448 if ui.verbose:
1449 1449 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1450 1450 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1451 1451
1452 1452 @command('debugdag',
1453 1453 [('t', 'tags', None, _('use tags as labels')),
1454 1454 ('b', 'branches', None, _('annotate with branch names')),
1455 1455 ('', 'dots', None, _('use dots for runs')),
1456 1456 ('s', 'spaces', None, _('separate elements by spaces'))],
1457 1457 _('[OPTION]... [FILE [REV]...]'))
1458 1458 def debugdag(ui, repo, file_=None, *revs, **opts):
1459 1459 """format the changelog or an index DAG as a concise textual description
1460 1460
1461 1461 If you pass a revlog index, the revlog's DAG is emitted. If you list
1462 1462 revision numbers, they get labelled in the output as rN.
1463 1463
1464 1464 Otherwise, the changelog DAG of the current repo is emitted.
1465 1465 """
1466 1466 spaces = opts.get('spaces')
1467 1467 dots = opts.get('dots')
1468 1468 if file_:
1469 1469 rlog = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1470 1470 revs = set((int(r) for r in revs))
1471 1471 def events():
1472 1472 for r in rlog:
1473 1473 yield 'n', (r, list(set(p for p in rlog.parentrevs(r) if p != -1)))
1474 1474 if r in revs:
1475 1475 yield 'l', (r, "r%i" % r)
1476 1476 elif repo:
1477 1477 cl = repo.changelog
1478 1478 tags = opts.get('tags')
1479 1479 branches = opts.get('branches')
1480 1480 if tags:
1481 1481 labels = {}
1482 1482 for l, n in repo.tags().items():
1483 1483 labels.setdefault(cl.rev(n), []).append(l)
1484 1484 def events():
1485 1485 b = "default"
1486 1486 for r in cl:
1487 1487 if branches:
1488 1488 newb = cl.read(cl.node(r))[5]['branch']
1489 1489 if newb != b:
1490 1490 yield 'a', newb
1491 1491 b = newb
1492 1492 yield 'n', (r, list(set(p for p in cl.parentrevs(r) if p != -1)))
1493 1493 if tags:
1494 1494 ls = labels.get(r)
1495 1495 if ls:
1496 1496 for l in ls:
1497 1497 yield 'l', (r, l)
1498 1498 else:
1499 1499 raise util.Abort(_('need repo for changelog dag'))
1500 1500
1501 1501 for line in dagparser.dagtextlines(events(),
1502 1502 addspaces=spaces,
1503 1503 wraplabels=True,
1504 1504 wrapannotations=True,
1505 1505 wrapnonlinear=dots,
1506 1506 usedots=dots,
1507 1507 maxlinewidth=70):
1508 1508 ui.write(line)
1509 1509 ui.write("\n")
1510 1510
1511 1511 @command('debugdata',
1512 1512 [('c', 'changelog', False, _('open changelog')),
1513 1513 ('m', 'manifest', False, _('open manifest'))],
1514 1514 _('-c|-m|FILE REV'))
1515 1515 def debugdata(ui, repo, file_, rev = None, **opts):
1516 1516 """dump the contents of a data file revision"""
1517 1517 if opts.get('changelog') or opts.get('manifest'):
1518 1518 file_, rev = None, file_
1519 1519 elif rev is None:
1520 1520 raise error.CommandError('debugdata', _('invalid arguments'))
1521 1521 r = cmdutil.openrevlog(repo, 'debugdata', file_, opts)
1522 1522 try:
1523 1523 ui.write(r.revision(r.lookup(rev)))
1524 1524 except KeyError:
1525 1525 raise util.Abort(_('invalid revision identifier %s') % rev)
1526 1526
1527 1527 @command('debugdate',
1528 1528 [('e', 'extended', None, _('try extended date formats'))],
1529 1529 _('[-e] DATE [RANGE]'))
1530 1530 def debugdate(ui, date, range=None, **opts):
1531 1531 """parse and display a date"""
1532 1532 if opts["extended"]:
1533 1533 d = util.parsedate(date, util.extendeddateformats)
1534 1534 else:
1535 1535 d = util.parsedate(date)
1536 1536 ui.write("internal: %s %s\n" % d)
1537 1537 ui.write("standard: %s\n" % util.datestr(d))
1538 1538 if range:
1539 1539 m = util.matchdate(range)
1540 1540 ui.write("match: %s\n" % m(d[0]))
1541 1541
1542 1542 @command('debugdiscovery',
1543 1543 [('', 'old', None, _('use old-style discovery')),
1544 1544 ('', 'nonheads', None,
1545 1545 _('use old-style discovery with non-heads included')),
1546 1546 ] + remoteopts,
1547 1547 _('[-l REV] [-r REV] [-b BRANCH]... [OTHER]'))
1548 1548 def debugdiscovery(ui, repo, remoteurl="default", **opts):
1549 1549 """runs the changeset discovery protocol in isolation"""
1550 1550 remoteurl, branches = hg.parseurl(ui.expandpath(remoteurl), opts.get('branch'))
1551 1551 remote = hg.peer(repo, opts, remoteurl)
1552 1552 ui.status(_('comparing with %s\n') % util.hidepassword(remoteurl))
1553 1553
1554 1554 # make sure tests are repeatable
1555 1555 random.seed(12323)
1556 1556
1557 1557 def doit(localheads, remoteheads):
1558 1558 if opts.get('old'):
1559 1559 if localheads:
1560 1560 raise util.Abort('cannot use localheads with old style discovery')
1561 1561 common, _in, hds = treediscovery.findcommonincoming(repo, remote,
1562 1562 force=True)
1563 1563 common = set(common)
1564 1564 if not opts.get('nonheads'):
1565 1565 ui.write("unpruned common: %s\n" % " ".join([short(n)
1566 1566 for n in common]))
1567 1567 dag = dagutil.revlogdag(repo.changelog)
1568 1568 all = dag.ancestorset(dag.internalizeall(common))
1569 1569 common = dag.externalizeall(dag.headsetofconnecteds(all))
1570 1570 else:
1571 1571 common, any, hds = setdiscovery.findcommonheads(ui, repo, remote)
1572 1572 common = set(common)
1573 1573 rheads = set(hds)
1574 1574 lheads = set(repo.heads())
1575 1575 ui.write("common heads: %s\n" % " ".join([short(n) for n in common]))
1576 1576 if lheads <= common:
1577 1577 ui.write("local is subset\n")
1578 1578 elif rheads <= common:
1579 1579 ui.write("remote is subset\n")
1580 1580
1581 1581 serverlogs = opts.get('serverlog')
1582 1582 if serverlogs:
1583 1583 for filename in serverlogs:
1584 1584 logfile = open(filename, 'r')
1585 1585 try:
1586 1586 line = logfile.readline()
1587 1587 while line:
1588 1588 parts = line.strip().split(';')
1589 1589 op = parts[1]
1590 1590 if op == 'cg':
1591 1591 pass
1592 1592 elif op == 'cgss':
1593 1593 doit(parts[2].split(' '), parts[3].split(' '))
1594 1594 elif op == 'unb':
1595 1595 doit(parts[3].split(' '), parts[2].split(' '))
1596 1596 line = logfile.readline()
1597 1597 finally:
1598 1598 logfile.close()
1599 1599
1600 1600 else:
1601 1601 remoterevs, _checkout = hg.addbranchrevs(repo, remote, branches,
1602 1602 opts.get('remote_head'))
1603 1603 localrevs = opts.get('local_head')
1604 1604 doit(localrevs, remoterevs)
1605 1605
1606 1606 @command('debugfileset', [], ('REVSPEC'))
1607 1607 def debugfileset(ui, repo, expr):
1608 1608 '''parse and apply a fileset specification'''
1609 1609 if ui.verbose:
1610 1610 tree = fileset.parse(expr)[0]
1611 1611 ui.note(tree, "\n")
1612 1612 matcher = lambda x: scmutil.match(repo, x, default='glob')
1613 1613
1614 1614 for f in fileset.getfileset(repo[None], matcher, expr):
1615 1615 ui.write("%s\n" % f)
1616 1616
1617 1617 @command('debugfsinfo', [], _('[PATH]'))
1618 1618 def debugfsinfo(ui, path = "."):
1619 1619 """show information detected about current filesystem"""
1620 1620 util.writefile('.debugfsinfo', '')
1621 1621 ui.write('exec: %s\n' % (util.checkexec(path) and 'yes' or 'no'))
1622 1622 ui.write('symlink: %s\n' % (util.checklink(path) and 'yes' or 'no'))
1623 1623 ui.write('case-sensitive: %s\n' % (util.checkcase('.debugfsinfo')
1624 1624 and 'yes' or 'no'))
1625 1625 os.unlink('.debugfsinfo')
1626 1626
1627 1627 @command('debuggetbundle',
1628 1628 [('H', 'head', [], _('id of head node'), _('ID')),
1629 1629 ('C', 'common', [], _('id of common node'), _('ID')),
1630 1630 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE'))],
1631 1631 _('REPO FILE [-H|-C ID]...'))
1632 1632 def debuggetbundle(ui, repopath, bundlepath, head=None, common=None, **opts):
1633 1633 """retrieves a bundle from a repo
1634 1634
1635 1635 Every ID must be a full-length hex node id string. Saves the bundle to the
1636 1636 given file.
1637 1637 """
1638 1638 repo = hg.peer(ui, opts, repopath)
1639 1639 if not repo.capable('getbundle'):
1640 1640 raise util.Abort("getbundle() not supported by target repository")
1641 1641 args = {}
1642 1642 if common:
1643 1643 args['common'] = [bin(s) for s in common]
1644 1644 if head:
1645 1645 args['heads'] = [bin(s) for s in head]
1646 1646 bundle = repo.getbundle('debug', **args)
1647 1647
1648 1648 bundletype = opts.get('type', 'bzip2').lower()
1649 1649 btypes = {'none': 'HG10UN', 'bzip2': 'HG10BZ', 'gzip': 'HG10GZ'}
1650 1650 bundletype = btypes.get(bundletype)
1651 1651 if bundletype not in changegroup.bundletypes:
1652 1652 raise util.Abort(_('unknown bundle type specified with --type'))
1653 1653 changegroup.writebundle(bundle, bundlepath, bundletype)
1654 1654
1655 1655 @command('debugignore', [], '')
1656 1656 def debugignore(ui, repo, *values, **opts):
1657 1657 """display the combined ignore pattern"""
1658 1658 ignore = repo.dirstate._ignore
1659 1659 if hasattr(ignore, 'includepat'):
1660 1660 ui.write("%s\n" % ignore.includepat)
1661 1661 else:
1662 1662 raise util.Abort(_("no ignore patterns found"))
1663 1663
1664 1664 @command('debugindex',
1665 1665 [('c', 'changelog', False, _('open changelog')),
1666 1666 ('m', 'manifest', False, _('open manifest')),
1667 1667 ('f', 'format', 0, _('revlog format'), _('FORMAT'))],
1668 1668 _('[-f FORMAT] -c|-m|FILE'))
1669 1669 def debugindex(ui, repo, file_ = None, **opts):
1670 1670 """dump the contents of an index file"""
1671 1671 r = cmdutil.openrevlog(repo, 'debugindex', file_, opts)
1672 1672 format = opts.get('format', 0)
1673 1673 if format not in (0, 1):
1674 1674 raise util.Abort(_("unknown format %d") % format)
1675 1675
1676 1676 generaldelta = r.version & revlog.REVLOGGENERALDELTA
1677 1677 if generaldelta:
1678 1678 basehdr = ' delta'
1679 1679 else:
1680 1680 basehdr = ' base'
1681 1681
1682 1682 if format == 0:
1683 1683 ui.write(" rev offset length " + basehdr + " linkrev"
1684 1684 " nodeid p1 p2\n")
1685 1685 elif format == 1:
1686 1686 ui.write(" rev flag offset length"
1687 1687 " size " + basehdr + " link p1 p2 nodeid\n")
1688 1688
1689 1689 for i in r:
1690 1690 node = r.node(i)
1691 1691 if generaldelta:
1692 1692 base = r.deltaparent(i)
1693 1693 else:
1694 1694 base = r.chainbase(i)
1695 1695 if format == 0:
1696 1696 try:
1697 1697 pp = r.parents(node)
1698 1698 except:
1699 1699 pp = [nullid, nullid]
1700 1700 ui.write("% 6d % 9d % 7d % 6d % 7d %s %s %s\n" % (
1701 1701 i, r.start(i), r.length(i), base, r.linkrev(i),
1702 1702 short(node), short(pp[0]), short(pp[1])))
1703 1703 elif format == 1:
1704 1704 pr = r.parentrevs(i)
1705 1705 ui.write("% 6d %04x % 8d % 8d % 8d % 6d % 6d % 6d % 6d %s\n" % (
1706 1706 i, r.flags(i), r.start(i), r.length(i), r.rawsize(i),
1707 1707 base, r.linkrev(i), pr[0], pr[1], short(node)))
1708 1708
1709 1709 @command('debugindexdot', [], _('FILE'))
1710 1710 def debugindexdot(ui, repo, file_):
1711 1711 """dump an index DAG as a graphviz dot file"""
1712 1712 r = None
1713 1713 if repo:
1714 1714 filelog = repo.file(file_)
1715 1715 if len(filelog):
1716 1716 r = filelog
1717 1717 if not r:
1718 1718 r = revlog.revlog(scmutil.opener(os.getcwd(), audit=False), file_)
1719 1719 ui.write("digraph G {\n")
1720 1720 for i in r:
1721 1721 node = r.node(i)
1722 1722 pp = r.parents(node)
1723 1723 ui.write("\t%d -> %d\n" % (r.rev(pp[0]), i))
1724 1724 if pp[1] != nullid:
1725 1725 ui.write("\t%d -> %d\n" % (r.rev(pp[1]), i))
1726 1726 ui.write("}\n")
1727 1727
1728 1728 @command('debuginstall', [], '')
1729 1729 def debuginstall(ui):
1730 1730 '''test Mercurial installation
1731 1731
1732 1732 Returns 0 on success.
1733 1733 '''
1734 1734
1735 1735 def writetemp(contents):
1736 1736 (fd, name) = tempfile.mkstemp(prefix="hg-debuginstall-")
1737 1737 f = os.fdopen(fd, "wb")
1738 1738 f.write(contents)
1739 1739 f.close()
1740 1740 return name
1741 1741
1742 1742 problems = 0
1743 1743
1744 1744 # encoding
1745 1745 ui.status(_("Checking encoding (%s)...\n") % encoding.encoding)
1746 1746 try:
1747 1747 encoding.fromlocal("test")
1748 1748 except util.Abort, inst:
1749 1749 ui.write(" %s\n" % inst)
1750 1750 ui.write(_(" (check that your locale is properly set)\n"))
1751 1751 problems += 1
1752 1752
1753 1753 # compiled modules
1754 1754 ui.status(_("Checking installed modules (%s)...\n")
1755 1755 % os.path.dirname(__file__))
1756 1756 try:
1757 1757 import bdiff, mpatch, base85, osutil
1758 1758 except Exception, inst:
1759 1759 ui.write(" %s\n" % inst)
1760 1760 ui.write(_(" One or more extensions could not be found"))
1761 1761 ui.write(_(" (check that you compiled the extensions)\n"))
1762 1762 problems += 1
1763 1763
1764 1764 # templates
1765 1765 ui.status(_("Checking templates...\n"))
1766 1766 try:
1767 1767 import templater
1768 1768 templater.templater(templater.templatepath("map-cmdline.default"))
1769 1769 except Exception, inst:
1770 1770 ui.write(" %s\n" % inst)
1771 1771 ui.write(_(" (templates seem to have been installed incorrectly)\n"))
1772 1772 problems += 1
1773 1773
1774 1774 # editor
1775 1775 ui.status(_("Checking commit editor...\n"))
1776 1776 editor = ui.geteditor()
1777 1777 cmdpath = util.findexe(editor) or util.findexe(editor.split()[0])
1778 1778 if not cmdpath:
1779 1779 if editor == 'vi':
1780 1780 ui.write(_(" No commit editor set and can't find vi in PATH\n"))
1781 1781 ui.write(_(" (specify a commit editor in your configuration"
1782 1782 " file)\n"))
1783 1783 else:
1784 1784 ui.write(_(" Can't find editor '%s' in PATH\n") % editor)
1785 1785 ui.write(_(" (specify a commit editor in your configuration"
1786 1786 " file)\n"))
1787 1787 problems += 1
1788 1788
1789 1789 # check username
1790 1790 ui.status(_("Checking username...\n"))
1791 1791 try:
1792 1792 ui.username()
1793 1793 except util.Abort, e:
1794 1794 ui.write(" %s\n" % e)
1795 1795 ui.write(_(" (specify a username in your configuration file)\n"))
1796 1796 problems += 1
1797 1797
1798 1798 if not problems:
1799 1799 ui.status(_("No problems detected\n"))
1800 1800 else:
1801 1801 ui.write(_("%s problems detected,"
1802 1802 " please check your install!\n") % problems)
1803 1803
1804 1804 return problems
1805 1805
1806 1806 @command('debugknown', [], _('REPO ID...'))
1807 1807 def debugknown(ui, repopath, *ids, **opts):
1808 1808 """test whether node ids are known to a repo
1809 1809
1810 1810 Every ID must be a full-length hex node id string. Returns a list of 0s and 1s
1811 1811 indicating unknown/known.
1812 1812 """
1813 1813 repo = hg.peer(ui, opts, repopath)
1814 1814 if not repo.capable('known'):
1815 1815 raise util.Abort("known() not supported by target repository")
1816 1816 flags = repo.known([bin(s) for s in ids])
1817 1817 ui.write("%s\n" % ("".join([f and "1" or "0" for f in flags])))
1818 1818
1819 1819 @command('debugpushkey', [], _('REPO NAMESPACE [KEY OLD NEW]'))
1820 1820 def debugpushkey(ui, repopath, namespace, *keyinfo, **opts):
1821 1821 '''access the pushkey key/value protocol
1822 1822
1823 1823 With two args, list the keys in the given namespace.
1824 1824
1825 1825 With five args, set a key to new if it currently is set to old.
1826 1826 Reports success or failure.
1827 1827 '''
1828 1828
1829 1829 target = hg.peer(ui, {}, repopath)
1830 1830 if keyinfo:
1831 1831 key, old, new = keyinfo
1832 1832 r = target.pushkey(namespace, key, old, new)
1833 1833 ui.status(str(r) + '\n')
1834 1834 return not r
1835 1835 else:
1836 1836 for k, v in target.listkeys(namespace).iteritems():
1837 1837 ui.write("%s\t%s\n" % (k.encode('string-escape'),
1838 1838 v.encode('string-escape')))
1839 1839
1840 1840 @command('debugrebuildstate',
1841 1841 [('r', 'rev', '', _('revision to rebuild to'), _('REV'))],
1842 1842 _('[-r REV] [REV]'))
1843 1843 def debugrebuildstate(ui, repo, rev="tip"):
1844 1844 """rebuild the dirstate as it would look like for the given revision"""
1845 1845 ctx = scmutil.revsingle(repo, rev)
1846 1846 wlock = repo.wlock()
1847 1847 try:
1848 1848 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
1849 1849 finally:
1850 1850 wlock.release()
1851 1851
1852 1852 @command('debugrename',
1853 1853 [('r', 'rev', '', _('revision to debug'), _('REV'))],
1854 1854 _('[-r REV] FILE'))
1855 1855 def debugrename(ui, repo, file1, *pats, **opts):
1856 1856 """dump rename information"""
1857 1857
1858 1858 ctx = scmutil.revsingle(repo, opts.get('rev'))
1859 1859 m = scmutil.match(repo, (file1,) + pats, opts)
1860 1860 for abs in ctx.walk(m):
1861 1861 fctx = ctx[abs]
1862 1862 o = fctx.filelog().renamed(fctx.filenode())
1863 1863 rel = m.rel(abs)
1864 1864 if o:
1865 1865 ui.write(_("%s renamed from %s:%s\n") % (rel, o[0], hex(o[1])))
1866 1866 else:
1867 1867 ui.write(_("%s not renamed\n") % rel)
1868 1868
1869 1869 @command('debugrevlog',
1870 1870 [('c', 'changelog', False, _('open changelog')),
1871 1871 ('m', 'manifest', False, _('open manifest')),
1872 1872 ('d', 'dump', False, _('dump index data'))],
1873 1873 _('-c|-m|FILE'))
1874 1874 def debugrevlog(ui, repo, file_ = None, **opts):
1875 1875 """show data and statistics about a revlog"""
1876 1876 r = cmdutil.openrevlog(repo, 'debugrevlog', file_, opts)
1877 1877
1878 1878 if opts.get("dump"):
1879 1879 numrevs = len(r)
1880 1880 ui.write("# rev p1rev p2rev start end deltastart base p1 p2"
1881 1881 " rawsize totalsize compression heads\n")
1882 1882 ts = 0
1883 1883 heads = set()
1884 1884 for rev in xrange(numrevs):
1885 1885 dbase = r.deltaparent(rev)
1886 1886 if dbase == -1:
1887 1887 dbase = rev
1888 1888 cbase = r.chainbase(rev)
1889 1889 p1, p2 = r.parentrevs(rev)
1890 1890 rs = r.rawsize(rev)
1891 1891 ts = ts + rs
1892 1892 heads -= set(r.parentrevs(rev))
1893 1893 heads.add(rev)
1894 1894 ui.write("%d %d %d %d %d %d %d %d %d %d %d %d %d\n" %
1895 1895 (rev, p1, p2, r.start(rev), r.end(rev),
1896 1896 r.start(dbase), r.start(cbase),
1897 1897 r.start(p1), r.start(p2),
1898 1898 rs, ts, ts / r.end(rev), len(heads)))
1899 1899 return 0
1900 1900
1901 1901 v = r.version
1902 1902 format = v & 0xFFFF
1903 1903 flags = []
1904 1904 gdelta = False
1905 1905 if v & revlog.REVLOGNGINLINEDATA:
1906 1906 flags.append('inline')
1907 1907 if v & revlog.REVLOGGENERALDELTA:
1908 1908 gdelta = True
1909 1909 flags.append('generaldelta')
1910 1910 if not flags:
1911 1911 flags = ['(none)']
1912 1912
1913 1913 nummerges = 0
1914 1914 numfull = 0
1915 1915 numprev = 0
1916 1916 nump1 = 0
1917 1917 nump2 = 0
1918 1918 numother = 0
1919 1919 nump1prev = 0
1920 1920 nump2prev = 0
1921 1921 chainlengths = []
1922 1922
1923 1923 datasize = [None, 0, 0L]
1924 1924 fullsize = [None, 0, 0L]
1925 1925 deltasize = [None, 0, 0L]
1926 1926
1927 1927 def addsize(size, l):
1928 1928 if l[0] is None or size < l[0]:
1929 1929 l[0] = size
1930 1930 if size > l[1]:
1931 1931 l[1] = size
1932 1932 l[2] += size
1933 1933
1934 1934 numrevs = len(r)
1935 1935 for rev in xrange(numrevs):
1936 1936 p1, p2 = r.parentrevs(rev)
1937 1937 delta = r.deltaparent(rev)
1938 1938 if format > 0:
1939 1939 addsize(r.rawsize(rev), datasize)
1940 1940 if p2 != nullrev:
1941 1941 nummerges += 1
1942 1942 size = r.length(rev)
1943 1943 if delta == nullrev:
1944 1944 chainlengths.append(0)
1945 1945 numfull += 1
1946 1946 addsize(size, fullsize)
1947 1947 else:
1948 1948 chainlengths.append(chainlengths[delta] + 1)
1949 1949 addsize(size, deltasize)
1950 1950 if delta == rev - 1:
1951 1951 numprev += 1
1952 1952 if delta == p1:
1953 1953 nump1prev += 1
1954 1954 elif delta == p2:
1955 1955 nump2prev += 1
1956 1956 elif delta == p1:
1957 1957 nump1 += 1
1958 1958 elif delta == p2:
1959 1959 nump2 += 1
1960 1960 elif delta != nullrev:
1961 1961 numother += 1
1962 1962
1963 1963 numdeltas = numrevs - numfull
1964 1964 numoprev = numprev - nump1prev - nump2prev
1965 1965 totalrawsize = datasize[2]
1966 1966 datasize[2] /= numrevs
1967 1967 fulltotal = fullsize[2]
1968 1968 fullsize[2] /= numfull
1969 1969 deltatotal = deltasize[2]
1970 1970 deltasize[2] /= numrevs - numfull
1971 1971 totalsize = fulltotal + deltatotal
1972 1972 avgchainlen = sum(chainlengths) / numrevs
1973 1973 compratio = totalrawsize / totalsize
1974 1974
1975 1975 basedfmtstr = '%%%dd\n'
1976 1976 basepcfmtstr = '%%%dd %s(%%5.2f%%%%)\n'
1977 1977
1978 1978 def dfmtstr(max):
1979 1979 return basedfmtstr % len(str(max))
1980 1980 def pcfmtstr(max, padding=0):
1981 1981 return basepcfmtstr % (len(str(max)), ' ' * padding)
1982 1982
1983 1983 def pcfmt(value, total):
1984 1984 return (value, 100 * float(value) / total)
1985 1985
1986 1986 ui.write('format : %d\n' % format)
1987 1987 ui.write('flags : %s\n' % ', '.join(flags))
1988 1988
1989 1989 ui.write('\n')
1990 1990 fmt = pcfmtstr(totalsize)
1991 1991 fmt2 = dfmtstr(totalsize)
1992 1992 ui.write('revisions : ' + fmt2 % numrevs)
1993 1993 ui.write(' merges : ' + fmt % pcfmt(nummerges, numrevs))
1994 1994 ui.write(' normal : ' + fmt % pcfmt(numrevs - nummerges, numrevs))
1995 1995 ui.write('revisions : ' + fmt2 % numrevs)
1996 1996 ui.write(' full : ' + fmt % pcfmt(numfull, numrevs))
1997 1997 ui.write(' deltas : ' + fmt % pcfmt(numdeltas, numrevs))
1998 1998 ui.write('revision size : ' + fmt2 % totalsize)
1999 1999 ui.write(' full : ' + fmt % pcfmt(fulltotal, totalsize))
2000 2000 ui.write(' deltas : ' + fmt % pcfmt(deltatotal, totalsize))
2001 2001
2002 2002 ui.write('\n')
2003 2003 fmt = dfmtstr(max(avgchainlen, compratio))
2004 2004 ui.write('avg chain length : ' + fmt % avgchainlen)
2005 2005 ui.write('compression ratio : ' + fmt % compratio)
2006 2006
2007 2007 if format > 0:
2008 2008 ui.write('\n')
2009 2009 ui.write('uncompressed data size (min/max/avg) : %d / %d / %d\n'
2010 2010 % tuple(datasize))
2011 2011 ui.write('full revision size (min/max/avg) : %d / %d / %d\n'
2012 2012 % tuple(fullsize))
2013 2013 ui.write('delta size (min/max/avg) : %d / %d / %d\n'
2014 2014 % tuple(deltasize))
2015 2015
2016 2016 if numdeltas > 0:
2017 2017 ui.write('\n')
2018 2018 fmt = pcfmtstr(numdeltas)
2019 2019 fmt2 = pcfmtstr(numdeltas, 4)
2020 2020 ui.write('deltas against prev : ' + fmt % pcfmt(numprev, numdeltas))
2021 2021 if numprev > 0:
2022 2022 ui.write(' where prev = p1 : ' + fmt2 % pcfmt(nump1prev, numprev))
2023 2023 ui.write(' where prev = p2 : ' + fmt2 % pcfmt(nump2prev, numprev))
2024 2024 ui.write(' other : ' + fmt2 % pcfmt(numoprev, numprev))
2025 2025 if gdelta:
2026 2026 ui.write('deltas against p1 : ' + fmt % pcfmt(nump1, numdeltas))
2027 2027 ui.write('deltas against p2 : ' + fmt % pcfmt(nump2, numdeltas))
2028 2028 ui.write('deltas against other : ' + fmt % pcfmt(numother, numdeltas))
2029 2029
2030 2030 @command('debugrevspec', [], ('REVSPEC'))
2031 2031 def debugrevspec(ui, repo, expr):
2032 2032 '''parse and apply a revision specification'''
2033 2033 if ui.verbose:
2034 2034 tree = revset.parse(expr)[0]
2035 2035 ui.note(tree, "\n")
2036 2036 newtree = revset.findaliases(ui, tree)
2037 2037 if newtree != tree:
2038 2038 ui.note(newtree, "\n")
2039 2039 func = revset.match(ui, expr)
2040 2040 for c in func(repo, range(len(repo))):
2041 2041 ui.write("%s\n" % c)
2042 2042
2043 2043 @command('debugsetparents', [], _('REV1 [REV2]'))
2044 2044 def debugsetparents(ui, repo, rev1, rev2=None):
2045 2045 """manually set the parents of the current working directory
2046 2046
2047 2047 This is useful for writing repository conversion tools, but should
2048 2048 be used with care.
2049 2049
2050 2050 Returns 0 on success.
2051 2051 """
2052 2052
2053 2053 r1 = scmutil.revsingle(repo, rev1).node()
2054 2054 r2 = scmutil.revsingle(repo, rev2, 'null').node()
2055 2055
2056 2056 wlock = repo.wlock()
2057 2057 try:
2058 2058 repo.dirstate.setparents(r1, r2)
2059 2059 finally:
2060 2060 wlock.release()
2061 2061
2062 2062 @command('debugstate',
2063 2063 [('', 'nodates', None, _('do not display the saved mtime')),
2064 2064 ('', 'datesort', None, _('sort by saved mtime'))],
2065 2065 _('[OPTION]...'))
2066 2066 def debugstate(ui, repo, nodates=None, datesort=None):
2067 2067 """show the contents of the current dirstate"""
2068 2068 timestr = ""
2069 2069 showdate = not nodates
2070 2070 if datesort:
2071 2071 keyfunc = lambda x: (x[1][3], x[0]) # sort by mtime, then by filename
2072 2072 else:
2073 2073 keyfunc = None # sort by filename
2074 2074 for file_, ent in sorted(repo.dirstate._map.iteritems(), key=keyfunc):
2075 2075 if showdate:
2076 2076 if ent[3] == -1:
2077 2077 # Pad or slice to locale representation
2078 2078 locale_len = len(time.strftime("%Y-%m-%d %H:%M:%S ",
2079 2079 time.localtime(0)))
2080 2080 timestr = 'unset'
2081 2081 timestr = (timestr[:locale_len] +
2082 2082 ' ' * (locale_len - len(timestr)))
2083 2083 else:
2084 2084 timestr = time.strftime("%Y-%m-%d %H:%M:%S ",
2085 2085 time.localtime(ent[3]))
2086 2086 if ent[1] & 020000:
2087 2087 mode = 'lnk'
2088 2088 else:
2089 2089 mode = '%3o' % (ent[1] & 0777)
2090 2090 ui.write("%c %s %10d %s%s\n" % (ent[0], mode, ent[2], timestr, file_))
2091 2091 for f in repo.dirstate.copies():
2092 2092 ui.write(_("copy: %s -> %s\n") % (repo.dirstate.copied(f), f))
2093 2093
2094 2094 @command('debugsub',
2095 2095 [('r', 'rev', '',
2096 2096 _('revision to check'), _('REV'))],
2097 2097 _('[-r REV] [REV]'))
2098 2098 def debugsub(ui, repo, rev=None):
2099 2099 ctx = scmutil.revsingle(repo, rev, None)
2100 2100 for k, v in sorted(ctx.substate.items()):
2101 2101 ui.write('path %s\n' % k)
2102 2102 ui.write(' source %s\n' % v[0])
2103 2103 ui.write(' revision %s\n' % v[1])
2104 2104
2105 2105 @command('debugwalk', walkopts, _('[OPTION]... [FILE]...'))
2106 2106 def debugwalk(ui, repo, *pats, **opts):
2107 2107 """show how files match on given patterns"""
2108 2108 m = scmutil.match(repo, pats, opts)
2109 2109 items = list(repo.walk(m))
2110 2110 if not items:
2111 2111 return
2112 2112 fmt = 'f %%-%ds %%-%ds %%s' % (
2113 2113 max([len(abs) for abs in items]),
2114 2114 max([len(m.rel(abs)) for abs in items]))
2115 2115 for abs in items:
2116 2116 line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
2117 2117 ui.write("%s\n" % line.rstrip())
2118 2118
2119 2119 @command('debugwireargs',
2120 2120 [('', 'three', '', 'three'),
2121 2121 ('', 'four', '', 'four'),
2122 2122 ('', 'five', '', 'five'),
2123 2123 ] + remoteopts,
2124 2124 _('REPO [OPTIONS]... [ONE [TWO]]'))
2125 2125 def debugwireargs(ui, repopath, *vals, **opts):
2126 2126 repo = hg.peer(ui, opts, repopath)
2127 2127 for opt in remoteopts:
2128 2128 del opts[opt[1]]
2129 2129 args = {}
2130 2130 for k, v in opts.iteritems():
2131 2131 if v:
2132 2132 args[k] = v
2133 2133 # run twice to check that we don't mess up the stream for the next command
2134 2134 res1 = repo.debugwireargs(*vals, **args)
2135 2135 res2 = repo.debugwireargs(*vals, **args)
2136 2136 ui.write("%s\n" % res1)
2137 2137 if res1 != res2:
2138 2138 ui.warn("%s\n" % res2)
2139 2139
2140 2140 @command('^diff',
2141 2141 [('r', 'rev', [], _('revision'), _('REV')),
2142 2142 ('c', 'change', '', _('change made by revision'), _('REV'))
2143 2143 ] + diffopts + diffopts2 + walkopts + subrepoopts,
2144 2144 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'))
2145 2145 def diff(ui, repo, *pats, **opts):
2146 2146 """diff repository (or selected files)
2147 2147
2148 2148 Show differences between revisions for the specified files.
2149 2149
2150 2150 Differences between files are shown using the unified diff format.
2151 2151
2152 2152 .. note::
2153 2153 diff may generate unexpected results for merges, as it will
2154 2154 default to comparing against the working directory's first
2155 2155 parent changeset if no revisions are specified.
2156 2156
2157 2157 When two revision arguments are given, then changes are shown
2158 2158 between those revisions. If only one revision is specified then
2159 2159 that revision is compared to the working directory, and, when no
2160 2160 revisions are specified, the working directory files are compared
2161 2161 to its parent.
2162 2162
2163 2163 Alternatively you can specify -c/--change with a revision to see
2164 2164 the changes in that changeset relative to its first parent.
2165 2165
2166 2166 Without the -a/--text option, diff will avoid generating diffs of
2167 2167 files it detects as binary. With -a, diff will generate a diff
2168 2168 anyway, probably with undesirable results.
2169 2169
2170 2170 Use the -g/--git option to generate diffs in the git extended diff
2171 2171 format. For more information, read :hg:`help diffs`.
2172 2172
2173 2173 Returns 0 on success.
2174 2174 """
2175 2175
2176 2176 revs = opts.get('rev')
2177 2177 change = opts.get('change')
2178 2178 stat = opts.get('stat')
2179 2179 reverse = opts.get('reverse')
2180 2180
2181 2181 if revs and change:
2182 2182 msg = _('cannot specify --rev and --change at the same time')
2183 2183 raise util.Abort(msg)
2184 2184 elif change:
2185 2185 node2 = scmutil.revsingle(repo, change, None).node()
2186 2186 node1 = repo[node2].p1().node()
2187 2187 else:
2188 2188 node1, node2 = scmutil.revpair(repo, revs)
2189 2189
2190 2190 if reverse:
2191 2191 node1, node2 = node2, node1
2192 2192
2193 2193 diffopts = patch.diffopts(ui, opts)
2194 2194 m = scmutil.match(repo, pats, opts)
2195 2195 cmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2196 2196 listsubrepos=opts.get('subrepos'))
2197 2197
2198 2198 @command('^export',
2199 2199 [('o', 'output', '',
2200 2200 _('print output to file with formatted name'), _('FORMAT')),
2201 2201 ('', 'switch-parent', None, _('diff against the second parent')),
2202 2202 ('r', 'rev', [], _('revisions to export'), _('REV')),
2203 2203 ] + diffopts,
2204 2204 _('[OPTION]... [-o OUTFILESPEC] REV...'))
2205 2205 def export(ui, repo, *changesets, **opts):
2206 2206 """dump the header and diffs for one or more changesets
2207 2207
2208 2208 Print the changeset header and diffs for one or more revisions.
2209 2209
2210 2210 The information shown in the changeset header is: author, date,
2211 2211 branch name (if non-default), changeset hash, parent(s) and commit
2212 2212 comment.
2213 2213
2214 2214 .. note::
2215 2215 export may generate unexpected diff output for merge
2216 2216 changesets, as it will compare the merge changeset against its
2217 2217 first parent only.
2218 2218
2219 2219 Output may be to a file, in which case the name of the file is
2220 2220 given using a format string. The formatting rules are as follows:
2221 2221
2222 2222 :``%%``: literal "%" character
2223 2223 :``%H``: changeset hash (40 hexadecimal digits)
2224 2224 :``%N``: number of patches being generated
2225 2225 :``%R``: changeset revision number
2226 2226 :``%b``: basename of the exporting repository
2227 2227 :``%h``: short-form changeset hash (12 hexadecimal digits)
2228 2228 :``%n``: zero-padded sequence number, starting at 1
2229 2229 :``%r``: zero-padded changeset revision number
2230 2230
2231 2231 Without the -a/--text option, export will avoid generating diffs
2232 2232 of files it detects as binary. With -a, export will generate a
2233 2233 diff anyway, probably with undesirable results.
2234 2234
2235 2235 Use the -g/--git option to generate diffs in the git extended diff
2236 2236 format. See :hg:`help diffs` for more information.
2237 2237
2238 2238 With the --switch-parent option, the diff will be against the
2239 2239 second parent. It can be useful to review a merge.
2240 2240
2241 2241 Returns 0 on success.
2242 2242 """
2243 2243 changesets += tuple(opts.get('rev', []))
2244 2244 if not changesets:
2245 2245 raise util.Abort(_("export requires at least one changeset"))
2246 2246 revs = scmutil.revrange(repo, changesets)
2247 2247 if len(revs) > 1:
2248 2248 ui.note(_('exporting patches:\n'))
2249 2249 else:
2250 2250 ui.note(_('exporting patch:\n'))
2251 2251 cmdutil.export(repo, revs, template=opts.get('output'),
2252 2252 switch_parent=opts.get('switch_parent'),
2253 2253 opts=patch.diffopts(ui, opts))
2254 2254
2255 2255 @command('^forget', walkopts, _('[OPTION]... FILE...'))
2256 2256 def forget(ui, repo, *pats, **opts):
2257 2257 """forget the specified files on the next commit
2258 2258
2259 2259 Mark the specified files so they will no longer be tracked
2260 2260 after the next commit.
2261 2261
2262 2262 This only removes files from the current branch, not from the
2263 2263 entire project history, and it does not delete them from the
2264 2264 working directory.
2265 2265
2266 2266 To undo a forget before the next commit, see :hg:`add`.
2267 2267
2268 2268 Returns 0 on success.
2269 2269 """
2270 2270
2271 2271 if not pats:
2272 2272 raise util.Abort(_('no files specified'))
2273 2273
2274 2274 m = scmutil.match(repo, pats, opts)
2275 2275 s = repo.status(match=m, clean=True)
2276 2276 forget = sorted(s[0] + s[1] + s[3] + s[6])
2277 2277 errs = 0
2278 2278
2279 2279 for f in m.files():
2280 2280 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
2281 2281 if os.path.exists(m.rel(f)):
2282 2282 ui.warn(_('not removing %s: file is already untracked\n')
2283 2283 % m.rel(f))
2284 2284 errs = 1
2285 2285
2286 2286 for f in forget:
2287 2287 if ui.verbose or not m.exact(f):
2288 2288 ui.status(_('removing %s\n') % m.rel(f))
2289 2289
2290 2290 repo[None].forget(forget)
2291 2291 return errs
2292 2292
2293 2293 @command('grep',
2294 2294 [('0', 'print0', None, _('end fields with NUL')),
2295 2295 ('', 'all', None, _('print all revisions that match')),
2296 2296 ('a', 'text', None, _('treat all files as text')),
2297 2297 ('f', 'follow', None,
2298 2298 _('follow changeset history,'
2299 2299 ' or file history across copies and renames')),
2300 2300 ('i', 'ignore-case', None, _('ignore case when matching')),
2301 2301 ('l', 'files-with-matches', None,
2302 2302 _('print only filenames and revisions that match')),
2303 2303 ('n', 'line-number', None, _('print matching line numbers')),
2304 2304 ('r', 'rev', [],
2305 2305 _('only search files changed within revision range'), _('REV')),
2306 2306 ('u', 'user', None, _('list the author (long with -v)')),
2307 2307 ('d', 'date', None, _('list the date (short with -q)')),
2308 2308 ] + walkopts,
2309 2309 _('[OPTION]... PATTERN [FILE]...'))
2310 2310 def grep(ui, repo, pattern, *pats, **opts):
2311 2311 """search for a pattern in specified files and revisions
2312 2312
2313 2313 Search revisions of files for a regular expression.
2314 2314
2315 2315 This command behaves differently than Unix grep. It only accepts
2316 2316 Python/Perl regexps. It searches repository history, not the
2317 2317 working directory. It always prints the revision number in which a
2318 2318 match appears.
2319 2319
2320 2320 By default, grep only prints output for the first revision of a
2321 2321 file in which it finds a match. To get it to print every revision
2322 2322 that contains a change in match status ("-" for a match that
2323 2323 becomes a non-match, or "+" for a non-match that becomes a match),
2324 2324 use the --all flag.
2325 2325
2326 2326 Returns 0 if a match is found, 1 otherwise.
2327 2327 """
2328 2328 reflags = 0
2329 2329 if opts.get('ignore_case'):
2330 2330 reflags |= re.I
2331 2331 try:
2332 2332 regexp = re.compile(pattern, reflags)
2333 2333 except re.error, inst:
2334 2334 ui.warn(_("grep: invalid match pattern: %s\n") % inst)
2335 2335 return 1
2336 2336 sep, eol = ':', '\n'
2337 2337 if opts.get('print0'):
2338 2338 sep = eol = '\0'
2339 2339
2340 2340 getfile = util.lrucachefunc(repo.file)
2341 2341
2342 2342 def matchlines(body):
2343 2343 begin = 0
2344 2344 linenum = 0
2345 2345 while True:
2346 2346 match = regexp.search(body, begin)
2347 2347 if not match:
2348 2348 break
2349 2349 mstart, mend = match.span()
2350 2350 linenum += body.count('\n', begin, mstart) + 1
2351 2351 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2352 2352 begin = body.find('\n', mend) + 1 or len(body)
2353 2353 lend = begin - 1
2354 2354 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2355 2355
2356 2356 class linestate(object):
2357 2357 def __init__(self, line, linenum, colstart, colend):
2358 2358 self.line = line
2359 2359 self.linenum = linenum
2360 2360 self.colstart = colstart
2361 2361 self.colend = colend
2362 2362
2363 2363 def __hash__(self):
2364 2364 return hash((self.linenum, self.line))
2365 2365
2366 2366 def __eq__(self, other):
2367 2367 return self.line == other.line
2368 2368
2369 2369 matches = {}
2370 2370 copies = {}
2371 2371 def grepbody(fn, rev, body):
2372 2372 matches[rev].setdefault(fn, [])
2373 2373 m = matches[rev][fn]
2374 2374 for lnum, cstart, cend, line in matchlines(body):
2375 2375 s = linestate(line, lnum, cstart, cend)
2376 2376 m.append(s)
2377 2377
2378 2378 def difflinestates(a, b):
2379 2379 sm = difflib.SequenceMatcher(None, a, b)
2380 2380 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2381 2381 if tag == 'insert':
2382 2382 for i in xrange(blo, bhi):
2383 2383 yield ('+', b[i])
2384 2384 elif tag == 'delete':
2385 2385 for i in xrange(alo, ahi):
2386 2386 yield ('-', a[i])
2387 2387 elif tag == 'replace':
2388 2388 for i in xrange(alo, ahi):
2389 2389 yield ('-', a[i])
2390 2390 for i in xrange(blo, bhi):
2391 2391 yield ('+', b[i])
2392 2392
2393 2393 def display(fn, ctx, pstates, states):
2394 2394 rev = ctx.rev()
2395 2395 datefunc = ui.quiet and util.shortdate or util.datestr
2396 2396 found = False
2397 2397 filerevmatches = {}
2398 2398 def binary():
2399 2399 flog = getfile(fn)
2400 2400 return util.binary(flog.read(ctx.filenode(fn)))
2401 2401
2402 2402 if opts.get('all'):
2403 2403 iter = difflinestates(pstates, states)
2404 2404 else:
2405 2405 iter = [('', l) for l in states]
2406 2406 for change, l in iter:
2407 2407 cols = [fn, str(rev)]
2408 2408 before, match, after = None, None, None
2409 2409 if opts.get('line_number'):
2410 2410 cols.append(str(l.linenum))
2411 2411 if opts.get('all'):
2412 2412 cols.append(change)
2413 2413 if opts.get('user'):
2414 2414 cols.append(ui.shortuser(ctx.user()))
2415 2415 if opts.get('date'):
2416 2416 cols.append(datefunc(ctx.date()))
2417 2417 if opts.get('files_with_matches'):
2418 2418 c = (fn, rev)
2419 2419 if c in filerevmatches:
2420 2420 continue
2421 2421 filerevmatches[c] = 1
2422 2422 else:
2423 2423 before = l.line[:l.colstart]
2424 2424 match = l.line[l.colstart:l.colend]
2425 2425 after = l.line[l.colend:]
2426 2426 ui.write(sep.join(cols))
2427 2427 if before is not None:
2428 2428 if not opts.get('text') and binary():
2429 2429 ui.write(sep + " Binary file matches")
2430 2430 else:
2431 2431 ui.write(sep + before)
2432 2432 ui.write(match, label='grep.match')
2433 2433 ui.write(after)
2434 2434 ui.write(eol)
2435 2435 found = True
2436 2436 return found
2437 2437
2438 2438 skip = {}
2439 2439 revfiles = {}
2440 2440 matchfn = scmutil.match(repo, pats, opts)
2441 2441 found = False
2442 2442 follow = opts.get('follow')
2443 2443
2444 2444 def prep(ctx, fns):
2445 2445 rev = ctx.rev()
2446 2446 pctx = ctx.p1()
2447 2447 parent = pctx.rev()
2448 2448 matches.setdefault(rev, {})
2449 2449 matches.setdefault(parent, {})
2450 2450 files = revfiles.setdefault(rev, [])
2451 2451 for fn in fns:
2452 2452 flog = getfile(fn)
2453 2453 try:
2454 2454 fnode = ctx.filenode(fn)
2455 2455 except error.LookupError:
2456 2456 continue
2457 2457
2458 2458 copied = flog.renamed(fnode)
2459 2459 copy = follow and copied and copied[0]
2460 2460 if copy:
2461 2461 copies.setdefault(rev, {})[fn] = copy
2462 2462 if fn in skip:
2463 2463 if copy:
2464 2464 skip[copy] = True
2465 2465 continue
2466 2466 files.append(fn)
2467 2467
2468 2468 if fn not in matches[rev]:
2469 2469 grepbody(fn, rev, flog.read(fnode))
2470 2470
2471 2471 pfn = copy or fn
2472 2472 if pfn not in matches[parent]:
2473 2473 try:
2474 2474 fnode = pctx.filenode(pfn)
2475 2475 grepbody(pfn, parent, flog.read(fnode))
2476 2476 except error.LookupError:
2477 2477 pass
2478 2478
2479 2479 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
2480 2480 rev = ctx.rev()
2481 2481 parent = ctx.p1().rev()
2482 2482 for fn in sorted(revfiles.get(rev, [])):
2483 2483 states = matches[rev][fn]
2484 2484 copy = copies.get(rev, {}).get(fn)
2485 2485 if fn in skip:
2486 2486 if copy:
2487 2487 skip[copy] = True
2488 2488 continue
2489 2489 pstates = matches.get(parent, {}).get(copy or fn, [])
2490 2490 if pstates or states:
2491 2491 r = display(fn, ctx, pstates, states)
2492 2492 found = found or r
2493 2493 if r and not opts.get('all'):
2494 2494 skip[fn] = True
2495 2495 if copy:
2496 2496 skip[copy] = True
2497 2497 del matches[rev]
2498 2498 del revfiles[rev]
2499 2499
2500 2500 return not found
2501 2501
2502 2502 @command('heads',
2503 2503 [('r', 'rev', '',
2504 2504 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
2505 2505 ('t', 'topo', False, _('show topological heads only')),
2506 2506 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
2507 2507 ('c', 'closed', False, _('show normal and closed branch heads')),
2508 2508 ] + templateopts,
2509 2509 _('[-ac] [-r STARTREV] [REV]...'))
2510 2510 def heads(ui, repo, *branchrevs, **opts):
2511 2511 """show current repository heads or show branch heads
2512 2512
2513 2513 With no arguments, show all repository branch heads.
2514 2514
2515 2515 Repository "heads" are changesets with no child changesets. They are
2516 2516 where development generally takes place and are the usual targets
2517 2517 for update and merge operations. Branch heads are changesets that have
2518 2518 no child changeset on the same branch.
2519 2519
2520 2520 If one or more REVs are given, only branch heads on the branches
2521 2521 associated with the specified changesets are shown.
2522 2522
2523 2523 If -c/--closed is specified, also show branch heads marked closed
2524 2524 (see :hg:`commit --close-branch`).
2525 2525
2526 2526 If STARTREV is specified, only those heads that are descendants of
2527 2527 STARTREV will be displayed.
2528 2528
2529 2529 If -t/--topo is specified, named branch mechanics will be ignored and only
2530 2530 changesets without children will be shown.
2531 2531
2532 2532 Returns 0 if matching heads are found, 1 if not.
2533 2533 """
2534 2534
2535 2535 start = None
2536 2536 if 'rev' in opts:
2537 2537 start = scmutil.revsingle(repo, opts['rev'], None).node()
2538 2538
2539 2539 if opts.get('topo'):
2540 2540 heads = [repo[h] for h in repo.heads(start)]
2541 2541 else:
2542 2542 heads = []
2543 2543 for branch in repo.branchmap():
2544 2544 heads += repo.branchheads(branch, start, opts.get('closed'))
2545 2545 heads = [repo[h] for h in heads]
2546 2546
2547 2547 if branchrevs:
2548 2548 branches = set(repo[br].branch() for br in branchrevs)
2549 2549 heads = [h for h in heads if h.branch() in branches]
2550 2550
2551 2551 if opts.get('active') and branchrevs:
2552 2552 dagheads = repo.heads(start)
2553 2553 heads = [h for h in heads if h.node() in dagheads]
2554 2554
2555 2555 if branchrevs:
2556 2556 haveheads = set(h.branch() for h in heads)
2557 2557 if branches - haveheads:
2558 2558 headless = ', '.join(b for b in branches - haveheads)
2559 2559 msg = _('no open branch heads found on branches %s')
2560 2560 if opts.get('rev'):
2561 2561 msg += _(' (started at %s)' % opts['rev'])
2562 2562 ui.warn((msg + '\n') % headless)
2563 2563
2564 2564 if not heads:
2565 2565 return 1
2566 2566
2567 2567 heads = sorted(heads, key=lambda x: -x.rev())
2568 2568 displayer = cmdutil.show_changeset(ui, repo, opts)
2569 2569 for ctx in heads:
2570 2570 displayer.show(ctx)
2571 2571 displayer.close()
2572 2572
2573 2573 @command('help',
2574 2574 [('e', 'extension', None, _('show only help for extensions')),
2575 2575 ('c', 'command', None, _('show only help for commands'))],
2576 2576 _('[-ec] [TOPIC]'))
2577 2577 def help_(ui, name=None, with_version=False, unknowncmd=False, full=True, **opts):
2578 2578 """show help for a given topic or a help overview
2579 2579
2580 2580 With no arguments, print a list of commands with short help messages.
2581 2581
2582 2582 Given a topic, extension, or command name, print help for that
2583 2583 topic.
2584 2584
2585 2585 Returns 0 if successful.
2586 2586 """
2587 2587 option_lists = []
2588 2588 textwidth = min(ui.termwidth(), 80) - 2
2589 2589
2590 2590 def addglobalopts(aliases):
2591 2591 if ui.verbose:
2592 2592 option_lists.append((_("global options:"), globalopts))
2593 2593 if name == 'shortlist':
2594 2594 option_lists.append((_('use "hg help" for the full list '
2595 2595 'of commands'), ()))
2596 2596 else:
2597 2597 if name == 'shortlist':
2598 2598 msg = _('use "hg help" for the full list of commands '
2599 2599 'or "hg -v" for details')
2600 2600 elif name and not full:
2601 2601 msg = _('use "hg help %s" to show the full help text' % name)
2602 2602 elif aliases:
2603 2603 msg = _('use "hg -v help%s" to show builtin aliases and '
2604 2604 'global options') % (name and " " + name or "")
2605 2605 else:
2606 2606 msg = _('use "hg -v help %s" to show global options') % name
2607 2607 option_lists.append((msg, ()))
2608 2608
2609 2609 def helpcmd(name):
2610 2610 if with_version:
2611 2611 version_(ui)
2612 2612 ui.write('\n')
2613 2613
2614 2614 try:
2615 2615 aliases, entry = cmdutil.findcmd(name, table, strict=unknowncmd)
2616 2616 except error.AmbiguousCommand, inst:
2617 2617 # py3k fix: except vars can't be used outside the scope of the
2618 2618 # except block, nor can be used inside a lambda. python issue4617
2619 2619 prefix = inst.args[0]
2620 2620 select = lambda c: c.lstrip('^').startswith(prefix)
2621 2621 helplist(_('list of commands:\n\n'), select)
2622 2622 return
2623 2623
2624 2624 # check if it's an invalid alias and display its error if it is
2625 2625 if getattr(entry[0], 'badalias', False):
2626 2626 if not unknowncmd:
2627 2627 entry[0](ui)
2628 2628 return
2629 2629
2630 2630 # synopsis
2631 2631 if len(entry) > 2:
2632 2632 if entry[2].startswith('hg'):
2633 2633 ui.write("%s\n" % entry[2])
2634 2634 else:
2635 2635 ui.write('hg %s %s\n' % (aliases[0], entry[2]))
2636 2636 else:
2637 2637 ui.write('hg %s\n' % aliases[0])
2638 2638
2639 2639 # aliases
2640 2640 if full and not ui.quiet and len(aliases) > 1:
2641 2641 ui.write(_("\naliases: %s\n") % ', '.join(aliases[1:]))
2642 2642
2643 2643 # description
2644 2644 doc = gettext(entry[0].__doc__)
2645 2645 if not doc:
2646 2646 doc = _("(no help text available)")
2647 2647 if hasattr(entry[0], 'definition'): # aliased command
2648 2648 if entry[0].definition.startswith('!'): # shell alias
2649 2649 doc = _('shell alias for::\n\n %s') % entry[0].definition[1:]
2650 2650 else:
2651 2651 doc = _('alias for: hg %s\n\n%s') % (entry[0].definition, doc)
2652 2652 if ui.quiet or not full:
2653 2653 doc = doc.splitlines()[0]
2654 2654 keep = ui.verbose and ['verbose'] or []
2655 2655 formatted, pruned = minirst.format(doc, textwidth, keep=keep)
2656 2656 ui.write("\n%s\n" % formatted)
2657 2657 if pruned:
2658 2658 ui.write(_('\nuse "hg -v help %s" to show verbose help\n') % name)
2659 2659
2660 2660 if not ui.quiet:
2661 2661 # options
2662 2662 if entry[1]:
2663 2663 option_lists.append((_("options:\n"), entry[1]))
2664 2664
2665 2665 addglobalopts(False)
2666 2666
2667 2667 # check if this command shadows a non-trivial (multi-line)
2668 2668 # extension help text
2669 2669 try:
2670 2670 mod = extensions.find(name)
2671 2671 doc = gettext(mod.__doc__) or ''
2672 2672 if '\n' in doc.strip():
2673 2673 msg = _('use "hg help -e %s" to show help for '
2674 2674 'the %s extension') % (name, name)
2675 2675 ui.write('\n%s\n' % msg)
2676 2676 except KeyError:
2677 2677 pass
2678 2678
2679 2679 def helplist(header, select=None):
2680 2680 h = {}
2681 2681 cmds = {}
2682 2682 for c, e in table.iteritems():
2683 2683 f = c.split("|", 1)[0]
2684 2684 if select and not select(f):
2685 2685 continue
2686 2686 if (not select and name != 'shortlist' and
2687 2687 e[0].__module__ != __name__):
2688 2688 continue
2689 2689 if name == "shortlist" and not f.startswith("^"):
2690 2690 continue
2691 2691 f = f.lstrip("^")
2692 2692 if not ui.debugflag and f.startswith("debug"):
2693 2693 continue
2694 2694 doc = e[0].__doc__
2695 2695 if doc and 'DEPRECATED' in doc and not ui.verbose:
2696 2696 continue
2697 2697 doc = gettext(doc)
2698 2698 if not doc:
2699 2699 doc = _("(no help text available)")
2700 2700 h[f] = doc.splitlines()[0].rstrip()
2701 2701 cmds[f] = c.lstrip("^")
2702 2702
2703 2703 if not h:
2704 2704 ui.status(_('no commands defined\n'))
2705 2705 return
2706 2706
2707 2707 ui.status(header)
2708 2708 fns = sorted(h)
2709 2709 m = max(map(len, fns))
2710 2710 for f in fns:
2711 2711 if ui.verbose:
2712 2712 commands = cmds[f].replace("|",", ")
2713 2713 ui.write(" %s:\n %s\n"%(commands, h[f]))
2714 2714 else:
2715 2715 ui.write('%s\n' % (util.wrap(h[f], textwidth,
2716 2716 initindent=' %-*s ' % (m, f),
2717 2717 hangindent=' ' * (m + 4))))
2718 2718
2719 2719 if not ui.quiet:
2720 2720 addglobalopts(True)
2721 2721
2722 2722 def helptopic(name):
2723 2723 for names, header, doc in help.helptable:
2724 2724 if name in names:
2725 2725 break
2726 2726 else:
2727 2727 raise error.UnknownCommand(name)
2728 2728
2729 2729 # description
2730 2730 if not doc:
2731 2731 doc = _("(no help text available)")
2732 2732 if hasattr(doc, '__call__'):
2733 2733 doc = doc()
2734 2734
2735 2735 ui.write("%s\n\n" % header)
2736 2736 ui.write("%s\n" % minirst.format(doc, textwidth, indent=4))
2737 2737 try:
2738 2738 cmdutil.findcmd(name, table)
2739 2739 ui.write(_('\nuse "hg help -c %s" to see help for '
2740 2740 'the %s command\n') % (name, name))
2741 2741 except error.UnknownCommand:
2742 2742 pass
2743 2743
2744 2744 def helpext(name):
2745 2745 try:
2746 2746 mod = extensions.find(name)
2747 2747 doc = gettext(mod.__doc__) or _('no help text available')
2748 2748 except KeyError:
2749 2749 mod = None
2750 2750 doc = extensions.disabledext(name)
2751 2751 if not doc:
2752 2752 raise error.UnknownCommand(name)
2753 2753
2754 2754 if '\n' not in doc:
2755 2755 head, tail = doc, ""
2756 2756 else:
2757 2757 head, tail = doc.split('\n', 1)
2758 2758 ui.write(_('%s extension - %s\n\n') % (name.split('.')[-1], head))
2759 2759 if tail:
2760 2760 ui.write(minirst.format(tail, textwidth))
2761 2761 ui.status('\n\n')
2762 2762
2763 2763 if mod:
2764 2764 try:
2765 2765 ct = mod.cmdtable
2766 2766 except AttributeError:
2767 2767 ct = {}
2768 2768 modcmds = set([c.split('|', 1)[0] for c in ct])
2769 2769 helplist(_('list of commands:\n\n'), modcmds.__contains__)
2770 2770 else:
2771 2771 ui.write(_('use "hg help extensions" for information on enabling '
2772 2772 'extensions\n'))
2773 2773
2774 2774 def helpextcmd(name):
2775 2775 cmd, ext, mod = extensions.disabledcmd(ui, name, ui.config('ui', 'strict'))
2776 2776 doc = gettext(mod.__doc__).splitlines()[0]
2777 2777
2778 2778 msg = help.listexts(_("'%s' is provided by the following "
2779 2779 "extension:") % cmd, {ext: doc}, indent=4)
2780 2780 ui.write(minirst.format(msg, textwidth))
2781 2781 ui.write('\n\n')
2782 2782 ui.write(_('use "hg help extensions" for information on enabling '
2783 2783 'extensions\n'))
2784 2784
2785 2785 if name and name != 'shortlist':
2786 2786 i = None
2787 2787 if unknowncmd:
2788 2788 queries = (helpextcmd,)
2789 2789 elif opts.get('extension'):
2790 2790 queries = (helpext,)
2791 2791 elif opts.get('command'):
2792 2792 queries = (helpcmd,)
2793 2793 else:
2794 2794 queries = (helptopic, helpcmd, helpext, helpextcmd)
2795 2795 for f in queries:
2796 2796 try:
2797 2797 f(name)
2798 2798 i = None
2799 2799 break
2800 2800 except error.UnknownCommand, inst:
2801 2801 i = inst
2802 2802 if i:
2803 2803 raise i
2804 2804
2805 2805 else:
2806 2806 # program name
2807 2807 if ui.verbose or with_version:
2808 2808 version_(ui)
2809 2809 else:
2810 2810 ui.status(_("Mercurial Distributed SCM\n"))
2811 2811 ui.status('\n')
2812 2812
2813 2813 # list of commands
2814 2814 if name == "shortlist":
2815 2815 header = _('basic commands:\n\n')
2816 2816 else:
2817 2817 header = _('list of commands:\n\n')
2818 2818
2819 2819 helplist(header)
2820 2820 if name != 'shortlist':
2821 2821 text = help.listexts(_('enabled extensions:'), extensions.enabled())
2822 2822 if text:
2823 2823 ui.write("\n%s\n" % minirst.format(text, textwidth))
2824 2824
2825 2825 # list all option lists
2826 2826 opt_output = []
2827 2827 multioccur = False
2828 2828 for title, options in option_lists:
2829 2829 opt_output.append(("\n%s" % title, None))
2830 2830 for option in options:
2831 2831 if len(option) == 5:
2832 2832 shortopt, longopt, default, desc, optlabel = option
2833 2833 else:
2834 2834 shortopt, longopt, default, desc = option
2835 2835 optlabel = _("VALUE") # default label
2836 2836
2837 2837 if _("DEPRECATED") in desc and not ui.verbose:
2838 2838 continue
2839 2839 if isinstance(default, list):
2840 2840 numqualifier = " %s [+]" % optlabel
2841 2841 multioccur = True
2842 2842 elif (default is not None) and not isinstance(default, bool):
2843 2843 numqualifier = " %s" % optlabel
2844 2844 else:
2845 2845 numqualifier = ""
2846 2846 opt_output.append(("%2s%s" %
2847 2847 (shortopt and "-%s" % shortopt,
2848 2848 longopt and " --%s%s" %
2849 2849 (longopt, numqualifier)),
2850 2850 "%s%s" % (desc,
2851 2851 default
2852 2852 and _(" (default: %s)") % default
2853 2853 or "")))
2854 2854 if multioccur:
2855 2855 msg = _("\n[+] marked option can be specified multiple times")
2856 2856 if ui.verbose and name != 'shortlist':
2857 2857 opt_output.append((msg, None))
2858 2858 else:
2859 2859 opt_output.insert(-1, (msg, None))
2860 2860
2861 2861 if not name:
2862 2862 ui.write(_("\nadditional help topics:\n\n"))
2863 2863 topics = []
2864 2864 for names, header, doc in help.helptable:
2865 2865 topics.append((sorted(names, key=len, reverse=True)[0], header))
2866 2866 topics_len = max([len(s[0]) for s in topics])
2867 2867 for t, desc in topics:
2868 2868 ui.write(" %-*s %s\n" % (topics_len, t, desc))
2869 2869
2870 2870 if opt_output:
2871 2871 colwidth = encoding.colwidth
2872 2872 # normalize: (opt or message, desc or None, width of opt)
2873 2873 entries = [desc and (opt, desc, colwidth(opt)) or (opt, None, 0)
2874 2874 for opt, desc in opt_output]
2875 2875 hanging = max([e[2] for e in entries])
2876 2876 for opt, desc, width in entries:
2877 2877 if desc:
2878 2878 initindent = ' %s%s ' % (opt, ' ' * (hanging - width))
2879 2879 hangindent = ' ' * (hanging + 3)
2880 2880 ui.write('%s\n' % (util.wrap(desc, textwidth,
2881 2881 initindent=initindent,
2882 2882 hangindent=hangindent)))
2883 2883 else:
2884 2884 ui.write("%s\n" % opt)
2885 2885
2886 2886 @command('identify|id',
2887 2887 [('r', 'rev', '',
2888 2888 _('identify the specified revision'), _('REV')),
2889 2889 ('n', 'num', None, _('show local revision number')),
2890 2890 ('i', 'id', None, _('show global revision id')),
2891 2891 ('b', 'branch', None, _('show branch')),
2892 2892 ('t', 'tags', None, _('show tags')),
2893 2893 ('B', 'bookmarks', None, _('show bookmarks'))],
2894 2894 _('[-nibtB] [-r REV] [SOURCE]'))
2895 2895 def identify(ui, repo, source=None, rev=None,
2896 2896 num=None, id=None, branch=None, tags=None, bookmarks=None):
2897 2897 """identify the working copy or specified revision
2898 2898
2899 2899 Print a summary identifying the repository state at REV using one or
2900 2900 two parent hash identifiers, followed by a "+" if the working
2901 2901 directory has uncommitted changes, the branch name (if not default),
2902 2902 a list of tags, and a list of bookmarks.
2903 2903
2904 2904 When REV is not given, print a summary of the current state of the
2905 2905 repository.
2906 2906
2907 2907 Specifying a path to a repository root or Mercurial bundle will
2908 2908 cause lookup to operate on that repository/bundle.
2909 2909
2910 2910 Returns 0 if successful.
2911 2911 """
2912 2912
2913 2913 if not repo and not source:
2914 2914 raise util.Abort(_("there is no Mercurial repository here "
2915 2915 "(.hg not found)"))
2916 2916
2917 2917 hexfunc = ui.debugflag and hex or short
2918 2918 default = not (num or id or branch or tags or bookmarks)
2919 2919 output = []
2920 2920 revs = []
2921 2921
2922 2922 if source:
2923 2923 source, branches = hg.parseurl(ui.expandpath(source))
2924 2924 repo = hg.peer(ui, {}, source)
2925 2925 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
2926 2926
2927 2927 if not repo.local():
2928 2928 if num or branch or tags:
2929 2929 raise util.Abort(
2930 2930 _("can't query remote revision number, branch, or tags"))
2931 2931 if not rev and revs:
2932 2932 rev = revs[0]
2933 2933 if not rev:
2934 2934 rev = "tip"
2935 2935
2936 2936 remoterev = repo.lookup(rev)
2937 2937 if default or id:
2938 2938 output = [hexfunc(remoterev)]
2939 2939
2940 2940 def getbms():
2941 2941 bms = []
2942 2942
2943 2943 if 'bookmarks' in repo.listkeys('namespaces'):
2944 2944 hexremoterev = hex(remoterev)
2945 2945 bms = [bm for bm, bmr in repo.listkeys('bookmarks').iteritems()
2946 2946 if bmr == hexremoterev]
2947 2947
2948 2948 return bms
2949 2949
2950 2950 if bookmarks:
2951 2951 output.extend(getbms())
2952 2952 elif default and not ui.quiet:
2953 2953 # multiple bookmarks for a single parent separated by '/'
2954 2954 bm = '/'.join(getbms())
2955 2955 if bm:
2956 2956 output.append(bm)
2957 2957 else:
2958 2958 if not rev:
2959 2959 ctx = repo[None]
2960 2960 parents = ctx.parents()
2961 2961 changed = ""
2962 2962 if default or id or num:
2963 2963 changed = util.any(repo.status()) and "+" or ""
2964 2964 if default or id:
2965 2965 output = ["%s%s" %
2966 2966 ('+'.join([hexfunc(p.node()) for p in parents]), changed)]
2967 2967 if num:
2968 2968 output.append("%s%s" %
2969 2969 ('+'.join([str(p.rev()) for p in parents]), changed))
2970 2970 else:
2971 2971 ctx = scmutil.revsingle(repo, rev)
2972 2972 if default or id:
2973 2973 output = [hexfunc(ctx.node())]
2974 2974 if num:
2975 2975 output.append(str(ctx.rev()))
2976 2976
2977 2977 if default and not ui.quiet:
2978 2978 b = ctx.branch()
2979 2979 if b != 'default':
2980 2980 output.append("(%s)" % b)
2981 2981
2982 2982 # multiple tags for a single parent separated by '/'
2983 2983 t = '/'.join(ctx.tags())
2984 2984 if t:
2985 2985 output.append(t)
2986 2986
2987 2987 # multiple bookmarks for a single parent separated by '/'
2988 2988 bm = '/'.join(ctx.bookmarks())
2989 2989 if bm:
2990 2990 output.append(bm)
2991 2991 else:
2992 2992 if branch:
2993 2993 output.append(ctx.branch())
2994 2994
2995 2995 if tags:
2996 2996 output.extend(ctx.tags())
2997 2997
2998 2998 if bookmarks:
2999 2999 output.extend(ctx.bookmarks())
3000 3000
3001 3001 ui.write("%s\n" % ' '.join(output))
3002 3002
3003 3003 @command('import|patch',
3004 3004 [('p', 'strip', 1,
3005 3005 _('directory strip option for patch. This has the same '
3006 3006 'meaning as the corresponding patch option'), _('NUM')),
3007 3007 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3008 3008 ('f', 'force', None, _('skip check for outstanding uncommitted changes')),
3009 3009 ('', 'no-commit', None,
3010 3010 _("don't commit, just update the working directory")),
3011 3011 ('', 'bypass', None,
3012 3012 _("apply patch without touching the working directory")),
3013 3013 ('', 'exact', None,
3014 3014 _('apply patch to the nodes from which it was generated')),
3015 3015 ('', 'import-branch', None,
3016 3016 _('use any branch information in patch (implied by --exact)'))] +
3017 3017 commitopts + commitopts2 + similarityopts,
3018 3018 _('[OPTION]... PATCH...'))
3019 3019 def import_(ui, repo, patch1, *patches, **opts):
3020 3020 """import an ordered set of patches
3021 3021
3022 3022 Import a list of patches and commit them individually (unless
3023 3023 --no-commit is specified).
3024 3024
3025 3025 If there are outstanding changes in the working directory, import
3026 3026 will abort unless given the -f/--force flag.
3027 3027
3028 3028 You can import a patch straight from a mail message. Even patches
3029 3029 as attachments work (to use the body part, it must have type
3030 3030 text/plain or text/x-patch). From and Subject headers of email
3031 3031 message are used as default committer and commit message. All
3032 3032 text/plain body parts before first diff are added to commit
3033 3033 message.
3034 3034
3035 3035 If the imported patch was generated by :hg:`export`, user and
3036 3036 description from patch override values from message headers and
3037 3037 body. Values given on command line with -m/--message and -u/--user
3038 3038 override these.
3039 3039
3040 3040 If --exact is specified, import will set the working directory to
3041 3041 the parent of each patch before applying it, and will abort if the
3042 3042 resulting changeset has a different ID than the one recorded in
3043 3043 the patch. This may happen due to character set problems or other
3044 3044 deficiencies in the text patch format.
3045 3045
3046 3046 Use --bypass to apply and commit patches directly to the
3047 3047 repository, not touching the working directory. Without --exact,
3048 3048 patches will be applied on top of the working directory parent
3049 3049 revision.
3050 3050
3051 3051 With -s/--similarity, hg will attempt to discover renames and
3052 3052 copies in the patch in the same way as 'addremove'.
3053 3053
3054 3054 To read a patch from standard input, use "-" as the patch name. If
3055 3055 a URL is specified, the patch will be downloaded from it.
3056 3056 See :hg:`help dates` for a list of formats valid for -d/--date.
3057 3057
3058 3058 Returns 0 on success.
3059 3059 """
3060 3060 patches = (patch1,) + patches
3061 3061
3062 3062 date = opts.get('date')
3063 3063 if date:
3064 3064 opts['date'] = util.parsedate(date)
3065 3065
3066 3066 update = not opts.get('bypass')
3067 3067 if not update and opts.get('no_commit'):
3068 3068 raise util.Abort(_('cannot use --no-commit with --bypass'))
3069 3069 try:
3070 3070 sim = float(opts.get('similarity') or 0)
3071 3071 except ValueError:
3072 3072 raise util.Abort(_('similarity must be a number'))
3073 3073 if sim < 0 or sim > 100:
3074 3074 raise util.Abort(_('similarity must be between 0 and 100'))
3075 3075 if sim and not update:
3076 3076 raise util.Abort(_('cannot use --similarity with --bypass'))
3077 3077
3078 3078 if (opts.get('exact') or not opts.get('force')) and update:
3079 3079 cmdutil.bailifchanged(repo)
3080 3080
3081 3081 d = opts["base"]
3082 3082 strip = opts["strip"]
3083 3083 wlock = lock = None
3084 3084 msgs = []
3085 3085
3086 3086 def checkexact(repo, n, nodeid):
3087 3087 if opts.get('exact') and hex(n) != nodeid:
3088 3088 repo.rollback()
3089 3089 raise util.Abort(_('patch is damaged or loses information'))
3090 3090
3091 3091 def tryone(ui, hunk, parents):
3092 3092 tmpname, message, user, date, branch, nodeid, p1, p2 = \
3093 3093 patch.extract(ui, hunk)
3094 3094
3095 3095 if not tmpname:
3096 3096 return None
3097 3097 commitid = _('to working directory')
3098 3098
3099 3099 try:
3100 cmdline_message = cmdutil.logmessage(opts)
3100 cmdline_message = cmdutil.logmessage(ui, opts)
3101 3101 if cmdline_message:
3102 3102 # pickup the cmdline msg
3103 3103 message = cmdline_message
3104 3104 elif message:
3105 3105 # pickup the patch msg
3106 3106 message = message.strip()
3107 3107 else:
3108 3108 # launch the editor
3109 3109 message = None
3110 3110 ui.debug('message:\n%s\n' % message)
3111 3111
3112 3112 if len(parents) == 1:
3113 3113 parents.append(repo[nullid])
3114 3114 if opts.get('exact'):
3115 3115 if not nodeid or not p1:
3116 3116 raise util.Abort(_('not a Mercurial patch'))
3117 3117 p1 = repo[p1]
3118 3118 p2 = repo[p2 or nullid]
3119 3119 elif p2:
3120 3120 try:
3121 3121 p1 = repo[p1]
3122 3122 p2 = repo[p2]
3123 3123 except error.RepoError:
3124 3124 p1, p2 = parents
3125 3125 else:
3126 3126 p1, p2 = parents
3127 3127
3128 3128 n = None
3129 3129 if update:
3130 3130 if opts.get('exact') and p1 != parents[0]:
3131 3131 hg.clean(repo, p1.node())
3132 3132 if p1 != parents[0] and p2 != parents[1]:
3133 3133 repo.dirstate.setparents(p1.node(), p2.node())
3134 3134
3135 3135 if opts.get('exact') or opts.get('import_branch'):
3136 3136 repo.dirstate.setbranch(branch or 'default')
3137 3137
3138 3138 files = set()
3139 3139 patch.patch(ui, repo, tmpname, strip=strip, files=files,
3140 3140 eolmode=None, similarity=sim / 100.0)
3141 3141 files = list(files)
3142 3142 if opts.get('no_commit'):
3143 3143 if message:
3144 3144 msgs.append(message)
3145 3145 else:
3146 3146 if opts.get('exact'):
3147 3147 m = None
3148 3148 else:
3149 3149 m = scmutil.matchfiles(repo, files or [])
3150 3150 n = repo.commit(message, opts.get('user') or user,
3151 3151 opts.get('date') or date, match=m,
3152 3152 editor=cmdutil.commiteditor)
3153 3153 checkexact(repo, n, nodeid)
3154 3154 # Force a dirstate write so that the next transaction
3155 3155 # backups an up-to-date file.
3156 3156 repo.dirstate.write()
3157 3157 else:
3158 3158 if opts.get('exact') or opts.get('import_branch'):
3159 3159 branch = branch or 'default'
3160 3160 else:
3161 3161 branch = p1.branch()
3162 3162 store = patch.filestore()
3163 3163 try:
3164 3164 files = set()
3165 3165 try:
3166 3166 patch.patchrepo(ui, repo, p1, store, tmpname, strip,
3167 3167 files, eolmode=None)
3168 3168 except patch.PatchError, e:
3169 3169 raise util.Abort(str(e))
3170 3170 memctx = patch.makememctx(repo, (p1.node(), p2.node()),
3171 3171 message,
3172 3172 opts.get('user') or user,
3173 3173 opts.get('date') or date,
3174 3174 branch, files, store,
3175 3175 editor=cmdutil.commiteditor)
3176 3176 repo.savecommitmessage(memctx.description())
3177 3177 n = memctx.commit()
3178 3178 checkexact(repo, n, nodeid)
3179 3179 finally:
3180 3180 store.close()
3181 3181 if n:
3182 3182 commitid = short(n)
3183 3183 return commitid
3184 3184 finally:
3185 3185 os.unlink(tmpname)
3186 3186
3187 3187 try:
3188 3188 wlock = repo.wlock()
3189 3189 lock = repo.lock()
3190 3190 parents = repo.parents()
3191 3191 lastcommit = None
3192 3192 for p in patches:
3193 3193 pf = os.path.join(d, p)
3194 3194
3195 3195 if pf == '-':
3196 3196 ui.status(_("applying patch from stdin\n"))
3197 3197 pf = sys.stdin
3198 3198 else:
3199 3199 ui.status(_("applying %s\n") % p)
3200 3200 pf = url.open(ui, pf)
3201 3201
3202 3202 haspatch = False
3203 3203 for hunk in patch.split(pf):
3204 3204 commitid = tryone(ui, hunk, parents)
3205 3205 if commitid:
3206 3206 haspatch = True
3207 3207 if lastcommit:
3208 3208 ui.status(_('applied %s\n') % lastcommit)
3209 3209 lastcommit = commitid
3210 3210 if update or opts.get('exact'):
3211 3211 parents = repo.parents()
3212 3212 else:
3213 3213 parents = [repo[commitid]]
3214 3214
3215 3215 if not haspatch:
3216 3216 raise util.Abort(_('no diffs found'))
3217 3217
3218 3218 if msgs:
3219 3219 repo.savecommitmessage('\n* * *\n'.join(msgs))
3220 3220 finally:
3221 3221 release(lock, wlock)
3222 3222
3223 3223 @command('incoming|in',
3224 3224 [('f', 'force', None,
3225 3225 _('run even if remote repository is unrelated')),
3226 3226 ('n', 'newest-first', None, _('show newest record first')),
3227 3227 ('', 'bundle', '',
3228 3228 _('file to store the bundles into'), _('FILE')),
3229 3229 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3230 3230 ('B', 'bookmarks', False, _("compare bookmarks")),
3231 3231 ('b', 'branch', [],
3232 3232 _('a specific branch you would like to pull'), _('BRANCH')),
3233 3233 ] + logopts + remoteopts + subrepoopts,
3234 3234 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'))
3235 3235 def incoming(ui, repo, source="default", **opts):
3236 3236 """show new changesets found in source
3237 3237
3238 3238 Show new changesets found in the specified path/URL or the default
3239 3239 pull location. These are the changesets that would have been pulled
3240 3240 if a pull at the time you issued this command.
3241 3241
3242 3242 For remote repository, using --bundle avoids downloading the
3243 3243 changesets twice if the incoming is followed by a pull.
3244 3244
3245 3245 See pull for valid source format details.
3246 3246
3247 3247 Returns 0 if there are incoming changes, 1 otherwise.
3248 3248 """
3249 3249 if opts.get('bundle') and opts.get('subrepos'):
3250 3250 raise util.Abort(_('cannot combine --bundle and --subrepos'))
3251 3251
3252 3252 if opts.get('bookmarks'):
3253 3253 source, branches = hg.parseurl(ui.expandpath(source),
3254 3254 opts.get('branch'))
3255 3255 other = hg.peer(repo, opts, source)
3256 3256 if 'bookmarks' not in other.listkeys('namespaces'):
3257 3257 ui.warn(_("remote doesn't support bookmarks\n"))
3258 3258 return 0
3259 3259 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3260 3260 return bookmarks.diff(ui, repo, other)
3261 3261
3262 3262 repo._subtoppath = ui.expandpath(source)
3263 3263 try:
3264 3264 return hg.incoming(ui, repo, source, opts)
3265 3265 finally:
3266 3266 del repo._subtoppath
3267 3267
3268 3268
3269 3269 @command('^init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'))
3270 3270 def init(ui, dest=".", **opts):
3271 3271 """create a new repository in the given directory
3272 3272
3273 3273 Initialize a new repository in the given directory. If the given
3274 3274 directory does not exist, it will be created.
3275 3275
3276 3276 If no directory is given, the current directory is used.
3277 3277
3278 3278 It is possible to specify an ``ssh://`` URL as the destination.
3279 3279 See :hg:`help urls` for more information.
3280 3280
3281 3281 Returns 0 on success.
3282 3282 """
3283 3283 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3284 3284
3285 3285 @command('locate',
3286 3286 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3287 3287 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3288 3288 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3289 3289 ] + walkopts,
3290 3290 _('[OPTION]... [PATTERN]...'))
3291 3291 def locate(ui, repo, *pats, **opts):
3292 3292 """locate files matching specific patterns
3293 3293
3294 3294 Print files under Mercurial control in the working directory whose
3295 3295 names match the given patterns.
3296 3296
3297 3297 By default, this command searches all directories in the working
3298 3298 directory. To search just the current directory and its
3299 3299 subdirectories, use "--include .".
3300 3300
3301 3301 If no patterns are given to match, this command prints the names
3302 3302 of all files under Mercurial control in the working directory.
3303 3303
3304 3304 If you want to feed the output of this command into the "xargs"
3305 3305 command, use the -0 option to both this command and "xargs". This
3306 3306 will avoid the problem of "xargs" treating single filenames that
3307 3307 contain whitespace as multiple filenames.
3308 3308
3309 3309 Returns 0 if a match is found, 1 otherwise.
3310 3310 """
3311 3311 end = opts.get('print0') and '\0' or '\n'
3312 3312 rev = scmutil.revsingle(repo, opts.get('rev'), None).node()
3313 3313
3314 3314 ret = 1
3315 3315 m = scmutil.match(repo, pats, opts, default='relglob')
3316 3316 m.bad = lambda x, y: False
3317 3317 for abs in repo[rev].walk(m):
3318 3318 if not rev and abs not in repo.dirstate:
3319 3319 continue
3320 3320 if opts.get('fullpath'):
3321 3321 ui.write(repo.wjoin(abs), end)
3322 3322 else:
3323 3323 ui.write(((pats and m.rel(abs)) or abs), end)
3324 3324 ret = 0
3325 3325
3326 3326 return ret
3327 3327
3328 3328 @command('^log|history',
3329 3329 [('f', 'follow', None,
3330 3330 _('follow changeset history, or file history across copies and renames')),
3331 3331 ('', 'follow-first', None,
3332 3332 _('only follow the first parent of merge changesets')),
3333 3333 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3334 3334 ('C', 'copies', None, _('show copied files')),
3335 3335 ('k', 'keyword', [],
3336 3336 _('do case-insensitive search for a given text'), _('TEXT')),
3337 3337 ('r', 'rev', [], _('show the specified revision or range'), _('REV')),
3338 3338 ('', 'removed', None, _('include revisions where files were removed')),
3339 3339 ('m', 'only-merges', None, _('show only merges')),
3340 3340 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3341 3341 ('', 'only-branch', [],
3342 3342 _('show only changesets within the given named branch (DEPRECATED)'),
3343 3343 _('BRANCH')),
3344 3344 ('b', 'branch', [],
3345 3345 _('show changesets within the given named branch'), _('BRANCH')),
3346 3346 ('P', 'prune', [],
3347 3347 _('do not display revision or any of its ancestors'), _('REV')),
3348 3348 ] + logopts + walkopts,
3349 3349 _('[OPTION]... [FILE]'))
3350 3350 def log(ui, repo, *pats, **opts):
3351 3351 """show revision history of entire repository or files
3352 3352
3353 3353 Print the revision history of the specified files or the entire
3354 3354 project.
3355 3355
3356 3356 File history is shown without following rename or copy history of
3357 3357 files. Use -f/--follow with a filename to follow history across
3358 3358 renames and copies. --follow without a filename will only show
3359 3359 ancestors or descendants of the starting revision. --follow-first
3360 3360 only follows the first parent of merge revisions.
3361 3361
3362 3362 If no revision range is specified, the default is ``tip:0`` unless
3363 3363 --follow is set, in which case the working directory parent is
3364 3364 used as the starting revision. You can specify a revision set for
3365 3365 log, see :hg:`help revsets` for more information.
3366 3366
3367 3367 See :hg:`help dates` for a list of formats valid for -d/--date.
3368 3368
3369 3369 By default this command prints revision number and changeset id,
3370 3370 tags, non-trivial parents, user, date and time, and a summary for
3371 3371 each commit. When the -v/--verbose switch is used, the list of
3372 3372 changed files and full commit message are shown.
3373 3373
3374 3374 .. note::
3375 3375 log -p/--patch may generate unexpected diff output for merge
3376 3376 changesets, as it will only compare the merge changeset against
3377 3377 its first parent. Also, only files different from BOTH parents
3378 3378 will appear in files:.
3379 3379
3380 3380 Returns 0 on success.
3381 3381 """
3382 3382
3383 3383 matchfn = scmutil.match(repo, pats, opts)
3384 3384 limit = cmdutil.loglimit(opts)
3385 3385 count = 0
3386 3386
3387 3387 endrev = None
3388 3388 if opts.get('copies') and opts.get('rev'):
3389 3389 endrev = max(scmutil.revrange(repo, opts.get('rev'))) + 1
3390 3390
3391 3391 df = False
3392 3392 if opts["date"]:
3393 3393 df = util.matchdate(opts["date"])
3394 3394
3395 3395 branches = opts.get('branch', []) + opts.get('only_branch', [])
3396 3396 opts['branch'] = [repo.lookupbranch(b) for b in branches]
3397 3397
3398 3398 displayer = cmdutil.show_changeset(ui, repo, opts, True)
3399 3399 def prep(ctx, fns):
3400 3400 rev = ctx.rev()
3401 3401 parents = [p for p in repo.changelog.parentrevs(rev)
3402 3402 if p != nullrev]
3403 3403 if opts.get('no_merges') and len(parents) == 2:
3404 3404 return
3405 3405 if opts.get('only_merges') and len(parents) != 2:
3406 3406 return
3407 3407 if opts.get('branch') and ctx.branch() not in opts['branch']:
3408 3408 return
3409 3409 if df and not df(ctx.date()[0]):
3410 3410 return
3411 3411 if opts['user'] and not [k for k in opts['user']
3412 3412 if k.lower() in ctx.user().lower()]:
3413 3413 return
3414 3414 if opts.get('keyword'):
3415 3415 for k in [kw.lower() for kw in opts['keyword']]:
3416 3416 if (k in ctx.user().lower() or
3417 3417 k in ctx.description().lower() or
3418 3418 k in " ".join(ctx.files()).lower()):
3419 3419 break
3420 3420 else:
3421 3421 return
3422 3422
3423 3423 copies = None
3424 3424 if opts.get('copies') and rev:
3425 3425 copies = []
3426 3426 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3427 3427 for fn in ctx.files():
3428 3428 rename = getrenamed(fn, rev)
3429 3429 if rename:
3430 3430 copies.append((fn, rename[0]))
3431 3431
3432 3432 revmatchfn = None
3433 3433 if opts.get('patch') or opts.get('stat'):
3434 3434 if opts.get('follow') or opts.get('follow_first'):
3435 3435 # note: this might be wrong when following through merges
3436 3436 revmatchfn = scmutil.match(repo, fns, default='path')
3437 3437 else:
3438 3438 revmatchfn = matchfn
3439 3439
3440 3440 displayer.show(ctx, copies=copies, matchfn=revmatchfn)
3441 3441
3442 3442 for ctx in cmdutil.walkchangerevs(repo, matchfn, opts, prep):
3443 3443 if count == limit:
3444 3444 break
3445 3445 if displayer.flush(ctx.rev()):
3446 3446 count += 1
3447 3447 displayer.close()
3448 3448
3449 3449 @command('manifest',
3450 3450 [('r', 'rev', '', _('revision to display'), _('REV')),
3451 3451 ('', 'all', False, _("list files from all revisions"))],
3452 3452 _('[-r REV]'))
3453 3453 def manifest(ui, repo, node=None, rev=None, **opts):
3454 3454 """output the current or given revision of the project manifest
3455 3455
3456 3456 Print a list of version controlled files for the given revision.
3457 3457 If no revision is given, the first parent of the working directory
3458 3458 is used, or the null revision if no revision is checked out.
3459 3459
3460 3460 With -v, print file permissions, symlink and executable bits.
3461 3461 With --debug, print file revision hashes.
3462 3462
3463 3463 If option --all is specified, the list of all files from all revisions
3464 3464 is printed. This includes deleted and renamed files.
3465 3465
3466 3466 Returns 0 on success.
3467 3467 """
3468 3468 if opts.get('all'):
3469 3469 if rev or node:
3470 3470 raise util.Abort(_("can't specify a revision with --all"))
3471 3471
3472 3472 res = []
3473 3473 prefix = "data/"
3474 3474 suffix = ".i"
3475 3475 plen = len(prefix)
3476 3476 slen = len(suffix)
3477 3477 lock = repo.lock()
3478 3478 try:
3479 3479 for fn, b, size in repo.store.datafiles():
3480 3480 if size != 0 and fn[-slen:] == suffix and fn[:plen] == prefix:
3481 3481 res.append(fn[plen:-slen])
3482 3482 finally:
3483 3483 lock.release()
3484 3484 for f in sorted(res):
3485 3485 ui.write("%s\n" % f)
3486 3486 return
3487 3487
3488 3488 if rev and node:
3489 3489 raise util.Abort(_("please specify just one revision"))
3490 3490
3491 3491 if not node:
3492 3492 node = rev
3493 3493
3494 3494 decor = {'l':'644 @ ', 'x':'755 * ', '':'644 '}
3495 3495 ctx = scmutil.revsingle(repo, node)
3496 3496 for f in ctx:
3497 3497 if ui.debugflag:
3498 3498 ui.write("%40s " % hex(ctx.manifest()[f]))
3499 3499 if ui.verbose:
3500 3500 ui.write(decor[ctx.flags(f)])
3501 3501 ui.write("%s\n" % f)
3502 3502
3503 3503 @command('^merge',
3504 3504 [('f', 'force', None, _('force a merge with outstanding changes')),
3505 3505 ('t', 'tool', '', _('specify merge tool')),
3506 3506 ('r', 'rev', '', _('revision to merge'), _('REV')),
3507 3507 ('P', 'preview', None,
3508 3508 _('review revisions to merge (no merge is performed)'))],
3509 3509 _('[-P] [-f] [[-r] REV]'))
3510 3510 def merge(ui, repo, node=None, **opts):
3511 3511 """merge working directory with another revision
3512 3512
3513 3513 The current working directory is updated with all changes made in
3514 3514 the requested revision since the last common predecessor revision.
3515 3515
3516 3516 Files that changed between either parent are marked as changed for
3517 3517 the next commit and a commit must be performed before any further
3518 3518 updates to the repository are allowed. The next commit will have
3519 3519 two parents.
3520 3520
3521 3521 ``--tool`` can be used to specify the merge tool used for file
3522 3522 merges. It overrides the HGMERGE environment variable and your
3523 3523 configuration files. See :hg:`help merge-tools` for options.
3524 3524
3525 3525 If no revision is specified, the working directory's parent is a
3526 3526 head revision, and the current branch contains exactly one other
3527 3527 head, the other head is merged with by default. Otherwise, an
3528 3528 explicit revision with which to merge with must be provided.
3529 3529
3530 3530 :hg:`resolve` must be used to resolve unresolved files.
3531 3531
3532 3532 To undo an uncommitted merge, use :hg:`update --clean .` which
3533 3533 will check out a clean copy of the original merge parent, losing
3534 3534 all changes.
3535 3535
3536 3536 Returns 0 on success, 1 if there are unresolved files.
3537 3537 """
3538 3538
3539 3539 if opts.get('rev') and node:
3540 3540 raise util.Abort(_("please specify just one revision"))
3541 3541 if not node:
3542 3542 node = opts.get('rev')
3543 3543
3544 3544 if not node:
3545 3545 branch = repo[None].branch()
3546 3546 bheads = repo.branchheads(branch)
3547 3547 if len(bheads) > 2:
3548 3548 raise util.Abort(_("branch '%s' has %d heads - "
3549 3549 "please merge with an explicit rev")
3550 3550 % (branch, len(bheads)),
3551 3551 hint=_("run 'hg heads .' to see heads"))
3552 3552
3553 3553 parent = repo.dirstate.p1()
3554 3554 if len(bheads) == 1:
3555 3555 if len(repo.heads()) > 1:
3556 3556 raise util.Abort(_("branch '%s' has one head - "
3557 3557 "please merge with an explicit rev")
3558 3558 % branch,
3559 3559 hint=_("run 'hg heads' to see all heads"))
3560 3560 msg = _('there is nothing to merge')
3561 3561 if parent != repo.lookup(repo[None].branch()):
3562 3562 msg = _('%s - use "hg update" instead') % msg
3563 3563 raise util.Abort(msg)
3564 3564
3565 3565 if parent not in bheads:
3566 3566 raise util.Abort(_('working directory not at a head revision'),
3567 3567 hint=_("use 'hg update' or merge with an "
3568 3568 "explicit revision"))
3569 3569 node = parent == bheads[0] and bheads[-1] or bheads[0]
3570 3570 else:
3571 3571 node = scmutil.revsingle(repo, node).node()
3572 3572
3573 3573 if opts.get('preview'):
3574 3574 # find nodes that are ancestors of p2 but not of p1
3575 3575 p1 = repo.lookup('.')
3576 3576 p2 = repo.lookup(node)
3577 3577 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
3578 3578
3579 3579 displayer = cmdutil.show_changeset(ui, repo, opts)
3580 3580 for node in nodes:
3581 3581 displayer.show(repo[node])
3582 3582 displayer.close()
3583 3583 return 0
3584 3584
3585 3585 try:
3586 3586 # ui.forcemerge is an internal variable, do not document
3587 3587 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
3588 3588 return hg.merge(repo, node, force=opts.get('force'))
3589 3589 finally:
3590 3590 ui.setconfig('ui', 'forcemerge', '')
3591 3591
3592 3592 @command('outgoing|out',
3593 3593 [('f', 'force', None, _('run even when the destination is unrelated')),
3594 3594 ('r', 'rev', [],
3595 3595 _('a changeset intended to be included in the destination'), _('REV')),
3596 3596 ('n', 'newest-first', None, _('show newest record first')),
3597 3597 ('B', 'bookmarks', False, _('compare bookmarks')),
3598 3598 ('b', 'branch', [], _('a specific branch you would like to push'),
3599 3599 _('BRANCH')),
3600 3600 ] + logopts + remoteopts + subrepoopts,
3601 3601 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'))
3602 3602 def outgoing(ui, repo, dest=None, **opts):
3603 3603 """show changesets not found in the destination
3604 3604
3605 3605 Show changesets not found in the specified destination repository
3606 3606 or the default push location. These are the changesets that would
3607 3607 be pushed if a push was requested.
3608 3608
3609 3609 See pull for details of valid destination formats.
3610 3610
3611 3611 Returns 0 if there are outgoing changes, 1 otherwise.
3612 3612 """
3613 3613
3614 3614 if opts.get('bookmarks'):
3615 3615 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3616 3616 dest, branches = hg.parseurl(dest, opts.get('branch'))
3617 3617 other = hg.peer(repo, opts, dest)
3618 3618 if 'bookmarks' not in other.listkeys('namespaces'):
3619 3619 ui.warn(_("remote doesn't support bookmarks\n"))
3620 3620 return 0
3621 3621 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
3622 3622 return bookmarks.diff(ui, other, repo)
3623 3623
3624 3624 repo._subtoppath = ui.expandpath(dest or 'default-push', dest or 'default')
3625 3625 try:
3626 3626 return hg.outgoing(ui, repo, dest, opts)
3627 3627 finally:
3628 3628 del repo._subtoppath
3629 3629
3630 3630 @command('parents',
3631 3631 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
3632 3632 ] + templateopts,
3633 3633 _('[-r REV] [FILE]'))
3634 3634 def parents(ui, repo, file_=None, **opts):
3635 3635 """show the parents of the working directory or revision
3636 3636
3637 3637 Print the working directory's parent revisions. If a revision is
3638 3638 given via -r/--rev, the parent of that revision will be printed.
3639 3639 If a file argument is given, the revision in which the file was
3640 3640 last changed (before the working directory revision or the
3641 3641 argument to --rev if given) is printed.
3642 3642
3643 3643 Returns 0 on success.
3644 3644 """
3645 3645
3646 3646 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3647 3647
3648 3648 if file_:
3649 3649 m = scmutil.match(repo, (file_,), opts)
3650 3650 if m.anypats() or len(m.files()) != 1:
3651 3651 raise util.Abort(_('can only specify an explicit filename'))
3652 3652 file_ = m.files()[0]
3653 3653 filenodes = []
3654 3654 for cp in ctx.parents():
3655 3655 if not cp:
3656 3656 continue
3657 3657 try:
3658 3658 filenodes.append(cp.filenode(file_))
3659 3659 except error.LookupError:
3660 3660 pass
3661 3661 if not filenodes:
3662 3662 raise util.Abort(_("'%s' not found in manifest!") % file_)
3663 3663 fl = repo.file(file_)
3664 3664 p = [repo.lookup(fl.linkrev(fl.rev(fn))) for fn in filenodes]
3665 3665 else:
3666 3666 p = [cp.node() for cp in ctx.parents()]
3667 3667
3668 3668 displayer = cmdutil.show_changeset(ui, repo, opts)
3669 3669 for n in p:
3670 3670 if n != nullid:
3671 3671 displayer.show(repo[n])
3672 3672 displayer.close()
3673 3673
3674 3674 @command('paths', [], _('[NAME]'))
3675 3675 def paths(ui, repo, search=None):
3676 3676 """show aliases for remote repositories
3677 3677
3678 3678 Show definition of symbolic path name NAME. If no name is given,
3679 3679 show definition of all available names.
3680 3680
3681 3681 Option -q/--quiet suppresses all output when searching for NAME
3682 3682 and shows only the path names when listing all definitions.
3683 3683
3684 3684 Path names are defined in the [paths] section of your
3685 3685 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
3686 3686 repository, ``.hg/hgrc`` is used, too.
3687 3687
3688 3688 The path names ``default`` and ``default-push`` have a special
3689 3689 meaning. When performing a push or pull operation, they are used
3690 3690 as fallbacks if no location is specified on the command-line.
3691 3691 When ``default-push`` is set, it will be used for push and
3692 3692 ``default`` will be used for pull; otherwise ``default`` is used
3693 3693 as the fallback for both. When cloning a repository, the clone
3694 3694 source is written as ``default`` in ``.hg/hgrc``. Note that
3695 3695 ``default`` and ``default-push`` apply to all inbound (e.g.
3696 3696 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email` and
3697 3697 :hg:`bundle`) operations.
3698 3698
3699 3699 See :hg:`help urls` for more information.
3700 3700
3701 3701 Returns 0 on success.
3702 3702 """
3703 3703 if search:
3704 3704 for name, path in ui.configitems("paths"):
3705 3705 if name == search:
3706 3706 ui.status("%s\n" % util.hidepassword(path))
3707 3707 return
3708 3708 if not ui.quiet:
3709 3709 ui.warn(_("not found!\n"))
3710 3710 return 1
3711 3711 else:
3712 3712 for name, path in ui.configitems("paths"):
3713 3713 if ui.quiet:
3714 3714 ui.write("%s\n" % name)
3715 3715 else:
3716 3716 ui.write("%s = %s\n" % (name, util.hidepassword(path)))
3717 3717
3718 3718 def postincoming(ui, repo, modheads, optupdate, checkout):
3719 3719 if modheads == 0:
3720 3720 return
3721 3721 if optupdate:
3722 3722 try:
3723 3723 return hg.update(repo, checkout)
3724 3724 except util.Abort, inst:
3725 3725 ui.warn(_("not updating: %s\n" % str(inst)))
3726 3726 return 0
3727 3727 if modheads > 1:
3728 3728 currentbranchheads = len(repo.branchheads())
3729 3729 if currentbranchheads == modheads:
3730 3730 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
3731 3731 elif currentbranchheads > 1:
3732 3732 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to merge)\n"))
3733 3733 else:
3734 3734 ui.status(_("(run 'hg heads' to see heads)\n"))
3735 3735 else:
3736 3736 ui.status(_("(run 'hg update' to get a working copy)\n"))
3737 3737
3738 3738 @command('^pull',
3739 3739 [('u', 'update', None,
3740 3740 _('update to new branch head if changesets were pulled')),
3741 3741 ('f', 'force', None, _('run even when remote repository is unrelated')),
3742 3742 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3743 3743 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
3744 3744 ('b', 'branch', [], _('a specific branch you would like to pull'),
3745 3745 _('BRANCH')),
3746 3746 ] + remoteopts,
3747 3747 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'))
3748 3748 def pull(ui, repo, source="default", **opts):
3749 3749 """pull changes from the specified source
3750 3750
3751 3751 Pull changes from a remote repository to a local one.
3752 3752
3753 3753 This finds all changes from the repository at the specified path
3754 3754 or URL and adds them to a local repository (the current one unless
3755 3755 -R is specified). By default, this does not update the copy of the
3756 3756 project in the working directory.
3757 3757
3758 3758 Use :hg:`incoming` if you want to see what would have been added
3759 3759 by a pull at the time you issued this command. If you then decide
3760 3760 to add those changes to the repository, you should use :hg:`pull
3761 3761 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
3762 3762
3763 3763 If SOURCE is omitted, the 'default' path will be used.
3764 3764 See :hg:`help urls` for more information.
3765 3765
3766 3766 Returns 0 on success, 1 if an update had unresolved files.
3767 3767 """
3768 3768 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
3769 3769 other = hg.peer(repo, opts, source)
3770 3770 ui.status(_('pulling from %s\n') % util.hidepassword(source))
3771 3771 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
3772 3772
3773 3773 if opts.get('bookmark'):
3774 3774 if not revs:
3775 3775 revs = []
3776 3776 rb = other.listkeys('bookmarks')
3777 3777 for b in opts['bookmark']:
3778 3778 if b not in rb:
3779 3779 raise util.Abort(_('remote bookmark %s not found!') % b)
3780 3780 revs.append(rb[b])
3781 3781
3782 3782 if revs:
3783 3783 try:
3784 3784 revs = [other.lookup(rev) for rev in revs]
3785 3785 except error.CapabilityError:
3786 3786 err = _("other repository doesn't support revision lookup, "
3787 3787 "so a rev cannot be specified.")
3788 3788 raise util.Abort(err)
3789 3789
3790 3790 modheads = repo.pull(other, heads=revs, force=opts.get('force'))
3791 3791 bookmarks.updatefromremote(ui, repo, other)
3792 3792 if checkout:
3793 3793 checkout = str(repo.changelog.rev(other.lookup(checkout)))
3794 3794 repo._subtoppath = source
3795 3795 try:
3796 3796 ret = postincoming(ui, repo, modheads, opts.get('update'), checkout)
3797 3797
3798 3798 finally:
3799 3799 del repo._subtoppath
3800 3800
3801 3801 # update specified bookmarks
3802 3802 if opts.get('bookmark'):
3803 3803 for b in opts['bookmark']:
3804 3804 # explicit pull overrides local bookmark if any
3805 3805 ui.status(_("importing bookmark %s\n") % b)
3806 3806 repo._bookmarks[b] = repo[rb[b]].node()
3807 3807 bookmarks.write(repo)
3808 3808
3809 3809 return ret
3810 3810
3811 3811 @command('^push',
3812 3812 [('f', 'force', None, _('force push')),
3813 3813 ('r', 'rev', [],
3814 3814 _('a changeset intended to be included in the destination'),
3815 3815 _('REV')),
3816 3816 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
3817 3817 ('b', 'branch', [],
3818 3818 _('a specific branch you would like to push'), _('BRANCH')),
3819 3819 ('', 'new-branch', False, _('allow pushing a new branch')),
3820 3820 ] + remoteopts,
3821 3821 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'))
3822 3822 def push(ui, repo, dest=None, **opts):
3823 3823 """push changes to the specified destination
3824 3824
3825 3825 Push changesets from the local repository to the specified
3826 3826 destination.
3827 3827
3828 3828 This operation is symmetrical to pull: it is identical to a pull
3829 3829 in the destination repository from the current one.
3830 3830
3831 3831 By default, push will not allow creation of new heads at the
3832 3832 destination, since multiple heads would make it unclear which head
3833 3833 to use. In this situation, it is recommended to pull and merge
3834 3834 before pushing.
3835 3835
3836 3836 Use --new-branch if you want to allow push to create a new named
3837 3837 branch that is not present at the destination. This allows you to
3838 3838 only create a new branch without forcing other changes.
3839 3839
3840 3840 Use -f/--force to override the default behavior and push all
3841 3841 changesets on all branches.
3842 3842
3843 3843 If -r/--rev is used, the specified revision and all its ancestors
3844 3844 will be pushed to the remote repository.
3845 3845
3846 3846 Please see :hg:`help urls` for important details about ``ssh://``
3847 3847 URLs. If DESTINATION is omitted, a default path will be used.
3848 3848
3849 3849 Returns 0 if push was successful, 1 if nothing to push.
3850 3850 """
3851 3851
3852 3852 if opts.get('bookmark'):
3853 3853 for b in opts['bookmark']:
3854 3854 # translate -B options to -r so changesets get pushed
3855 3855 if b in repo._bookmarks:
3856 3856 opts.setdefault('rev', []).append(b)
3857 3857 else:
3858 3858 # if we try to push a deleted bookmark, translate it to null
3859 3859 # this lets simultaneous -r, -b options continue working
3860 3860 opts.setdefault('rev', []).append("null")
3861 3861
3862 3862 dest = ui.expandpath(dest or 'default-push', dest or 'default')
3863 3863 dest, branches = hg.parseurl(dest, opts.get('branch'))
3864 3864 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
3865 3865 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
3866 3866 other = hg.peer(repo, opts, dest)
3867 3867 if revs:
3868 3868 revs = [repo.lookup(rev) for rev in revs]
3869 3869
3870 3870 repo._subtoppath = dest
3871 3871 try:
3872 3872 # push subrepos depth-first for coherent ordering
3873 3873 c = repo['']
3874 3874 subs = c.substate # only repos that are committed
3875 3875 for s in sorted(subs):
3876 3876 if not c.sub(s).push(opts.get('force')):
3877 3877 return False
3878 3878 finally:
3879 3879 del repo._subtoppath
3880 3880 result = repo.push(other, opts.get('force'), revs=revs,
3881 3881 newbranch=opts.get('new_branch'))
3882 3882
3883 3883 result = (result == 0)
3884 3884
3885 3885 if opts.get('bookmark'):
3886 3886 rb = other.listkeys('bookmarks')
3887 3887 for b in opts['bookmark']:
3888 3888 # explicit push overrides remote bookmark if any
3889 3889 if b in repo._bookmarks:
3890 3890 ui.status(_("exporting bookmark %s\n") % b)
3891 3891 new = repo[b].hex()
3892 3892 elif b in rb:
3893 3893 ui.status(_("deleting remote bookmark %s\n") % b)
3894 3894 new = '' # delete
3895 3895 else:
3896 3896 ui.warn(_('bookmark %s does not exist on the local '
3897 3897 'or remote repository!\n') % b)
3898 3898 return 2
3899 3899 old = rb.get(b, '')
3900 3900 r = other.pushkey('bookmarks', b, old, new)
3901 3901 if not r:
3902 3902 ui.warn(_('updating bookmark %s failed!\n') % b)
3903 3903 if not result:
3904 3904 result = 2
3905 3905
3906 3906 return result
3907 3907
3908 3908 @command('recover', [])
3909 3909 def recover(ui, repo):
3910 3910 """roll back an interrupted transaction
3911 3911
3912 3912 Recover from an interrupted commit or pull.
3913 3913
3914 3914 This command tries to fix the repository status after an
3915 3915 interrupted operation. It should only be necessary when Mercurial
3916 3916 suggests it.
3917 3917
3918 3918 Returns 0 if successful, 1 if nothing to recover or verify fails.
3919 3919 """
3920 3920 if repo.recover():
3921 3921 return hg.verify(repo)
3922 3922 return 1
3923 3923
3924 3924 @command('^remove|rm',
3925 3925 [('A', 'after', None, _('record delete for missing files')),
3926 3926 ('f', 'force', None,
3927 3927 _('remove (and delete) file even if added or modified')),
3928 3928 ] + walkopts,
3929 3929 _('[OPTION]... FILE...'))
3930 3930 def remove(ui, repo, *pats, **opts):
3931 3931 """remove the specified files on the next commit
3932 3932
3933 3933 Schedule the indicated files for removal from the repository.
3934 3934
3935 3935 This only removes files from the current branch, not from the
3936 3936 entire project history. -A/--after can be used to remove only
3937 3937 files that have already been deleted, -f/--force can be used to
3938 3938 force deletion, and -Af can be used to remove files from the next
3939 3939 revision without deleting them from the working directory.
3940 3940
3941 3941 The following table details the behavior of remove for different
3942 3942 file states (columns) and option combinations (rows). The file
3943 3943 states are Added [A], Clean [C], Modified [M] and Missing [!] (as
3944 3944 reported by :hg:`status`). The actions are Warn, Remove (from
3945 3945 branch) and Delete (from disk)::
3946 3946
3947 3947 A C M !
3948 3948 none W RD W R
3949 3949 -f R RD RD R
3950 3950 -A W W W R
3951 3951 -Af R R R R
3952 3952
3953 3953 Note that remove never deletes files in Added [A] state from the
3954 3954 working directory, not even if option --force is specified.
3955 3955
3956 3956 This command schedules the files to be removed at the next commit.
3957 3957 To undo a remove before that, see :hg:`revert`.
3958 3958
3959 3959 Returns 0 on success, 1 if any warnings encountered.
3960 3960 """
3961 3961
3962 3962 ret = 0
3963 3963 after, force = opts.get('after'), opts.get('force')
3964 3964 if not pats and not after:
3965 3965 raise util.Abort(_('no files specified'))
3966 3966
3967 3967 m = scmutil.match(repo, pats, opts)
3968 3968 s = repo.status(match=m, clean=True)
3969 3969 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
3970 3970
3971 3971 for f in m.files():
3972 3972 if f not in repo.dirstate and not os.path.isdir(m.rel(f)):
3973 3973 if os.path.exists(m.rel(f)):
3974 3974 ui.warn(_('not removing %s: file is untracked\n') % m.rel(f))
3975 3975 ret = 1
3976 3976
3977 3977 if force:
3978 3978 list = modified + deleted + clean + added
3979 3979 elif after:
3980 3980 list = deleted
3981 3981 for f in modified + added + clean:
3982 3982 ui.warn(_('not removing %s: file still exists (use -f'
3983 3983 ' to force removal)\n') % m.rel(f))
3984 3984 ret = 1
3985 3985 else:
3986 3986 list = deleted + clean
3987 3987 for f in modified:
3988 3988 ui.warn(_('not removing %s: file is modified (use -f'
3989 3989 ' to force removal)\n') % m.rel(f))
3990 3990 ret = 1
3991 3991 for f in added:
3992 3992 ui.warn(_('not removing %s: file has been marked for add (use -f'
3993 3993 ' to force removal)\n') % m.rel(f))
3994 3994 ret = 1
3995 3995
3996 3996 for f in sorted(list):
3997 3997 if ui.verbose or not m.exact(f):
3998 3998 ui.status(_('removing %s\n') % m.rel(f))
3999 3999
4000 4000 wlock = repo.wlock()
4001 4001 try:
4002 4002 if not after:
4003 4003 for f in list:
4004 4004 if f in added:
4005 4005 continue # we never unlink added files on remove
4006 4006 try:
4007 4007 util.unlinkpath(repo.wjoin(f))
4008 4008 except OSError, inst:
4009 4009 if inst.errno != errno.ENOENT:
4010 4010 raise
4011 4011 repo[None].forget(list)
4012 4012 finally:
4013 4013 wlock.release()
4014 4014
4015 4015 return ret
4016 4016
4017 4017 @command('rename|move|mv',
4018 4018 [('A', 'after', None, _('record a rename that has already occurred')),
4019 4019 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4020 4020 ] + walkopts + dryrunopts,
4021 4021 _('[OPTION]... SOURCE... DEST'))
4022 4022 def rename(ui, repo, *pats, **opts):
4023 4023 """rename files; equivalent of copy + remove
4024 4024
4025 4025 Mark dest as copies of sources; mark sources for deletion. If dest
4026 4026 is a directory, copies are put in that directory. If dest is a
4027 4027 file, there can only be one source.
4028 4028
4029 4029 By default, this command copies the contents of files as they
4030 4030 exist in the working directory. If invoked with -A/--after, the
4031 4031 operation is recorded, but no copying is performed.
4032 4032
4033 4033 This command takes effect at the next commit. To undo a rename
4034 4034 before that, see :hg:`revert`.
4035 4035
4036 4036 Returns 0 on success, 1 if errors are encountered.
4037 4037 """
4038 4038 wlock = repo.wlock(False)
4039 4039 try:
4040 4040 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4041 4041 finally:
4042 4042 wlock.release()
4043 4043
4044 4044 @command('resolve',
4045 4045 [('a', 'all', None, _('select all unresolved files')),
4046 4046 ('l', 'list', None, _('list state of files needing merge')),
4047 4047 ('m', 'mark', None, _('mark files as resolved')),
4048 4048 ('u', 'unmark', None, _('mark files as unresolved')),
4049 4049 ('t', 'tool', '', _('specify merge tool')),
4050 4050 ('n', 'no-status', None, _('hide status prefix'))]
4051 4051 + walkopts,
4052 4052 _('[OPTION]... [FILE]...'))
4053 4053 def resolve(ui, repo, *pats, **opts):
4054 4054 """redo merges or set/view the merge status of files
4055 4055
4056 4056 Merges with unresolved conflicts are often the result of
4057 4057 non-interactive merging using the ``internal:merge`` configuration
4058 4058 setting, or a command-line merge tool like ``diff3``. The resolve
4059 4059 command is used to manage the files involved in a merge, after
4060 4060 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4061 4061 working directory must have two parents).
4062 4062
4063 4063 The resolve command can be used in the following ways:
4064 4064
4065 4065 - :hg:`resolve [--tool TOOL] FILE...`: attempt to re-merge the specified
4066 4066 files, discarding any previous merge attempts. Re-merging is not
4067 4067 performed for files already marked as resolved. Use ``--all/-a``
4068 4068 to selects all unresolved files. ``--tool`` can be used to specify
4069 4069 the merge tool used for the given files. It overrides the HGMERGE
4070 4070 environment variable and your configuration files.
4071 4071
4072 4072 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4073 4073 (e.g. after having manually fixed-up the files). The default is
4074 4074 to mark all unresolved files.
4075 4075
4076 4076 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4077 4077 default is to mark all resolved files.
4078 4078
4079 4079 - :hg:`resolve -l`: list files which had or still have conflicts.
4080 4080 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4081 4081
4082 4082 Note that Mercurial will not let you commit files with unresolved
4083 4083 merge conflicts. You must use :hg:`resolve -m ...` before you can
4084 4084 commit after a conflicting merge.
4085 4085
4086 4086 Returns 0 on success, 1 if any files fail a resolve attempt.
4087 4087 """
4088 4088
4089 4089 all, mark, unmark, show, nostatus = \
4090 4090 [opts.get(o) for o in 'all mark unmark list no_status'.split()]
4091 4091
4092 4092 if (show and (mark or unmark)) or (mark and unmark):
4093 4093 raise util.Abort(_("too many options specified"))
4094 4094 if pats and all:
4095 4095 raise util.Abort(_("can't specify --all and patterns"))
4096 4096 if not (all or pats or show or mark or unmark):
4097 4097 raise util.Abort(_('no files or directories specified; '
4098 4098 'use --all to remerge all files'))
4099 4099
4100 4100 ms = mergemod.mergestate(repo)
4101 4101 m = scmutil.match(repo, pats, opts)
4102 4102 ret = 0
4103 4103
4104 4104 for f in ms:
4105 4105 if m(f):
4106 4106 if show:
4107 4107 if nostatus:
4108 4108 ui.write("%s\n" % f)
4109 4109 else:
4110 4110 ui.write("%s %s\n" % (ms[f].upper(), f),
4111 4111 label='resolve.' +
4112 4112 {'u': 'unresolved', 'r': 'resolved'}[ms[f]])
4113 4113 elif mark:
4114 4114 ms.mark(f, "r")
4115 4115 elif unmark:
4116 4116 ms.mark(f, "u")
4117 4117 else:
4118 4118 wctx = repo[None]
4119 4119 mctx = wctx.parents()[-1]
4120 4120
4121 4121 # backup pre-resolve (merge uses .orig for its own purposes)
4122 4122 a = repo.wjoin(f)
4123 4123 util.copyfile(a, a + ".resolve")
4124 4124
4125 4125 try:
4126 4126 # resolve file
4127 4127 ui.setconfig('ui', 'forcemerge', opts.get('tool', ''))
4128 4128 if ms.resolve(f, wctx, mctx):
4129 4129 ret = 1
4130 4130 finally:
4131 4131 ui.setconfig('ui', 'forcemerge', '')
4132 4132
4133 4133 # replace filemerge's .orig file with our resolve file
4134 4134 util.rename(a + ".resolve", a + ".orig")
4135 4135
4136 4136 ms.commit()
4137 4137 return ret
4138 4138
4139 4139 @command('revert',
4140 4140 [('a', 'all', None, _('revert all changes when no arguments given')),
4141 4141 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
4142 4142 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
4143 4143 ('', 'no-backup', None, _('do not save backup copies of files')),
4144 4144 ] + walkopts + dryrunopts,
4145 4145 _('[OPTION]... [-r REV] [NAME]...'))
4146 4146 def revert(ui, repo, *pats, **opts):
4147 4147 """restore files to their checkout state
4148 4148
4149 4149 .. note::
4150 4150 To check out earlier revisions, you should use :hg:`update REV`.
4151 4151 To cancel a merge (and lose your changes), use :hg:`update --clean .`.
4152 4152
4153 4153 With no revision specified, revert the specified files or directories
4154 4154 to the state they had in the first parent of the working directory.
4155 4155 This restores the contents of files to an unmodified
4156 4156 state and unschedules adds, removes, copies, and renames.
4157 4157
4158 4158 Using the -r/--rev or -d/--date options, revert the given files or
4159 4159 directories to their states as of a specific revision. Because
4160 4160 revert does not change the working directory parents, this will
4161 4161 cause these files to appear modified. This can be helpful to "back
4162 4162 out" some or all of an earlier change. See :hg:`backout` for a
4163 4163 related method.
4164 4164
4165 4165 Modified files are saved with a .orig suffix before reverting.
4166 4166 To disable these backups, use --no-backup.
4167 4167
4168 4168 See :hg:`help dates` for a list of formats valid for -d/--date.
4169 4169
4170 4170 Returns 0 on success.
4171 4171 """
4172 4172
4173 4173 if opts.get("date"):
4174 4174 if opts.get("rev"):
4175 4175 raise util.Abort(_("you can't specify a revision and a date"))
4176 4176 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
4177 4177
4178 4178 parent, p2 = repo.dirstate.parents()
4179 4179
4180 4180 if not pats and not opts.get('all'):
4181 4181 raise util.Abort(_('no files or directories specified'),
4182 4182 hint=_('use --all to revert all files'))
4183 4183
4184 4184 ctx = scmutil.revsingle(repo, opts.get('rev'))
4185 4185 node = ctx.node()
4186 4186 mf = ctx.manifest()
4187 4187 if node == parent:
4188 4188 pmf = mf
4189 4189 else:
4190 4190 pmf = None
4191 4191
4192 4192 # need all matching names in dirstate and manifest of target rev,
4193 4193 # so have to walk both. do not print errors if files exist in one
4194 4194 # but not other.
4195 4195
4196 4196 names = {}
4197 4197
4198 4198 wlock = repo.wlock()
4199 4199 try:
4200 4200 # walk dirstate.
4201 4201
4202 4202 m = scmutil.match(repo, pats, opts)
4203 4203 m.bad = lambda x, y: False
4204 4204 for abs in repo.walk(m):
4205 4205 names[abs] = m.rel(abs), m.exact(abs)
4206 4206
4207 4207 # walk target manifest.
4208 4208
4209 4209 def badfn(path, msg):
4210 4210 if path in names:
4211 4211 return
4212 4212 path_ = path + '/'
4213 4213 for f in names:
4214 4214 if f.startswith(path_):
4215 4215 return
4216 4216 ui.warn("%s: %s\n" % (m.rel(path), msg))
4217 4217
4218 4218 m = scmutil.match(repo, pats, opts)
4219 4219 m.bad = badfn
4220 4220 for abs in repo[node].walk(m):
4221 4221 if abs not in names:
4222 4222 names[abs] = m.rel(abs), m.exact(abs)
4223 4223
4224 4224 m = scmutil.matchfiles(repo, names)
4225 4225 changes = repo.status(match=m)[:4]
4226 4226 modified, added, removed, deleted = map(set, changes)
4227 4227
4228 4228 # if f is a rename, also revert the source
4229 4229 cwd = repo.getcwd()
4230 4230 for f in added:
4231 4231 src = repo.dirstate.copied(f)
4232 4232 if src and src not in names and repo.dirstate[src] == 'r':
4233 4233 removed.add(src)
4234 4234 names[src] = (repo.pathto(src, cwd), True)
4235 4235
4236 4236 def removeforget(abs):
4237 4237 if repo.dirstate[abs] == 'a':
4238 4238 return _('forgetting %s\n')
4239 4239 return _('removing %s\n')
4240 4240
4241 4241 revert = ([], _('reverting %s\n'))
4242 4242 add = ([], _('adding %s\n'))
4243 4243 remove = ([], removeforget)
4244 4244 undelete = ([], _('undeleting %s\n'))
4245 4245
4246 4246 disptable = (
4247 4247 # dispatch table:
4248 4248 # file state
4249 4249 # action if in target manifest
4250 4250 # action if not in target manifest
4251 4251 # make backup if in target manifest
4252 4252 # make backup if not in target manifest
4253 4253 (modified, revert, remove, True, True),
4254 4254 (added, revert, remove, True, False),
4255 4255 (removed, undelete, None, False, False),
4256 4256 (deleted, revert, remove, False, False),
4257 4257 )
4258 4258
4259 4259 for abs, (rel, exact) in sorted(names.items()):
4260 4260 mfentry = mf.get(abs)
4261 4261 target = repo.wjoin(abs)
4262 4262 def handle(xlist, dobackup):
4263 4263 xlist[0].append(abs)
4264 4264 if (dobackup and not opts.get('no_backup') and
4265 4265 os.path.lexists(target)):
4266 4266 bakname = "%s.orig" % rel
4267 4267 ui.note(_('saving current version of %s as %s\n') %
4268 4268 (rel, bakname))
4269 4269 if not opts.get('dry_run'):
4270 4270 util.rename(target, bakname)
4271 4271 if ui.verbose or not exact:
4272 4272 msg = xlist[1]
4273 4273 if not isinstance(msg, basestring):
4274 4274 msg = msg(abs)
4275 4275 ui.status(msg % rel)
4276 4276 for table, hitlist, misslist, backuphit, backupmiss in disptable:
4277 4277 if abs not in table:
4278 4278 continue
4279 4279 # file has changed in dirstate
4280 4280 if mfentry:
4281 4281 handle(hitlist, backuphit)
4282 4282 elif misslist is not None:
4283 4283 handle(misslist, backupmiss)
4284 4284 break
4285 4285 else:
4286 4286 if abs not in repo.dirstate:
4287 4287 if mfentry:
4288 4288 handle(add, True)
4289 4289 elif exact:
4290 4290 ui.warn(_('file not managed: %s\n') % rel)
4291 4291 continue
4292 4292 # file has not changed in dirstate
4293 4293 if node == parent:
4294 4294 if exact:
4295 4295 ui.warn(_('no changes needed to %s\n') % rel)
4296 4296 continue
4297 4297 if pmf is None:
4298 4298 # only need parent manifest in this unlikely case,
4299 4299 # so do not read by default
4300 4300 pmf = repo[parent].manifest()
4301 4301 if abs in pmf:
4302 4302 if mfentry:
4303 4303 # if version of file is same in parent and target
4304 4304 # manifests, do nothing
4305 4305 if (pmf[abs] != mfentry or
4306 4306 pmf.flags(abs) != mf.flags(abs)):
4307 4307 handle(revert, False)
4308 4308 else:
4309 4309 handle(remove, False)
4310 4310
4311 4311 if not opts.get('dry_run'):
4312 4312 def checkout(f):
4313 4313 fc = ctx[f]
4314 4314 repo.wwrite(f, fc.data(), fc.flags())
4315 4315
4316 4316 audit_path = scmutil.pathauditor(repo.root)
4317 4317 for f in remove[0]:
4318 4318 if repo.dirstate[f] == 'a':
4319 4319 repo.dirstate.drop(f)
4320 4320 continue
4321 4321 audit_path(f)
4322 4322 try:
4323 4323 util.unlinkpath(repo.wjoin(f))
4324 4324 except OSError:
4325 4325 pass
4326 4326 repo.dirstate.remove(f)
4327 4327
4328 4328 normal = None
4329 4329 if node == parent:
4330 4330 # We're reverting to our parent. If possible, we'd like status
4331 4331 # to report the file as clean. We have to use normallookup for
4332 4332 # merges to avoid losing information about merged/dirty files.
4333 4333 if p2 != nullid:
4334 4334 normal = repo.dirstate.normallookup
4335 4335 else:
4336 4336 normal = repo.dirstate.normal
4337 4337 for f in revert[0]:
4338 4338 checkout(f)
4339 4339 if normal:
4340 4340 normal(f)
4341 4341
4342 4342 for f in add[0]:
4343 4343 checkout(f)
4344 4344 repo.dirstate.add(f)
4345 4345
4346 4346 normal = repo.dirstate.normallookup
4347 4347 if node == parent and p2 == nullid:
4348 4348 normal = repo.dirstate.normal
4349 4349 for f in undelete[0]:
4350 4350 checkout(f)
4351 4351 normal(f)
4352 4352
4353 4353 finally:
4354 4354 wlock.release()
4355 4355
4356 4356 @command('rollback', dryrunopts)
4357 4357 def rollback(ui, repo, **opts):
4358 4358 """roll back the last transaction (dangerous)
4359 4359
4360 4360 This command should be used with care. There is only one level of
4361 4361 rollback, and there is no way to undo a rollback. It will also
4362 4362 restore the dirstate at the time of the last transaction, losing
4363 4363 any dirstate changes since that time. This command does not alter
4364 4364 the working directory.
4365 4365
4366 4366 Transactions are used to encapsulate the effects of all commands
4367 4367 that create new changesets or propagate existing changesets into a
4368 4368 repository. For example, the following commands are transactional,
4369 4369 and their effects can be rolled back:
4370 4370
4371 4371 - commit
4372 4372 - import
4373 4373 - pull
4374 4374 - push (with this repository as the destination)
4375 4375 - unbundle
4376 4376
4377 4377 This command is not intended for use on public repositories. Once
4378 4378 changes are visible for pull by other users, rolling a transaction
4379 4379 back locally is ineffective (someone else may already have pulled
4380 4380 the changes). Furthermore, a race is possible with readers of the
4381 4381 repository; for example an in-progress pull from the repository
4382 4382 may fail if a rollback is performed.
4383 4383
4384 4384 Returns 0 on success, 1 if no rollback data is available.
4385 4385 """
4386 4386 return repo.rollback(opts.get('dry_run'))
4387 4387
4388 4388 @command('root', [])
4389 4389 def root(ui, repo):
4390 4390 """print the root (top) of the current working directory
4391 4391
4392 4392 Print the root directory of the current repository.
4393 4393
4394 4394 Returns 0 on success.
4395 4395 """
4396 4396 ui.write(repo.root + "\n")
4397 4397
4398 4398 @command('^serve',
4399 4399 [('A', 'accesslog', '', _('name of access log file to write to'),
4400 4400 _('FILE')),
4401 4401 ('d', 'daemon', None, _('run server in background')),
4402 4402 ('', 'daemon-pipefds', '', _('used internally by daemon mode'), _('NUM')),
4403 4403 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
4404 4404 # use string type, then we can check if something was passed
4405 4405 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
4406 4406 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
4407 4407 _('ADDR')),
4408 4408 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
4409 4409 _('PREFIX')),
4410 4410 ('n', 'name', '',
4411 4411 _('name to show in web pages (default: working directory)'), _('NAME')),
4412 4412 ('', 'web-conf', '',
4413 4413 _('name of the hgweb config file (see "hg help hgweb")'), _('FILE')),
4414 4414 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
4415 4415 _('FILE')),
4416 4416 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
4417 4417 ('', 'stdio', None, _('for remote clients')),
4418 4418 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
4419 4419 ('', 'style', '', _('template style to use'), _('STYLE')),
4420 4420 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
4421 4421 ('', 'certificate', '', _('SSL certificate file'), _('FILE'))],
4422 4422 _('[OPTION]...'))
4423 4423 def serve(ui, repo, **opts):
4424 4424 """start stand-alone webserver
4425 4425
4426 4426 Start a local HTTP repository browser and pull server. You can use
4427 4427 this for ad-hoc sharing and browsing of repositories. It is
4428 4428 recommended to use a real web server to serve a repository for
4429 4429 longer periods of time.
4430 4430
4431 4431 Please note that the server does not implement access control.
4432 4432 This means that, by default, anybody can read from the server and
4433 4433 nobody can write to it by default. Set the ``web.allow_push``
4434 4434 option to ``*`` to allow everybody to push to the server. You
4435 4435 should use a real web server if you need to authenticate users.
4436 4436
4437 4437 By default, the server logs accesses to stdout and errors to
4438 4438 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
4439 4439 files.
4440 4440
4441 4441 To have the server choose a free port number to listen on, specify
4442 4442 a port number of 0; in this case, the server will print the port
4443 4443 number it uses.
4444 4444
4445 4445 Returns 0 on success.
4446 4446 """
4447 4447
4448 4448 if opts["stdio"]:
4449 4449 if repo is None:
4450 4450 raise error.RepoError(_("There is no Mercurial repository here"
4451 4451 " (.hg not found)"))
4452 4452 s = sshserver.sshserver(ui, repo)
4453 4453 s.serve_forever()
4454 4454
4455 4455 # this way we can check if something was given in the command-line
4456 4456 if opts.get('port'):
4457 4457 opts['port'] = util.getport(opts.get('port'))
4458 4458
4459 4459 baseui = repo and repo.baseui or ui
4460 4460 optlist = ("name templates style address port prefix ipv6"
4461 4461 " accesslog errorlog certificate encoding")
4462 4462 for o in optlist.split():
4463 4463 val = opts.get(o, '')
4464 4464 if val in (None, ''): # should check against default options instead
4465 4465 continue
4466 4466 baseui.setconfig("web", o, val)
4467 4467 if repo and repo.ui != baseui:
4468 4468 repo.ui.setconfig("web", o, val)
4469 4469
4470 4470 o = opts.get('web_conf') or opts.get('webdir_conf')
4471 4471 if not o:
4472 4472 if not repo:
4473 4473 raise error.RepoError(_("There is no Mercurial repository"
4474 4474 " here (.hg not found)"))
4475 4475 o = repo.root
4476 4476
4477 4477 app = hgweb.hgweb(o, baseui=ui)
4478 4478
4479 4479 class service(object):
4480 4480 def init(self):
4481 4481 util.setsignalhandler()
4482 4482 self.httpd = hgweb.server.create_server(ui, app)
4483 4483
4484 4484 if opts['port'] and not ui.verbose:
4485 4485 return
4486 4486
4487 4487 if self.httpd.prefix:
4488 4488 prefix = self.httpd.prefix.strip('/') + '/'
4489 4489 else:
4490 4490 prefix = ''
4491 4491
4492 4492 port = ':%d' % self.httpd.port
4493 4493 if port == ':80':
4494 4494 port = ''
4495 4495
4496 4496 bindaddr = self.httpd.addr
4497 4497 if bindaddr == '0.0.0.0':
4498 4498 bindaddr = '*'
4499 4499 elif ':' in bindaddr: # IPv6
4500 4500 bindaddr = '[%s]' % bindaddr
4501 4501
4502 4502 fqaddr = self.httpd.fqaddr
4503 4503 if ':' in fqaddr:
4504 4504 fqaddr = '[%s]' % fqaddr
4505 4505 if opts['port']:
4506 4506 write = ui.status
4507 4507 else:
4508 4508 write = ui.write
4509 4509 write(_('listening at http://%s%s/%s (bound to %s:%d)\n') %
4510 4510 (fqaddr, port, prefix, bindaddr, self.httpd.port))
4511 4511
4512 4512 def run(self):
4513 4513 self.httpd.serve_forever()
4514 4514
4515 4515 service = service()
4516 4516
4517 4517 cmdutil.service(opts, initfn=service.init, runfn=service.run)
4518 4518
4519 4519 @command('showconfig|debugconfig',
4520 4520 [('u', 'untrusted', None, _('show untrusted configuration options'))],
4521 4521 _('[-u] [NAME]...'))
4522 4522 def showconfig(ui, repo, *values, **opts):
4523 4523 """show combined config settings from all hgrc files
4524 4524
4525 4525 With no arguments, print names and values of all config items.
4526 4526
4527 4527 With one argument of the form section.name, print just the value
4528 4528 of that config item.
4529 4529
4530 4530 With multiple arguments, print names and values of all config
4531 4531 items with matching section names.
4532 4532
4533 4533 With --debug, the source (filename and line number) is printed
4534 4534 for each config item.
4535 4535
4536 4536 Returns 0 on success.
4537 4537 """
4538 4538
4539 4539 for f in scmutil.rcpath():
4540 4540 ui.debug(_('read config from: %s\n') % f)
4541 4541 untrusted = bool(opts.get('untrusted'))
4542 4542 if values:
4543 4543 sections = [v for v in values if '.' not in v]
4544 4544 items = [v for v in values if '.' in v]
4545 4545 if len(items) > 1 or items and sections:
4546 4546 raise util.Abort(_('only one config item permitted'))
4547 4547 for section, name, value in ui.walkconfig(untrusted=untrusted):
4548 4548 value = str(value).replace('\n', '\\n')
4549 4549 sectname = section + '.' + name
4550 4550 if values:
4551 4551 for v in values:
4552 4552 if v == section:
4553 4553 ui.debug('%s: ' %
4554 4554 ui.configsource(section, name, untrusted))
4555 4555 ui.write('%s=%s\n' % (sectname, value))
4556 4556 elif v == sectname:
4557 4557 ui.debug('%s: ' %
4558 4558 ui.configsource(section, name, untrusted))
4559 4559 ui.write(value, '\n')
4560 4560 else:
4561 4561 ui.debug('%s: ' %
4562 4562 ui.configsource(section, name, untrusted))
4563 4563 ui.write('%s=%s\n' % (sectname, value))
4564 4564
4565 4565 @command('^status|st',
4566 4566 [('A', 'all', None, _('show status of all files')),
4567 4567 ('m', 'modified', None, _('show only modified files')),
4568 4568 ('a', 'added', None, _('show only added files')),
4569 4569 ('r', 'removed', None, _('show only removed files')),
4570 4570 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
4571 4571 ('c', 'clean', None, _('show only files without changes')),
4572 4572 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
4573 4573 ('i', 'ignored', None, _('show only ignored files')),
4574 4574 ('n', 'no-status', None, _('hide status prefix')),
4575 4575 ('C', 'copies', None, _('show source of copied files')),
4576 4576 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
4577 4577 ('', 'rev', [], _('show difference from revision'), _('REV')),
4578 4578 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
4579 4579 ] + walkopts + subrepoopts,
4580 4580 _('[OPTION]... [FILE]...'))
4581 4581 def status(ui, repo, *pats, **opts):
4582 4582 """show changed files in the working directory
4583 4583
4584 4584 Show status of files in the repository. If names are given, only
4585 4585 files that match are shown. Files that are clean or ignored or
4586 4586 the source of a copy/move operation, are not listed unless
4587 4587 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
4588 4588 Unless options described with "show only ..." are given, the
4589 4589 options -mardu are used.
4590 4590
4591 4591 Option -q/--quiet hides untracked (unknown and ignored) files
4592 4592 unless explicitly requested with -u/--unknown or -i/--ignored.
4593 4593
4594 4594 .. note::
4595 4595 status may appear to disagree with diff if permissions have
4596 4596 changed or a merge has occurred. The standard diff format does
4597 4597 not report permission changes and diff only reports changes
4598 4598 relative to one merge parent.
4599 4599
4600 4600 If one revision is given, it is used as the base revision.
4601 4601 If two revisions are given, the differences between them are
4602 4602 shown. The --change option can also be used as a shortcut to list
4603 4603 the changed files of a revision from its first parent.
4604 4604
4605 4605 The codes used to show the status of files are::
4606 4606
4607 4607 M = modified
4608 4608 A = added
4609 4609 R = removed
4610 4610 C = clean
4611 4611 ! = missing (deleted by non-hg command, but still tracked)
4612 4612 ? = not tracked
4613 4613 I = ignored
4614 4614 = origin of the previous file listed as A (added)
4615 4615
4616 4616 Returns 0 on success.
4617 4617 """
4618 4618
4619 4619 revs = opts.get('rev')
4620 4620 change = opts.get('change')
4621 4621
4622 4622 if revs and change:
4623 4623 msg = _('cannot specify --rev and --change at the same time')
4624 4624 raise util.Abort(msg)
4625 4625 elif change:
4626 4626 node2 = repo.lookup(change)
4627 4627 node1 = repo[node2].p1().node()
4628 4628 else:
4629 4629 node1, node2 = scmutil.revpair(repo, revs)
4630 4630
4631 4631 cwd = (pats and repo.getcwd()) or ''
4632 4632 end = opts.get('print0') and '\0' or '\n'
4633 4633 copy = {}
4634 4634 states = 'modified added removed deleted unknown ignored clean'.split()
4635 4635 show = [k for k in states if opts.get(k)]
4636 4636 if opts.get('all'):
4637 4637 show += ui.quiet and (states[:4] + ['clean']) or states
4638 4638 if not show:
4639 4639 show = ui.quiet and states[:4] or states[:5]
4640 4640
4641 4641 stat = repo.status(node1, node2, scmutil.match(repo, pats, opts),
4642 4642 'ignored' in show, 'clean' in show, 'unknown' in show,
4643 4643 opts.get('subrepos'))
4644 4644 changestates = zip(states, 'MAR!?IC', stat)
4645 4645
4646 4646 if (opts.get('all') or opts.get('copies')) and not opts.get('no_status'):
4647 4647 ctxn = repo[nullid]
4648 4648 ctx1 = repo[node1]
4649 4649 ctx2 = repo[node2]
4650 4650 added = stat[1]
4651 4651 if node2 is None:
4652 4652 added = stat[0] + stat[1] # merged?
4653 4653
4654 4654 for k, v in copies.copies(repo, ctx1, ctx2, ctxn)[0].iteritems():
4655 4655 if k in added:
4656 4656 copy[k] = v
4657 4657 elif v in added:
4658 4658 copy[v] = k
4659 4659
4660 4660 for state, char, files in changestates:
4661 4661 if state in show:
4662 4662 format = "%s %%s%s" % (char, end)
4663 4663 if opts.get('no_status'):
4664 4664 format = "%%s%s" % end
4665 4665
4666 4666 for f in files:
4667 4667 ui.write(format % repo.pathto(f, cwd),
4668 4668 label='status.' + state)
4669 4669 if f in copy:
4670 4670 ui.write(' %s%s' % (repo.pathto(copy[f], cwd), end),
4671 4671 label='status.copied')
4672 4672
4673 4673 @command('^summary|sum',
4674 4674 [('', 'remote', None, _('check for push and pull'))], '[--remote]')
4675 4675 def summary(ui, repo, **opts):
4676 4676 """summarize working directory state
4677 4677
4678 4678 This generates a brief summary of the working directory state,
4679 4679 including parents, branch, commit status, and available updates.
4680 4680
4681 4681 With the --remote option, this will check the default paths for
4682 4682 incoming and outgoing changes. This can be time-consuming.
4683 4683
4684 4684 Returns 0 on success.
4685 4685 """
4686 4686
4687 4687 ctx = repo[None]
4688 4688 parents = ctx.parents()
4689 4689 pnode = parents[0].node()
4690 4690
4691 4691 for p in parents:
4692 4692 # label with log.changeset (instead of log.parent) since this
4693 4693 # shows a working directory parent *changeset*:
4694 4694 ui.write(_('parent: %d:%s ') % (p.rev(), str(p)),
4695 4695 label='log.changeset')
4696 4696 ui.write(' '.join(p.tags()), label='log.tag')
4697 4697 if p.bookmarks():
4698 4698 ui.write(' ' + ' '.join(p.bookmarks()), label='log.bookmark')
4699 4699 if p.rev() == -1:
4700 4700 if not len(repo):
4701 4701 ui.write(_(' (empty repository)'))
4702 4702 else:
4703 4703 ui.write(_(' (no revision checked out)'))
4704 4704 ui.write('\n')
4705 4705 if p.description():
4706 4706 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
4707 4707 label='log.summary')
4708 4708
4709 4709 branch = ctx.branch()
4710 4710 bheads = repo.branchheads(branch)
4711 4711 m = _('branch: %s\n') % branch
4712 4712 if branch != 'default':
4713 4713 ui.write(m, label='log.branch')
4714 4714 else:
4715 4715 ui.status(m, label='log.branch')
4716 4716
4717 4717 st = list(repo.status(unknown=True))[:6]
4718 4718
4719 4719 c = repo.dirstate.copies()
4720 4720 copied, renamed = [], []
4721 4721 for d, s in c.iteritems():
4722 4722 if s in st[2]:
4723 4723 st[2].remove(s)
4724 4724 renamed.append(d)
4725 4725 else:
4726 4726 copied.append(d)
4727 4727 if d in st[1]:
4728 4728 st[1].remove(d)
4729 4729 st.insert(3, renamed)
4730 4730 st.insert(4, copied)
4731 4731
4732 4732 ms = mergemod.mergestate(repo)
4733 4733 st.append([f for f in ms if ms[f] == 'u'])
4734 4734
4735 4735 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
4736 4736 st.append(subs)
4737 4737
4738 4738 labels = [ui.label(_('%d modified'), 'status.modified'),
4739 4739 ui.label(_('%d added'), 'status.added'),
4740 4740 ui.label(_('%d removed'), 'status.removed'),
4741 4741 ui.label(_('%d renamed'), 'status.copied'),
4742 4742 ui.label(_('%d copied'), 'status.copied'),
4743 4743 ui.label(_('%d deleted'), 'status.deleted'),
4744 4744 ui.label(_('%d unknown'), 'status.unknown'),
4745 4745 ui.label(_('%d ignored'), 'status.ignored'),
4746 4746 ui.label(_('%d unresolved'), 'resolve.unresolved'),
4747 4747 ui.label(_('%d subrepos'), 'status.modified')]
4748 4748 t = []
4749 4749 for s, l in zip(st, labels):
4750 4750 if s:
4751 4751 t.append(l % len(s))
4752 4752
4753 4753 t = ', '.join(t)
4754 4754 cleanworkdir = False
4755 4755
4756 4756 if len(parents) > 1:
4757 4757 t += _(' (merge)')
4758 4758 elif branch != parents[0].branch():
4759 4759 t += _(' (new branch)')
4760 4760 elif (parents[0].extra().get('close') and
4761 4761 pnode in repo.branchheads(branch, closed=True)):
4762 4762 t += _(' (head closed)')
4763 4763 elif not (st[0] or st[1] or st[2] or st[3] or st[4] or st[9]):
4764 4764 t += _(' (clean)')
4765 4765 cleanworkdir = True
4766 4766 elif pnode not in bheads:
4767 4767 t += _(' (new branch head)')
4768 4768
4769 4769 if cleanworkdir:
4770 4770 ui.status(_('commit: %s\n') % t.strip())
4771 4771 else:
4772 4772 ui.write(_('commit: %s\n') % t.strip())
4773 4773
4774 4774 # all ancestors of branch heads - all ancestors of parent = new csets
4775 4775 new = [0] * len(repo)
4776 4776 cl = repo.changelog
4777 4777 for a in [cl.rev(n) for n in bheads]:
4778 4778 new[a] = 1
4779 4779 for a in cl.ancestors(*[cl.rev(n) for n in bheads]):
4780 4780 new[a] = 1
4781 4781 for a in [p.rev() for p in parents]:
4782 4782 if a >= 0:
4783 4783 new[a] = 0
4784 4784 for a in cl.ancestors(*[p.rev() for p in parents]):
4785 4785 new[a] = 0
4786 4786 new = sum(new)
4787 4787
4788 4788 if new == 0:
4789 4789 ui.status(_('update: (current)\n'))
4790 4790 elif pnode not in bheads:
4791 4791 ui.write(_('update: %d new changesets (update)\n') % new)
4792 4792 else:
4793 4793 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
4794 4794 (new, len(bheads)))
4795 4795
4796 4796 if opts.get('remote'):
4797 4797 t = []
4798 4798 source, branches = hg.parseurl(ui.expandpath('default'))
4799 4799 other = hg.peer(repo, {}, source)
4800 4800 revs, checkout = hg.addbranchrevs(repo, other, branches, opts.get('rev'))
4801 4801 ui.debug('comparing with %s\n' % util.hidepassword(source))
4802 4802 repo.ui.pushbuffer()
4803 4803 commoninc = discovery.findcommonincoming(repo, other)
4804 4804 _common, incoming, _rheads = commoninc
4805 4805 repo.ui.popbuffer()
4806 4806 if incoming:
4807 4807 t.append(_('1 or more incoming'))
4808 4808
4809 4809 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
4810 4810 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
4811 4811 if source != dest:
4812 4812 other = hg.peer(repo, {}, dest)
4813 4813 commoninc = None
4814 4814 ui.debug('comparing with %s\n' % util.hidepassword(dest))
4815 4815 repo.ui.pushbuffer()
4816 4816 common, outheads = discovery.findcommonoutgoing(repo, other,
4817 4817 commoninc=commoninc)
4818 4818 repo.ui.popbuffer()
4819 4819 o = repo.changelog.findmissing(common=common, heads=outheads)
4820 4820 if o:
4821 4821 t.append(_('%d outgoing') % len(o))
4822 4822 if 'bookmarks' in other.listkeys('namespaces'):
4823 4823 lmarks = repo.listkeys('bookmarks')
4824 4824 rmarks = other.listkeys('bookmarks')
4825 4825 diff = set(rmarks) - set(lmarks)
4826 4826 if len(diff) > 0:
4827 4827 t.append(_('%d incoming bookmarks') % len(diff))
4828 4828 diff = set(lmarks) - set(rmarks)
4829 4829 if len(diff) > 0:
4830 4830 t.append(_('%d outgoing bookmarks') % len(diff))
4831 4831
4832 4832 if t:
4833 4833 ui.write(_('remote: %s\n') % (', '.join(t)))
4834 4834 else:
4835 4835 ui.status(_('remote: (synced)\n'))
4836 4836
4837 4837 @command('tag',
4838 4838 [('f', 'force', None, _('force tag')),
4839 4839 ('l', 'local', None, _('make the tag local')),
4840 4840 ('r', 'rev', '', _('revision to tag'), _('REV')),
4841 4841 ('', 'remove', None, _('remove a tag')),
4842 4842 # -l/--local is already there, commitopts cannot be used
4843 4843 ('e', 'edit', None, _('edit commit message')),
4844 4844 ('m', 'message', '', _('use <text> as commit message'), _('TEXT')),
4845 4845 ] + commitopts2,
4846 4846 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'))
4847 4847 def tag(ui, repo, name1, *names, **opts):
4848 4848 """add one or more tags for the current or given revision
4849 4849
4850 4850 Name a particular revision using <name>.
4851 4851
4852 4852 Tags are used to name particular revisions of the repository and are
4853 4853 very useful to compare different revisions, to go back to significant
4854 4854 earlier versions or to mark branch points as releases, etc. Changing
4855 4855 an existing tag is normally disallowed; use -f/--force to override.
4856 4856
4857 4857 If no revision is given, the parent of the working directory is
4858 4858 used, or tip if no revision is checked out.
4859 4859
4860 4860 To facilitate version control, distribution, and merging of tags,
4861 4861 they are stored as a file named ".hgtags" which is managed similarly
4862 4862 to other project files and can be hand-edited if necessary. This
4863 4863 also means that tagging creates a new commit. The file
4864 4864 ".hg/localtags" is used for local tags (not shared among
4865 4865 repositories).
4866 4866
4867 4867 Tag commits are usually made at the head of a branch. If the parent
4868 4868 of the working directory is not a branch head, :hg:`tag` aborts; use
4869 4869 -f/--force to force the tag commit to be based on a non-head
4870 4870 changeset.
4871 4871
4872 4872 See :hg:`help dates` for a list of formats valid for -d/--date.
4873 4873
4874 4874 Since tag names have priority over branch names during revision
4875 4875 lookup, using an existing branch name as a tag name is discouraged.
4876 4876
4877 4877 Returns 0 on success.
4878 4878 """
4879 4879
4880 4880 rev_ = "."
4881 4881 names = [t.strip() for t in (name1,) + names]
4882 4882 if len(names) != len(set(names)):
4883 4883 raise util.Abort(_('tag names must be unique'))
4884 4884 for n in names:
4885 4885 if n in ['tip', '.', 'null']:
4886 4886 raise util.Abort(_("the name '%s' is reserved") % n)
4887 4887 if not n:
4888 4888 raise util.Abort(_('tag names cannot consist entirely of whitespace'))
4889 4889 if opts.get('rev') and opts.get('remove'):
4890 4890 raise util.Abort(_("--rev and --remove are incompatible"))
4891 4891 if opts.get('rev'):
4892 4892 rev_ = opts['rev']
4893 4893 message = opts.get('message')
4894 4894 if opts.get('remove'):
4895 4895 expectedtype = opts.get('local') and 'local' or 'global'
4896 4896 for n in names:
4897 4897 if not repo.tagtype(n):
4898 4898 raise util.Abort(_("tag '%s' does not exist") % n)
4899 4899 if repo.tagtype(n) != expectedtype:
4900 4900 if expectedtype == 'global':
4901 4901 raise util.Abort(_("tag '%s' is not a global tag") % n)
4902 4902 else:
4903 4903 raise util.Abort(_("tag '%s' is not a local tag") % n)
4904 4904 rev_ = nullid
4905 4905 if not message:
4906 4906 # we don't translate commit messages
4907 4907 message = 'Removed tag %s' % ', '.join(names)
4908 4908 elif not opts.get('force'):
4909 4909 for n in names:
4910 4910 if n in repo.tags():
4911 4911 raise util.Abort(_("tag '%s' already exists "
4912 4912 "(use -f to force)") % n)
4913 4913 if not opts.get('local'):
4914 4914 p1, p2 = repo.dirstate.parents()
4915 4915 if p2 != nullid:
4916 4916 raise util.Abort(_('uncommitted merge'))
4917 4917 bheads = repo.branchheads()
4918 4918 if not opts.get('force') and bheads and p1 not in bheads:
4919 4919 raise util.Abort(_('not at a branch head (use -f to force)'))
4920 4920 r = scmutil.revsingle(repo, rev_).node()
4921 4921
4922 4922 if not message:
4923 4923 # we don't translate commit messages
4924 4924 message = ('Added tag %s for changeset %s' %
4925 4925 (', '.join(names), short(r)))
4926 4926
4927 4927 date = opts.get('date')
4928 4928 if date:
4929 4929 date = util.parsedate(date)
4930 4930
4931 4931 if opts.get('edit'):
4932 4932 message = ui.edit(message, ui.username())
4933 4933
4934 4934 repo.tag(names, r, message, opts.get('local'), opts.get('user'), date)
4935 4935
4936 4936 @command('tags', [], '')
4937 4937 def tags(ui, repo):
4938 4938 """list repository tags
4939 4939
4940 4940 This lists both regular and local tags. When the -v/--verbose
4941 4941 switch is used, a third column "local" is printed for local tags.
4942 4942
4943 4943 Returns 0 on success.
4944 4944 """
4945 4945
4946 4946 hexfunc = ui.debugflag and hex or short
4947 4947 tagtype = ""
4948 4948
4949 4949 for t, n in reversed(repo.tagslist()):
4950 4950 if ui.quiet:
4951 4951 ui.write("%s\n" % t)
4952 4952 continue
4953 4953
4954 4954 hn = hexfunc(n)
4955 4955 r = "%5d:%s" % (repo.changelog.rev(n), hn)
4956 4956 spaces = " " * (30 - encoding.colwidth(t))
4957 4957
4958 4958 if ui.verbose:
4959 4959 if repo.tagtype(t) == 'local':
4960 4960 tagtype = " local"
4961 4961 else:
4962 4962 tagtype = ""
4963 4963 ui.write("%s%s %s%s\n" % (t, spaces, r, tagtype))
4964 4964
4965 4965 @command('tip',
4966 4966 [('p', 'patch', None, _('show patch')),
4967 4967 ('g', 'git', None, _('use git extended diff format')),
4968 4968 ] + templateopts,
4969 4969 _('[-p] [-g]'))
4970 4970 def tip(ui, repo, **opts):
4971 4971 """show the tip revision
4972 4972
4973 4973 The tip revision (usually just called the tip) is the changeset
4974 4974 most recently added to the repository (and therefore the most
4975 4975 recently changed head).
4976 4976
4977 4977 If you have just made a commit, that commit will be the tip. If
4978 4978 you have just pulled changes from another repository, the tip of
4979 4979 that repository becomes the current tip. The "tip" tag is special
4980 4980 and cannot be renamed or assigned to a different changeset.
4981 4981
4982 4982 Returns 0 on success.
4983 4983 """
4984 4984 displayer = cmdutil.show_changeset(ui, repo, opts)
4985 4985 displayer.show(repo[len(repo) - 1])
4986 4986 displayer.close()
4987 4987
4988 4988 @command('unbundle',
4989 4989 [('u', 'update', None,
4990 4990 _('update to new branch head if changesets were unbundled'))],
4991 4991 _('[-u] FILE...'))
4992 4992 def unbundle(ui, repo, fname1, *fnames, **opts):
4993 4993 """apply one or more changegroup files
4994 4994
4995 4995 Apply one or more compressed changegroup files generated by the
4996 4996 bundle command.
4997 4997
4998 4998 Returns 0 on success, 1 if an update has unresolved files.
4999 4999 """
5000 5000 fnames = (fname1,) + fnames
5001 5001
5002 5002 lock = repo.lock()
5003 5003 wc = repo['.']
5004 5004 try:
5005 5005 for fname in fnames:
5006 5006 f = url.open(ui, fname)
5007 5007 gen = changegroup.readbundle(f, fname)
5008 5008 modheads = repo.addchangegroup(gen, 'unbundle', 'bundle:' + fname,
5009 5009 lock=lock)
5010 5010 bookmarks.updatecurrentbookmark(repo, wc.node(), wc.branch())
5011 5011 finally:
5012 5012 lock.release()
5013 5013 return postincoming(ui, repo, modheads, opts.get('update'), None)
5014 5014
5015 5015 @command('^update|up|checkout|co',
5016 5016 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
5017 5017 ('c', 'check', None,
5018 5018 _('update across branches if no uncommitted changes')),
5019 5019 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5020 5020 ('r', 'rev', '', _('revision'), _('REV'))],
5021 5021 _('[-c] [-C] [-d DATE] [[-r] REV]'))
5022 5022 def update(ui, repo, node=None, rev=None, clean=False, date=None, check=False):
5023 5023 """update working directory (or switch revisions)
5024 5024
5025 5025 Update the repository's working directory to the specified
5026 5026 changeset. If no changeset is specified, update to the tip of the
5027 5027 current named branch.
5028 5028
5029 5029 If the changeset is not a descendant of the working directory's
5030 5030 parent, the update is aborted. With the -c/--check option, the
5031 5031 working directory is checked for uncommitted changes; if none are
5032 5032 found, the working directory is updated to the specified
5033 5033 changeset.
5034 5034
5035 5035 The following rules apply when the working directory contains
5036 5036 uncommitted changes:
5037 5037
5038 5038 1. If neither -c/--check nor -C/--clean is specified, and if
5039 5039 the requested changeset is an ancestor or descendant of
5040 5040 the working directory's parent, the uncommitted changes
5041 5041 are merged into the requested changeset and the merged
5042 5042 result is left uncommitted. If the requested changeset is
5043 5043 not an ancestor or descendant (that is, it is on another
5044 5044 branch), the update is aborted and the uncommitted changes
5045 5045 are preserved.
5046 5046
5047 5047 2. With the -c/--check option, the update is aborted and the
5048 5048 uncommitted changes are preserved.
5049 5049
5050 5050 3. With the -C/--clean option, uncommitted changes are discarded and
5051 5051 the working directory is updated to the requested changeset.
5052 5052
5053 5053 Use null as the changeset to remove the working directory (like
5054 5054 :hg:`clone -U`).
5055 5055
5056 5056 If you want to update just one file to an older changeset, use
5057 5057 :hg:`revert`.
5058 5058
5059 5059 See :hg:`help dates` for a list of formats valid for -d/--date.
5060 5060
5061 5061 Returns 0 on success, 1 if there are unresolved files.
5062 5062 """
5063 5063 if rev and node:
5064 5064 raise util.Abort(_("please specify just one revision"))
5065 5065
5066 5066 if rev is None or rev == '':
5067 5067 rev = node
5068 5068
5069 5069 # if we defined a bookmark, we have to remember the original bookmark name
5070 5070 brev = rev
5071 5071 rev = scmutil.revsingle(repo, rev, rev).rev()
5072 5072
5073 5073 if check and clean:
5074 5074 raise util.Abort(_("cannot specify both -c/--check and -C/--clean"))
5075 5075
5076 5076 if check:
5077 5077 # we could use dirty() but we can ignore merge and branch trivia
5078 5078 c = repo[None]
5079 5079 if c.modified() or c.added() or c.removed():
5080 5080 raise util.Abort(_("uncommitted local changes"))
5081 5081
5082 5082 if date:
5083 5083 if rev is not None:
5084 5084 raise util.Abort(_("you can't specify a revision and a date"))
5085 5085 rev = cmdutil.finddate(ui, repo, date)
5086 5086
5087 5087 if clean or check:
5088 5088 ret = hg.clean(repo, rev)
5089 5089 else:
5090 5090 ret = hg.update(repo, rev)
5091 5091
5092 5092 if brev in repo._bookmarks:
5093 5093 bookmarks.setcurrent(repo, brev)
5094 5094
5095 5095 return ret
5096 5096
5097 5097 @command('verify', [])
5098 5098 def verify(ui, repo):
5099 5099 """verify the integrity of the repository
5100 5100
5101 5101 Verify the integrity of the current repository.
5102 5102
5103 5103 This will perform an extensive check of the repository's
5104 5104 integrity, validating the hashes and checksums of each entry in
5105 5105 the changelog, manifest, and tracked files, as well as the
5106 5106 integrity of their crosslinks and indices.
5107 5107
5108 5108 Returns 0 on success, 1 if errors are encountered.
5109 5109 """
5110 5110 return hg.verify(repo)
5111 5111
5112 5112 @command('version', [])
5113 5113 def version_(ui):
5114 5114 """output version and copyright information"""
5115 5115 ui.write(_("Mercurial Distributed SCM (version %s)\n")
5116 5116 % util.version())
5117 5117 ui.status(_(
5118 5118 "(see http://mercurial.selenic.com for more information)\n"
5119 5119 "\nCopyright (C) 2005-2011 Matt Mackall and others\n"
5120 5120 "This is free software; see the source for copying conditions. "
5121 5121 "There is NO\nwarranty; "
5122 5122 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
5123 5123 ))
5124 5124
5125 5125 norepo = ("clone init version help debugcommands debugcomplete"
5126 5126 " debugdate debuginstall debugfsinfo debugpushkey debugwireargs"
5127 5127 " debugknown debuggetbundle debugbundle")
5128 5128 optionalrepo = ("identify paths serve showconfig debugancestor debugdag"
5129 5129 " debugdata debugindex debugindexdot debugrevlog")
General Comments 0
You need to be logged in to leave comments. Login now